@dcl/vesting-dashboard 3.6.1-16577537275.commit-a4c65b5 → 3.7.1-19868070294.commit-e76f047
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/PhArrowCircleDown-b4d1b9f0.js +14 -0
- package/assets/PhArrowClockwise-35e72491.js +14 -0
- package/assets/PhArrowDown-57c22b7e.js +14 -0
- package/assets/PhArrowLeft-f48f6a32.js +14 -0
- package/assets/PhArrowRight-86fee956.js +14 -0
- package/assets/PhArrowSquareOut-7b8bc76d.js +14 -0
- package/assets/PhArrowUp-cb14a0b1.js +14 -0
- package/assets/PhArrowUpRight-72a93a0e.js +14 -0
- package/assets/PhArrowsClockwise-ecc02e05.js +14 -0
- package/assets/PhArrowsDownUp-336a1435.js +14 -0
- package/assets/PhArrowsLeftRight-fbdccc02.js +14 -0
- package/assets/PhBank-31d2eba3.js +14 -0
- package/assets/PhBrowser-90d21d12.js +14 -0
- package/assets/PhCaretDown-3aabbdc5.js +14 -0
- package/assets/PhCaretLeft-282326ec.js +14 -0
- package/assets/PhCaretRight-7b09ae84.js +14 -0
- package/assets/PhCaretUp-e4584d94.js +14 -0
- package/assets/PhCheck-5730aae2.js +14 -0
- package/assets/PhCircleHalf-7d16bc06.js +14 -0
- package/assets/PhClock-8b060e99.js +14 -0
- package/assets/PhCompass-45d3bde6.js +14 -0
- package/assets/PhCopy-f77992ef.js +14 -0
- package/assets/PhCreditCard-c353277e.js +14 -0
- package/assets/PhCurrencyDollar-510272c7.js +14 -0
- package/assets/PhDesktop-49e8128e.js +14 -0
- package/assets/PhDeviceMobile-cfdf19ef.js +14 -0
- package/assets/PhDotsThree-69a484e4.js +14 -0
- package/assets/PhEnvelope-fc3dd2a0.js +14 -0
- package/assets/PhFunnelSimple-5abe9858.js +14 -0
- package/assets/PhGlobe-a1b4ca91.js +14 -0
- package/assets/PhIdentificationCard-80541484.js +14 -0
- package/assets/PhImage-6bbac6b7.js +14 -0
- package/assets/PhInfo-3481abef.js +14 -0
- package/assets/PhLightbulb-26b52ed2.js +14 -0
- package/assets/PhMagnifyingGlass-4dfb76cc.js +14 -0
- package/assets/PhPaperPlaneRight-e6cf54ef.js +14 -0
- package/assets/PhPlus-f5753116.js +14 -0
- package/assets/PhPower-8bf5c9c7.js +14 -0
- package/assets/PhPuzzlePiece-93f1c92b.js +14 -0
- package/assets/PhQrCode-03aa9f8a.js +14 -0
- package/assets/PhQuestion-6c2bd1ad.js +14 -0
- package/assets/PhQuestionMark-820f14af.js +14 -0
- package/assets/PhSealCheck-137e0b1b.js +14 -0
- package/assets/PhSignOut-ed65c268.js +14 -0
- package/assets/PhSpinner-19f53f69.js +14 -0
- package/assets/PhTrash-acb3ad59.js +14 -0
- package/assets/PhUser-92aa32ba.js +14 -0
- package/assets/PhVault-ed94ef20.js +14 -0
- package/assets/PhWarning-b2396b99.js +14 -0
- package/assets/PhWarningCircle-0f363973.js +14 -0
- package/assets/PhX-522d79dd.js +14 -0
- package/assets/basic-eeeaaaeb.js +1435 -0
- package/assets/core-84b3ed1e.js +254 -0
- package/assets/features-21cad012.js +5 -0
- package/assets/{fortmatic-38f79735.js → fortmatic-f30106eb.js} +1 -1
- package/assets/{index-5fe88343.js → index-04415554.js} +1 -1
- package/assets/index-069f2f19.js +40 -0
- package/assets/index-388893ce.js +1321 -0
- package/assets/index-516a1ffc.js +26 -0
- package/assets/{index-9c03b9eb.css → index-91d98a83.css} +7 -7
- package/assets/{index-d9a3300d.js → index-be0620a9.js} +1 -1
- package/assets/{index-db35fe51.js → index-cf405d3f.js} +1 -1
- package/assets/index-ec27bc27.js +7 -0
- package/assets/{index-1e0cfb06.js → index-fec77d48.js} +136 -130
- package/assets/native-bf1092f7.js +1 -0
- package/assets/property-70d704fc.js +27 -0
- package/assets/w3m-modal-4a2f6c0b.js +1209 -0
- package/index.html +4 -4
- package/package.json +3 -3
- package/assets/add-423b3765.js +0 -15
- package/assets/all-wallets-6318b594.js +0 -6
- package/assets/app-store-c30317c0.js +0 -17
- package/assets/apple-248aca7f.js +0 -18
- package/assets/arrow-bottom-99c2809a.js +0 -8
- package/assets/arrow-bottom-circle-52aa2a11.js +0 -11
- package/assets/arrow-left-69c01e2b.js +0 -8
- package/assets/arrow-right-1c1b5b19.js +0 -8
- package/assets/arrow-top-741c53b5.js +0 -8
- package/assets/bank-24f6d02d.js +0 -14
- package/assets/basic-9dc8174a.js +0 -2128
- package/assets/browser-95dd5a39.js +0 -14
- package/assets/card-2db2dba3.js +0 -14
- package/assets/checkmark-b219f135.js +0 -11
- package/assets/checkmark-bold-25fa686a.js +0 -8
- package/assets/chevron-bottom-f075ffbd.js +0 -8
- package/assets/chevron-left-71e407e9.js +0 -8
- package/assets/chevron-right-6189a026.js +0 -8
- package/assets/chevron-top-3b0f639b.js +0 -8
- package/assets/chrome-store-bcf03a9a.js +0 -61
- package/assets/clock-ccbbd268.js +0 -8
- package/assets/close-7a27f645.js +0 -8
- package/assets/coinPlaceholder-ae5a3855.js +0 -8
- package/assets/compass-313e8cfe.js +0 -8
- package/assets/copy-12ca4475.js +0 -15
- package/assets/core-10800243.js +0 -910
- package/assets/cursor-07342d1b.js +0 -3
- package/assets/cursor-transparent-4c6027d5.js +0 -12
- package/assets/desktop-739920a7.js +0 -9
- package/assets/disconnect-4c3a444c.js +0 -8
- package/assets/discord-15059aa1.js +0 -17
- package/assets/etherscan-94f3dd64.js +0 -6
- package/assets/exclamation-triangle-2f387115.js +0 -4
- package/assets/extension-9d4a1b73.js +0 -8
- package/assets/external-link-a8b07c98.js +0 -8
- package/assets/facebook-55d423f7.js +0 -26
- package/assets/farcaster-dd4a3e14.js +0 -12
- package/assets/filters-602ee0e2.js +0 -8
- package/assets/github-bec58e5b.js +0 -18
- package/assets/google-98d84a2c.js +0 -18
- package/assets/help-circle-ef60da9e.js +0 -12
- package/assets/id-d31bfc51.js +0 -12
- package/assets/image-fb1f3e63.js +0 -4
- package/assets/index-376d9ca5.js +0 -394
- package/assets/index-4c3c4c35.js +0 -7
- package/assets/index.es-63034a59.js +0 -26
- package/assets/info-8e7d9734.js +0 -3
- package/assets/info-circle-beb255df.js +0 -12
- package/assets/lightbulb-9b5bc46f.js +0 -3
- package/assets/mail-a8cb5474.js +0 -8
- package/assets/mobile-830dba07.js +0 -9
- package/assets/more-94154d68.js +0 -11
- package/assets/network-placeholder-feda2a74.js +0 -14
- package/assets/nftPlaceholder-3500f4ec.js +0 -8
- package/assets/off-514e4de1.js +0 -8
- package/assets/play-store-2e9bbeb8.js +0 -32
- package/assets/plus-a33257e8.js +0 -13
- package/assets/qr-code-2dd8cc67.js +0 -6
- package/assets/recycle-horizontal-1cac807c.js +0 -9
- package/assets/refresh-1a3f6cce.js +0 -8
- package/assets/reown-logo-f43b0e23.js +0 -12
- package/assets/search-3bd8cbcb.js +0 -8
- package/assets/secp256k1-68a098fa.js +0 -1
- package/assets/secp256k1-bb840cb1.js +0 -1
- package/assets/send-10d3ed06.js +0 -15
- package/assets/swapHorizontal-5baadf98.js +0 -8
- package/assets/swapHorizontalBold-f2a3ad00.js +0 -8
- package/assets/swapHorizontalMedium-cf44b565.js +0 -16
- package/assets/swapHorizontalRoundedBold-342fa240.js +0 -8
- package/assets/swapVertical-178d166c.js +0 -8
- package/assets/telegram-795f2864.js +0 -16
- package/assets/three-dots-0198b4c0.js +0 -5
- package/assets/twitch-27573001.js +0 -18
- package/assets/twitterIcon-cb8f65cb.js +0 -6
- package/assets/verify-37b11cb7.js +0 -8
- package/assets/verify-filled-f1000698.js +0 -8
- package/assets/w3m-modal-22f5aa95.js +0 -642
- package/assets/wallet-97c0e814.js +0 -8
- package/assets/wallet-placeholder-24cab014.js +0 -14
- package/assets/walletconnect-63e804b2.js +0 -30
- package/assets/warning-circle-d5eaf6d9.js +0 -12
- package/assets/x-44f57cce.js +0 -12
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import{p as Os,h as Us,_ as lo,B as me,b as ie,e as $n,x as Ac}from"./index-fec77d48.js";import{d as Oi,s as _c,c as Yp,g as tl,a as Jp,b as Xp,k as Zp,e as Qp,f as uo,I as ur,Y as Ic,h as ef,i as j,j as Ht,t as Ct,l as nr,m as Nu,n as hr,o as tf,p as sf,q as nf,r as rf,u as of,v as af,w as cf,x as xr,y as xa,C as lf,X as Pt,z as kt,D as Su,A as df,B as Nc,E as uf,F as Sc,G as Tc,H as qr,J as pr,K as ls,P as sl,Q as hf,L as pf,M as En,N as Tu,O as Es,R as cs,S as Ds,T as Ou}from"./index-516a1ffc.js";const N={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",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"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},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 Os<"u"&&typeof{}<"u"?{}.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."}}},IS_DEVELOPMENT:typeof Os<"u"&&{}.NODE_ENV==="development",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"]},Ru={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return(t==null?void 0:t.filter(s=>s.chainNamespace===e))||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){var r;if(!e)return;const s=t.find(i=>i.caipNetworkId===e);if(s)return s.name;const[n]=e.split(":");return((r=N.CHAIN_NAME_MAP)==null?void 0:r[n])||void 0}},Pu=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"],ff={bigNumber(t){return t?new Us(t):new Us(0)},multiply(t,e){if(t===void 0||e===void 0)return new Us(0);const s=new Us(t),n=new Us(e);return s.times(n)},toFixed(t,e=2){return t===void 0||t===""?new Us(0).toFixed(e):new Us(t).toFixed(e)},formatNumberToLocalString(t,e=2){return t===void 0||t===""?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"})},parseLocalStringToNumber(t){if(t===void 0||t==="")return 0;const e=t.replace(/,/gu,"");return new Us(e).toNumber()}},gf=[{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"}]}],mf=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],yf=[{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"}]}],wf={getERC20Abi:t=>N.USDT_CONTRACT_ADDRESSES.includes(t)?yf:gf,getSwapAbi:()=>mf},Qe={validateCaipAddress(t){var e;if(((e=t.split(":"))==null?void 0:e.length)!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,n,r]=e;if(!s||!n||!r)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:n,address:r}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,n]=e;if(!s||!n)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:n}}},Ns={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError"},isRpcProviderError(t){try{if(typeof t=="object"&&t!==null){const e=t,s=typeof e.message=="string",n=typeof e.code=="number";return s&&n}return!1}catch{return!1}},isUserRejectedMessage(t){return t.toLowerCase().includes("user rejected")||t.toLowerCase().includes("user cancelled")||t.toLowerCase().includes("user canceled")},isUserRejectedRequestError(t){if(Ns.isRpcProviderError(t)){const e=t.code===Ns.RPC_ERROR_CODE.USER_REJECTED_REQUEST,s=t.code===Ns.RPC_ERROR_CODE.USER_REJECTED_METHODS;return e||s||Ns.isUserRejectedMessage(t.message)}return t instanceof Error?Ns.isUserRejectedMessage(t.message):!1}};let bf=class extends Error{constructor(e,s){super(s.message,{cause:e}),this.name=Ns.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=s.code}},ku=class extends bf{constructor(e){super(e,{code:Ns.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=Ns.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}};const Z={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"};function Ko(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Y={setItem(t,e){Tr()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(Tr())return localStorage.getItem(t)||void 0},removeItem(t){Tr()&&localStorage.removeItem(t)},clear(){Tr()&&localStorage.clear()}};function Tr(){return typeof window<"u"&&typeof localStorage<"u"}function ho(t,e){return e==="light"?{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const Ef=Symbol(),nl=Object.getPrototypeOf,$a=new WeakMap,Cf=t=>t&&($a.has(t)?$a.get(t):nl(t)===Object.prototype||nl(t)===Array.prototype),vf=t=>Cf(t)&&t[Ef]||null,rl=(t,e=!0)=>{$a.set(t,e)},Oc=t=>typeof t=="object"&&t!==null,Af=t=>Oc(t)&&!bi.has(t)&&(Array.isArray(t)||!(Symbol.iterator in t))&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!(t instanceof Error)&&!(t instanceof Number)&&!(t instanceof Date)&&!(t instanceof String)&&!(t instanceof RegExp)&&!(t instanceof ArrayBuffer)&&!(t instanceof Promise),xu=(t,e)=>{const s=Ua.get(t);if((s==null?void 0:s[0])===e)return s[1];const n=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return rl(n,!0),Ua.set(t,[e,n]),Reflect.ownKeys(t).forEach(r=>{if(Object.getOwnPropertyDescriptor(n,r))return;const i=Reflect.get(t,r),{enumerable:o}=Reflect.getOwnPropertyDescriptor(t,r),a={value:i,enumerable:o,configurable:!0};if(bi.has(i))rl(i,!1);else if(sn.has(i)){const[c,l]=sn.get(i);a.value=xu(c,l())}Object.defineProperty(n,r,a)}),Object.preventExtensions(n)},_f=(t,e,s,n)=>({deleteProperty(r,i){const o=Reflect.get(r,i);s(i);const a=Reflect.deleteProperty(r,i);return a&&n(["delete",[i],o]),a},set(r,i,o,a){const c=!t()&&Reflect.has(r,i),l=Reflect.get(r,i,a);if(c&&(il(l,o)||Wr.has(o)&&il(l,Wr.get(o))))return!0;s(i),Oc(o)&&(o=vf(o)||o);const d=!sn.has(o)&&Nf(o)?ke(o):o;return e(i,d),Reflect.set(r,i,d,a),n(["set",[i],o,l]),!0}}),sn=new WeakMap,bi=new WeakSet,Ua=new WeakMap,Zi=[1],Wr=new WeakMap;let il=Object.is,If=(t,e)=>new Proxy(t,e),Nf=Af,Sf=xu,Tf=_f;function ke(t={}){if(!Oc(t))throw new Error("object required");const e=Wr.get(t);if(e)return e;let s=Zi[0];const n=new Set,r=(y,w=++Zi[0])=>{s!==w&&(i=s=w,n.forEach(b=>b(y,w)))};let i=s;const o=(y=Zi[0])=>(i!==y&&(i=y,c.forEach(([w])=>{const b=w[1](y);b>s&&(s=b)})),s),a=y=>(w,b)=>{const A=[...w];A[1]=[y,...A[1]],r(A,b)},c=new Map,l=(y,w)=>{const b=!bi.has(w)&&sn.get(w);if(b)if(n.size){const A=b[2](a(y));c.set(y,[b,A])}else c.set(y,[b])},d=y=>{var w;const b=c.get(y);b&&(c.delete(y),(w=b[1])==null||w.call(b))},u=y=>(n.add(y),n.size===1&&c.forEach(([b,A],k)=>{const $=b[2](a(k));c.set(k,[b,$])}),()=>{n.delete(y),n.size===0&&c.forEach(([b,A],k)=>{A&&(A(),c.set(k,[b]))})});let h=!0;const p=Tf(()=>h,l,d,r),f=If(t,p);Wr.set(t,f);const m=[t,o,u];return sn.set(f,m),Reflect.ownKeys(t).forEach(y=>{const w=Object.getOwnPropertyDescriptor(t,y);"value"in w&&w.writable&&(f[y]=t[y])}),h=!1,f}function et(t,e,s){const n=sn.get(t);let r;const i=[],o=n[2];let a=!1;const l=o(d=>{if(i.push(d),s){e(i.splice(0));return}r||(r=Promise.resolve().then(()=>{r=void 0,a&&e(i.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Hr(t){const e=sn.get(t),[s,n]=e;return Sf(s,n())}function Kr(t){return bi.add(t),t}function Of(){return{proxyStateMap:sn,refSet:bi,snapCache:Ua,versionHolder:Zi,proxyCache:Wr}}function tt(t,e,s,n){let r=t[e];return et(t,()=>{const i=t[e];Object.is(r,i)||s(r=i)},n)}const{proxyStateMap:Rf,snapCache:Pf}=Of(),Ri=t=>Rf.has(t);function kf(t){const e=[];let s=0;const n=new Map,r=new WeakMap,i=()=>{const l=Pf.get(a),d=l==null?void 0:l[1];if(d&&!r.has(d)){const u=new Map(n);r.set(d,u)}},o=l=>r.get(l)||n;if(t){if(typeof t[Symbol.iterator]!="function")throw new TypeError(`proxyMap:
|
|
2
|
+
initial state must be iterable
|
|
3
|
+
tip: structure should be [[key, value]]`);for(const[l,d]of t)n.set(l,s),e[s++]=d}const a={data:e,index:s,epoch:0,get size(){return Ri(this)||i(),o(this).size},get(l){const u=o(this).get(l);if(u===void 0){this.epoch;return}return this.data[u]},has(l){const d=o(this);return this.epoch,d.has(l)},set(l,d){if(!Ri(this))throw new Error("Cannot perform mutations on a snapshot");const u=n.get(l);return u===void 0?(n.set(l,this.index),this.data[this.index++]=d):this.data[u]=d,this.epoch++,this},delete(l){if(!Ri(this))throw new Error("Cannot perform mutations on a snapshot");const d=n.get(l);return d===void 0?!1:(delete this.data[d],n.delete(l),this.epoch++,!0)},clear(){if(!Ri(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,n.clear()},forEach(l){this.epoch,o(this).forEach((u,h)=>{l(this.data[u],h,this)})},*entries(){this.epoch;const l=o(this);for(const[d,u]of l)yield[d,this.data[u]]},*keys(){this.epoch;const l=o(this);for(const d of l.keys())yield d},*values(){this.epoch;const l=o(this);for(const d of l.values())yield this.data[d]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=ke(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}const Vo=(typeof Os<"u"&&typeof{}<"u"?{}.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",$u=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],xf="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",be={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:Vo,SECURE_SITE_DASHBOARD:`${Vo}/dashboard`,SECURE_SITE_FAVICON:`${Vo}/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₮0"]},BALANCE_SUPPORTED_CHAINS:[N.CHAIN.EVM,N.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[N.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:[N.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[N.CHAIN.EVM,N.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[N.CHAIN.EVM,N.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[N.CHAIN.EVM],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"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:[N.CHAIN.EVM,N.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},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!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},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0}},R={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=R.getActiveNamespace(),e=R.getActiveCaipNetworkId(),s=e?e.split(":")[1]:void 0,n=s?isNaN(Number(s))?s:Number(s):void 0;return{namespace:t,caipNetworkId:e,chainId:n}},setWalletConnectDeepLink({name:t,href:e}){try{Y.setItem(Z.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Y.getItem(Z.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Y.removeItem(Z.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Y.setItem(Z.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Y.setItem(Z.ACTIVE_CAIP_NETWORK_ID,t),R.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Y.getItem(Z.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Y.removeItem(Z.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=Ko(t);Y.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=R.getRecentWallets();e.find(n=>n.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Y.setItem(Z.RECENT_WALLETS,JSON.stringify(e)),Y.setItem(Z.RECENT_WALLET,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Y.getItem(Z.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const t=Y.getItem(Z.RECENT_WALLET);return t?JSON.parse(t):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Y.removeItem(Z.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(t,e){try{const s=Ko(t);Y.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Y.getItem(Z.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=Ko(t);return Y.getItem(e)}catch{console.info("Unable to get connected connector id in namespace",t)}},setConnectedSocialProvider(t){try{Y.setItem(Z.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Y.getItem(Z.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Y.removeItem(Z.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Y.getItem(Z.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var s;const t=Y.getItem(Z.ACTIVE_CAIP_NETWORK_ID);return(s=t==null?void 0:t.split(":"))==null?void 0:s[1]},setConnectionStatus(t){try{Y.setItem(Z.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Y.getItem(Z.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Y.getItem(Z.CONNECTED_NAMESPACES);return t!=null&&t.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Y.setItem(Z.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=R.getConnectedNamespaces();e.includes(t)||(e.push(t),R.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=R.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),R.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Y.getItem(Z.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Y.setItem(Z.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Y.removeItem(Z.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Y.getItem(Z.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=R.getBalanceCache();Y.setItem(Z.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=R.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;R.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=R.getBalanceCache();e[t.caipAddress]=t,Y.setItem(Z.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Y.getItem(Z.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=R.getBalanceCache();Y.setItem(Z.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const s=R.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),R.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=R.getNativeBalanceCache();e[t.caipAddress]=t,Y.setItem(Z.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Y.getItem(Z.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const s=R.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;R.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=R.getEnsCache();e[t.address]=t,Y.setItem(Z.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=R.getEnsCache();Y.setItem(Z.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Y.getItem(Z.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=R.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;R.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=R.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Y.setItem(Z.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=R.getIdentityCache();Y.setItem(Z.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Y.removeItem(Z.PORTFOLIO_CACHE),Y.removeItem(Z.NATIVE_BALANCE_CACHE),Y.removeItem(Z.ENS_CACHE),Y.removeItem(Z.IDENTITY_CACHE),Y.removeItem(Z.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Y.setItem(Z.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Y.getItem(Z.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s=R.getConnections(),n=s[e]??[],r=new Map;for(const o of n)r.set(o.connectorId,{...o});for(const o of t){const a=r.get(o.connectorId),c=o.connectorId===N.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(u=>u.address.toLowerCase())),d=o.accounts.filter(u=>!l.has(u.address.toLowerCase()));a.accounts.push(...d)}else r.set(o.connectorId,{...o})}const i={...s,[e]:Array.from(r.values())};Y.setItem(Z.CONNECTIONS,JSON.stringify(i))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=Y.getItem(Z.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}},deleteAddressFromConnection({connectorId:t,address:e,namespace:s}){try{const n=R.getConnections(),r=n[s]??[],i=new Map(r.map(a=>[a.connectorId,a])),o=i.get(t);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase()).length===0?i.delete(t):i.set(t,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase())})),Y.setItem(Z.CONNECTIONS,JSON.stringify({...n,[s]:Array.from(i.values())}))}catch{console.error(`Unable to remove address "${e}" from connector "${t}" in namespace "${s}"`)}},getDisconnectedConnectorIds(){try{const t=Y.getItem(Z.DISCONNECTED_CONNECTOR_IDS);return t?JSON.parse(t):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(t,e){try{const s=R.getDisconnectedConnectorIds(),n=s[e]??[];n.push(t),Y.setItem(Z.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[e]:Array.from(new Set(n))}))}catch{console.error(`Unable to set disconnected connector id "${t}" for namespace "${e}"`)}},removeDisconnectedConnectorId(t,e){try{const s=R.getDisconnectedConnectorIds();let n=s[e]??[];n=n.filter(r=>r.toLowerCase()!==t.toLowerCase()),Y.setItem(Z.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[e]:Array.from(new Set(n))}))}catch{console.error(`Unable to remove disconnected connector id "${t}" for namespace "${e}"`)}},isConnectorDisconnected(t,e){try{return(R.getDisconnectedConnectorIds()[e]??[]).some(r=>r.toLowerCase()===t.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${t}" for namespace "${e}"`)}return!1},getTransactionsCache(){try{const t=Y.getItem(Z.HISTORY_TRANSACTIONS_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:t,chainId:e=""}){var s;try{const r=(s=R.getTransactionsCache()[t])==null?void 0:s[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;R.removeTransactionsCache({address:t,chainId:e})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:t,chainId:e="",timestamp:s,transactions:n}){try{const r=R.getTransactionsCache();r[t]={...r[t],[e]:{timestamp:s,transactions:n}},Y.setItem(Z.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(r))}catch{console.info("Unable to update transactions cache",{address:t,chainId:e,timestamp:s,transactions:n})}},removeTransactionsCache({address:t,chainId:e}){try{const s=R.getTransactionsCache(),n=(s==null?void 0:s[t])||{},{[e]:r,...i}=n;Y.setItem(Z.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...s,[t]:i}))}catch{console.info("Unable to remove transactions cache",{address:t,chainId:e})}},getTokenPriceCache(){try{const t=Y.getItem(Z.TOKEN_PRICE_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(t){try{const s=R.getTokenPriceCache()[t.join(",")];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.tokenPrice))return s.tokenPrice;R.removeTokenPriceCache(t)}catch{console.info("Unable to get token price cache for addresses",t)}},updateTokenPriceCache(t){try{const e=R.getTokenPriceCache();e[t.addresses.join(",")]={timestamp:t.timestamp,tokenPrice:t.tokenPrice},Y.setItem(Z.TOKEN_PRICE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update token price cache",t)}},removeTokenPriceCache(t){try{const e=R.getTokenPriceCache();Y.setItem(Z.TOKEN_PRICE_CACHE,JSON.stringify({...e,[t.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",t)}},getLatestAppKitVersion(){try{const t=this.getLatestAppKitVersionCache(),e=t==null?void 0:t.version;return e&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.latestAppKitVersion)?e:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const t=Y.getItem(Z.LATEST_APPKIT_VERSION);return t?JSON.parse(t):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(t){try{const e=R.getLatestAppKitVersionCache();e.timestamp=t.timestamp,e.version=t.version,Y.setItem(Z.LATEST_APPKIT_VERSION,JSON.stringify(e))}catch{console.info("Unable to update latest AppKit version on local storage",t)}}},z={isMobile(){var t;return this.isClient()?!!(window!=null&&window.matchMedia&&typeof window.matchMedia=="function"&&((t=window.matchMedia("(pointer:coarse)"))!=null&&t.matches)||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t==null?void 0:t.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return z.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window==null?void 0:window.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=be.TEN_SEC_MS:!0},isAllowedRetry(t,e=be.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return(window==null?void 0:window.self)!==(window==null?void 0:window.top)}catch{return!1}},isSafeApp(){var t,e;if(z.isClient()&&window.self!==window.top)try{const s=(e=(t=window==null?void 0:window.location)==null?void 0:t.ancestorOrigins)==null?void 0:e[0],n="https://app.safe.global";if(s){const r=new URL(s),i=new URL(n);return r.hostname===i.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+be.FOUR_MINUTES_MS},getNetworkId(t){return t==null?void 0:t.split(":")[1]},getPlainAddress(t){return t==null?void 0:t.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let s;return(...n)=>{function r(){t(...n)}s&&clearTimeout(s),s=setTimeout(r,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(z.isHttpUrl(t))return this.formatUniversalUrl(t,e);let n=t,r=s;n.includes("://")||(n=t.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),r&&!(r!=null&&r.endsWith("/"))&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${n}wc?uri=${i}`,redirectUniversalLink:r?`${r}wc?uri=${i}`:void 0,href:n}},formatUniversalUrl(t,e){if(!z.isHttpUrl(t))return this.formatNativeUrl(t,e);let s=t;s.endsWith("/")||(s=`${s}/`);const n=encodeURIComponent(e);return{redirect:`${s}wc?uri=${n}`,href:s}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?R.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window==null||window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window==null?void 0:window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){var s,n;if(typeof window>"u")return!1;const t=window!=null&&window.matchMedia&&typeof window.matchMedia=="function"?(s=window.matchMedia("(display-mode: standalone)"))==null?void 0:s.matches:!1,e=(n=window==null?void 0:window.navigator)==null?void 0:n.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,n)=>{const r=new Image;r.onload=s,r.onerror=n,r.crossOrigin="anonymous",r.src=t});return Promise.race([e,z.wait(2e3)])},parseBalance(t,e){let s="0.000";if(typeof t=="string"){const c=Number(t);if(!isNaN(c)){const l=(Math.floor(c*1e3)/1e3).toFixed(3);l&&(s=l)}}const[n,r]=s.split("."),i=n||"0",o=r||"000";return{formattedText:`${i}.${o}${e?` ${e}`:""}`,value:i,decimals:o,symbol:e}},getApiUrl(){return N.W3M_API_URL},getBlockchainApiUrl(){return N.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return N.PULSE_API_URL},getUUID(){return crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){var e,s;return typeof t=="string"?t:typeof((s=(e=t==null?void 0:t.issues)==null?void 0:e[0])==null?void 0:s.message)=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const s={};return e&&t&&(t.forEach((n,r)=>{s[n]=r}),e.sort((n,r)=>{const i=s[n.id],o=s[r.id];return i!==void 0&&o!==void 0?i-o:i!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const s of t)e+=s.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[s,n]=e.split(".");return{dollars:s,pennies:n}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const s=new Set;return t.filter(n=>{const r=n[e];return s.has(r)?!1:(s.add(r),!0)})},generateSdkVersion(t,e,s){const r=t.length===0?be.ADAPTER_TYPES.UNIVERSAL:t.map(i=>i.adapterType).join(",");return`${e}-${r}-${s}`},createAccount(t,e,s,n,r){return{namespace:t,address:e,type:s,publicKey:n,path:r}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),s=e[0];return e.filter(Boolean).length===3&&s in N.CHAIN_NAME_MAP},getAccount(t){return t?typeof t=="string"?{address:t,chainId:void 0}:{address:t.address,chainId:t.chainId}:{address:void 0,chainId:void 0}},isMac(){const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window==null?void 0:window.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const r="provider_authorization_url=",i=t.substring(t.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(i),s,e);return t.replace(i,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const n=t.indexOf(e);if(n===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const r=t.indexOf("&",n),i=e.length,o=r!==-1?r:t.length,a=t.substring(0,n+i),c=t.substring(n+i,o),l=t.substring(r),d=c+s;return a+d+l}},Xs={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"},Wt={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"}},ol={address:/^0x(?:[A-Fa-f0-9]{40})$/u,transactionHash:/^0x(?:[A-Fa-f0-9]{64})$/u,signedMessage:/^0x(?:[a-fA-F0-9]{62,})$/u},Da={set(t,e){zo.isClient&&localStorage.setItem(`${Xs.STORAGE_KEY}${t}`,e)},get(t){return zo.isClient?localStorage.getItem(`${Xs.STORAGE_KEY}${t}`):null},delete(t,e){zo.isClient&&(e?localStorage.removeItem(t):localStorage.removeItem(`${Xs.STORAGE_KEY}${t}`))}},Pi=30*1e3,zo={checkIfAllowedToTriggerEmail(){const t=Da.get(Xs.LAST_EMAIL_LOGIN_TIME);if(t){const e=Date.now()-Number(t);if(e<Pi){const s=Math.ceil((Pi-e)/1e3);throw new Error(`Please try again after ${s} seconds`)}}},getTimeToNextEmailLogin(){const t=Da.get(Xs.LAST_EMAIL_LOGIN_TIME);if(t){const e=Date.now()-Number(t);if(e<Pi)return Math.ceil((Pi-e)/1e3)}return 0},checkIfRequestExists(t){return Wt.NOT_SAFE_RPC_METHODS.includes(t.method)||Wt.SAFE_RPC_METHODS.includes(t.method)},getResponseType(t){return typeof t=="string"&&((t==null?void 0:t.match(ol.transactionHash))||(t==null?void 0:t.match(ol.signedMessage)))?Xs.RPC_RESPONSE_TYPE_TX:Xs.RPC_RESPONSE_TYPE_OBJECT},checkIfRequestIsSafe(t){return Wt.SAFE_RPC_METHODS.includes(t.method)},isClient:typeof window<"u"};function Uu(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function al(t){return Uu(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Du="2.40.3";let Kn={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${Du}`};function QI(t){Kn=t}class _e extends Error{constructor(e,s={}){var a;const n=(()=>{var c;return s.cause instanceof _e?s.cause.details:(c=s.cause)!=null&&c.message?s.cause.message:s.details})(),r=(()=>s.cause instanceof _e&&s.cause.docsPath||s.docsPath)(),i=(a=Kn.getDocsUrl)==null?void 0:a.call(Kn,{...s,docsPath:r}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...Kn.version?[`Version: ${Kn.version}`]:[]].join(`
|
|
4
|
+
`);super(o,s.cause?{cause:s.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=r,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=Du}walk(e){return Mu(this,e)}}function Mu(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Mu(t.cause,e):e?null:t}class eN extends _e{constructor({offset:e,position:s,size:n}){super(`Slice ${s==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}class Lu extends _e{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}}class tN extends _e{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${s} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function fr(t,{dir:e,size:s=32}={}){return typeof t=="string"?$f(t,{dir:e,size:s}):Uf(t,{dir:e,size:s})}function $f(t,{dir:e,size:s=32}={}){if(s===null)return t;const n=t.replace("0x","");if(n.length>s*2)throw new Lu({size:Math.ceil(n.length/2),targetSize:s,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function Uf(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new Lu({size:t.length,targetSize:s,type:"bytes"});const n=new Uint8Array(s);for(let r=0;r<s;r++){const i=e==="right";n[i?r:s-r-1]=t[i?r:t.length-r-1]}return n}class Df extends _e{constructor({max:e,min:s,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${r*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${s} to ${e})`:`(above ${s})`}`,{name:"IntegerOutOfRangeError"})}}class sN extends _e{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class Mf extends _e{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}class nN extends _e{constructor(e){super(`Hex value "${e}" is an odd length (${e.length}). It must be an even length.`,{name:"InvalidHexValueError"})}}class Lf extends _e{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Qi(t,{dir:e="left"}={}){let s=typeof t=="string"?t.replace("0x",""):t,n=0;for(let r=0;r<s.length-1&&s[e==="left"?r:s.length-r-1].toString()==="0";r++)n++;return s=e==="left"?s.slice(n):s.slice(0,s.length-n),typeof t=="string"?(s.length===1&&e==="right"&&(s=`${s}0`),`0x${s.length%2===1?`0${s}`:s}`):s}function rn(t,{size:e}){if(al(t)>e)throw new Lf({givenSize:al(t),maxSize:e})}function rN(t,e){const s=typeof e=="string"?{to:e}:e,n=s.to;return n==="number"?Bf(t,s):n==="bigint"?Fu(t,s):n==="string"?jf(t,s):n==="boolean"?Ff(t,s):ko(t,s)}function Fu(t,e={}){const{signed:s}=e;e.size&&rn(t,{size:e.size});const n=BigInt(t);if(!s)return n;const r=(t.length-2)/2,i=(1n<<BigInt(r)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function Ff(t,e={}){let s=t;if(e.size&&(rn(s,{size:e.size}),s=Qi(s)),Qi(s)==="0x00")return!1;if(Qi(s)==="0x01")return!0;throw new Mf(s)}function Bf(t,e={}){return Number(Fu(t,e))}function jf(t,e={}){let s=ko(t);return e.size&&(rn(s,{size:e.size}),s=Qi(s,{dir:"right"})),new TextDecoder().decode(s)}const qf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function cl(t,e={}){return typeof t=="number"||typeof t=="bigint"?ju(t,e):typeof t=="string"?qu(t,e):typeof t=="boolean"?Wf(t,e):Bu(t,e)}function Wf(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(rn(s,{size:e.size}),fr(s,{size:e.size})):s}function Bu(t,e={}){let s="";for(let r=0;r<t.length;r++)s+=qf[t[r]];const n=`0x${s}`;return typeof e.size=="number"?(rn(n,{size:e.size}),fr(n,{dir:"right",size:e.size})):n}function ju(t,e={}){const{signed:s,size:n}=e,r=BigInt(t);let i;n?s?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&s?-i-1n:0;if(i&&r>i||r<o){const c=typeof t=="bigint"?"n":"";throw new Df({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:s,size:n,value:`${t}${c}`})}const a=`0x${(s&&r<0?(1n<<BigInt(n*8))+BigInt(r):r).toString(16)}`;return n?fr(a,{size:n}):a}const Hf=new TextEncoder;function qu(t,e={}){const s=Hf.encode(t);return Bu(s,e)}const Kf=new TextEncoder;function iN(t,e={}){return typeof t=="number"||typeof t=="bigint"?zf(t,e):typeof t=="boolean"?Vf(t,e):Uu(t)?ko(t,e):Gf(t,e)}function Vf(t,e={}){const s=new Uint8Array(1);return s[0]=Number(t),typeof e.size=="number"?(rn(s,{size:e.size}),fr(s,{size:e.size})):s}const ys={zero:48,nine:57,A:65,F:70,a:97,f:102};function ll(t){if(t>=ys.zero&&t<=ys.nine)return t-ys.zero;if(t>=ys.A&&t<=ys.F)return t-(ys.A-10);if(t>=ys.a&&t<=ys.f)return t-(ys.a-10)}function ko(t,e={}){let s=t;e.size&&(rn(s,{size:e.size}),s=fr(s,{dir:"right",size:e.size}));let n=s.slice(2);n.length%2&&(n=`0${n}`);const r=n.length/2,i=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=ll(n.charCodeAt(a++)),l=ll(n.charCodeAt(a++));if(c===void 0||l===void 0)throw new _e(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+l}return i}function zf(t,e){const s=ju(t,e);return ko(s)}function Gf(t,e={}){const s=Kf.encode(t);return typeof e.size=="number"?(rn(s,{size:e.size}),fr(s,{dir:"right",size:e.size})):s}class Yf extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const s=super.get(e);return super.has(e)&&s!==void 0&&(this.delete(e),super.set(e,s)),s}set(e,s){if(super.set(e,s),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const Zs=(t,e,s)=>JSON.stringify(t,(n,r)=>{const i=typeof r=="bigint"?r.toString():r;return typeof e=="function"?e(n,i):i},s),oN={gwei:9,wei:18},Jf={ether:-9,wei:9},aN={ether:-18,gwei:-9};function Rc(t,e){let s=t.toString();const n=s.startsWith("-");n&&(s=s.slice(1)),s=s.padStart(e,"0");let[r,i]=[s.slice(0,s.length-e),s.slice(s.length-e)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${r||"0"}${i?`.${i}`:""}`}function po(t,e="wei"){return Rc(t,Jf[e])}const cN=t=>t,Ei=t=>t;class $r extends _e{constructor({body:e,cause:s,details:n,headers:r,status:i,url:o}){super("HTTP request failed.",{cause:s,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${Ei(o)}`,e&&`Request body: ${Zs(e)}`].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=e,this.headers=r,this.status=i,this.url=o}}class lN extends _e{constructor({body:e,cause:s,details:n,url:r}){super("WebSocket request failed.",{cause:s,details:n,metaMessages:[`URL: ${Ei(r)}`,e&&`Request body: ${Zs(e)}`].filter(Boolean),name:"WebSocketRequestError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=r}}class Wu extends _e{constructor({body:e,error:s,url:n}){super("RPC Request failed.",{cause:s,details:s.message,metaMessages:[`URL: ${Ei(n)}`,`Request body: ${Zs(e)}`],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,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=s.code,this.data=s.data,this.url=n}}class dN extends _e{constructor({url:e}={}){super("The socket has been closed.",{metaMessages:[e&&`URL: ${Ei(e)}`].filter(Boolean),name:"SocketClosedError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=e}}class dl extends _e{constructor({body:e,url:s}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Ei(s)}`,`Request body: ${Zs(e)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=s}}const Xf=-1;class vt extends _e{constructor(e,{code:s,docsPath:n,metaMessages:r,name:i,shortMessage:o}){super(o,{cause:e,docsPath:n,metaMessages:r||(e==null?void 0:e.metaMessages),name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||e.name,this.code=e instanceof Wu?e.code:s??Xf}}class xt extends vt{constructor(e,s){super(e,s),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=s.data}}class Vr extends vt{constructor(e){super(e,{code:Vr.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Vr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class zr extends vt{constructor(e){super(e,{code:zr.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(zr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Gr extends vt{constructor(e,{method:s}={}){super(e,{code:Gr.code,name:"MethodNotFoundRpcError",shortMessage:`The method${s?` "${s}"`:""} does not exist / is not available.`})}}Object.defineProperty(Gr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Yr extends vt{constructor(e){super(e,{code:Yr.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
|
|
5
|
+
`)})}}Object.defineProperty(Yr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class rr extends vt{constructor(e){super(e,{code:rr.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(rr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class Jr extends vt{constructor(e){super(e,{code:Jr.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
|
|
6
|
+
`)})}}Object.defineProperty(Jr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Xr extends vt{constructor(e){super(e,{code:Xr.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Xr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Zr extends vt{constructor(e){super(e,{code:Zr.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Zr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class ir extends vt{constructor(e){super(e,{code:ir.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(ir,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Cn extends vt{constructor(e,{method:s}={}){super(e,{code:Cn.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${s?` "${s}"`:""} is not supported.`})}}Object.defineProperty(Cn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class or extends vt{constructor(e){super(e,{code:or.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(or,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Qr extends vt{constructor(e){super(e,{code:Qr.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Qr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Tn extends xt{constructor(e){super(e,{code:Tn.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Tn,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class ei extends xt{constructor(e){super(e,{code:ei.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(ei,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class ti extends xt{constructor(e,{method:s}={}){super(e,{code:ti.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${s?` " ${s}"`:""}.`})}}Object.defineProperty(ti,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class si extends xt{constructor(e){super(e,{code:si.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(si,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class ni extends xt{constructor(e){super(e,{code:ni.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(ni,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class ri extends xt{constructor(e){super(e,{code:ri.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class ii extends xt{constructor(e){super(e,{code:ii.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(ii,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class oi extends xt{constructor(e){super(e,{code:oi.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(oi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class ai extends xt{constructor(e){super(e,{code:ai.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(ai,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class ci extends xt{constructor(e){super(e,{code:ci.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class li extends xt{constructor(e){super(e,{code:li.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(li,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class di extends xt{constructor(e){super(e,{code:di.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(di,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class ui extends xt{constructor(e){super(e,{code:ui.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(ui,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class Zf extends vt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}class Pc extends _e{constructor({cause:e,message:s}={}){var r;const n=(r=s==null?void 0:s.replace("execution reverted: ",""))==null?void 0:r.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(Pc,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(Pc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});class Qf extends _e{constructor({cause:e,maxFeePerGas:s}={}){super(`The fee cap (\`maxFeePerGas\`${s?` = ${po(s)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(Qf,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class eg extends _e{constructor({cause:e,maxFeePerGas:s}={}){super(`The fee cap (\`maxFeePerGas\`${s?` = ${po(s)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(eg,"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/});class tg extends _e{constructor({cause:e,nonce:s}={}){super(`Nonce provided for the transaction ${s?`(${s}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(tg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class sg extends _e{constructor({cause:e,nonce:s}={}){super([`Nonce provided for the transaction ${s?`(${s}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
|
|
7
|
+
`),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(sg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class ng extends _e{constructor({cause:e,nonce:s}={}){super(`Nonce provided for the transaction ${s?`(${s}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(ng,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class rg extends _e{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
|
|
8
|
+
`),{cause:e,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(rg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class ig extends _e{constructor({cause:e,gas:s}={}){super(`The amount of gas ${s?`(${s}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(ig,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class og extends _e{constructor({cause:e,gas:s}={}){super(`The amount of gas ${s?`(${s}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(og,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class ag extends _e{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(ag,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class cg extends _e{constructor({cause:e,maxPriorityFeePerGas:s,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${s?` = ${po(s)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${po(n)} gwei`:""}).`].join(`
|
|
9
|
+
`),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(cg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class uN extends _e{constructor({cause:e}){super(`An error occurred while executing: ${e==null?void 0:e.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}const hN=[{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:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],pN=[{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"}]}],Hu=[{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"}],fN=[...Hu,{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"}]}],gN=[...Hu,{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"}]}],mN=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],yN=[{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"}]}],wN=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],bN=[{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"}],ki=[{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"}]}],EN=[{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"}]}],CN=[{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"}],vN=[{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:[]}],AN=[{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"}];function lg(){let t=()=>{},e=()=>{};return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}}const Go=new Map;function dg({fn:t,id:e,shouldSplitBatch:s,wait:n=0,sort:r}){const i=async()=>{const d=c();o();const u=d.map(({args:h})=>h);u.length!==0&&t(u).then(h=>{r&&Array.isArray(h)&&h.sort(r);for(let p=0;p<d.length;p++){const{resolve:f}=d[p];f==null||f([h[p],h])}}).catch(h=>{for(let p=0;p<d.length;p++){const{reject:f}=d[p];f==null||f(h)}})},o=()=>Go.delete(e),a=()=>c().map(({args:d})=>d),c=()=>Go.get(e)||[],l=d=>Go.set(e,[...c(),d]);return{flush:o,async schedule(d){const{promise:u,resolve:h,reject:p}=lg();return(s==null?void 0:s([...a(),d]))&&i(),c().length>0?(l({args:d,resolve:h,reject:p}),u):(l({args:d,resolve:h,reject:p}),setTimeout(i,n),u)}}}async function Ku(t){return new Promise(e=>setTimeout(e,t))}function ug(t,{delay:e=100,retryCount:s=2,shouldRetry:n=()=>!0}={}){return new Promise((r,i)=>{const o=async({count:a=0}={})=>{const c=async({error:l})=>{const d=typeof e=="function"?e({count:a,error:l}):e;d&&await Ku(d),o({count:a+1})};try{const l=await t();r(l)}catch(l){if(a<s&&await n({count:a,error:l}))return c({error:l});i(l)}};o()})}const Ma=256;let xi=Ma,$i;function hg(t=11){if(!$i||xi+t>Ma*2){$i="",xi=0;for(let e=0;e<Ma;e++)$i+=(256+Math.random()*256|0).toString(16).substring(1)}return $i.substring(xi,xi+++t)}const Ui=new Yf(8192);function pg(t,{enabled:e=!0,id:s}){if(!e||!s)return t();if(Ui.get(s))return Ui.get(s);const n=t().finally(()=>Ui.delete(s));return Ui.set(s,n),n}function fg(t,e={}){return async(s,n={})=>{var u;const{dedupe:r=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...n},{method:l}=s;if((u=i==null?void 0:i.exclude)!=null&&u.includes(l))throw new Cn(new Error("method not supported"),{method:l});if(i!=null&&i.include&&!i.include.includes(l))throw new Cn(new Error("method not supported"),{method:l});const d=r?qu(`${c}.${Zs(s)}`):void 0;return pg(()=>ug(async()=>{try{return await t(s)}catch(h){const p=h;switch(p.code){case Vr.code:throw new Vr(p);case zr.code:throw new zr(p);case Gr.code:throw new Gr(p,{method:s.method});case Yr.code:throw new Yr(p);case rr.code:throw new rr(p);case Jr.code:throw new Jr(p);case Xr.code:throw new Xr(p);case Zr.code:throw new Zr(p);case ir.code:throw new ir(p);case Cn.code:throw new Cn(p,{method:s.method});case or.code:throw new or(p);case Qr.code:throw new Qr(p);case Tn.code:throw new Tn(p);case ei.code:throw new ei(p);case ti.code:throw new ti(p);case si.code:throw new si(p);case ni.code:throw new ni(p);case ri.code:throw new ri(p);case ii.code:throw new ii(p);case oi.code:throw new oi(p);case ai.code:throw new ai(p);case ci.code:throw new ci(p);case li.code:throw new li(p);case di.code:throw new di(p);case ui.code:throw new ui(p);case 5e3:throw new Tn(p);default:throw h instanceof _e?h:new Zf(p)}}},{delay:({count:h,error:p})=>{var f;if(p&&p instanceof $r){const m=(f=p==null?void 0:p.headers)==null?void 0:f.get("Retry-After");if(m!=null&&m.match(/\d/))return Number.parseInt(m,10)*1e3}return~~(1<<h)*o},retryCount:a,shouldRetry:({error:h})=>gg(h)}),{enabled:r,id:d})}}function gg(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===or.code||t.code===rr.code:t instanceof $r&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function mg(t,{errorInstance:e=new Error("timed out"),timeout:s,signal:n}){return new Promise((r,i)=>{(async()=>{let o;try{const a=new AbortController;s>0&&(o=setTimeout(()=>{n?a.abort():i(e)},s)),r(await t({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&i(e),i(a)}finally{clearTimeout(o)}})()})}function yg(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const ul=yg();function wg(t,e={}){return{async request(s){var h;const{body:n,fetchFn:r=e.fetchFn??fetch,onRequest:i=e.onRequest,onResponse:o=e.onResponse,timeout:a=e.timeout??1e4}=s,c={...e.fetchOptions??{},...s.fetchOptions??{}},{headers:l,method:d,signal:u}=c;try{const p=await mg(async({signal:m})=>{const y={...c,body:Array.isArray(n)?Zs(n.map(k=>({jsonrpc:"2.0",id:k.id??ul.take(),...k}))):Zs({jsonrpc:"2.0",id:n.id??ul.take(),...n}),headers:{"Content-Type":"application/json",...l},method:d||"POST",signal:u||(a>0?m:null)},w=new Request(t,y),b=await(i==null?void 0:i(w,y))??{...y,url:t};return await r(b.url??t,b)},{errorInstance:new dl({body:n,url:t}),timeout:a,signal:!0});o&&await o(p);let f;if((h=p.headers.get("Content-Type"))!=null&&h.startsWith("application/json"))f=await p.json();else{f=await p.text();try{f=JSON.parse(f||"{}")}catch(m){if(p.ok)throw m;f={error:f}}}if(!p.ok)throw new $r({body:n,details:Zs(f.error)||p.statusText,headers:p.headers,status:p.status,url:t});return f}catch(p){throw p instanceof $r||p instanceof dl?p:new $r({body:n,cause:p,url:t})}}}}function Vu({key:t,methods:e,name:s,request:n,retryCount:r=3,retryDelay:i=150,timeout:o,type:a},c){const l=hg();return{config:{key:t,methods:e,name:s,request:n,retryCount:r,retryDelay:i,timeout:o,type:a},request:fg(n,{methods:e,retryCount:r,retryDelay:i,uid:l}),value:c}}function hl(t,e={}){const{key:s="fallback",name:n="Fallback",rank:r=!1,shouldThrow:i=bg,retryCount:o,retryDelay:a}=e;return({chain:c,pollingInterval:l=4e3,timeout:d,...u})=>{let h=t,p=()=>{};const f=Vu({key:s,name:n,async request({method:m,params:y}){let w;const b=async(A=0)=>{const k=h[A]({...u,chain:c,retryCount:0,timeout:d});try{const $=await k.request({method:m,params:y});return p({method:m,params:y,response:$,transport:k,status:"success"}),$}catch($){if(p({error:$,method:m,params:y,transport:k,status:"error"}),i($)||A===h.length-1||(w??(w=h.slice(A+1).some(M=>{const{include:H,exclude:G}=M({chain:c}).config.methods||{};return H?H.includes(m):G?!G.includes(m):!0})),!w))throw $;return b(A+1)}};return b()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:m=>p=m,transports:h.map(m=>m({chain:c,retryCount:0}))});if(r){const m=typeof r=="object"?r:{};Eg({chain:c,interval:m.interval??l,onTransports:y=>h=y,ping:m.ping,sampleCount:m.sampleCount,timeout:m.timeout,transports:h,weights:m.weights})}return f}}function bg(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===ir.code||t.code===Tn.code||Pc.nodeMessage.test(t.message)||t.code===5e3))}function Eg({chain:t,interval:e=4e3,onTransports:s,ping:n,sampleCount:r=10,timeout:i=1e3,transports:o,weights:a={}}){const{stability:c=.7,latency:l=.3}=a,d=[],u=async()=>{const h=await Promise.all(o.map(async m=>{const y=m({chain:t,retryCount:0,timeout:i}),w=Date.now();let b,A;try{await(n?n({transport:y}):y.request({method:"net_listening"})),A=1}catch{A=0}finally{b=Date.now()}return{latency:b-w,success:A}}));d.push(h),d.length>r&&d.shift();const p=Math.max(...d.map(m=>Math.max(...m.map(({latency:y})=>y)))),f=o.map((m,y)=>{const w=d.map(M=>M[y].latency),A=1-w.reduce((M,H)=>M+H,0)/w.length/p,k=d.map(M=>M[y].success),$=k.reduce((M,H)=>M+H,0)/k.length;return $===0?[0,y]:[l*A+c*$,y]}).sort((m,y)=>y[0]-m[0]);s(f.map(([,m])=>o[m])),await Ku(e),u()};u()}class Cg extends _e{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 Di(t,e={}){const{batch:s,fetchFn:n,fetchOptions:r,key:i="http",methods:o,name:a="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:l,retryDelay:d,raw:u}=e;return({chain:h,retryCount:p,timeout:f})=>{const{batchSize:m=1e3,wait:y=0}=typeof s=="object"?s:{},w=e.retryCount??p,b=f??e.timeout??1e4,A=t||(h==null?void 0:h.rpcUrls.default.http[0]);if(!A)throw new Cg;const k=wg(A,{fetchFn:n,fetchOptions:r,onRequest:c,onResponse:l,timeout:b});return Vu({key:i,methods:o,name:a,async request({method:$,params:M}){const H={method:$,params:M},{schedule:G}=dg({id:A,wait:y,shouldSplitBatch(T){return T.length>m},fn:T=>k.request({body:T}),sort:(T,E)=>T.id-E.id}),P=async T=>s?G(T):[await k.request({body:T})],[{error:Q,result:se}]=await P(H);if(u)return{error:Q,result:se};if(Q)throw new Wu({body:H,error:Q,url:A});return se},retryCount:w,retryDelay:d,timeout:b,type:"http"},{fetchOptions:r,url:A})}}async function yr(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class Ci{constructor({baseUrl:e,clientId:s}){this.baseUrl=e,this.clientId=s}async get({headers:e,signal:s,cache:n,...r}){const i=this.createUrl(r);return(await yr(i,{method:"GET",headers:e,signal:s,cache:n})).json()}async getBlob({headers:e,signal:s,...n}){const r=this.createUrl(n);return(await yr(r,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await yr(i,{method:"POST",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}async put({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await yr(i,{method:"PUT",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}async delete({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await yr(i,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}createUrl({path:e,params:s}){const n=new URL(e,this.baseUrl);return s&&Object.entries(s).forEach(([r,i])=>{i&&n.searchParams.append(r,i)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}sendBeacon({body:e,...s}){const n=this.createUrl(s);return navigator.sendBeacon(n.toString(),e?JSON.stringify(e):void 0)}}const La={getFeatureValue(t,e){const s=e==null?void 0:e[t];return s===void 0?be.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;let e=t;return z.isTelegram()&&(z.isIos()&&(e=e.filter(s=>s!=="google")),z.isMac()&&(e=e.filter(s=>s!=="x")),z.isAndroid()&&(e=e.filter(s=>!["facebook","x"].includes(s)))),z.isMobile()&&(e=e.filter(s=>s!=="facebook")),e},isSocialsEnabled(){var t,e,s,n;return Array.isArray((t=I.state.features)==null?void 0:t.socials)&&((e=I.state.features)==null?void 0:e.socials.length)>0||Array.isArray((s=I.state.remoteFeatures)==null?void 0:s.socials)&&((n=I.state.remoteFeatures)==null?void 0:n.socials.length)>0},isEmailEnabled(){var t,e;return!!((t=I.state.features)!=null&&t.email||(e=I.state.remoteFeatures)!=null&&e.email)}},X=ke({features:be.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:be.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1,coinbasePreference:"all"}),I={state:X,subscribeKey(t,e){return tt(X,t,e)},setOptions(t){Object.assign(X,t)},setRemoteFeatures(t){var s,n;if(!t)return;const e={...X.remoteFeatures,...t};X.remoteFeatures=e,(s=X.remoteFeatures)!=null&&s.socials&&(X.remoteFeatures.socials=La.filterSocialsByPlatform(X.remoteFeatures.socials)),(n=X.features)!=null&&n.pay&&(X.remoteFeatures.email=!1,X.remoteFeatures.socials=!1)},setFeatures(t){var s;if(!t)return;X.features||(X.features=be.DEFAULT_FEATURES);const e={...X.features,...t};X.features=e,(s=X.features)!=null&&s.pay&&X.remoteFeatures&&(X.remoteFeatures.email=!1,X.remoteFeatures.socials=!1)},setProjectId(t){X.projectId=t},setCustomRpcUrls(t){X.customRpcUrls=t},setAllWallets(t){X.allWallets=t},setIncludeWalletIds(t){X.includeWalletIds=t},setExcludeWalletIds(t){X.excludeWalletIds=t},setFeaturedWalletIds(t){X.featuredWalletIds=t},setTokens(t){X.tokens=t},setTermsConditionsUrl(t){X.termsConditionsUrl=t},setPrivacyPolicyUrl(t){X.privacyPolicyUrl=t},setCustomWallets(t){X.customWallets=t},setIsSiweEnabled(t){X.isSiweEnabled=t},setIsUniversalProvider(t){X.isUniversalProvider=t},setSdkVersion(t){X.sdkVersion=t},setMetadata(t){X.metadata=t},setDisableAppend(t){X.disableAppend=t},setEIP6963Enabled(t){X.enableEIP6963=t},setDebug(t){X.debug=t},setEnableWalletGuide(t){X.enableWalletGuide=t},setEnableAuthLogger(t){X.enableAuthLogger=t},setEnableWallets(t){X.enableWallets=t},setPreferUniversalLinks(t){X.experimental_preferUniversalLinks=t},setSIWX(t){if(t)for(const[e,s]of Object.entries(be.SIWX_DEFAULTS))t[e]??(t[e]=s);X.siwx=t},setConnectMethodsOrder(t){X.features={...X.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){X.features={...X.features,walletFeaturesOrder:t}},setSocialsOrder(t){X.remoteFeatures={...X.remoteFeatures,socials:t}},setCollapseWallets(t){X.features={...X.features,collapseWallets:t}},setEnableEmbedded(t){X.enableEmbedded=t},setAllowUnsupportedChain(t){X.allowUnsupportedChain=t},setManualWCControl(t){X.manualWCControl=t},setEnableNetworkSwitch(t){X.enableNetworkSwitch=t},setEnableMobileFullScreen(t){X.enableMobileFullScreen=z.isMobile()&&t},setEnableReconnect(t){X.enableReconnect=t},setCoinbasePreference(t){X.coinbasePreference=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(X.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){X.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return X.universalProviderConfigOverride},getSnapshot(){return Hr(X)}},gn=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),We=ke({...gn}),vg={state:We,subscribeKey(t,e){return tt(We,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=z.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){We.message=gn.message,We.variant=gn.variant,We.svg=gn.svg,We.open=gn.open,We.autoClose=gn.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:n=gn.autoClose}){We.open?(We.open=!1,setTimeout(()=>{We.message=t,We.variant=s,We.svg=e,We.open=!0,We.autoClose=n},150)):(We.message=t,We.variant=s,We.svg=e,We.open=!0,We.autoClose=n)}},us=vg,Ag={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"}]}]},zu=z.getBlockchainApiUrl(),ht=ke({clientId:null,api:new Ci({baseUrl:zu,clientId:null}),supportedChains:{http:[],ws:[]}}),te={state:ht,async get(t){const{st:e,sv:s}=te.getSdkProperties(),n=I.state.projectId,r={...t.params||{},st:e,sv:s,projectId:n};return ht.api.get({...t,params:r})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=I.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{ht.supportedChains.http.length||await te.getSupportedNetworks()}catch{return!1}return ht.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await te.get({path:"v1/supported-chains"});return ht.supportedChains=t,t}catch{return ht.supportedChains}},async fetchIdentity({address:t}){const e=R.getIdentityFromCacheForAddress(t);if(e)return e;const s=await te.get({path:`/v1/identity/${t}`,params:{sender:g.state.activeCaipAddress?z.getPlainAddress(g.state.activeCaipAddress):void 0}});return R.updateIdentityCache({address:t,identity:s,timestamp:Date.now()}),s},async fetchTransactions({account:t,cursor:e,signal:s,cache:n,chainId:r}){var c;if(!await te.isNetworkSupported((c=g.state.activeCaipNetwork)==null?void 0:c.caipNetworkId))return{data:[],next:void 0};const o=R.getTransactionsCacheForAddress({address:t,chainId:r});if(o)return o;const a=await te.get({path:`/v1/account/${t}/history`,params:{cursor:e,chainId:r},signal:s,cache:n});return R.updateTransactionsCache({address:t,chainId:r,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:n,gasPrice:r}){var o;return await te.isNetworkSupported((o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?te.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:s,to:n,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){var s;return await te.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?te.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){var r;if(!await te.isNetworkSupported((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))return{fungibles:[]};const s=R.getTokenPriceCacheForAddresses(t);if(s)return s;const n=await ht.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:I.state.projectId},headers:{"Content-Type":"application/json"}});return R.updateTokenPriceCache({addresses:t,timestamp:Date.now(),tokenPrice:n}),n},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){var n;return await te.isNetworkSupported((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?te.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){var r;const{st:e,sv:s}=te.getSdkProperties();if(!await te.isNetworkSupported((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))throw new Error("Network not supported for Gas Price");return te.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:s}})},async generateSwapCalldata({amount:t,from:e,to:s,userAddress:n,disableEstimate:r}){var o;if(!await te.isNetworkSupported((o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return ht.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:be.CONVERT_SLIPPAGE_TOLERANCE},projectId:I.state.projectId,from:e,to:s,userAddress:n,disableEstimate:r}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){var o;const{st:n,sv:r}=te.getSdkProperties();if(!await te.isNetworkSupported((o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return te.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:t,to:e,st:n,sv:r}})},async getBalance(t,e,s){var l;const{st:n,sv:r}=te.getSdkProperties();if(!await te.isNetworkSupported((l=g.state.activeCaipNetwork)==null?void 0:l.caipNetworkId))return us.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=R.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await te.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:n,sv:r}});return R.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){var s;return await te.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?te.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){var n,r;if(!await te.isNetworkSupported((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId))return[];const s=(r=g.getAccountData())==null?void 0:r.address;return te.get({path:`/v1/profile/reverse/${t}`,params:{sender:s,apiVersion:"2"}})},async getEnsNameSuggestions(t){var s;return await te.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?te.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:n}){var i;return await te.isNetworkSupported((i=g.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?ht.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:s,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:s,purchaseAmount:n,paymentAmount:r}){var a;return await te.isNetworkSupported((a=g.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await ht.api.post({path:"/v1/generators/onrampurl",params:{projectId:I.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:r}})).url:""},async getOnrampOptions(){var e;if(!await te.isNetworkSupported((e=g.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await te.get({path:"/v1/onramp/options"})}catch{return Ag}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}){var r;try{return await te.isNetworkSupported((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?await ht.api.post({path:"/v1/onramp/quote",params:{projectId:I.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}}):null}catch{return{networkFee:{amount:s,currency:e.id},paymentSubtotal:{amount:s,currency:e.id},paymentTotal:{amount:s,currency:e.id},purchaseAmount:{amount:s,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){var s;return await te.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?te.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){var r;return await te.isNetworkSupported((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?ht.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:I.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){ht.clientId=t,ht.api=new Ci({baseUrl:zu,clientId:t})}},Ft={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"}},_g={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,n=encodeURIComponent(s);if(t===Ft.PHANTOM.id&&!("phantom"in window)){const r=s.startsWith("https")?"https":"http",i=s.split("/")[2],o=encodeURIComponent(`${r}://${i}`);window.location.href=`${Ft.PHANTOM.url}/ul/browse/${n}?ref=${o}`}if(t===Ft.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Ft.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),e===N.CHAIN.SOLANA&&t===Ft.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Ft.COINBASE.url}/dapp?cb_url=${n}`),e===N.CHAIN.BITCOIN&&t===Ft.BINANCE.id&&!("binancew3w"in window)){const r=g.state.activeCaipNetwork,i=window.btoa("/pages/browser/index"),o=window.btoa(`url=${n}&defaultChainId=${(r==null?void 0:r.id)??1}`),a=new URL(Ft.BINANCE.deeplink);a.searchParams.set("appId",Ft.BINANCE.appId),a.searchParams.set("startPagePath",i),a.searchParams.set("startPageQuery",o);const c=new URL(Ft.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}},Ig=Object.freeze({enabled:!0,events:[]}),Ng=new Ci({baseUrl:z.getAnalyticsUrl(),clientId:null}),Sg=5,Tg=60*1e3,Ms=ke({...Ig}),Og={state:Ms,subscribeKey(t,e){return tt(Ms,t,e)},async sendError(t,e){if(!Ms.enabled)return;const s=Date.now();if(Ms.events.filter(i=>{const o=new Date(i.properties.timestamp||"").getTime();return s-o<Tg}).length>=Sg)return;const r={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Ms.events.push(r);try{if(typeof window>"u")return;const{projectId:i,sdkType:o,sdkVersion:a}=I.state;await Ng.post({path:"/e",params:{projectId:i,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:z.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){Ms.enabled=!0},disable(){Ms.enabled=!1},clearEvents(){Ms.events=[]}};class Rn extends Error{constructor(e,s,n){super(e),this.originalName="AppKitError",this.name="AppKitError",this.category=s,this.originalError=n,n&&n instanceof Error&&(this.originalName=n.name),Object.setPrototypeOf(this,Rn.prototype);let r=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){const i=n.stack,o=i.indexOf(`
|
|
10
|
+
`);if(o>-1){const a=i.substring(o+1);this.stack=`${this.name}: ${this.message}
|
|
11
|
+
${a}`,r=!0}}r||(Error.captureStackTrace?Error.captureStackTrace(this,Rn):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function pl(t,e){let s="";try{t instanceof Error?s=t.message:typeof t=="string"?s=t:typeof t=="object"&&t!==null?Object.keys(t).length===0?s="Unknown error":s=(t==null?void 0:t.message)||JSON.stringify(t):s=String(t)}catch(r){s="Unknown error",console.error("Error parsing error message",r)}const n=t instanceof Rn?t:new Rn(s,e,t);throw Og.sendError(n,n.category),n}function zt(t,e="INTERNAL_SDK_ERROR"){const s={};return Object.keys(t).forEach(n=>{const r=t[n];if(typeof r=="function"){let i=r;r.constructor.name==="AsyncFunction"?i=async(...o)=>{try{return await r(...o)}catch(a){return pl(a,e)}}:i=(...o)=>{try{return r(...o)}catch(a){return pl(a,e)}},s[n]=i}else s[n]=r}),s}const At=ke({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Rg={state:At,subscribeNetworkImages(t){return et(At.networkImages,()=>t(At.networkImages))},subscribeKey(t,e){return tt(At,t,e)},subscribe(t){return et(At,()=>t(At))},setWalletImage(t,e){At.walletImages[t]=e},setNetworkImage(t,e){At.networkImages[t]=e},setChainImage(t,e){At.chainImages[t]=e},setConnectorImage(t,e){At.connectorImages={...At.connectorImages,[t]:e}},setTokenImage(t,e){At.tokenImages[t]=e},setCurrencyImage(t,e){At.currencyImages[t]=e}},qt=zt(Rg),Pg={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:""},Yo=ke({networkImagePromises:{}}),Gu={async fetchWalletImage(t){if(t)return await J._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(Yo.networkImagePromises[t]||(Yo.networkImagePromises[t]=J._fetchNetworkImage(t)),await Yo.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return qt.state.walletImages[t]},getWalletImage(t){if(t!=null&&t.image_url)return t==null?void 0:t.image_url;if(t!=null&&t.image_id)return qt.state.walletImages[t.image_id]},getNetworkImage(t){var e,s,n;if((e=t==null?void 0:t.assets)!=null&&e.imageUrl)return(s=t==null?void 0:t.assets)==null?void 0:s.imageUrl;if((n=t==null?void 0:t.assets)!=null&&n.imageId)return qt.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return qt.state.networkImages[t]},getConnectorImage(t){var e;if(t!=null&&t.imageUrl)return t.imageUrl;if((e=t==null?void 0:t.info)!=null&&e.icon)return t.info.icon;if(t!=null&&t.imageId)return qt.state.connectorImages[t.imageId]},getChainImage(t){return qt.state.networkImages[Pg[t]]},getTokenImage(t){if(t)return qt.state.tokenImages[t]}},kg=z.getAnalyticsUrl(),xg=new Ci({baseUrl:kg,clientId:null}),$g=["MODAL_CREATED"],Ug=45,fl=1e3*10,De=ke({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),ce={state:De,subscribe(t){return et(De,()=>t(De))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=I.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},shouldFlushEvents(){const t=JSON.stringify(De.pendingEvents).length/1024>Ug,e=De.lastFlush+fl<Date.now();return t||e},_setPendingEvent(t){var e,s;try{let n=(e=g.getAccountData())==null?void 0:e.address;if("address"in t.data&&t.data.address&&(n=t.data.address),$g.includes(t.data.event)||typeof window>"u")return;const r=(s=g.getActiveCaipNetwork())==null?void 0:s.caipNetworkId;this.state.pendingEvents.push({eventId:z.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:n,properties:{..."properties"in t.data?t.data.properties:{},caipNetworkId:r}}}),De.reportedErrors.FORBIDDEN=!1,ce.shouldFlushEvents()&&ce._submitPendingEvents()}catch(n){console.warn("_setPendingEvent",n)}},sendEvent(t){var s;De.timestamp=Date.now(),De.data=t;const e=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];((s=I.state.features)!=null&&s.analytics||e.includes(t.event))&&ce._setPendingEvent(De),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(t){De.walletImpressions.push(t)},_transformPendingEventsForBatch(t){try{return t.filter(e=>e.props.event!=="WALLET_IMPRESSION_V2")}catch{return t}},_submitPendingEvents(){if(De.lastFlush=Date.now(),!(De.pendingEvents.length===0&&De.walletImpressions.length===0))try{const t=ce._transformPendingEventsForBatch(De.pendingEvents);De.walletImpressions.length&&t.push({eventId:z.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION_V2",items:[...De.walletImpressions]}}),xg.sendBeacon({path:"/batch",params:ce.getSdkProperties(),body:t}),De.reportedErrors.FORBIDDEN=!1,De.pendingEvents=[],De.walletImpressions=[]}catch{De.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){var t,e,s;De.subscribedToVisibilityChange||typeof document>"u"||(De.subscribedToVisibilityChange=!0,(t=document==null?void 0:document.addEventListener)==null||t.call(document,"visibilitychange",()=>{document.visibilityState==="hidden"&&ce._submitPendingEvents()}),(e=document==null?void 0:document.addEventListener)==null||e.call(document,"freeze",()=>{ce._submitPendingEvents()}),(s=window==null?void 0:window.addEventListener)==null||s.call(window,"pagehide",()=>{ce._submitPendingEvents()}),setInterval(()=>{ce._submitPendingEvents()},fl))}},Dg=z.getApiUrl(),lt=new Ci({baseUrl:Dg,clientId:null}),Mg=40,gl=4,Lg=20,re=ke({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}}}),J={state:re,subscribeKey(t,e){return tt(re,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=I.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return I.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${lt.baseUrl}/getWalletImage/${t}`,s=await lt.getBlob({path:e,params:J._getSdkProperties()});qt.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${lt.baseUrl}/public/getAssetImage/${t}`,s=await lt.getBlob({path:e,params:J._getSdkProperties()});qt.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${lt.baseUrl}/public/getAssetImage/${t}`,s=await lt.getBlob({path:e,params:J._getSdkProperties()});qt.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${lt.baseUrl}/public/getCurrencyImage/${t}`,s=await lt.getBlob({path:e,params:J._getSdkProperties()});qt.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${lt.baseUrl}/public/getTokenImage/${t}`,s=await lt.getBlob({path:e,params:J._getSdkProperties()});qt.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){const e=t.length,s=z.isMobile()?t==null?void 0:t.filter(r=>r.mobile_link||r.webapp_link?!0:Object.values(Ft).map(o=>o.id).includes(r.id)):t,n=e-s.length;return{filteredWallets:s,mobileFilteredOutWalletsLength:n}},async fetchProjectConfig(){return(await lt.get({path:"/appkit/v1/config",params:J._getSdkProperties()})).features},async fetchUsage(){try{const t=await lt.get({path:"/appkit/v1/project-limits",params:J._getSdkProperties()}),{tier:e,isAboveMauLimit:s,isAboveRpcLimit:n}=t.planLimits,r=e==="starter",i=s||n;J.state.plan={tier:e,hasExceededUsageLimit:r&&i,limits:{isAboveRpcLimit:n,isAboveMauLimit:s}}}catch(t){console.warn("Failed to fetch usage",t)}},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await lt.get({path:"/projects/v1/origins",params:J._getSdkProperties()});return t}catch(t){if(t instanceof Error&&t.cause instanceof Response){const e=t.cause.status;if(e===N.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:t});if(e>=N.HTTP_STATUS_CODES.SERVER_ERROR&&e<600)throw new Error("SERVER_ERROR",{cause:t});return[]}return[]}},async fetchNetworkImages(){const t=g.getAllRequestedCaipNetworks(),e=t==null?void 0:t.map(({assets:s})=>s==null?void 0:s.imageId).filter(Boolean).filter(s=>!Gu.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>J._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=D.state,e=t.map(({imageId:s})=>s).filter(Boolean);await Promise.allSettled(e.map(s=>J._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>J._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>J._fetchTokenImage(e)))},async fetchWallets(t){var o;const e=t.exclude??[];J._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Ft).map(a=>a.id));const n=await lt.get({path:"/getWallets",params:{...J._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:(o=t.include)==null?void 0:o.join(","),exclude:e.join(",")}}),{filteredWallets:r,mobileFilteredOutWalletsLength:i}=J._filterWalletsByPlatform(n==null?void 0:n.data);return{data:r||[],count:n==null?void 0:n.count,mobileFilteredOutWalletsLength:i}},async prefetchWalletRanks(){const t=D.state.connectors;if(!(t!=null&&t.length))return;const e={page:1,entries:20,badge:"certified"};if(e.names=t.map(r=>r.name).join(","),g.state.activeChain===N.CHAIN.EVM){const r=[...t.flatMap(i=>{var o;return((o=i.connectors)==null?void 0:o.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}))||[]}),...t.map(i=>{var o;return(o=i.info)==null?void 0:o.rdns})].filter(i=>typeof i=="string"&&i.length>0);r.length&&(e.rdns=r.join(","))}const{data:s}=await J.fetchWallets(e);re.explorerWallets=s;const n=g.getRequestedCaipNetworkIds().join(",");re.explorerFilteredWallets=s.filter(r=>{var i;return(i=r.chains)==null?void 0:i.some(o=>n.includes(o))})},async fetchFeaturedWallets(){const{featuredWalletIds:t}=I.state;if(t!=null&&t.length){const e={...J._getSdkProperties(),page:1,entries:(t==null?void 0:t.length)??gl,include:t},{data:s}=await J.fetchWallets(e),n=[...s].sort((i,o)=>t.indexOf(i.id)-t.indexOf(o.id)),r=n.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(r.map(i=>J._fetchWalletImage(i))),re.featured=n,re.allFeatured=n}},async fetchRecommendedWallets(){try{re.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=I.state,n=[...e??[],...s??[]].filter(Boolean),r=g.getRequestedCaipNetworkIds().join(","),i={page:1,entries:gl,include:t,exclude:n,chains:r},{data:o,count:a}=await J.fetchWallets(i),c=R.getRecentWallets(),l=o.map(u=>u.image_id).filter(Boolean),d=c.map(u=>u.image_id).filter(Boolean);await Promise.allSettled([...l,...d].map(u=>J._fetchWalletImage(u))),re.recommended=o,re.allRecommended=o,re.count=a??0}catch{}finally{re.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:n}=I.state,r=g.getRequestedCaipNetworkIds().join(","),i=[...re.recommended.map(({id:u})=>u),...s??[],...n??[]].filter(Boolean),o={page:t,entries:Mg,include:e,exclude:i,chains:r},{data:a,count:c,mobileFilteredOutWalletsLength:l}=await J.fetchWallets(o);re.mobileFilteredOutWalletsLength=l+(re.mobileFilteredOutWalletsLength??0);const d=a.slice(0,Lg).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(d.map(u=>J._fetchWalletImage(u))),re.wallets=z.uniqueBy([...re.wallets,...J._filterOutExtensions(a)],"id").filter(u=>{var h;return(h=u.chains)==null?void 0:h.some(p=>r.includes(p))}),re.count=c>re.count?c:re.count,re.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await J.fetchWallets(e);s&&s.forEach(n=>{re.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:n}=I.state,r=g.getRequestedCaipNetworkIds().join(",");re.search=[];const i={page:1,entries:100,search:t==null?void 0:t.trim(),badge_type:e,include:s,exclude:n,chains:r},{data:o}=await J.fetchWallets(i);ce.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:t??""}});const a=o.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>J._fetchWalletImage(c)),z.wait(300)]),re.search=J._filterOutExtensions(o)},initPromise(t,e){const s=re.promises[t];return s||(re.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:n=!0,fetchWalletRanks:r=!0}={}){const i=[t&&J.initPromise("connectorImages",J.fetchConnectorImages),e&&J.initPromise("featuredWallets",J.fetchFeaturedWallets),s&&J.initPromise("recommendedWallets",J.fetchRecommendedWallets),n&&J.initPromise("networkImages",J.fetchNetworkImages),r&&J.initPromise("walletRanks",J.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){var t;(t=I.state.features)!=null&&t.analytics&&J.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await lt.get({path:"/getAnalyticsConfig",params:J._getSdkProperties()});I.setFeatures({analytics:t})}catch{I.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!(t!=null&&t.length)){re.featured=re.allFeatured,re.recommended=re.allRecommended;return}const e=g.getRequestedCaipNetworkIds().join(",");re.featured=re.allFeatured.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),re.recommended=re.allRecommended.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),re.filteredWallets=re.wallets.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))})},clearFilterByNamespaces(){re.filteredWallets=[]},setFilterByNamespace(t){if(!t){re.featured=re.allFeatured,re.recommended=re.allRecommended;return}const e=g.getRequestedCaipNetworkIds().join(",");re.featured=re.allFeatured.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),re.recommended=re.allRecommended.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),re.filteredWallets=re.wallets.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))})}},Fg=["ConnectingExternal","ConnectingMultiChain","ConnectingSocial","ConnectingFarcaster"],Ie=ke({view:"Connect",history:["Connect"],transactionStack:[]}),Bg={state:Ie,subscribeKey(t,e){return tt(Ie,t,e)},pushTransactionStack(t){Ie.transactionStack.push(t)},popTransactionStack(t){const e=Ie.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:n,onCancel:r}=e;switch(t){case"success":s==null||s();break;case"error":n==null||n(),ee.goBack();break;case"cancel":r==null||r(),ee.goBack();break}},push(t,e){let s=t,n=e;J.state.plan.hasExceededUsageLimit&&Fg.includes(t)&&(s="UsageExceeded",n=void 0),s!==Ie.view&&(Ie.view=s,Ie.history.push(s),Ie.data=n)},reset(t,e){Ie.view=t,Ie.history=[t],Ie.data=e},replace(t,e){Ie.history.at(-1)===t||(Ie.view=t,Ie.history[Ie.history.length-1]=t,Ie.data=e)},goBack(){var n,r;const t=g.state.activeCaipAddress,e=ee.state.view==="ConnectingFarcaster",s=!t&&e;if(Ie.history.length>1){Ie.history.pop();const[i]=Ie.history.slice(-1);i&&(t&&i==="Connect"?Ie.view="Account":Ie.view=i)}else he.close();(n=Ie.data)!=null&&n.wallet&&(Ie.data.wallet=void 0),(r=Ie.data)!=null&&r.redirectView&&(Ie.data.redirectView=void 0),setTimeout(()=>{var i,o,a;if(s){g.setAccountProp("farcasterUrl",void 0,g.state.activeChain);const c=D.getAuthConnector();(i=c==null?void 0:c.provider)==null||i.reload();const l=Hr(I.state);(a=(o=c==null?void 0:c.provider)==null?void 0:o.syncDappData)==null||a.call(o,{metadata:l.metadata,sdkVersion:l.sdkVersion,projectId:l.projectId,sdkType:l.sdkType})}},100)},goBackToIndex(t){if(Ie.history.length>1){Ie.history=Ie.history.slice(0,t+1);const[e]=Ie.history.slice(-1);e&&(Ie.view=e)}},goBackOrCloseModal(){ee.state.history.length>1?ee.goBack():he.close()}},ee=zt(Bg),ws=ke({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Fa={state:ws,subscribe(t){return et(ws,()=>t(ws))},setThemeMode(t){ws.themeMode=t;try{const e=D.getAuthConnector();if(e){const s=Fa.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:ho(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){ws.themeVariables={...ws.themeVariables,...t};try{const e=D.getAuthConnector();if(e){const s=Fa.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:ho(ws.themeVariables,ws.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Hr(ws)}},St=zt(Fa),Yu=Object.fromEntries(Pu.map(t=>[t,void 0])),jg=Object.fromEntries(Pu.map(t=>[t,!0])),Ce=ke({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:Yu,filterByNamespaceMap:jg}),qg={state:Ce,subscribe(t){return et(Ce,()=>{t(Ce)})},subscribeKey(t,e){return tt(Ce,t,e)},initialize(t){t.forEach(e=>{const s=R.getConnectedConnectorId(e);s&&D.setConnectorId(s,e)})},setActiveConnector(t){t&&(Ce.activeConnector=Kr(t))},setConnectors(t){t.filter(r=>!Ce.allConnectors.some(i=>i.id===r.id&&D.getConnectorName(i.name)===D.getConnectorName(r.name)&&i.chain===r.chain)).forEach(r=>{r.type!=="MULTI_CHAIN"&&Ce.allConnectors.push(Kr(r))});const s=D.getEnabledNamespaces(),n=D.getEnabledConnectors(s);Ce.connectors=D.mergeMultiChainConnectors(n)},filterByNamespaces(t){Object.keys(Ce.filterByNamespaceMap).forEach(e=>{Ce.filterByNamespaceMap[e]=!1}),t.forEach(e=>{Ce.filterByNamespaceMap[e]=!0}),D.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){Ce.filterByNamespaceMap[t]=e,D.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=D.getEnabledNamespaces(),e=D.getEnabledConnectors(t),s=D.areAllNamespacesEnabled();Ce.connectors=D.mergeMultiChainConnectors(e),s?J.clearFilterByNamespaces():J.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(Ce.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return Ce.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(Ce.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=D.generateConnectorMapByName(t),s=[];return e.forEach(n=>{const r=n[0],i=(r==null?void 0:r.id)===N.CONNECTOR_ID.AUTH;n.length>1&&r?s.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...n],type:i?"AUTH":"MULTI_CHAIN",chain:"eip155",id:(r==null?void 0:r.id)||""}):r&&s.push(r)}),s},generateConnectorMapByName(t){const e=new Map;return t.forEach(s=>{const{name:n}=s,r=D.getConnectorName(n);if(!r)return;const i=e.get(r)||[];i.find(a=>a.chain===s.chain)||i.push(s),e.set(r,i)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(s=>{e.find(n=>n.chain===s.chain)||e.push(s)}),e},addConnector(t){var e,s,n;if(t.id===N.CONNECTOR_ID.AUTH){const r=t,i=Hr(I.state),o=St.getSnapshot().themeMode,a=St.getSnapshot().themeVariables;(s=(e=r==null?void 0:r.provider)==null?void 0:e.syncDappData)==null||s.call(e,{metadata:i.metadata,sdkVersion:i.sdkVersion,projectId:i.projectId,sdkType:i.sdkType}),(n=r==null?void 0:r.provider)==null||n.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:ho(a,o)}),D.setConnectors([t])}else D.setConnectors([t])},getAuthConnector(t){var n;const e=t||g.state.activeChain,s=Ce.connectors.find(r=>r.id===N.CONNECTOR_ID.AUTH);if(s)return(n=s==null?void 0:s.connectors)!=null&&n.length?s.connectors.find(i=>i.chain===e):s},getAnnouncedConnectorRdns(){return Ce.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>{var e;return(e=t.info)==null?void 0:e.rdns})},getConnectorById(t){return Ce.allConnectors.find(e=>e.id===t)},getConnector({id:t,rdns:e,namespace:s}){const n=s||g.state.activeChain;return Ce.allConnectors.filter(i=>i.chain===n).find(i=>{var o;return i.explorerId===t||((o=i.info)==null?void 0:o.rdns)===e})},syncIfAuthConnector(t){var i,o;if(t.id!=="AUTH")return;const e=t,s=Hr(I.state),n=St.getSnapshot().themeMode,r=St.getSnapshot().themeVariables;(o=(i=e==null?void 0:e.provider)==null?void 0:i.syncDappData)==null||o.call(i,{metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:ho(r,n)})},getConnectorsByNamespace(t){const e=Ce.allConnectors.filter(s=>s.chain===t);return D.mergeMultiChainConnectors(e)},canSwitchToSmartAccount(t){return g.checkIfSmartAccountEnabled()&&Kt(t)===Wt.ACCOUNT_TYPES.EOA},selectWalletConnector(t){var n;const e=(n=ee.state.data)==null?void 0:n.redirectView,s=D.getConnector({id:t.id,rdns:t.rdns});_g.handleMobileDeeplinkRedirect((s==null?void 0:s.explorerId)||t.id,g.state.activeChain),s?ee.push("ConnectingExternal",{connector:s,wallet:t,redirectView:e}):ee.push("ConnectingWalletConnect",{wallet:t,redirectView:e})},getConnectors(t){return t?D.getConnectorsByNamespace(t):D.mergeMultiChainConnectors(Ce.allConnectors)},setFilterByNamespace(t){Ce.filterByNamespace=t,Ce.connectors=D.getConnectors(t),J.setFilterByNamespace(t)},setConnectorId(t,e){t&&(Ce.activeConnectorIds={...Ce.activeConnectorIds,[e]:t},R.setConnectedConnectorId(e,t))},removeConnectorId(t){Ce.activeConnectorIds={...Ce.activeConnectorIds,[t]:void 0},R.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return Ce.activeConnectorIds[t]},isConnected(t){return t?!!Ce.activeConnectorIds[t]:Object.values(Ce.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){Ce.activeConnectorIds={...Yu}}},D=zt(qg),Wg=1e3,wr={checkNamespaceConnectorId(t,e){return D.getConnectorId(t)===e},isSocialProvider(t){return be.DEFAULT_REMOTE_FEATURES.socials.includes(t)},connectWalletConnect({walletConnect:t,connector:e,closeModalOnConnect:s=!0,redirectViewOnModalClose:n="Connect",onOpen:r,onConnect:i}){return new Promise((o,a)=>{if(t&&D.setActiveConnector(e),r==null||r(z.isMobile()&&t),n){const l=he.subscribeKey("open",d=>{d||(ee.state.view!==n&&ee.replace(n),l(),a(new Error("Modal closed")))})}const c=g.subscribeKey("activeCaipAddress",l=>{l&&(i==null||i(),s&&he.close(),c(),o(Qe.parseCaipAddress(l)))})})},connectExternal(t){return new Promise((e,s)=>{const n=g.subscribeKey("activeCaipAddress",r=>{r&&(he.close(),n(),e(Qe.parseCaipAddress(r)))});B.connectExternal(t,t.chain).catch(()=>{n(),s(new Error("Connection rejected"))})})},connectSocial({social:t,namespace:e,closeModalOnConnect:s=!0,onOpenFarcaster:n,onConnect:r}){let i,o=!1,a=null;const c=e||g.state.activeChain,l=g.subscribeKey("activeCaipAddress",d=>{d&&(s&&he.close(),l())});return new Promise((d,u)=>{async function h(f){var m;if((m=f.data)!=null&&m.resultUri)if(f.origin===N.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",h,!1);try{const y=D.getAuthConnector(c);if(y&&!o){i&&i.close(),o=!0;const w=f.data.resultUri;ce.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:t}}),R.setConnectedSocialProvider(t),await B.connectExternal({id:y.id,type:y.type,socialUri:w},y.chain);const b=g.state.activeCaipAddress;if(!b){u(new Error("Failed to connect"));return}d(Qe.parseCaipAddress(b)),ce.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:t}})}}catch(y){ce.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:t,message:z.parseError(y)}}),u(new Error("Failed to connect"))}}else ce.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:t,message:"Untrusted Origin"}})}async function p(){if(ce.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:t}}),t==="farcaster"){n==null||n();const f=he.subscribeKey("open",y=>{!y&&t==="farcaster"&&(u(new Error("Popup closed")),r==null||r(),f())}),m=D.getAuthConnector();if(m){const y=g.getAccountData(c);if(!(y!=null&&y.farcasterUrl))try{const{url:w}=await m.provider.getFarcasterUri();g.setAccountProp("farcasterUrl",w,c)}catch{u(new Error("Failed to connect to farcaster"))}}}else{const f=D.getAuthConnector();a=z.returnOpenHref(`${N.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(f){const{uri:m}=await f.provider.getSocialRedirectUri({provider:t});if(a&&m){a.location.href=m,i=a;const y=setInterval(()=>{i!=null&&i.closed&&!o&&(u(new Error("Popup closed")),clearInterval(y))},1e3);window.addEventListener("message",h,!1)}else a==null||a.close(),u(new Error("Failed to initiate social connection"))}}catch{u(new Error("Failed to initiate social connection")),a==null||a.close()}}}p()})},connectEmail({closeModalOnConnect:t=!0,redirectViewOnModalClose:e="Connect",onOpen:s,onConnect:n}){return new Promise((r,i)=>{if(s==null||s(),e){const a=he.subscribeKey("open",c=>{c||(ee.state.view!==e&&ee.replace(e),a(),i(new Error("Modal closed")))})}const o=g.subscribeKey("activeCaipAddress",a=>{a&&(n==null||n(),t&&he.close(),o(),r(Qe.parseCaipAddress(a)))})})},async updateEmail(){const t=R.getConnectedConnectorId(g.state.activeChain),e=D.getAuthConnector();if(!e)throw new Error("No auth connector found");if(t!==N.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");const s=e.provider.getEmail()??"";return await he.open({view:"UpdateEmailWallet",data:{email:s,redirectView:void 0}}),new Promise((n,r)=>{const i=setInterval(()=>{const a=e.provider.getEmail()??"";a!==s&&(he.close(),clearInterval(i),o(),n({email:a}))},Wg),o=he.subscribeKey("open",a=>{a||(ee.state.view!=="Connect"&&ee.push("Connect"),clearInterval(i),o(),r(new Error("Modal closed")))})})},canSwitchToSmartAccount(t){return g.checkIfSmartAccountEnabled()&&Kt(t)===Wt.ACCOUNT_TYPES.EOA}};function Ju(){var n,r;const t=((n=g.state.activeCaipNetwork)==null?void 0:n.chainNamespace)||"eip155",e=((r=g.state.activeCaipNetwork)==null?void 0:r.id)||1,s=be.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`}function Kt(t){var s;return(s=g.getAccountData(t))==null?void 0:s.preferredAccountType}function Mi(t){var e,s;return t?(s=(e=g.state.chains.get(t))==null?void 0:e.networkState)==null?void 0:s.caipNetwork:g.state.activeCaipNetwork}const fo={getConnectionStatus(t,e){const s=D.state.activeConnectorIds[e],n=B.getConnections(e);return!!s&&t.connectorId===s?"connected":n.some(o=>o.connectorId.toLowerCase()===t.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:t,connectorId:e,addresses:s}){return t.map(n=>{if((e?n.connectorId.toLowerCase()===e.toLowerCase():!1)&&s){const i=n.accounts.filter(o=>!s.some(c=>c.toLowerCase()===o.address.toLowerCase()));return{...n,accounts:i}}return n})},excludeExistingConnections(t,e){const s=new Set(t);return e.filter(n=>!s.has(n.connectorId))},getConnectionsByConnectorId(t,e){return t.filter(s=>s.connectorId.toLowerCase()===e.toLowerCase())},getConnectionsData(t){var a;const e=!!((a=I.state.remoteFeatures)!=null&&a.multiWallet),s=D.state.activeConnectorIds[t],n=B.getConnections(t),i=(B.state.recentConnections.get(t)??[]).filter(c=>D.getConnectorById(c.connectorId)),o=fo.excludeExistingConnections([...n.map(c=>c.connectorId),...s?[s]:[]],i);return e?{connections:n,recentConnections:o}:{connections:n.filter(c=>c.connectorId.toLowerCase()===(s==null?void 0:s.toLowerCase())),recentConnections:[]}}},xe=ke({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Hg={state:xe,subscribe(t){return et(xe,()=>t(xe))},setLastNetworkInView(t){xe.lastNetworkInView=t},async fetchTransactions(t){var e;if(!t)throw new Error("Transactions can't be fetched without an accountAddress");xe.loading=!0;try{const s=await te.fetchTransactions({account:t,cursor:xe.next,chainId:(e=g.state.activeCaipNetwork)==null?void 0:e.caipNetworkId}),n=eo.filterSpamTransactions(s.data),r=eo.filterByConnectedChain(n),i=[...xe.transactions,...r];xe.loading=!1,xe.transactions=i,xe.transactionsByYear=eo.groupTransactionsByYearAndMonth(xe.transactionsByYear,r),xe.empty=i.length===0,xe.next=s.next?s.next:void 0}catch{const n=g.state.activeChain;ce.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:I.state.projectId,cursor:xe.next,isSmartAccount:Kt(n)===Wt.ACCOUNT_TYPES.SMART_ACCOUNT}}),us.showError("Failed to fetch transactions"),xe.loading=!1,xe.empty=!0,xe.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const s=t;return e.forEach(n=>{const r=new Date(n.metadata.minedAt).getFullYear(),i=new Date(n.metadata.minedAt).getMonth(),o=s[r]??{},c=(o[i]??[]).filter(l=>l.id!==n.id);s[r]={...o,[i]:[...c,n].sort((l,d)=>new Date(d.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),s},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(n=>{var r;return((r=n.nft_info)==null?void 0:r.flags.is_spam)===!0}))},filterByConnectedChain(t){var n;const e=(n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId;return t.filter(r=>r.metadata.chain===e)},clearCursor(){xe.next=void 0},resetTransactions(){xe.transactions=[],xe.transactionsByYear={},xe.lastNetworkInView=void 0,xe.loading=!1,xe.empty=!1,xe.next=void 0}},eo=zt(Hg,"API_ERROR"),ye=ke({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,buffering:!1,status:"disconnected"});let ln;const Kg={state:ye,subscribe(t){return et(ye,()=>t(ye))},subscribeKey(t,e){return tt(ye,t,e)},_getClient(){return ye._client},setClient(t){ye._client=Kr(t)},initialize(t){const e=t.filter(s=>!!s.namespace).map(s=>s.namespace);B.syncStorageConnections(e)},syncStorageConnections(t){const e=R.getConnections(),s=t??Array.from(g.state.chains.keys());for(const n of s){const r=e[n]??[],i=new Map(ye.recentConnections);i.set(n,r),ye.recentConnections=i}},getConnections(t){return t?ye.connections.get(t)??[]:[]},hasAnyConnection(t){const e=B.state.connections;return Array.from(e.values()).flatMap(s=>s).some(({connectorId:s})=>s===t)},async connectWalletConnect({cache:t="auto"}={}){var s,n,r,i;const e=z.isTelegram()||z.isSafari()&&z.isIos();if(t==="always"||t==="auto"&&e){if(ln){await ln,ln=void 0;return}if(!z.isPairingExpired(ye==null?void 0:ye.wcPairingExpiry)){const o=ye.wcUri;ye.wcUri=o;return}ln=(n=(s=B._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:n.call(s).catch(()=>{}),B.state.status="connecting",await ln,ln=void 0,ye.wcPairingExpiry=void 0,B.state.status="connected"}else await((i=(r=B._getClient())==null?void 0:r.connectWalletConnect)==null?void 0:i.call(r))},async connectExternal(t,e,s=!0){var r,i;const n=await((i=(r=B._getClient())==null?void 0:r.connectExternal)==null?void 0:i.call(r,t));return s&&g.setActiveNamespace(e),n},async reconnectExternal(t){var s,n;await((n=(s=B._getClient())==null?void 0:s.reconnectExternal)==null?void 0:n.call(s,t));const e=t.chain||g.state.activeChain;e&&D.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){var n;if(!e)return;he.setLoading(!0,g.state.activeChain);const s=D.getAuthConnector();s&&(g.setAccountProp("preferredAccountType",t,e),await s.provider.setPreferredAccount(t),R.setPreferredAccountTypes(Object.entries(g.state.chains).reduce((r,[i,o])=>{const a=i,c=Kt(a);return c!==void 0&&(r[a]=c),r},{})),await B.reconnectExternal(s),he.setLoading(!1,g.state.activeChain),ce.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}}))},async signMessage(t){var e;return(e=B._getClient())==null?void 0:e.signMessage(t)},parseUnits(t,e){var s;return(s=B._getClient())==null?void 0:s.parseUnits(t,e)},formatUnits(t,e){var s;return(s=B._getClient())==null?void 0:s.formatUnits(t,e)},updateBalance(t){var e;return(e=B._getClient())==null?void 0:e.updateBalance(t)},async sendTransaction(t){var e;return(e=B._getClient())==null?void 0:e.sendTransaction(t)},async getCapabilities(t){var e;return(e=B._getClient())==null?void 0:e.getCapabilities(t)},async grantPermissions(t){var e;return(e=B._getClient())==null?void 0:e.grantPermissions(t)},async walletGetAssets(t){var e;return((e=B._getClient())==null?void 0:e.walletGetAssets(t))??{}},async estimateGas(t){var e;return(e=B._getClient())==null?void 0:e.estimateGas(t)},async writeContract(t){var e;return(e=B._getClient())==null?void 0:e.writeContract(t)},async getEnsAddress(t){var e;return(e=B._getClient())==null?void 0:e.getEnsAddress(t)},async getEnsAvatar(t){var e;return(e=B._getClient())==null?void 0:e.getEnsAvatar(t)},checkInstalled(t){var e,s;return((s=(e=B._getClient())==null?void 0:e.checkInstalled)==null?void 0:s.call(e,t))||!1},resetWcConnection(){ye.wcUri=void 0,ye.wcPairingExpiry=void 0,ye.wcLinking=void 0,ye.recentWallet=void 0,ye.status="disconnected",eo.resetTransactions(),R.deleteWalletConnectDeepLink(),R.deleteRecentWallet()},resetUri(){ye.wcUri=void 0,ye.wcPairingExpiry=void 0,ln=void 0},finalizeWcConnection(t){var n,r;const{wcLinking:e,recentWallet:s}=B.state;e&&R.setWalletConnectDeepLink(e),s&&R.setAppKitRecent(s),t&&ce.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:t,properties:{method:e?"mobile":"qrcode",name:((r=(n=ee.state.data)==null?void 0:n.wallet)==null?void 0:r.name)||"Unknown",view:ee.state.view,walletRank:s==null?void 0:s.order}})},setWcBasic(t){ye.wcBasic=t},setUri(t){ye.wcUri=t,ye.wcPairingExpiry=z.getPairingExpiry()},setWcLinking(t){ye.wcLinking=t},setWcError(t){ye.wcError=t,ye.buffering=!1},setRecentWallet(t){ye.recentWallet=t},setBuffering(t){ye.buffering=t},setStatus(t){ye.status=t},setIsSwitchingConnection(t){ye.isSwitchingConnection=t},async disconnect({id:t,namespace:e,initialDisconnect:s}={}){var n;try{await((n=B._getClient())==null?void 0:n.disconnect({id:t,chainNamespace:e,initialDisconnect:s}))}catch(r){throw new Rn("Failed to disconnect","INTERNAL_SDK_ERROR",r)}},async disconnectConnector({id:t,namespace:e}){var s;try{await((s=B._getClient())==null?void 0:s.disconnectConnector({id:t,namespace:e}))}catch(n){throw new Rn("Failed to disconnect connector","INTERNAL_SDK_ERROR",n)}},setConnections(t,e){const s=new Map(ye.connections);s.set(e,t),ye.connections=s},async handleAuthAccountSwitch({address:t,namespace:e}){var i,o;const s=g.getAccountData(e),n=(o=(i=s==null?void 0:s.user)==null?void 0:i.accounts)==null?void 0:o.find(a=>a.type==="smartAccount"),r=n&&n.address.toLowerCase()===t.toLowerCase()&&wr.canSwitchToSmartAccount(e)?"smartAccount":"eoa";await B.setPreferredAccountType(r,e)},async handleActiveConnection({connection:t,namespace:e,address:s}){const n=D.getConnectorById(t.connectorId),r=t.connectorId===N.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${t.connectorId}`);if(r)s&&await B.handleAuthAccountSwitch({address:s,namespace:e});else{const i=await B.connectExternal({id:n.id,type:n.type,provider:n.provider,address:s,chain:e},e);return i==null?void 0:i.address}return s},async handleDisconnectedConnection({connection:t,namespace:e,address:s,closeModalOnConnect:n}){var l,d;const r=D.getConnectorById(t.connectorId),i=(d=(l=t.auth)==null?void 0:l.name)==null?void 0:d.toLowerCase(),o=t.connectorId===N.CONNECTOR_ID.AUTH,a=t.connectorId===N.CONNECTOR_ID.WALLET_CONNECT;if(!r)throw new Error(`No connector found for connection: ${t.connectorId}`);let c;if(o)if(i&&wr.isSocialProvider(i)){const{address:u}=await wr.connectSocial({social:i,closeModalOnConnect:n,onOpenFarcaster(){he.open({view:"ConnectingFarcaster"})},onConnect(){ee.replace("ProfileWallets")}});c=u}else{const{address:u}=await wr.connectEmail({closeModalOnConnect:n,onOpen(){he.open({view:"EmailLogin"})},onConnect(){ee.replace("ProfileWallets")}});c=u}else if(a){const{address:u}=await wr.connectWalletConnect({walletConnect:!0,connector:r,closeModalOnConnect:n,onOpen(h){const p=h?"AllWallets":"ConnectingWalletConnect";he.state.open?ee.push(p):he.open({view:p})},onConnect(){ee.replace("ProfileWallets")}});c=u}else{const u=await B.connectExternal({id:r.id,type:r.type,provider:r.provider,chain:e},e);u&&(c=u.address)}return o&&s&&await B.handleAuthAccountSwitch({address:s,namespace:e}),c},async switchConnection({connection:t,address:e,namespace:s,closeModalOnConnect:n,onChange:r}){var c;let i;const o=(c=g.getAccountData(s))==null?void 0:c.caipAddress;if(o){const{address:l}=Qe.parseCaipAddress(o);i=l}const a=fo.getConnectionStatus(t,s);switch(a){case"connected":case"active":{const l=await B.handleActiveConnection({connection:t,namespace:s,address:e});if(i&&l){const d=l.toLowerCase()!==i.toLowerCase();r==null||r({address:l,namespace:s,hasSwitchedAccount:d,hasSwitchedWallet:a==="active"})}break}case"disconnected":{const l=await B.handleDisconnectedConnection({connection:t,namespace:s,address:e,closeModalOnConnect:n});l&&(r==null||r({address:l,namespace:s,hasSwitchedAccount:!0,hasSwitchedWallet:!0}));break}default:throw new Error(`Invalid connection status: ${a}`)}}},B=zt(Kg),Jo={createBalance(t,e){const s={name:t.metadata.name||"",symbol:t.metadata.symbol||"",decimals:t.metadata.decimals||0,value:t.metadata.value||0,price:t.metadata.price||0,iconUrl:t.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:e,address:t.address==="native"?void 0:this.convertAddressToCAIP10Address(t.address,e),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:t.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance({hex:t,decimals:e}){return Rc(BigInt(t),e)},convertAddressToCAIP10Address(t,e){return`${e}:${t}`},createCAIP2ChainId(t,e){return`${e}:${parseInt(t,16)}`},getChainIdHexFromCAIP2ChainId(t){const e=t.split(":");if(e.length<2||!e[1])return"0x0";const s=e[1],n=parseInt(s,10);return isNaN(n)?"0x0":`0x${n.toString(16)}`},isWalletGetAssetsResponse(t){return typeof t!="object"||t===null?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(s=>this.isValidAsset(s)))},isValidAsset(t){return typeof t=="object"&&t!==null&&typeof t.address=="string"&&typeof t.balance=="string"&&(t.type==="ERC20"||t.type==="NATIVE")&&typeof t.metadata=="object"&&t.metadata!==null&&typeof t.metadata.name=="string"&&typeof t.metadata.symbol=="string"&&typeof t.metadata.decimals=="number"&&typeof t.metadata.price=="number"&&typeof t.metadata.iconUrl=="string"}};let Xo;async function ml(){if(!Xo){const{createPublicClient:t,http:e,defineChain:s}=await lo(()=>import("./index-069f2f19.js"),["assets/index-069f2f19.js","assets/index-fec77d48.js","assets/index-91d98a83.css","assets/index-516a1ffc.js"]);Xo={createPublicClient:t,http:e,defineChain:s}}return Xo}const Ba={getBlockchainApiRpcUrl(t,e){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",t),s.searchParams.set("projectId",e),s.toString()},async getViemChain(t){const{defineChain:e}=await ml(),{chainId:s}=Qe.parseCaipNetworkId(t.caipNetworkId);return e({...t,id:Number(s)})},async createViemPublicClient(t){const{createPublicClient:e,http:s}=await ml(),n=I.state.projectId,r=await Ba.getViemChain(t);if(!r)throw new Error(`Chain ${t.caipNetworkId} not found in viem/chains`);return e({chain:r,transport:s(Ba.getBlockchainApiRpcUrl(t.caipNetworkId,n))})}},kc={async getMyTokensWithBalance(t){var a;const e=(a=g.getAccountData())==null?void 0:a.address,s=g.state.activeCaipNetwork,n=D.getConnectorId("eip155")===N.CONNECTOR_ID.AUTH;if(!e||!s)return[];const r=`${s.caipNetworkId}:${e}`,i=R.getBalanceCacheForCaipAddress(r);if(i)return i.balances;if(s.chainNamespace===N.CHAIN.EVM&&n){const c=await this.getEIP155Balances(e,s);if(c)return this.filterLowQualityTokens(c)}const o=await te.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(t,e){var s,n;try{const r=Jo.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),i=await B.getCapabilities(t);if(!((n=(s=i==null?void 0:i[r])==null?void 0:s.assetDiscovery)!=null&&n.supported))return null;const o=await B.walletGetAssets({account:t,chainFilter:[r]});if(!Jo.isWalletGetAssetsResponse(o))return null;const c=(o[r]||[]).map(l=>Jo.createBalance(l,e.caipNetworkId));return R.updateBalanceCache({caipAddress:`${e.caipNetworkId}:${t}`,balance:{balances:c},timestamp:Date.now()}),c}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:t,assetAddress:e,caipNetwork:s}){const n=await Ba.createViemPublicClient(s),{address:r}=Qe.parseCaipAddress(t),[{result:i},{result:o},{result:a},{result:c}]=await n.multicall({contracts:[{address:e,functionName:"name",args:[],abi:ki},{address:e,functionName:"symbol",args:[],abi:ki},{address:e,functionName:"balanceOf",args:[r],abi:ki},{address:e,functionName:"decimals",args:[],abi:ki}]});return{name:i,symbol:o,decimals:c,balance:a&&c?Rc(a,c):"0"}}},Zo={adapters:{}},Xu={state:Zo,initialize(t){Zo.adapters={...t}},get(t){return Zo.adapters[t]}},go={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0},pt=ke({providers:{...go},providerIds:{...go}}),$e={state:pt,subscribeKey(t,e){return tt(pt,t,e)},subscribe(t){return et(pt,()=>{t(pt)})},subscribeProviders(t){return et(pt.providers,()=>t(pt.providers))},setProvider(t,e){t&&e&&(pt.providers[t]=Kr(e))},getProvider(t){if(t)return pt.providers[t]},setProviderId(t,e){e&&(pt.providerIds[t]=e)},getProviderId(t){if(t)return pt.providerIds[t]},reset(){pt.providers={...go},pt.providerIds={...go}},resetChain(t){pt.providers[t]=void 0,pt.providerIds[t]=void 0}},Ln=ke({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),Ss={state:Ln,subscribe(t){return et(Ln,()=>t(Ln))},subscribeOpen(t){return tt(Ln,"open",t)},set(t){Object.assign(Ln,{...Ln,...t})}},Vg={async getTokenList(t){var n;const e=await te.fetchSwapTokens({chainId:t});return((n=e==null?void 0:e.tokens)==null?void 0:n.map(r=>({...r,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0})))||[]},async fetchGasPrice(){var e;const t=g.state.activeCaipNetwork;if(!t)return null;try{switch(t.chainNamespace){case"solana":const s=(e=await(B==null?void 0:B.estimateGas({chainNamespace:"solana"})))==null?void 0:e.toString();return{standard:s,fast:s,instant:s};case"eip155":default:return await te.fetchGasPrice({chainId:t.caipNetworkId})}}catch{return null}},async fetchSwapAllowance({tokenAddress:t,userAddress:e,sourceTokenAmount:s,sourceTokenDecimals:n}){const r=await te.fetchSwapAllowance({tokenAddress:t,userAddress:e});if(r!=null&&r.allowance&&s&&n){const i=B.parseUnits(s,n)||0;return BigInt(r.allowance)>=i}return!1},async getMyTokensWithBalance(t){const e=await kc.getMyTokensWithBalance(t);return g.setAccountProp("tokenBalance",e,g.state.activeChain),this.mapBalancesToSwapTokens(e)},mapBalancesToSwapTokens(t){return(t==null?void 0:t.map(e=>({...e,address:e!=null&&e.address?e.address:Ju(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]},async handleSwapError(t){var e,s;try{const n=t==null?void 0:t.cause;if(!(n!=null&&n.json))return;const r=await n.json(),i=(s=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:s.description;return i!=null&&i.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}},we=ke({tokenBalances:[],loading:!1}),zg={state:we,subscribe(t){return et(we,()=>t(we))},subscribeKey(t,e){return tt(we,t,e)},setToken(t){t&&(we.token=Kr(t))},setTokenAmount(t){we.sendTokenAmount=t},setReceiverAddress(t){we.receiverAddress=t},setReceiverProfileImageUrl(t){we.receiverProfileImageUrl=t},setReceiverProfileName(t){we.receiverProfileName=t},setNetworkBalanceInUsd(t){we.networkBalanceInUSD=t},setLoading(t){we.loading=t},getSdkEventProperties(t){var e,s;return{message:z.parseError(t),isSmartAccount:Kt(g.state.activeChain)===Wt.ACCOUNT_TYPES.SMART_ACCOUNT,token:((e=we.token)==null?void 0:e.symbol)||"",amount:we.sendTokenAmount??0,network:((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||""}},async sendToken(){var t;try{switch(ae.setLoading(!0),(t=g.state.activeCaipNetwork)==null?void 0:t.chainNamespace){case"eip155":await ae.sendEvmToken();return;case"solana":await ae.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(e){throw Ns.isUserRejectedRequestError(e)?new ku(e):e}finally{ae.setLoading(!1)}},async sendEvmToken(){var s,n,r;const t=g.state.activeChain;if(!t)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const e=Kt(t);if(!ae.state.sendTokenAmount||!ae.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!ae.state.token)throw new Error("A token is required");if((s=ae.state.token)!=null&&s.address){ce.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Wt.ACCOUNT_TYPES.SMART_ACCOUNT,token:ae.state.token.address,amount:ae.state.sendTokenAmount,network:((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}});const{hash:i}=await ae.sendERC20Token({receiverAddress:ae.state.receiverAddress,tokenAddress:ae.state.token.address,sendTokenAmount:ae.state.sendTokenAmount,decimals:ae.state.token.quantity.decimals});i&&(we.hash=i)}else{ce.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Wt.ACCOUNT_TYPES.SMART_ACCOUNT,token:ae.state.token.symbol||"",amount:ae.state.sendTokenAmount,network:((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}});const{hash:i}=await ae.sendNativeToken({receiverAddress:ae.state.receiverAddress,sendTokenAmount:ae.state.sendTokenAmount,decimals:ae.state.token.quantity.decimals});i&&(we.hash=i)}},async fetchTokenBalance(t){var o,a,c;we.loading=!0;const e=g.state.activeChain,s=(o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId,n=(a=g.state.activeCaipNetwork)==null?void 0:a.chainNamespace,r=((c=g.getAccountData(e))==null?void 0:c.caipAddress)??g.state.activeCaipAddress,i=r?z.getPlainAddress(r):void 0;if(we.lastRetry&&!z.isAllowedRetry(we.lastRetry,30*be.ONE_SEC_MS))return we.loading=!1,[];try{if(i&&s&&n){const l=await kc.getMyTokensWithBalance();return we.tokenBalances=l,we.lastRetry=void 0,l}}catch(l){we.lastRetry=Date.now(),t==null||t(l),us.showError("Token Balance Unavailable")}finally{we.loading=!1}return[]},fetchNetworkBalance(){if(we.tokenBalances.length===0)return;const t=Vg.mapBalancesToSwapTokens(we.tokenBalances);if(!t)return;const e=t.find(s=>s.address===Ju());e&&(we.networkBalanceInUSD=e?ff.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){var o,a,c,l;ee.pushTransactionStack({});const e=t.receiverAddress,s=(o=g.getAccountData())==null?void 0:o.address,n=B.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),r="0x",i=await B.sendTransaction({chainNamespace:N.CHAIN.EVM,to:e,address:s,data:r,value:n??BigInt(0)});return ce.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Kt("eip155")===Wt.ACCOUNT_TYPES.SMART_ACCOUNT,token:((a=ae.state.token)==null?void 0:a.symbol)||"",amount:t.sendTokenAmount,network:((c=g.state.activeCaipNetwork)==null?void 0:c.caipNetworkId)||"",hash:i||""}}),(l=B._getClient())==null||l.updateBalance("eip155"),ae.resetSend(),{hash:i}},async sendERC20Token(t){var n,r,i;ee.pushTransactionStack({onSuccess(){ee.replace("Account")}});const e=B.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),s=(n=g.getAccountData())==null?void 0:n.address;if(s&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const o=z.getPlainAddress(t.tokenAddress);if(!o)throw new Error("SendController:sendERC20Token - tokenAddress is required");const a=await B.writeContract({fromAddress:s,tokenAddress:o,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:wf.getERC20Abi(o),chainNamespace:N.CHAIN.EVM});return ce.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Kt("eip155")===Wt.ACCOUNT_TYPES.SMART_ACCOUNT,token:((r=ae.state.token)==null?void 0:r.symbol)||"",amount:t.sendTokenAmount,network:((i=g.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||"",hash:a||""}}),ae.resetSend(),{hash:a}}return{hash:void 0}},async sendSolanaToken(){var s,n,r;if(!ae.state.sendTokenAmount||!ae.state.receiverAddress)throw new Error("An amount and receiver address are required");ee.pushTransactionStack({onSuccess(){ee.replace("Account")}});let t;ae.state.token&&ae.state.token.address!==be.SOLANA_NATIVE_TOKEN_ADDRESS&&(z.isCaipAddress(ae.state.token.address)?t=z.getPlainAddress(ae.state.token.address):t=ae.state.token.address);const e=await B.sendTransaction({chainNamespace:"solana",tokenMint:t,to:ae.state.receiverAddress,value:ae.state.sendTokenAmount});e&&(we.hash=e),(s=B._getClient())==null||s.updateBalance("solana"),ce.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:!1,token:((n=ae.state.token)==null?void 0:n.symbol)||"",amount:ae.state.sendTokenAmount,network:((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||"",hash:e||""}}),ae.resetSend()},resetSend(){we.token=void 0,we.sendTokenAmount=void 0,we.receiverAddress=void 0,we.receiverProfileImageUrl=void 0,we.receiverProfileName=void 0,we.loading=!1,we.tokenBalances=[]}},ae=zt(zg),Qo={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},Li={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},q=ke({chains:kf(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{connectionControllerClient:void 0},isSwitchingNamespace:!1}),Zu={state:q,subscribe(t){return et(q,()=>{t(q)})},subscribeKey(t,e){return tt(q,t,e)},subscribeAccountStateProp(t,e,s){var r;const n=s||q.activeChain;return n?tt(((r=q.chains.get(n))==null?void 0:r.accountState)||{},t,e):()=>{}},subscribeChainProp(t,e,s){let n;return et(q.chains,()=>{var i;const r=s||q.activeChain;if(r){const o=(i=q.chains.get(r))==null?void 0:i[t];n!==o&&(n=o,e(o))}})},initialize(t,e,s){const{chainId:n,namespace:r}=R.getActiveNetworkProps(),i=e==null?void 0:e.find(d=>d.id.toString()===(n==null?void 0:n.toString())),a=t.find(d=>(d==null?void 0:d.namespace)===r)||(t==null?void 0:t[0]),c=t.map(d=>d.namespace).filter(d=>d!==void 0),l=I.state.enableEmbedded?new Set([...c]):new Set([...(e==null?void 0:e.map(d=>d.chainNamespace))??[]]);((t==null?void 0:t.length)===0||!a)&&(q.noAdapters=!0),q.noAdapters||(q.activeChain=a==null?void 0:a.namespace,q.activeCaipNetwork=i,g.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:i}),q.activeChain&&Ss.set({activeChain:a==null?void 0:a.namespace})),l.forEach(d=>{const u=e==null?void 0:e.filter(f=>f.chainNamespace===d),h=R.getPreferredAccountTypes()||{},p={...I.state.defaultAccountTypes,...h};g.state.chains.set(d,{namespace:d,networkState:ke({...Li,caipNetwork:u==null?void 0:u[0]}),accountState:ke({...Qo,preferredAccountType:p[d]}),caipNetworks:u??[],...s}),g.setRequestedCaipNetworks(u??[],d)})},removeAdapter(t){var e,s;if(q.activeChain===t){const n=Array.from(q.chains.entries()).find(([r])=>r!==t);if(n){const r=(s=(e=n[1])==null?void 0:e.caipNetworks)==null?void 0:s[0];r&&g.setActiveCaipNetwork(r)}}q.chains.delete(t)},addAdapter(t,{connectionControllerClient:e},s){if(!t.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");q.chains.set(t.namespace,{namespace:t.namespace,networkState:{...Li,caipNetwork:s[0]},accountState:{...Qo},caipNetworks:s,connectionControllerClient:e}),g.setRequestedCaipNetworks((s==null?void 0:s.filter(n=>n.chainNamespace===t.namespace))??[],t.namespace)},addNetwork(t){var s;const e=q.chains.get(t.chainNamespace);if(e){const n=[...e.caipNetworks||[]];(s=e.caipNetworks)!=null&&s.find(r=>r.id===t.id)||n.push(t),q.chains.set(t.chainNamespace,{...e,caipNetworks:n}),g.setRequestedCaipNetworks(n,t.chainNamespace),D.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){var n,r,i;const s=q.chains.get(t);if(s){const o=((n=q.activeCaipNetwork)==null?void 0:n.id)===e,a=[...((r=s.caipNetworks)==null?void 0:r.filter(c=>c.id!==e))||[]];o&&((i=s==null?void 0:s.caipNetworks)!=null&&i[0])&&g.setActiveCaipNetwork(s.caipNetworks[0]),q.chains.set(t,{...s,caipNetworks:a}),g.setRequestedCaipNetworks(a||[],t),a.length===0&&D.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=q.chains.get(t);s&&(s.networkState={...s.networkState||Li,...e},q.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const n=q.chains.get(t);if(n){const r={...n.accountState||Qo,...e};q.chains.set(t,{...n,accountState:r}),(q.chains.size===1||q.activeChain===t)&&e.caipAddress&&(q.activeCaipAddress=e.caipAddress)}},setChainNetworkData(t,e){if(!t)return;const s=q.chains.get(t);if(s){const n={...s.networkState||Li,...e};q.chains.set(t,{...s,networkState:n})}},setAccountProp(t,e,s,n=!0){g.setChainAccountData(s,{[t]:e},n)},setActiveNamespace(t){var n,r;q.activeChain=t;const e=t?q.chains.get(t):void 0,s=(n=e==null?void 0:e.networkState)==null?void 0:n.caipNetwork;s!=null&&s.id&&t&&(q.activeCaipAddress=(r=e==null?void 0:e.accountState)==null?void 0:r.caipAddress,q.activeCaipNetwork=s,g.setChainNetworkData(t,{caipNetwork:s}),R.setActiveCaipNetworkId(s==null?void 0:s.caipNetworkId),Ss.set({activeChain:t,selectedNetworkId:s==null?void 0:s.caipNetworkId}))},setActiveCaipNetwork(t){var i,o;if(!t)return;const e=q.activeChain===t.chainNamespace;e||g.setIsSwitchingNamespace(!0);const s=q.chains.get(t.chainNamespace);q.activeChain=t.chainNamespace,q.activeCaipNetwork=t,g.setChainNetworkData(t.chainNamespace,{caipNetwork:t});let n=(i=s==null?void 0:s.accountState)==null?void 0:i.address;if(n)q.activeCaipAddress=`${t.chainNamespace}:${t.id}:${n}`;else if(e&&q.activeCaipAddress){const{address:a}=Qe.parseCaipAddress(q.activeCaipAddress);n=a,q.activeCaipAddress=`${t.caipNetworkId}:${n}`}else q.activeCaipAddress=void 0;g.setChainAccountData(t.chainNamespace,{address:n,caipAddress:q.activeCaipAddress}),ae.resetSend(),Ss.set({activeChain:q.activeChain,selectedNetworkId:(o=q.activeCaipNetwork)==null?void 0:o.caipNetworkId}),R.setActiveCaipNetworkId(t.caipNetworkId),!g.checkIfSupportedNetwork(t.chainNamespace)&&I.state.enableNetworkSwitch&&!I.state.allowUnsupportedChain&&!B.state.wcBasic&&g.showUnsupportedChainUI()},addCaipNetwork(t){var s;if(!t)return;const e=q.chains.get(t.chainNamespace);e&&((s=e==null?void 0:e.caipNetworks)==null||s.push(t))},async switchActiveNamespace(t){var r;if(!t)return;const e=t!==g.state.activeChain,s=(r=g.getNetworkData(t))==null?void 0:r.caipNetwork,n=g.getCaipNetworkByNamespace(t,s==null?void 0:s.id);e&&n&&await g.switchActiveNetwork(n)},async switchActiveNetwork(t,{throwOnFailure:e=!1}={}){var o;const s=g.state.activeChain;if(!s)throw new Error("ChainController:switchActiveNetwork - namespace is required");const n=$e.getProviderId(q.activeChain)==="AUTH",r=(o=g.getAccountData(s))==null?void 0:o.address,i=N.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(t.chainNamespace);try{if(r&&t.chainNamespace===s||n&&i){const a=Xu.get(t.chainNamespace);if(!a)throw new Error("Adapter not found");await a.switchNetwork({caipNetwork:t})}g.setActiveCaipNetwork(t)}catch(a){if(e)throw a}ce.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})},getConnectionControllerClient(t){const e=t||q.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=q.chains.get(e);if(!(s!=null&&s.connectionControllerClient))throw new Error("ConnectionController client not set");return s.connectionControllerClient},getNetworkProp(t,e){var n;const s=(n=q.chains.get(e))==null?void 0:n.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=q.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:n=[]}=(e==null?void 0:e.networkState)||{};return z.sortRequestedNetworks(s,n).filter(o=>o==null?void 0:o.id)},getAllRequestedCaipNetworks(){const t=[];return q.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const s=g.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){g.setAdapterNetworkState(e,{requestedCaipNetworks:t});const n=g.getAllRequestedCaipNetworks().map(i=>i.chainNamespace),r=Array.from(new Set(n));D.filterByNamespaces(r)},getAllApprovedCaipNetworkIds(){const t=[];return q.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const s=g.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(t){var e,s;return t?(s=(e=q.chains.get(t))==null?void 0:e.networkState)==null?void 0:s.caipNetwork:q.activeCaipNetwork},getActiveCaipAddress(){return q.activeCaipAddress},getApprovedCaipNetworkIds(t){var n;const e=q.chains.get(t);return((n=e==null?void 0:e.networkState)==null?void 0:n.approvedCaipNetworkIds)||[]},setApprovedCaipNetworksData(t,e){g.setAdapterNetworkState(t,e)},checkIfSupportedNetwork(t,e){var r;const s=e||((r=q.activeCaipNetwork)==null?void 0:r.caipNetworkId),n=g.getRequestedCaipNetworks(t);return n.length?n==null?void 0:n.some(i=>i.caipNetworkId===s):!0},checkIfSupportedChainId(t){if(!q.activeChain)return!0;const e=g.getRequestedCaipNetworks(q.activeChain);return e==null?void 0:e.some(s=>s.id===t)},checkIfSmartAccountEnabled(){var n,r;const t=Ru.caipNetworkIdToNumber((n=q.activeCaipNetwork)==null?void 0:n.caipNetworkId);if(!q.activeChain||!t)return!1;const s=((r=Da.get(Xs.SMART_ACCOUNT_ENABLED_NETWORKS))==null?void 0:r.split(","))||[];return!!(s!=null&&s.includes(t.toString()))},showUnsupportedChainUI(){he.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=q.activeCaipNetwork;return!!(t!=null&&t.chainNamespace&&be.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){g.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(t){var r,i;const e=t;if(!e)throw new Error("Chain is required to set account prop");const s=(i=(r=g.state.chains.get(e))==null?void 0:r.accountState)==null?void 0:i.preferredAccountType,n=I.state.defaultAccountTypes[e];q.activeCaipAddress=void 0,g.setChainAccountData(e,{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||s,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),D.removeConnectorId(e)},setIsSwitchingNamespace(t){q.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){var s,n;const t=[];let e;if(q.chains.forEach(r=>{N.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(i=>i===r.namespace)&&r.namespace&&t.push(r.namespace)}),t.length>0){const r=t[0];return e=r?(n=(s=q.chains.get(r))==null?void 0:s.caipNetworks)==null?void 0:n[0]:void 0,e}},getAccountData(t){var s;const e=t||q.activeChain;if(e)return(s=g.state.chains.get(e))==null?void 0:s.accountState},getNetworkData(t){var s;const e=t||q.activeChain;if(e)return(s=g.state.chains.get(e))==null?void 0:s.networkState},getCaipNetworkByNamespace(t,e){var r,i,o;if(!t)return;const s=g.state.chains.get(t),n=(r=s==null?void 0:s.caipNetworks)==null?void 0:r.find(a=>a.id.toString()===(e==null?void 0:e.toString()));return n||((i=s==null?void 0:s.networkState)==null?void 0:i.caipNetwork)||((o=s==null?void 0:s.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const t=D.state.filterByNamespace;return(t?[q.chains.get(t)]:Array.from(q.chains.values())).flatMap(s=>(s==null?void 0:s.caipNetworks)||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?g.getRequestedCaipNetworks(t):g.getAllRequestedCaipNetworks()},getCaipNetworkById(t,e){return Zu.getCaipNetworks(e).find(s=>s.id.toString()===t.toString()||s.caipNetworkId.toString()===t.toString())},setLastConnectedSIWECaipNetwork(t){q.lastConnectedSIWECaipNetwork=t},getLastConnectedSIWECaipNetwork(){return q.lastConnectedSIWECaipNetwork},async fetchTokenBalance(t){var o,a;const e=g.getAccountData();if(!e)return[];const s=(o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId,n=(a=g.state.activeCaipNetwork)==null?void 0:a.chainNamespace,r=g.state.activeCaipAddress,i=r?z.getPlainAddress(r):void 0;if(g.setAccountProp("balanceLoading",!0,n),e.lastRetry&&!z.isAllowedRetry(e.lastRetry,30*be.ONE_SEC_MS))return g.setAccountProp("balanceLoading",!1,n),[];try{if(i&&s&&n){const c=await kc.getMyTokensWithBalance();return g.setAccountProp("tokenBalance",c,n),g.setAccountProp("lastRetry",void 0,n),g.setAccountProp("balanceLoading",!1,n),c}}catch(c){g.setAccountProp("lastRetry",Date.now(),n),t==null||t(c),us.showError("Token Balance Unavailable")}finally{g.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(t){var c;const e=t.chainNamespace,s=!!((c=g.getAccountData(e))!=null&&c.caipAddress),n=g.getAllApprovedCaipNetworkIds(),r=g.getNetworkProp("supportsAllNetworks",e)!==!1,i=D.getConnectorId(e),o=D.getAuthConnector(),a=i===N.CONNECTOR_ID.AUTH&&o;return!s||r||a?!1:!(n!=null&&n.includes(t.caipNetworkId))}},g=zt(Zu),Gg={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){var h,p;const s=g.state.activeCaipNetwork,n=g.state.activeChain,r=ee.state.data;if(t.id===(s==null?void 0:s.id))return;const o=!!((h=g.getAccountData(n))!=null&&h.address),a=!!((p=g.getAccountData(t.chainNamespace))!=null&&p.address),c=t.chainNamespace!==n,d=D.getConnectorId(n)===N.CONNECTOR_ID.AUTH,u=N.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(f=>f===t.chainNamespace);e||d&&u?ee.push("SwitchNetwork",{...r,network:t}):o&&c&&!a?ee.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):ee.push("SwitchNetwork",{...r,network:t})}},ft=ke({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),Yg={state:ft,subscribe(t){return et(ft,()=>t(ft))},subscribeKey(t,e){return tt(ft,t,e)},async open(t){var o,a;const e=t==null?void 0:t.namespace,s=g.state.activeChain,n=e&&e!==s,r=(o=g.getAccountData(t==null?void 0:t.namespace))==null?void 0:o.caipAddress,i=g.state.noAdapters;if(B.state.wcBasic?J.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await J.prefetch(),D.setFilterByNamespace(t==null?void 0:t.namespace),he.setLoading(!0,e),e&&n){const c=((a=g.getNetworkData(e))==null?void 0:a.caipNetwork)||g.getRequestedCaipNetworks(e)[0];c&&(i?(await g.switchActiveNetwork(c),ee.push("ConnectingWalletConnectBasic")):Gg.onSwitchNetwork({network:c,ignoreSwitchConfirmation:!0}))}else I.state.manualWCControl||i&&!r?z.isMobile()?ee.reset("AllWallets"):ee.reset("ConnectingWalletConnectBasic"):t!=null&&t.view?ee.reset(t.view,t.data):r?ee.reset("Account"):ee.reset("Connect");ft.open=!0,Ss.set({open:!0}),ce.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!r}})},close(){const t=I.state.enableEmbedded,e=!!g.state.activeCaipAddress;ft.open&&ce.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),ft.open=!1,ee.reset("Connect"),he.clearLoading(),t?e?ee.replace("Account"):ee.push("Connect"):Ss.set({open:!1}),B.resetUri()},setLoading(t,e){e&&ft.loadingNamespaceMap.set(e,t),ft.loading=t,Ss.set({loading:t})},clearLoading(){ft.loadingNamespaceMap.clear(),ft.loading=!1,Ss.set({loading:!1})},shake(){ft.shake||(ft.shake=!0,setTimeout(()=>{ft.shake=!1},500))}},he=zt(Yg),Ur={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"}]},ja={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},Jg={providers:$u,selectedProvider:null,error:null,purchaseCurrency:Ur,paymentCurrency:ja,purchaseCurrencies:[Ur],paymentCurrencies:[],quotesLoading:!1},Ee=ke(Jg),Xg={state:Ee,subscribe(t){return et(Ee,()=>t(Ee))},subscribeKey(t,e){return tt(Ee,t,e)},setSelectedProvider(t){var e,s;if(t&&t.name==="meld"){const n=g.state.activeChain,r=n===N.CHAIN.SOLANA?"SOL":"USDC",i=n?((s=(e=g.state.chains.get(n))==null?void 0:e.accountState)==null?void 0:s.address)??"":"",o=new URL(t.url);o.searchParams.append("publicKey",xf),o.searchParams.append("destinationCurrencyCode",r),o.searchParams.append("walletAddress",i),o.searchParams.append("externalCustomerId",I.state.projectId),Ee.selectedProvider={...t,url:o.toString()}}else Ee.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=$u.filter(n=>e.includes(n.name));Ee.providers=s}else Ee.providers=[]},setPurchaseCurrency(t){Ee.purchaseCurrency=t},setPaymentCurrency(t){Ee.paymentCurrency=t},setPurchaseAmount(t){qa.state.purchaseAmount=t},setPaymentAmount(t){qa.state.paymentAmount=t},async getAvailableCurrencies(){const t=await te.getOnrampOptions();Ee.purchaseCurrencies=t.purchaseCurrencies,Ee.paymentCurrencies=t.paymentCurrencies,Ee.paymentCurrency=t.paymentCurrencies[0]||ja,Ee.purchaseCurrency=t.purchaseCurrencies[0]||Ur,await J.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await J.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){var t,e;Ee.quotesLoading=!0;try{const s=await te.getOnrampQuote({purchaseCurrency:Ee.purchaseCurrency,paymentCurrency:Ee.paymentCurrency,amount:((t=Ee.paymentAmount)==null?void 0:t.toString())||"0",network:(e=Ee.purchaseCurrency)==null?void 0:e.symbol});return Ee.quotesLoading=!1,Ee.purchaseAmount=Number(s==null?void 0:s.purchaseAmount.amount),s}catch(s){return Ee.error=s.message,Ee.quotesLoading=!1,null}finally{Ee.quotesLoading=!1}},resetState(){Ee.selectedProvider=null,Ee.error=null,Ee.purchaseCurrency=Ur,Ee.paymentCurrency=ja,Ee.purchaseCurrencies=[Ur],Ee.paymentCurrencies=[],Ee.paymentAmount=void 0,Ee.purchaseAmount=void 0,Ee.quotesLoading=!1}},qa=zt(Xg),yl=2147483648,Zg={convertEVMChainIdToCoinType(t){if(t>=yl)throw new Error("Invalid chainId");return(yl|t)>>>0}},$t=ke({suggestions:[],loading:!1}),Qg={state:$t,subscribe(t){return et($t,()=>t($t))},subscribeKey(t,e){return tt($t,t,e)},async resolveName(t){var e,s;try{return await te.lookupEnsName(t)}catch(n){const r=n;throw new Error(((s=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:s.description)||"Error resolving name")}},async isNameRegistered(t){try{return await te.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{$t.loading=!0,$t.suggestions=[];const e=await te.getEnsNameSuggestions(t);return $t.suggestions=e.suggestions||[],$t.suggestions}catch(e){const s=Dr.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{$t.loading=!1}},async getNamesForAddress(t){try{if(!g.state.activeCaipNetwork)return[];const s=R.getEnsFromCacheForAddress(t);if(s)return s;const n=await te.reverseLookupEnsName({address:t});return R.updateEnsCache({address:t,ens:n,timestamp:Date.now()}),n}catch(e){const s=Dr.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){var r;const e=g.state.activeCaipNetwork,s=(r=g.getAccountData(e==null?void 0:e.chainNamespace))==null?void 0:r.address,n=D.getAuthConnector();if(!e)throw new Error("Network not found");if(!s||!n)throw new Error("Address or auth connector not found");$t.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});ee.pushTransactionStack({onCancel(){ee.replace("RegisterAccountName")}});const o=await B.signMessage(i);$t.loading=!1;const a=e.id;if(!a)throw new Error("Network not found");const c=Zg.convertEVMChainIdToCoinType(Number(a));await te.registerEnsName({coinType:c,address:s,signature:o,message:i}),g.setAccountProp("profileName",t,e.chainNamespace),R.updateEnsCache({address:s,ens:[{name:t,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),ee.replace("RegisterAccountNameSuccess")}catch(i){const o=Dr.parseEnsApiError(i,`Error registering name ${t}`);throw ee.replace("RegisterAccountName"),new Error(o)}finally{$t.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){var n,r;const s=t;return((r=(n=s==null?void 0:s.reasons)==null?void 0:n[0])==null?void 0:r.description)||e}},Dr=zt(Qg),em={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"]},Qs={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace(t){return em[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const s={...t},n=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>n.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>n.add(r)),e.events&&Object.keys(e.events).forEach(r=>n.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[i]=r.split(":");i&&n.add(i)}),n.forEach(r=>{s[r]||(s[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,i])=>{s[r]&&(s[r].methods=i)}),e.chains&&Object.entries(e.chains).forEach(([r,i])=>{s[r]&&(s[r].chains=i)}),e.events&&Object.entries(e.events).forEach(([r,i])=>{s[r]&&(s[r].events=i)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([i,o])=>{const[a,c]=i.split(":");!a||!c||!s[a]||(s[a].rpcMap||(s[a].rpcMap={}),r.has(a)||(s[a].rpcMap={},r.add(a)),s[a].rpcMap[c]=o)})}return s},createNamespaces(t,e){const s=t.reduce((n,r)=>{const{id:i,chainNamespace:o,rpcUrls:a}=r,c=a.default.http[0];n[o]||(n[o]=this.createDefaultNamespace(o));const l=`${o}:${i}`,d=n[o];switch(d.chains.push(l),l){case"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":d.chains.push("solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ");break;case"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":d.chains.push("solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K");break}return d!=null&&d.rpcMap&&c&&(d.rpcMap[i]=c),n},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{var n;const e=await Dr.resolveName(t);return((n=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:n.address)||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],n=e.accounts.map(r=>{const[i,o]=r.split(":");return`${i}:${o}`});return Array.from(new Set([...s,...n]))})},isSessionEventData(t){return typeof t=="object"&&t!==null&&"id"in t&&"topic"in t&&"params"in t&&typeof t.params=="object"&&t.params!==null&&"chainId"in t.params&&"event"in t.params&&typeof t.params.event=="object"&&t.params.event!==null},isUserRejectedRequestError(t){try{if(typeof t=="object"&&t!==null){const e=t,s=typeof e.code=="number",n=s&&e.code===Qs.RPC_ERROR_CODE.USER_REJECTED_METHODS,r=s&&e.code===Qs.RPC_ERROR_CODE.USER_REJECTED;return n||r}return!1}catch{return!1}},isOriginAllowed(t,e,s){for(const n of[...e,...s])if(n.includes("*")){const i=`^${n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(i,"u").test(t))return!0}else try{if(new URL(n).origin===t)return!0}catch{if(n===t)return!0}return!1},listenWcProvider({universalProvider:t,namespace:e,onConnect:s,onDisconnect:n,onAccountsChanged:r,onChainChanged:i,onDisplayUri:o}){s&&t.on("connect",()=>{const a=Qs.getWalletConnectAccounts(t,e);s(a)}),n&&t.on("disconnect",()=>{n()}),r&&t.on("accountsChanged",a=>{var c,l,d,u,h;try{const p=((d=(l=(c=t.session)==null?void 0:c.namespaces)==null?void 0:l[e])==null?void 0:d.accounts)||[],f=(h=(u=t.rpcProviders)==null?void 0:u[e])==null?void 0:h.getDefaultChain(),m=a.map(y=>{const w=p.find(k=>k.includes(`${e}:${f}:${y}`));if(!w)return;const{chainId:b,chainNamespace:A}=Qe.parseCaipAddress(w);return{address:y,chainId:b,chainNamespace:A}}).filter(y=>y!==void 0);m.length>0&&r(m)}catch(p){console.warn("Failed to parse accounts for namespace on accountsChanged event",e,a,p)}}),i&&t.on("chainChanged",a=>{i(a)}),o&&t.on("display_uri",a=>{o(a)})},getWalletConnectAccounts(t,e){var r,i,o,a;const s=new Set,n=(a=(o=(i=(r=t==null?void 0:t.session)==null?void 0:r.namespaces)==null?void 0:i[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>Qe.parseCaipAddress(c)).filter(({address:c})=>s.has(c.toLowerCase())?!1:(s.add(c.toLowerCase()),!0));return n&&n.length>0?n:[]}},tm=[N.CONNECTOR_ID.AUTH,N.CONNECTOR_ID.WALLET_CONNECT];class sm{constructor(e){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=s=>g.getCaipNetworks(s),this.getConnectorId=s=>D.getConnectorId(s),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get connections(){return this.availableConnections}get networks(){return this.getCaipNetworks(this.namespace)}onAuthConnected({accounts:e,chainId:s}){const n=this.getCaipNetworks().filter(r=>r.chainNamespace===this.namespace).find(r=>r.id.toString()===(s==null?void 0:s.toString()));e&&n&&this.addConnection({connectorId:N.CONNECTOR_ID.AUTH,accounts:e,caipNetwork:n})}setAuthProvider(e){e.onConnect(this.onAuthConnected.bind(this)),e.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:N.CONNECTOR_ID.AUTH,type:"AUTH",name:N.CONNECTOR_NAMES.AUTH,provider:e,imageId:void 0,chain:this.namespace,chains:[]})}addConnector(...e){const s=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(n=>s.has(n.id)?!1:(s.add(n.id),!0)),this.emit("connectors",this.availableConnectors)}addConnection(...e){const s=new Set;this.availableConnections=[...e,...this.availableConnections].filter(n=>s.has(n.connectorId.toLowerCase())?!1:(s.add(n.connectorId.toLowerCase()),!0)),this.emit("connections",this.availableConnections)}deleteConnection(e){this.availableConnections=this.availableConnections.filter(s=>s.connectorId.toLowerCase()!==e.toLowerCase()),this.emit("connections",this.availableConnections)}clearConnections(e=!1){this.availableConnections=[],e&&this.emit("connections",this.availableConnections)}setStatus(e,s){g.setAccountProp("status",e,s)}on(e,s){var n;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(n=this.eventListeners.get(e))==null||n.add(s)}off(e,s){const n=this.eventListeners.get(e);n&&n.delete(s)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const n=this.eventListeners.get(e);n&&n.forEach(r=>r(s))}async connectWalletConnect(e){try{return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}catch(s){throw Qs.isUserRejectedRequestError(s)?new ku(s):s}}async switchNetwork(e){var i;const{caipNetwork:s}=e,n=$e.getProviderId(s.chainNamespace),r=$e.getProvider(s.chainNamespace);if(!r)throw new Error("Provider not found");if(n==="WALLET_CONNECT"){r.setDefaultChain(s.caipNetworkId);return}if(n==="AUTH"){const o=(i=D.getAuthConnector())==null?void 0:i.provider;if(!o)throw new Error("Auth provider not found");const a=Kt(s.chainNamespace);await o.switchNetwork({chainId:s.caipNetworkId});const c=await o.getUser({chainId:s.caipNetworkId,preferredAccountType:a});this.emit("switchNetwork",c)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s.id==="walletConnect");if(!e)throw new Error("WalletConnectConnector not found");return e}onConnect(e,s){if(e.length>0){const{address:n,chainId:r}=z.getAccount(e[0]),i=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===(r==null?void 0:r.toString())),o=this.connectors.find(a=>a.id===s);n&&(this.emit("accountChanged",{address:n,chainId:r,connector:o}),this.addConnection({connectorId:s,accounts:e.map(a=>{const{address:c}=z.getAccount(a);return{address:c}}),caipNetwork:i}))}}onAccountsChanged(e,s,n=!0){var r,i;if(e.length>0){const{address:o}=z.getAccount(e[0]),a=this.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors});o&&((r=this.getConnectorId(N.CHAIN.EVM))==null?void 0:r.toLowerCase())===s.toLowerCase()&&this.emit("accountChanged",{address:o,chainId:(i=a==null?void 0:a.caipNetwork)==null?void 0:i.id,connector:a==null?void 0:a.connector}),this.addConnection({connectorId:s,accounts:e.map(c=>{const{address:l}=z.getAccount(c);return{address:l}}),caipNetwork:a==null?void 0:a.caipNetwork})}else n&&this.onDisconnect(s)}onDisconnect(e){var s;this.removeProviderListeners(e),this.deleteConnection(e),((s=this.getConnectorId(N.CHAIN.EVM))==null?void 0:s.toLowerCase())===e.toLowerCase()&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(e,s){var o;const n=typeof e=="string"&&e.startsWith("0x")?parseInt(e,16).toString():e.toString(),r=this.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors}),i=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===n);r&&this.addConnection({connectorId:s,accounts:r.accounts,caipNetwork:i}),((o=this.getConnectorId(N.CHAIN.EVM))==null?void 0:o.toLowerCase())===s.toLowerCase()&&this.emit("switchNetwork",{chainId:n})}listenProviderEvents(e,s){if(tm.includes(e))return;const n=o=>this.onAccountsChanged(o,e),r=o=>this.onChainChanged(o,e),i=()=>this.onDisconnect(e);this.providerHandlers[e]||(s.on("disconnect",i),s.on("accountsChanged",n),s.on("chainChanged",r),this.providerHandlers[e]={provider:s,disconnect:i,accountsChanged:n,chainChanged:r})}removeProviderListeners(e){if(this.providerHandlers[e]){const{provider:s,disconnect:n,accountsChanged:r,chainChanged:i}=this.providerHandlers[e];s.removeListener("disconnect",n),s.removeListener("accountsChanged",r),s.removeListener("chainChanged",i),this.providerHandlers[e]=null}}emitFirstAvailableConnection(){var s;const e=this.getConnection({connections:this.connections,connectors:this.connectors});if(e){const[n]=e.accounts;this.emit("accountChanged",{address:n==null?void 0:n.address,chainId:(s=e.caipNetwork)==null?void 0:s.id,connector:e.connector})}}getConnection({address:e,connectorId:s,connections:n,connectors:r}){if(s){const o=n.find(l=>l.connectorId.toLowerCase()===s.toLowerCase());if(!o)return null;const a=r.find(l=>l.id.toLowerCase()===o.connectorId.toLowerCase()),c=e?o.accounts.find(l=>l.address.toLowerCase()===e.toLowerCase()):o.accounts[0];return{...o,account:c,connector:a}}const i=n.find(o=>o.accounts.length>0&&r.some(a=>a.id.toLowerCase()===o.connectorId.toLowerCase()));if(i){const[o]=i.accounts,a=r.find(c=>c.id.toLowerCase()===i.connectorId.toLowerCase());return{...i,account:o,connector:a}}return null}}let dn=null;const ts={getSIWX(){return I.state.siwx},async initializeIfEnabled(t=g.getActiveCaipAddress()){var i,o,a;const e=I.state.siwx;if(!(e&&t))return;const[s,n,r]=t.split(":");if(g.checkIfSupportedNetwork(s,`${s}:${n}`))try{if((i=I.state.remoteFeatures)!=null&&i.emailCapture){const l=(o=g.getAccountData(s))==null?void 0:o.user;await he.open({view:"DataCapture",data:{email:(l==null?void 0:l.email)??void 0}});return}if(dn&&await dn,(await e.getSessions(`${s}:${n}`,r)).length)return;await he.open({view:"SIWXSignMessage"})}catch(c){console.error("SIWXUtil:initializeIfEnabled",c),ce.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(c)}),await((a=B._getClient())==null?void 0:a.disconnect().catch(console.error)),ee.reset("Connect"),us.showError("A problem occurred while trying initialize authentication")}},async isAuthenticated(t=g.getActiveCaipAddress()){if(!I.state.siwx||!t)return!0;const{chainNamespace:s,chainId:n,address:r}=Qe.parseCaipAddress(t),i=`${s}:${n}`;return(await ts.getSessions({address:r,caipNetworkId:i})).length>0},async requestSignMessage(){const t=I.state.siwx,e=z.getPlainAddress(g.getActiveCaipAddress()),s=Mi(),n=B._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!n)throw new Error("No ConnectionController client found");try{const r=await t.createMessage({chainId:s.caipNetworkId,accountAddress:e}),i=r.toString();D.getConnectorId(s.chainNamespace)===N.CONNECTOR_ID.AUTH&&ee.pushTransactionStack({});const a=await n.signMessage(i);await t.addSession({data:r,message:i,signature:a}),g.setLastConnectedSIWECaipNetwork(s),he.close(),ce.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){(!he.state.open||ee.state.view==="ApproveTransaction")&&await he.open({view:"SIWXSignMessage"}),us.showError("Error signing message"),ce.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(r)}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){var t;try{const e=this.getSIWX();if((t=e==null?void 0:e.getRequired)==null?void 0:t.call(e)){const n=g.getLastConnectedSIWECaipNetwork();if(n){const r=await(e==null?void 0:e.getSessions(n==null?void 0:n.caipNetworkId,z.getPlainAddress(g.getActiveCaipAddress())||""));r&&r.length>0?await g.switchActiveNetwork(n):await B.disconnect()}else await B.disconnect()}else he.close();he.close(),ce.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getAllSessions(){const t=this.getSIWX(),e=g.getAllRequestedCaipNetworks(),s=[];return await Promise.all(e.map(async n=>{const r=await(t==null?void 0:t.getSessions(n.caipNetworkId,z.getPlainAddress(g.getActiveCaipAddress())||""));r&&s.push(...r)})),s},async getSessions(t){const e=I.state.siwx;let s=t==null?void 0:t.address;if(!s){const r=g.getActiveCaipAddress();s=z.getPlainAddress(r)}let n=t==null?void 0:t.caipNetworkId;if(!n){const r=g.getActiveCaipNetwork();n=r==null?void 0:r.caipNetworkId}return e&&s&&n?e.getSessions(n,s):[]},async isSIWXCloseDisabled(){var e;const t=this.getSIWX();if(t){const s=ee.state.view==="ApproveTransaction",n=ee.state.view==="SIWXSignMessage";if(s||n)return((e=t.getRequired)==null?void 0:e.call(t))&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:t,chainId:e,socialUri:s,preferredAccountType:n,chainNamespace:r}){var u;const i=ts.getSIWX(),o=Mi();if(!i||!r.includes(N.CHAIN.EVM)||(u=I.state.remoteFeatures)!=null&&u.emailCapture){const h=await t.connect({chainId:e,socialUri:s,preferredAccountType:n});return{address:h.address,chainId:h.chainId,accounts:h.accounts}}const a=`${r}:${e}`,c=await i.createMessage({chainId:a,accountAddress:"<<AccountAddress>>"}),l={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 t.connect({chainId:e,socialUri:s,siwxMessage:l,preferredAccountType:n});return l.accountAddress=d.address,l.serializedMessage=d.message||"",d.signature&&d.message&&await ts.addEmbeddedWalletSession(l,d.message,d.signature),g.setLastConnectedSIWECaipNetwork(o),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(t,e,s){if(dn)return dn;const n=ts.getSIWX();return n?(dn=n.addSession({data:t,message:e,signature:s}).finally(()=>{dn=null}),dn):Promise.resolve()},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){var l,d,u;const n=ts.getSIWX(),r=Mi(),i=new Set(e.map(h=>h.split(":")[0]));if(!n||i.size!==1||!i.has("eip155"))return!1;const o=await n.createMessage({chainId:((l=Mi())==null?void 0:l.caipNetworkId)||"",accountAddress:""}),a=await t.authenticate({nonce:o.nonce,domain:o.domain,uri:o.uri,exp:o.expirationTime,iat:o.issuedAt,nbf:o.notBefore,requestId:o.requestId,version:o.version,resources:o.resources,statement:o.statement,chainId:o.chainId,methods:s,chains:[o.chainId,...e.filter(h=>h!==o.chainId)]});us.showLoading("Authenticating...",{autoClose:!1});const c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:(d=a.session.peer.metadata.icons)==null?void 0:d[0],type:"WALLET_CONNECT"};if(g.setAccountProp("connectedWalletInfo",c,Array.from(i)[0]),(u=a==null?void 0:a.auths)!=null&&u.length){const h=a.auths.map(p=>{const f=t.client.formatAuthMessage({request:p.p,iss:p.p.iss});return{data:{...p.p,accountAddress:p.p.iss.split(":").slice(-1).join(""),chainId:p.p.iss.split(":").slice(2,4).join(":"),uri:p.p.aud,version:p.p.version||o.version,expirationTime:p.p.exp,issuedAt:p.p.iat,notBefore:p.p.nbf},message:f,signature:p.s.s,cacao:p}});try{await n.setSessions(h),r&&g.setLastConnectedSIWECaipNetwork(r),ce.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:ts.getSIWXEventProperties()})}catch(p){throw console.error("SIWX:universalProviderAuth - failed to set sessions",p),ce.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:ts.getSIWXEventProperties(p)}),await t.disconnect().catch(console.error),p}finally{us.hide()}}return!0},getSIWXEventProperties(t){var s;const e=g.state.activeChain;if(!e)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||"",isSmartAccount:Kt(e)===Wt.ACCOUNT_TYPES.SMART_ACCOUNT,message:t?z.parseError(t):void 0}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};class nm{constructor({provider:e,namespace:s}){this.id=N.CONNECTOR_ID.WALLET_CONNECT,this.name="WalletConnect",this.type="WALLET_CONNECT",this.imageId="ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",this.getCaipNetworks=g.getCaipNetworks.bind(g),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=s}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const s=this.getCaipNetworks(),n=I.state.universalProviderConfigOverride,r=Qs.createNamespaces(s,n);await this.provider.connect({optionalNamespaces:r})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(s=>s.caipNetworkId);return ts.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:rm})}}const rm=["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"],Yt=ke({message:"",variant:"info",open:!1}),im={state:Yt,subscribeKey(t,e){return tt(Yt,t,e)},open(t,e){const{debug:s}=I.state,{code:n,displayMessage:r,debugMessage:i}=t;r&&s&&(Yt.message=r,Yt.variant=e,Yt.open=!0),i&&console.error(typeof i=="function"?i():i,n?{code:n}:void 0)},warn(t,e,s){Yt.open=!0,Yt.message=t,Yt.variant="warning",e&&console.warn(e,s)},close(){Yt.open=!1,Yt.message="",Yt.variant="info"}},It=zt(im),om={network:"eip155:8453",asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},am={network:"eip155:84532",asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}};function cm(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Ge(t,...e){try{return cm(t(...e))}catch(s){return Promise.reject(s)}}function lm(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function dm(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function to(t){if(lm(t))return String(t);if(dm(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return to(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Wa="base64:";function um(t){return typeof t=="string"?t:Wa+fm(t)}function hm(t){return typeof t!="string"||!t.startsWith(Wa)?t:pm(t.slice(Wa.length))}function pm(t){return globalThis.Buffer?me.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function fm(t){return globalThis.Buffer?me.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function mt(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function gm(...t){return mt(t.join(":"))}function Fi(t){return t=mt(t),t?t+":":""}function mm(t,e){if(e===void 0)return!0;let s=0,n=t.indexOf(":");for(;n>-1;)s++,n=t.indexOf(":",n+1);return s<=e}function ym(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const wm="memory",bm=()=>{const t=new Map;return{name:wm,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,s){t.set(e,s)},setItemRaw(e,s){t.set(e,s)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Em(t={}){const e={mounts:{"":t.driver||bm()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},s=l=>{for(const d of e.mountpoints)if(l.startsWith(d))return{base:d,relativeKey:l.slice(d.length),driver:e.mounts[d]};return{base:"",relativeKey:l,driver:e.mounts[""]}},n=(l,d)=>e.mountpoints.filter(u=>u.startsWith(l)||d&&l.startsWith(u)).map(u=>({relativeBase:l.length>u.length?l.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(l,d)=>{if(e.watching){d=mt(d);for(const u of e.watchListeners)u(l,d)}},i=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await wl(e.mounts[l],r,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,d,u)=>{const h=new Map,p=f=>{let m=h.get(f.base);return m||(m={driver:f.driver,base:f.base,items:[]},h.set(f.base,m)),m};for(const f of l){const m=typeof f=="string",y=mt(m?f:f.key),w=m?void 0:f.value,b=m||!f.options?d:{...d,...f.options},A=s(y);p(A).items.push({key:y,value:w,relativeKey:A.relativeKey,options:b})}return Promise.all([...h.values()].map(f=>u(f))).then(f=>f.flat())},c={hasItem(l,d={}){l=mt(l);const{relativeKey:u,driver:h}=s(l);return Ge(h.hasItem,u,d)},getItem(l,d={}){l=mt(l);const{relativeKey:u,driver:h}=s(l);return Ge(h.getItem,u,d).then(p=>Oi(p))},getItems(l,d={}){return a(l,d,u=>u.driver.getItems?Ge(u.driver.getItems,u.items.map(h=>({key:h.relativeKey,options:h.options})),d).then(h=>h.map(p=>({key:gm(u.base,p.key),value:Oi(p.value)}))):Promise.all(u.items.map(h=>Ge(u.driver.getItem,h.relativeKey,h.options).then(p=>({key:h.key,value:Oi(p)})))))},getItemRaw(l,d={}){l=mt(l);const{relativeKey:u,driver:h}=s(l);return h.getItemRaw?Ge(h.getItemRaw,u,d):Ge(h.getItem,u,d).then(p=>hm(p))},async setItem(l,d,u={}){if(d===void 0)return c.removeItem(l);l=mt(l);const{relativeKey:h,driver:p}=s(l);p.setItem&&(await Ge(p.setItem,h,to(d),u),p.watch||r("update",l))},async setItems(l,d){await a(l,d,async u=>{if(u.driver.setItems)return Ge(u.driver.setItems,u.items.map(h=>({key:h.relativeKey,value:to(h.value),options:h.options})),d);u.driver.setItem&&await Promise.all(u.items.map(h=>Ge(u.driver.setItem,h.relativeKey,to(h.value),h.options)))})},async setItemRaw(l,d,u={}){if(d===void 0)return c.removeItem(l,u);l=mt(l);const{relativeKey:h,driver:p}=s(l);if(p.setItemRaw)await Ge(p.setItemRaw,h,d,u);else if(p.setItem)await Ge(p.setItem,h,um(d),u);else return;p.watch||r("update",l)},async removeItem(l,d={}){typeof d=="boolean"&&(d={removeMeta:d}),l=mt(l);const{relativeKey:u,driver:h}=s(l);h.removeItem&&(await Ge(h.removeItem,u,d),(d.removeMeta||d.removeMata)&&await Ge(h.removeItem,u+"$",d),h.watch||r("remove",l))},async getMeta(l,d={}){typeof d=="boolean"&&(d={nativeOnly:d}),l=mt(l);const{relativeKey:u,driver:h}=s(l),p=Object.create(null);if(h.getMeta&&Object.assign(p,await Ge(h.getMeta,u,d)),!d.nativeOnly){const f=await Ge(h.getItem,u+"$",d).then(m=>Oi(m));f&&typeof f=="object"&&(typeof f.atime=="string"&&(f.atime=new Date(f.atime)),typeof f.mtime=="string"&&(f.mtime=new Date(f.mtime)),Object.assign(p,f))}return p},setMeta(l,d,u={}){return this.setItem(l+"$",d,u)},removeMeta(l,d={}){return this.removeItem(l+"$",d)},async getKeys(l,d={}){var y;l=Fi(l);const u=n(l,!0);let h=[];const p=[];let f=!0;for(const w of u){(y=w.driver.flags)!=null&&y.maxDepth||(f=!1);const b=await Ge(w.driver.getKeys,w.relativeBase,d);for(const A of b){const k=w.mountpoint+mt(A);h.some($=>k.startsWith($))||p.push(k)}h=[w.mountpoint,...h.filter(A=>!A.startsWith(w.mountpoint))]}const m=d.maxDepth!==void 0&&!f;return p.filter(w=>(!m||mm(w,d.maxDepth))&&ym(w,l))},async clear(l,d={}){l=Fi(l),await Promise.all(n(l,!1).map(async u=>{if(u.driver.clear)return Ge(u.driver.clear,u.relativeBase,d);if(u.driver.removeItem){const h=await u.driver.getKeys(u.relativeBase||"",d);return Promise.all(h.map(p=>u.driver.removeItem(p,d)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>bl(l)))},async watch(l){return await i(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(d=>d!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,d){if(l=Fi(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((u,h)=>h.length-u.length)),e.mounts[l]=d,e.watching&&Promise.resolve(wl(d,r,l)).then(u=>{e.unwatch[l]=u}).catch(console.error),c},async unmount(l,d=!0){var u,h;l=Fi(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&((h=(u=e.unwatch)[l])==null||h.call(u),delete e.unwatch[l]),d&&await bl(e.mounts[l]),e.mountpoints=e.mountpoints.filter(p=>p!==l),delete e.mounts[l])},getMount(l=""){l=mt(l)+":";const d=s(l);return{driver:d.driver,base:d.base}},getMounts(l="",d={}){return l=mt(l),n(l,d.parents).map(h=>({driver:h.driver,base:h.mountpoint}))},keys:(l,d={})=>c.getKeys(l,d),get:(l,d={})=>c.getItem(l,d),set:(l,d,u={})=>c.setItem(l,d,u),has:(l,d={})=>c.hasItem(l,d),del:(l,d={})=>c.removeItem(l,d),remove:(l,d={})=>c.removeItem(l,d)};return c}function wl(t,e,s){return t.watch?t.watch((n,r)=>e(n,s+r)):()=>{}}async function bl(t){typeof t.dispose=="function"&&await Ge(t.dispose)}const Cm="idb-keyval";var vm=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",s=r=>e+r;let n;return t.dbName&&t.storeName&&(n=Yp(t.dbName,t.storeName)),{name:Cm,options:t,async hasItem(r){return!(typeof await tl(s(r),n)>"u")},async getItem(r){return await tl(s(r),n)??null},setItem(r,i){return Jp(s(r),i,n)},removeItem(r){return Xp(s(r),n)},getKeys(){return Zp(n)},clear(){return Qp(n)}}};const Am="WALLET_CONNECT_V2_INDEXED_DB",_m="keyvaluestorage";let Im=class{constructor(){this.indexedDb=Em({driver:vm({dbName:Am,storeName:_m})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const s=await this.indexedDb.getItem(e);if(s!==null)return s}async setItem(e,s){await this.indexedDb.setItem(e,_c(s))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ea=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof ie<"u"?ie:typeof self<"u"?self:{},so={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(s){return this.hasOwnProperty(s)?String(this[s]):null},t.prototype.setItem=function(s,n){this[s]=String(n)},t.prototype.removeItem=function(s){delete this[s]},t.prototype.clear=function(){const s=this;Object.keys(s).forEach(function(n){s[n]=void 0,delete s[n]})},t.prototype.key=function(s){return s=s||0,Object.keys(this)[s]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ea<"u"&&ea.localStorage?so.exports=ea.localStorage:typeof window<"u"&&window.localStorage?so.exports=window.localStorage:so.exports=new e})();function Nm(t){var e;return[t[0],uo((e=t[1])!=null?e:"")]}let Sm=class{constructor(){this.localStorage=so.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Nm)}async getItem(e){const s=this.localStorage.getItem(e);if(s!==null)return uo(s)}async setItem(e,s){this.localStorage.setItem(e,_c(s))}async removeItem(e){this.localStorage.removeItem(e)}};const Tm="wc_storage_version",El=1,Om=async(t,e,s)=>{const n=Tm,r=await e.getItem(n);if(r&&r>=El){s(e);return}const i=await t.getKeys();if(!i.length){s(e);return}const o=[];for(;i.length;){const a=i.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(n,El),s(e),Rm(t,o)},Rm=async(t,e)=>{e.length&&e.forEach(async s=>{await t.removeItem(s)})};let Pm=class{constructor(){this.initialized=!1,this.setInitialized=s=>{this.storage=s,this.initialized=!0};const e=new Sm;this.storage=e;try{const s=new Im;Om(e,s,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(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,s){return await this.initialize(),this.storage.setItem(e,s)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const s=setInterval(()=>{this.initialized&&(clearInterval(s),e())},20)})}};var km=Object.defineProperty,xm=(t,e,s)=>e in t?km(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Cl=(t,e,s)=>xm(t,typeof e!="symbol"?e+"":e,s);let $m=class extends ur{constructor(e){super(),this.opts=e,Cl(this,"protocol","wc"),Cl(this,"version",2)}};var Um=Object.defineProperty,Dm=(t,e,s)=>e in t?Um(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Mm=(t,e,s)=>Dm(t,typeof e!="symbol"?e+"":e,s);let Lm=class extends ur{constructor(e,s){super(),this.core=e,this.logger=s,Mm(this,"records",new Map)}},Fm=class{constructor(e,s){this.logger=e,this.core=s}},Bm=class extends ur{constructor(e,s){super(),this.relayer=e,this.logger=s}},jm=class extends ur{constructor(e){super()}},qm=class{constructor(e,s,n,r){this.core=e,this.logger=s,this.name=n}},Wm=class extends ur{constructor(e,s){super(),this.relayer=e,this.logger=s}},Hm=class extends ur{constructor(e,s){super(),this.core=e,this.logger=s}},Km=class{constructor(e,s,n){this.core=e,this.logger=s,this.store=n}},Vm=class{constructor(e,s){this.projectId=e,this.logger=s}},zm=class{constructor(e,s,n){this.core=e,this.logger=s,this.telemetryEnabled=n}};var Gm=Object.defineProperty,Ym=(t,e,s)=>e in t?Gm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vl=(t,e,s)=>Ym(t,typeof e!="symbol"?e+"":e,s);let Jm=class{constructor(e){this.opts=e,vl(this,"protocol","wc"),vl(this,"version",2)}},Xm=class{constructor(e){this.client=e}};/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Zm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Qu(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(s=>typeof s=="string"):e.every(s=>Number.isSafeInteger(s)):!1}function mo(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function xc(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Ha(t){if(!Array.isArray(t))throw new Error("array expected")}function yo(t,e){if(!Qu(!0,e))throw new Error(`${t}: array of strings expected`)}function Qm(t,e){if(!Qu(!1,e))throw new Error(`${t}: array of numbers expected`)}function ey(...t){const e=i=>i,s=(i,o)=>a=>i(o(a)),n=t.map(i=>i.encode).reduceRight(s,e),r=t.map(i=>i.decode).reduce(s,e);return{encode:n,decode:r}}function ty(t){const e=typeof t=="string"?t.split(""):t,s=e.length;yo("alphabet",e);const n=new Map(e.map((r,i)=>[r,i]));return{encode:r=>(Ha(r),r.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=s)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:r=>(Ha(r),r.map(i=>{mo("alphabet.decode",i);const o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return o}))}}function sy(t=""){return mo("join",t),{encode:e=>(yo("join.decode",e),e.join(t)),decode:e=>(mo("join.decode",e),e.split(t))}}function ny(t,e="="){return xc(t),mo("padding",e),{encode(s){for(yo("padding.encode",s);s.length*t%8;)s.push(e);return s},decode(s){yo("padding.decode",s);let n=s.length;if(n*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&s[n-1]===e;n--)if((n-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return s.slice(0,n)}}}const eh=(t,e)=>e===0?t:eh(e,t%e),wo=(t,e)=>t+(e-eh(t,e)),ta=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Al(t,e,s,n){if(Ha(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(s<=0||s>32)throw new Error(`convertRadix2: wrong to=${s}`);if(wo(e,s)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${s} carryBits=${wo(e,s)}`);let r=0,i=0;const o=ta[e],a=ta[s]-1,c=[];for(const l of t){if(xc(l),l>=o)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(r=r<<e|l,i+e>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=s;i-=s)c.push((r>>i-s&a)>>>0);const d=ta[i];if(d===void 0)throw new Error("invalid carry");r&=d-1}if(r=r<<s-i&a,!n&&i>=e)throw new Error("Excess padding");if(!n&&r>0)throw new Error(`Non-zero padding: ${r}`);return n&&i>0&&c.push(r>>>0),c}function ry(t,e=!1){if(xc(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(wo(8,t)>32||wo(t,8)>32)throw new Error("radix2: carry overflow");return{encode:s=>{if(!Zm(s))throw new Error("radix2.encode input should be Uint8Array");return Al(Array.from(s),8,t,!e)},decode:s=>(Qm("radix2.decode",s),Uint8Array.from(Al(s,t,8,e)))}}const iy=ey(ry(5),ty("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ny(5),sy("")),oy=":";function Rs(t){const[e,s]=t.split(oy);return{namespace:e,reference:s}}function th(t,e){return t.includes(":")?[t]:e.chains||[]}var ay=Object.defineProperty,cy=Object.defineProperties,ly=Object.getOwnPropertyDescriptors,_l=Object.getOwnPropertySymbols,dy=Object.prototype.hasOwnProperty,uy=Object.prototype.propertyIsEnumerable,Ka=(t,e,s)=>e in t?ay(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Il=(t,e)=>{for(var s in e||(e={}))dy.call(e,s)&&Ka(t,s,e[s]);if(_l)for(var s of _l(e))uy.call(e,s)&&Ka(t,s,e[s]);return t},hy=(t,e)=>cy(t,ly(e)),Nl=(t,e,s)=>Ka(t,typeof e!="symbol"?e+"":e,s);const py="ReactNative",Rt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},fy="js";function bo(){return typeof Os<"u"&&typeof Os.versions<"u"&&typeof Os.versions.node<"u"}function on(){return!nr()&&!!Nu()&&navigator.product===py}function gy(){return on()&&typeof ie<"u"&&typeof(ie==null?void 0:ie.Platform)<"u"&&(ie==null?void 0:ie.Platform.OS)==="android"}function my(){return on()&&typeof ie<"u"&&typeof(ie==null?void 0:ie.Platform)<"u"&&(ie==null?void 0:ie.Platform.OS)==="ios"}function gr(){return!bo()&&!!Nu()&&!!nr()}function vi(){return on()?Rt.reactNative:bo()?Rt.node:gr()?Rt.browser:Rt.unknown}function Sl(){var t;try{return on()&&typeof ie<"u"&&typeof(ie==null?void 0:ie.Application)<"u"?(t=ie.Application)==null?void 0:t.applicationId:void 0}catch{return}}function yy(t,e){const s=new URLSearchParams(t);return Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!=null&&s.set(n,String(r))}),s.toString()}function wy(t){var e,s;const n=sh();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(r=>r!=="")),hy(Il(Il({},n),t),{url:(t==null?void 0:t.url)||n.url,name:(t==null?void 0:t.name)||n.name,description:(t==null?void 0:t.description)||n.description,icons:(s=t==null?void 0:t.icons)!=null&&s.length&&t.icons.length>0?t.icons:n.icons})}catch(r){return console.warn("Error populating app metadata",r),t||n}}function sh(){return ef()||{name:"",description:"",url:"",icons:[""]}}function by(){if(vi()===Rt.reactNative&&typeof ie<"u"&&typeof(ie==null?void 0:ie.Platform)<"u"){const{OS:s,Version:n}=ie.Platform;return[s,n].join("-")}const t=af();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function Ey(){var t;const e=vi();return e===Rt.browser?[e,((t=cf())==null?void 0:t.host)||"unknown"].join(":"):e}function nh(t,e,s){const n=by(),r=Ey();return[[t,e].join("-"),[fy,s].join("-"),n,r].join("/")}function Cy({protocol:t,version:e,relayUrl:s,sdkVersion:n,auth:r,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d=nh(t,e,n),u={auth:r,ua:d,projectId:i,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=yy(l[1]||"",u);return l[0]+"?"+h}function vn(t,e){return t.filter(s=>e.includes(s)).length===t.length}function Va(t){return Object.fromEntries(t.entries())}function za(t){return new Map(Object.entries(t))}function mn(t=j.FIVE_MINUTES,e){const s=j.toMiliseconds(t||j.FIVE_MINUTES);let n,r,i,o;return{resolve:a=>{i&&n&&(clearTimeout(i),n(a),o=Promise.resolve(a))},reject:a=>{i&&r&&(clearTimeout(i),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);i=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),n=a,r=c})}}function hs(t,e,s){return new Promise(async(n,r)=>{const i=setTimeout(()=>r(new Error(s)),e);try{const o=await t;n(o)}catch(o){r(o)}clearTimeout(i)})}function rh(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function vy(t){return rh("topic",t)}function Ay(t){return rh("id",t)}function ih(t){const[e,s]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")n.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))n.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return n}function je(t,e){return j.fromMiliseconds((e||Date.now())+j.toMiliseconds(t))}function ds(t){return Date.now()>=j.toMiliseconds(t)}function Ne(t,e){return`${t}${e?`:${e}`:""}`}function fs(t=[],e=[]){return[...new Set([...t,...e])]}async function _y({id:t,topic:e,wcDeepLink:s}){var n;try{if(!s)return;const r=typeof s=="string"?JSON.parse(s):s,i=r==null?void 0:r.href;if(typeof i!="string")return;const o=Iy(i,t,e),a=vi();if(a===Rt.browser){if(!((n=nr())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Ny(o)}else a===Rt.reactNative&&typeof(ie==null?void 0:ie.Linking)<"u"&&await ie.Linking.openURL(o)}catch(r){console.error(r)}}function Iy(t,e,s){const n=`requestId=${e}&sessionTopic=${s}`;t.endsWith("/")&&(t=t.slice(0,-1));let r=`${t}`;if(t.startsWith("https://t.me")){const i=t.includes("?")?"&startapp=":"?startapp=";r=`${r}${i}${Ry(n,!0)}`}else r=`${r}/wc?${n}`;return r}function Ny(t){let e="_self";Oy()?e="_top":(Ty()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function Sy(t,e){let s="";try{if(gr()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(n){console.error(n)}return s}function Tl(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),n=s.indexOf(e);return s[n+2]}function Ol(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function $c(){return typeof Os<"u"&&{}.IS_VITEST==="true"}function Ty(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Oy(){try{return window.self!==window.top}catch{return!1}}function Ry(t,e=!1){const s=me.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function oh(t){return me.from(t,"base64").toString("utf-8")}function Py(t){return new Promise(e=>setTimeout(e,t))}let ky=class{constructor({limit:e}){Nl(this,"limit"),Nl(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const s=this.set.values().next().value;s&&this.set.delete(s)}this.set.add(e)}}has(e){return this.set.has(e)}};const Bi=BigInt(2**32-1),Rl=BigInt(32);function ah(t,e=!1){return e?{h:Number(t&Bi),l:Number(t>>Rl&Bi)}:{h:Number(t>>Rl&Bi)|0,l:Number(t&Bi)|0}}function ch(t,e=!1){const s=t.length;let n=new Uint32Array(s),r=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=ah(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const Pl=(t,e,s)=>t>>>s,kl=(t,e,s)=>t<<32-s|e>>>s,Hs=(t,e,s)=>t>>>s|e<<32-s,Ks=(t,e,s)=>t<<32-s|e>>>s,Or=(t,e,s)=>t<<64-s|e>>>s-32,Rr=(t,e,s)=>t>>>s-32|e<<64-s,xy=(t,e)=>e,$y=(t,e)=>t,Uy=(t,e,s)=>t<<s|e>>>32-s,Dy=(t,e,s)=>e<<s|t>>>32-s,My=(t,e,s)=>e<<s-32|t>>>64-s,Ly=(t,e,s)=>t<<s-32|e>>>64-s;function Qt(t,e,s,n){const r=(e>>>0)+(n>>>0);return{h:t+s+(r/2**32|0)|0,l:r|0}}const Uc=(t,e,s)=>(t>>>0)+(e>>>0)+(s>>>0),Dc=(t,e,s,n)=>e+s+n+(t/2**32|0)|0,Fy=(t,e,s,n)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0),By=(t,e,s,n,r)=>e+s+n+r+(t/2**32|0)|0,jy=(t,e,s,n,r)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0)+(r>>>0),qy=(t,e,s,n,r,i)=>e+s+n+r+i+(t/2**32|0)|0,Fn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function xo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xs(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ns(t,...e){if(!xo(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function $o(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");xs(t.outputLen),xs(t.blockLen)}function nn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Mc(t,e){ns(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function hi(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Vt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function sa(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function rs(t,e){return t<<32-e|t>>>e}const lh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function dh(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Cs=lh?t=>t:t=>dh(t);function Wy(t){for(let e=0;e<t.length;e++)t[e]=dh(t[e]);return t}const Vs=lh?t=>t:Wy,uh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Hy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Zn(t){if(ns(t),uh)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=Hy[t[s]];return e}const bs={_0:48,_9:57,A:65,F:70,a:97,f:102};function xl(t){if(t>=bs._0&&t<=bs._9)return t-bs._0;if(t>=bs.A&&t<=bs.F)return t-(bs.A-10);if(t>=bs.a&&t<=bs.f)return t-(bs.a-10)}function Eo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(uh)return Uint8Array.fromHex(t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=xl(t.charCodeAt(i)),a=xl(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[r]=o*16+a}return n}function hh(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ss(t){return typeof t=="string"&&(t=hh(t)),ns(t),t}function zs(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];ns(r),e+=r.length}const s=new Uint8Array(e);for(let n=0,r=0;n<t.length;n++){const i=t[n];s.set(i,r),r+=i.length}return s}class Uo{}function Ai(t){const e=n=>t().update(ss(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function Ky(t){const e=(n,r)=>t(r).update(ss(n)).digest(),s=t({});return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}function Un(t=32){if(Fn&&typeof Fn.getRandomValues=="function")return Fn.getRandomValues(new Uint8Array(t));if(Fn&&typeof Fn.randomBytes=="function")return Uint8Array.from(Fn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Vy=BigInt(0),br=BigInt(1),zy=BigInt(2),Gy=BigInt(7),Yy=BigInt(256),Jy=BigInt(113),ph=[],fh=[],gh=[];for(let t=0,e=br,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],ph.push(2*(5*n+s)),fh.push((t+1)*(t+2)/2%64);let r=Vy;for(let i=0;i<7;i++)e=(e<<br^(e>>Gy)*Jy)%Yy,e&zy&&(r^=br<<(br<<BigInt(i))-br);gh.push(r)}const mh=ch(gh,!0),Xy=mh[0],Zy=mh[1],$l=(t,e,s)=>s>32?My(t,e,s):Uy(t,e,s),Ul=(t,e,s)=>s>32?Ly(t,e,s):Dy(t,e,s);function Qy(t,e=24){const s=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],d=s[c+1],u=$l(l,d,1)^s[a],h=Ul(l,d,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=fh[o],c=$l(r,i,a),l=Ul(r,i,a),d=ph[o];r=t[d],i=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=Xy[n],t[1]^=Zy[n]}Vt(s)}let ew=class yh extends Uo{constructor(e,s,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=s,this.outputLen=n,this.enableXOF=r,this.rounds=i,xs(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=hi(this.state)}clone(){return this._cloneInto()}keccak(){Vs(this.state32),Qy(this.state32,this.rounds),Vs(this.state32),this.posOut=0,this.pos=0}update(e){nn(this),e=ss(e),ns(e);const{blockLen:s,state:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:n,blockLen:r}=this;e[n]^=s,s&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){nn(this,!1),ns(e),this.finish();const s=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(s.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return xs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Mc(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Vt(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new yh(s,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const tw=(t,e,s)=>Ai(()=>new ew(e,t,s)),sw=tw(1,136,256/8);function nw(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function rw(t,e,s){return t&e^~t&s}function iw(t,e,s){return t&e^t&s^e&s}let wh=class extends Uo{constructor(e,s,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=s,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=sa(this.buffer)}update(e){nn(this),e=ss(e),ns(e);const{view:s,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(r-this.pos,i-o);if(a===r){const c=sa(e);for(;r<=i-o;o+=r)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){nn(this),Mc(e,this),this.finished=!0;const{buffer:s,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,Vt(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)s[u]=0;nw(n,r-8,BigInt(this.length*8),i),this.process(n,0);const a=sa(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=a,r%s&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const Ls=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),nt=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),rt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ow=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]),Fs=new Uint32Array(64);class aw extends wh{constructor(e=32){super(64,e,8,!1),this.A=Ls[0]|0,this.B=Ls[1]|0,this.C=Ls[2]|0,this.D=Ls[3]|0,this.E=Ls[4]|0,this.F=Ls[5]|0,this.G=Ls[6]|0,this.H=Ls[7]|0}get(){const{A:e,B:s,C:n,D:r,E:i,F:o,G:a,H:c}=this;return[e,s,n,r,i,o,a,c]}set(e,s,n,r,i,o,a,c){this.A=e|0,this.B=s|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let u=0;u<16;u++,s+=4)Fs[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const h=Fs[u-15],p=Fs[u-2],f=rs(h,7)^rs(h,18)^h>>>3,m=rs(p,17)^rs(p,19)^p>>>10;Fs[u]=m+Fs[u-7]+f+Fs[u-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=rs(a,6)^rs(a,11)^rs(a,25),p=d+h+rw(a,c,l)+ow[u]+Fs[u]|0,f=(rs(n,2)^rs(n,13)^rs(n,22))+iw(n,r,i)|0;d=l,l=c,c=a,a=o+p|0,o=i,i=r,r=n,n=p+f|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,r,i,o,a,c,l,d)}roundClean(){Vt(Fs)}destroy(){this.set(0,0,0,0,0,0,0,0),Vt(this.buffer)}}const bh=ch(["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(t=>BigInt(t))),cw=bh[0],lw=bh[1],Bs=new Uint32Array(80),js=new Uint32Array(80);let Lc=class extends wh{constructor(e=64){super(128,e,16,!1),this.Ah=rt[0]|0,this.Al=rt[1]|0,this.Bh=rt[2]|0,this.Bl=rt[3]|0,this.Ch=rt[4]|0,this.Cl=rt[5]|0,this.Dh=rt[6]|0,this.Dl=rt[7]|0,this.Eh=rt[8]|0,this.El=rt[9]|0,this.Fh=rt[10]|0,this.Fl=rt[11]|0,this.Gh=rt[12]|0,this.Gl=rt[13]|0,this.Hh=rt[14]|0,this.Hl=rt[15]|0}get(){const{Ah:e,Al:s,Bh:n,Bl:r,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:h,Gh:p,Gl:f,Hh:m,Hl:y}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,f,m,y]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,f,m,y){this.Ah=e|0,this.Al=s|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=h|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=y|0}process(e,s){for(let A=0;A<16;A++,s+=4)Bs[A]=e.getUint32(s),js[A]=e.getUint32(s+=4);for(let A=16;A<80;A++){const k=Bs[A-15]|0,$=js[A-15]|0,M=Hs(k,$,1)^Hs(k,$,8)^Pl(k,$,7),H=Ks(k,$,1)^Ks(k,$,8)^kl(k,$,7),G=Bs[A-2]|0,P=js[A-2]|0,Q=Hs(G,P,19)^Or(G,P,61)^Pl(G,P,6),se=Ks(G,P,19)^Rr(G,P,61)^kl(G,P,6),T=Fy(H,se,js[A-7],js[A-16]),E=By(T,M,Q,Bs[A-7],Bs[A-16]);Bs[A]=E|0,js[A]=T|0}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:h,Fh:p,Fl:f,Gh:m,Gl:y,Hh:w,Hl:b}=this;for(let A=0;A<80;A++){const k=Hs(u,h,14)^Hs(u,h,18)^Or(u,h,41),$=Ks(u,h,14)^Ks(u,h,18)^Rr(u,h,41),M=u&p^~u&m,H=h&f^~h&y,G=jy(b,$,H,lw[A],js[A]),P=qy(G,w,k,M,cw[A],Bs[A]),Q=G|0,se=Hs(n,r,28)^Or(n,r,34)^Or(n,r,39),T=Ks(n,r,28)^Rr(n,r,34)^Rr(n,r,39),E=n&i^n&a^i&a,C=r&o^r&c^o&c;w=m|0,b=y|0,m=p|0,y=f|0,p=u|0,f=h|0,{h:u,l:h}=Qt(l|0,d|0,P|0,Q|0),l=a|0,d=c|0,a=i|0,c=o|0,i=n|0,o=r|0;const v=Uc(Q,T,C);n=Dc(v,P,se,E),r=v|0}({h:n,l:r}=Qt(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:o}=Qt(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Qt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Qt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:h}=Qt(this.Eh|0,this.El|0,u|0,h|0),{h:p,l:f}=Qt(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:y}=Qt(this.Gh|0,this.Gl|0,m|0,y|0),{h:w,l:b}=Qt(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,r,i,o,a,c,l,d,u,h,p,f,m,y,w,b)}roundClean(){Vt(Bs,js)}destroy(){Vt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class dw extends Lc{constructor(){super(48),this.Ah=nt[0]|0,this.Al=nt[1]|0,this.Bh=nt[2]|0,this.Bl=nt[3]|0,this.Ch=nt[4]|0,this.Cl=nt[5]|0,this.Dh=nt[6]|0,this.Dl=nt[7]|0,this.Eh=nt[8]|0,this.El=nt[9]|0,this.Fh=nt[10]|0,this.Fl=nt[11]|0,this.Gh=nt[12]|0,this.Gl=nt[13]|0,this.Hh=nt[14]|0,this.Hl=nt[15]|0}}const it=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class uw extends Lc{constructor(){super(32),this.Ah=it[0]|0,this.Al=it[1]|0,this.Bh=it[2]|0,this.Bl=it[3]|0,this.Ch=it[4]|0,this.Cl=it[5]|0,this.Dh=it[6]|0,this.Dl=it[7]|0,this.Eh=it[8]|0,this.El=it[9]|0,this.Fh=it[10]|0,this.Fl=it[11]|0,this.Gh=it[12]|0,this.Gl=it[13]|0,this.Hh=it[14]|0,this.Hl=it[15]|0}}const Do=Ai(()=>new aw),hw=Ai(()=>new Lc),pw=Ai(()=>new dw),fw=Ai(()=>new uw),gw=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]),He=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),W=new Uint32Array(32);function qs(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=W[2*t],l=W[2*t+1],d=W[2*e],u=W[2*e+1],h=W[2*s],p=W[2*s+1],f=W[2*n],m=W[2*n+1],y=Uc(c,d,o);l=Dc(y,l,u,a),c=y|0,{Dh:m,Dl:f}={Dh:m^l,Dl:f^c},{Dh:m,Dl:f}={Dh:xy(m,f),Dl:$y(m)},{h:p,l:h}=Qt(p,h,m,f),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:Hs(u,d,24),Bl:Ks(u,d,24)},W[2*t]=c,W[2*t+1]=l,W[2*e]=d,W[2*e+1]=u,W[2*s]=h,W[2*s+1]=p,W[2*n]=f,W[2*n+1]=m}function Ws(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=W[2*t],l=W[2*t+1],d=W[2*e],u=W[2*e+1],h=W[2*s],p=W[2*s+1],f=W[2*n],m=W[2*n+1],y=Uc(c,d,o);l=Dc(y,l,u,a),c=y|0,{Dh:m,Dl:f}={Dh:m^l,Dl:f^c},{Dh:m,Dl:f}={Dh:Hs(m,f,16),Dl:Ks(m,f,16)},{h:p,l:h}=Qt(p,h,m,f),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:Or(u,d,63),Bl:Rr(u,d,63)},W[2*t]=c,W[2*t+1]=l,W[2*e]=d,W[2*e+1]=u,W[2*s]=h,W[2*s+1]=p,W[2*n]=f,W[2*n+1]=m}function mw(t,e={},s,n,r){if(xs(s),t<0||t>s)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.length>s))throw new Error("key length must be undefined or 1.."+s);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==r)throw new Error("personalization must be undefined or "+r)}class yw extends Uo{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,xs(e),xs(s),this.blockLen=e,this.outputLen=s,this.buffer=new Uint8Array(e),this.buffer32=hi(this.buffer)}update(e){nn(this),e=ss(e),ns(e);const{blockLen:s,buffer:n,buffer32:r}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===s&&(Vs(r),this.compress(r,0,!1),Vs(r),this.pos=0);const l=Math.min(s-this.pos,i-c),d=o+c;if(l===s&&!(d%4)&&c+l<i){const u=new Uint32Array(a,d,Math.floor((i-c)/4));Vs(u);for(let h=0;c+s<i;h+=r.length,c+=s)this.length+=s,this.compress(u,h,!1);Vs(u);continue}n.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){nn(this),Mc(e,this);const{pos:s,buffer32:n}=this;this.finished=!0,Vt(this.buffer.subarray(s)),Vs(n),this.compress(n,0,!0),Vs(n);const r=hi(e);this.get().forEach((i,o)=>r[o]=Cs(i))}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){const{buffer:s,length:n,finished:r,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(s),e.destroyed=i,e.finished=r,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class ww extends yw{constructor(e={}){const s=e.dkLen===void 0?64:e.dkLen;super(128,s),this.v0l=He[0]|0,this.v0h=He[1]|0,this.v1l=He[2]|0,this.v1h=He[3]|0,this.v2l=He[4]|0,this.v2h=He[5]|0,this.v3l=He[6]|0,this.v3h=He[7]|0,this.v4l=He[8]|0,this.v4h=He[9]|0,this.v5l=He[10]|0,this.v5h=He[11]|0,this.v6l=He[12]|0,this.v6h=He[13]|0,this.v7l=He[14]|0,this.v7h=He[15]|0,mw(s,e,64,16,16);let{key:n,personalization:r,salt:i}=e,o=0;if(n!==void 0&&(n=ss(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=ss(i);const a=hi(i);this.v4l^=Cs(a[0]),this.v4h^=Cs(a[1]),this.v5l^=Cs(a[2]),this.v5h^=Cs(a[3])}if(r!==void 0){r=ss(r);const a=hi(r);this.v6l^=Cs(a[0]),this.v6h^=Cs(a[1]),this.v7l^=Cs(a[2]),this.v7h^=Cs(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:s,v1l:n,v1h:r,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:d,v5l:u,v5h:h,v6l:p,v6h:f,v7l:m,v7h:y}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,f,m,y]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,f,m,y){this.v0l=e|0,this.v0h=s|0,this.v1l=n|0,this.v1h=r|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=d|0,this.v5l=u|0,this.v5h=h|0,this.v6l=p|0,this.v6h=f|0,this.v7l=m|0,this.v7h=y|0}compress(e,s,n){this.get().forEach((c,l)=>W[l]=c),W.set(He,16);let{h:r,l:i}=ah(BigInt(this.length));W[24]=He[8]^i,W[25]=He[9]^r,n&&(W[28]=~W[28],W[29]=~W[29]);let o=0;const a=gw;for(let c=0;c<12;c++)qs(0,4,8,12,e,s+2*a[o++]),Ws(0,4,8,12,e,s+2*a[o++]),qs(1,5,9,13,e,s+2*a[o++]),Ws(1,5,9,13,e,s+2*a[o++]),qs(2,6,10,14,e,s+2*a[o++]),Ws(2,6,10,14,e,s+2*a[o++]),qs(3,7,11,15,e,s+2*a[o++]),Ws(3,7,11,15,e,s+2*a[o++]),qs(0,5,10,15,e,s+2*a[o++]),Ws(0,5,10,15,e,s+2*a[o++]),qs(1,6,11,12,e,s+2*a[o++]),Ws(1,6,11,12,e,s+2*a[o++]),qs(2,7,8,13,e,s+2*a[o++]),Ws(2,7,8,13,e,s+2*a[o++]),qs(3,4,9,14,e,s+2*a[o++]),Ws(3,4,9,14,e,s+2*a[o++]);this.v0l^=W[0]^W[16],this.v0h^=W[1]^W[17],this.v1l^=W[2]^W[18],this.v1h^=W[3]^W[19],this.v2l^=W[4]^W[20],this.v2h^=W[5]^W[21],this.v3l^=W[6]^W[22],this.v3h^=W[7]^W[23],this.v4l^=W[8]^W[24],this.v4h^=W[9]^W[25],this.v5l^=W[10]^W[26],this.v5h^=W[11]^W[27],this.v6l^=W[12]^W[28],this.v6h^=W[13]^W[29],this.v7l^=W[14]^W[30],this.v7h^=W[15]^W[31],Vt(W)}destroy(){this.destroyed=!0,Vt(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const bw=Ky(t=>new ww(t)),Ew="https://rpc.walletconnect.org/v1";function Eh(t){const e=`Ethereum Signed Message:
|
|
12
|
+
${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+me.from(sw(s)).toString("hex")}async function Cw(t,e,s,n,r,i){switch(s.t){case"eip191":return await vw(t,e,s.s);case"eip1271":return await Aw(t,e,s.s,n,r,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}function vw(t,e,s){const n=nf(s);return rf({payload:Eh(e),signature:n}).toLowerCase()===t.toLowerCase()}async function Aw(t,e,s,n,r,i){const o=Rs(n);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l=s.substring(2),d=(l.length/2).toString(16).padStart(64,"0"),u=(e.startsWith("0x")?e:Eh(e)).substring(2),h=a+u+c+d+l,p=await fetch(`${i||Ew}/?chainId=${n}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:_w(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:f}=await p.json();return f?f.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function _w(){return Date.now()+Math.floor(Math.random()*1e3)}function Iw(t){const e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);const n=s[0];if(n===0)throw new Error("No signatures found");const r=1+n*64;if(s.length<r)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const i=me.from(t,"base64").slice(1,65);return hr.encode(i)}function Nw(t){const e=new Uint8Array(me.from(t,"base64")),s=Array.from("TransactionData::").map(i=>i.charCodeAt(0)),n=new Uint8Array(s.length+e.length);n.set(s),n.set(e,s.length);const r=bw(n,{dkLen:32});return hr.encode(r)}function Dl(t){const e=new Uint8Array(Do(Sw(t)));return hr.encode(e)}function Sw(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function Ml(t){const e=me.from(t,"base64"),s=tf(e).txn;if(!s)throw new Error("Invalid signed transaction: missing 'txn' field");const n=sf(s),r=me.from("TX"),i=me.concat([r,me.from(n)]),o=fw(i);return iy.encode(o).replace(/=+$/,"")}function na(t){const e=[];let s=BigInt(t);for(;s>=BigInt(128);)e.push(Number(s&BigInt(127)|BigInt(128))),s>>=BigInt(7);return e.push(Number(s)),me.from(e)}function Tw(t){const e=me.from(t.signed.bodyBytes,"base64"),s=me.from(t.signed.authInfoBytes,"base64"),n=me.from(t.signature.signature,"base64"),r=[];r.push(me.from([10])),r.push(na(e.length)),r.push(e),r.push(me.from([18])),r.push(na(s.length)),r.push(s),r.push(me.from([26])),r.push(na(n.length)),r.push(n);const i=me.concat(r),o=Do(i);return me.from(o).toString("hex").toUpperCase()}function Ow(t){var e,s;const n=[];try{if(typeof t=="string")return n.push(t),n;if(typeof t!="object")return n;t!=null&&t.id&&n.push(t.id);const r=(s=(e=t==null?void 0:t.capabilities)==null?void 0:e.caip345)==null?void 0:s.transactionHashes;r&&n.push(...r)}catch(r){console.warn("getWalletSendCallsHashes failed: ",r)}return n}var Rw=Object.defineProperty,Pw=Object.defineProperties,kw=Object.getOwnPropertyDescriptors,Ll=Object.getOwnPropertySymbols,xw=Object.prototype.hasOwnProperty,$w=Object.prototype.propertyIsEnumerable,Fl=(t,e,s)=>e in t?Rw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Uw=(t,e)=>{for(var s in e||(e={}))xw.call(e,s)&&Fl(t,s,e[s]);if(Ll)for(var s of Ll(e))$w.call(e,s)&&Fl(t,s,e[s]);return t},Dw=(t,e)=>Pw(t,kw(e));const Mw="did:pkh:",Fc=t=>t==null?void 0:t.split(":"),Lw=t=>{const e=t&&Fc(t);if(e)return t.includes(Mw)?e[3]:e[1]},Ga=t=>{const e=t&&Fc(t);if(e)return e[2]+":"+e[3]},Co=t=>{const e=t&&Fc(t);if(e)return e.pop()};async function Bl(t){const{cacao:e,projectId:s}=t,{s:n,p:r}=e,i=Ch(r,r.iss),o=Co(r.iss);return await Cw(o,i,n,Ga(r.iss),s)}const Ch=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,n=Co(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=t.statement||void 0;const i=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${Lw(e)}`,c=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,d=t.exp?`Expiration Time: ${t.exp}`:void 0,u=t.nbf?`Not Before: ${t.nbf}`:void 0,h=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(m=>`
|
|
13
|
+
- ${m}`).join("")}`:void 0,f=no(t.resources);if(f){const m=pi(f);r=zw(r,m)}return[s,n,"",r,"",i,o,a,c,l,d,u,h,p].filter(m=>m!=null).join(`
|
|
14
|
+
`)};function Fw(t){return me.from(JSON.stringify(t)).toString("base64")}function Bw(t){return JSON.parse(me.from(t,"base64").toString("utf-8"))}function Pn(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(s=>{const n=t.att[s];if(Array.isArray(n))throw new Error(`Resource must be an object: ${s}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${s}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${s}`);Object.keys(n).forEach(r=>{const i=n[r];if(!Array.isArray(i))throw new Error(`Ability limits ${r} must be an array of objects, found: ${i}`);if(!i.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);i.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function jw(t,e,s,n={}){return s==null||s.sort((r,i)=>r.localeCompare(i)),{att:{[t]:qw(e,s,n)}}}function qw(t,e,s={}){e=e==null?void 0:e.sort((r,i)=>r.localeCompare(i));const n=e.map(r=>({[`${t}/${r}`]:[s]}));return Object.assign({},...n)}function vh(t){return Pn(t),`urn:recap:${Fw(t).replace(/=/g,"")}`}function pi(t){const e=Bw(t.replace("urn:recap:",""));return Pn(e),e}function Ww(t,e,s){const n=jw(t,e,s);return vh(n)}function Hw(t){return t&&t.includes("urn:recap:")}function Kw(t,e){const s=pi(t),n=pi(e),r=Vw(s,n);return vh(r)}function Vw(t,e){Pn(t),Pn(e);const s=Object.keys(t.att).concat(Object.keys(e.att)).sort((r,i)=>r.localeCompare(i)),n={att:{}};return s.forEach(r=>{var i,o;Object.keys(((i=t.att)==null?void 0:i[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;n.att[r]=Dw(Uw({},n.att[r]),{[a]:((c=t.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),n}function zw(t="",e){Pn(e);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(s))return t;const n=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,h)=>u.action.localeCompare(h.action));const l={};c.forEach(u=>{l[u.ability]||(l[u.ability]=[]),l[u.ability].push(u.action)});const d=Object.keys(l).map(u=>(r++,`(${r}) '${u}': '${l[u].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});const i=n.join(" "),o=`${s}${i}`;return`${t?t+" ":""}${o}`}function jl(t){var e;const s=pi(t);Pn(s);const n=(e=s.att)==null?void 0:e.eip155;return n?Object.keys(n).map(r=>r.split("/")[1]):[]}function ql(t){const e=pi(t);Pn(e);const s=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(r=>{var i;(i=r==null?void 0:r[0])!=null&&i.chains&&s.push(r[0].chains)})}),[...new Set(s.flat())]}function no(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return Hw(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Ah(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ya(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function ra(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function wt(t,...e){if(!Ah(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Wl(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Gw(t,e){wt(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function en(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function ar(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Yw(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Jw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Xw(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ja(t){if(typeof t=="string")t=Xw(t);else if(Ah(t))t=Xa(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Zw(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Qw(t,e){if(t.length!==e.length)return!1;let s=0;for(let n=0;n<t.length;n++)s|=t[n]^e[n];return s===0}const eb=(t,e)=>{function s(n,...r){if(wt(n),!Jw)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?wt(l):wt(l,t.nonceLength)}const i=t.tagLength;i&&r[1]!==void 0&&wt(r[1]);const o=e(n,...r),a=(l,d)=>{if(d!==void 0){if(l!==2)throw new Error("cipher output not supported");wt(d)}};let c=!1;return{encrypt(l,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,wt(l),a(o.encrypt.length,d),o.encrypt(l,d)},decrypt(l,d){if(wt(l),i&&l.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return a(o.decrypt.length,d),o.decrypt(l,d)}}}return Object.assign(s,t),s};function Hl(t,e,s=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(s&&!sb(e))throw new Error("invalid output, must be aligned");return e}function Kl(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function tb(t,e,s){Ya(s);const n=new Uint8Array(16),r=Yw(n);return Kl(r,0,BigInt(e),s),Kl(r,8,BigInt(t),s),n}function sb(t){return t.byteOffset%4===0}function Xa(t){return Uint8Array.from(t)}const _h=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),nb=_h("expand 16-byte k"),rb=_h("expand 32-byte k"),ib=en(nb),ob=en(rb);function ve(t,e){return t<<e|t>>>32-e}function Za(t){return t.byteOffset%4===0}const ji=64,ab=16,Ih=2**32-1,Vl=new Uint32Array;function cb(t,e,s,n,r,i,o,a){const c=r.length,l=new Uint8Array(ji),d=en(l),u=Za(r)&&Za(i),h=u?en(r):Vl,p=u?en(i):Vl;for(let f=0;f<c;o++){if(t(e,s,n,d,o,a),o>=Ih)throw new Error("arx: counter overflow");const m=Math.min(ji,c-f);if(u&&m===ji){const y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let w=0,b;w<ab;w++)b=y+w,p[b]=h[b]^d[w];f+=ji;continue}for(let y=0,w;y<m;y++)w=f+y,i[w]=r[w]^l[y];f+=m}}function lb(t,e){const{allowShortKeys:s,extendNonceFn:n,counterLength:r,counterRight:i,rounds:o}=Zw({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return ra(r),ra(o),Ya(i),Ya(s),(a,c,l,d,u=0)=>{wt(a),wt(c),wt(l);const h=l.length;if(d===void 0&&(d=new Uint8Array(h)),wt(d),ra(u),u<0||u>=Ih)throw new Error("arx: counter overflow");if(d.length<h)throw new Error(`arx: output (${d.length}) is shorter than data (${h})`);const p=[];let f=a.length,m,y;if(f===32)p.push(m=Xa(a)),y=ob;else if(f===16&&s)m=new Uint8Array(32),m.set(a),m.set(a,16),y=ib,p.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${f}`);Za(c)||p.push(c=Xa(c));const w=en(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(y,w,en(c.subarray(0,16)),w),c=c.subarray(16)}const b=16-r;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){const k=new Uint8Array(12);k.set(c,i?0:12-c.length),c=k,p.push(c)}const A=en(c);return cb(t,y,w,A,l,d,u,o),ar(...p),d}}const Je=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class db{constructor(e){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,e=Ja(e),wt(e,32);const s=Je(e,0),n=Je(e,2),r=Je(e,4),i=Je(e,6),o=Je(e,8),a=Je(e,10),c=Je(e,12),l=Je(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Je(e,16+2*d)}process(e,s,n=!1){const r=n?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],d=o[3],u=o[4],h=o[5],p=o[6],f=o[7],m=o[8],y=o[9],w=Je(e,s+0),b=Je(e,s+2),A=Je(e,s+4),k=Je(e,s+6),$=Je(e,s+8),M=Je(e,s+10),H=Je(e,s+12),G=Je(e,s+14);let P=i[0]+(w&8191),Q=i[1]+((w>>>13|b<<3)&8191),se=i[2]+((b>>>10|A<<6)&8191),T=i[3]+((A>>>7|k<<9)&8191),E=i[4]+((k>>>4|$<<12)&8191),C=i[5]+($>>>1&8191),v=i[6]+(($>>>14|M<<2)&8191),S=i[7]+((M>>>11|H<<5)&8191),U=i[8]+((H>>>8|G<<8)&8191),F=i[9]+(G>>>5|r),_=0,x=_+P*a+Q*(5*y)+se*(5*m)+T*(5*f)+E*(5*p);_=x>>>13,x&=8191,x+=C*(5*h)+v*(5*u)+S*(5*d)+U*(5*l)+F*(5*c),_+=x>>>13,x&=8191;let V=_+P*c+Q*a+se*(5*y)+T*(5*m)+E*(5*f);_=V>>>13,V&=8191,V+=C*(5*p)+v*(5*h)+S*(5*u)+U*(5*d)+F*(5*l),_+=V>>>13,V&=8191;let K=_+P*l+Q*c+se*a+T*(5*y)+E*(5*m);_=K>>>13,K&=8191,K+=C*(5*f)+v*(5*p)+S*(5*h)+U*(5*u)+F*(5*d),_+=K>>>13,K&=8191;let pe=_+P*d+Q*l+se*c+T*a+E*(5*y);_=pe>>>13,pe&=8191,pe+=C*(5*m)+v*(5*f)+S*(5*p)+U*(5*h)+F*(5*u),_+=pe>>>13,pe&=8191;let oe=_+P*u+Q*d+se*l+T*c+E*a;_=oe>>>13,oe&=8191,oe+=C*(5*y)+v*(5*m)+S*(5*f)+U*(5*p)+F*(5*h),_+=oe>>>13,oe&=8191;let ne=_+P*h+Q*u+se*d+T*l+E*c;_=ne>>>13,ne&=8191,ne+=C*a+v*(5*y)+S*(5*m)+U*(5*f)+F*(5*p),_+=ne>>>13,ne&=8191;let ue=_+P*p+Q*h+se*u+T*d+E*l;_=ue>>>13,ue&=8191,ue+=C*c+v*a+S*(5*y)+U*(5*m)+F*(5*f),_+=ue>>>13,ue&=8191;let le=_+P*f+Q*p+se*h+T*u+E*d;_=le>>>13,le&=8191,le+=C*l+v*c+S*a+U*(5*y)+F*(5*m),_+=le>>>13,le&=8191;let Re=_+P*m+Q*f+se*p+T*h+E*u;_=Re>>>13,Re&=8191,Re+=C*d+v*l+S*c+U*a+F*(5*y),_+=Re>>>13,Re&=8191;let de=_+P*y+Q*m+se*f+T*p+E*h;_=de>>>13,de&=8191,de+=C*u+v*d+S*l+U*c+F*a,_+=de>>>13,de&=8191,_=(_<<2)+_|0,_=_+x|0,x=_&8191,_=_>>>13,V+=_,i[0]=x,i[1]=V,i[2]=K,i[3]=pe,i[4]=oe,i[5]=ne,i[6]=ue,i[7]=le,i[8]=Re,i[9]=de}finalize(){const{h:e,pad:s}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+r,r=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(r^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+s[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+s[a]|0)+(o>>>16)|0,e[a]=o&65535;ar(n)}update(e){Wl(this),e=Ja(e),wt(e);const{buffer:s,blockLen:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(n-this.pos,r-i);if(o===n){for(;n<=r-i;i+=n)this.process(e,i);continue}s.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){ar(this.h,this.r,this.buffer,this.pad)}digestInto(e){Wl(this),Gw(e,this),this.finished=!0;const{buffer:s,h:n}=this;let{pos:r}=this;if(r){for(s[r++]=1;r<16;r++)s[r]=0;this.process(s,0,!0)}this.finalize();let i=0;for(let o=0;o<8;o++)e[i++]=n[o]>>>0,e[i++]=n[o]>>>8;return e}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}}function ub(t){const e=(n,r)=>t(r).update(Ja(n)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}const hb=ub(t=>new db(t));function pb(t,e,s,n,r,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],h=e[2],p=e[3],f=e[4],m=e[5],y=e[6],w=e[7],b=r,A=s[0],k=s[1],$=s[2],M=o,H=a,G=c,P=l,Q=d,se=u,T=h,E=p,C=f,v=m,S=y,U=w,F=b,_=A,x=k,V=$;for(let pe=0;pe<i;pe+=2)M=M+Q|0,F=ve(F^M,16),C=C+F|0,Q=ve(Q^C,12),M=M+Q|0,F=ve(F^M,8),C=C+F|0,Q=ve(Q^C,7),H=H+se|0,_=ve(_^H,16),v=v+_|0,se=ve(se^v,12),H=H+se|0,_=ve(_^H,8),v=v+_|0,se=ve(se^v,7),G=G+T|0,x=ve(x^G,16),S=S+x|0,T=ve(T^S,12),G=G+T|0,x=ve(x^G,8),S=S+x|0,T=ve(T^S,7),P=P+E|0,V=ve(V^P,16),U=U+V|0,E=ve(E^U,12),P=P+E|0,V=ve(V^P,8),U=U+V|0,E=ve(E^U,7),M=M+se|0,V=ve(V^M,16),S=S+V|0,se=ve(se^S,12),M=M+se|0,V=ve(V^M,8),S=S+V|0,se=ve(se^S,7),H=H+T|0,F=ve(F^H,16),U=U+F|0,T=ve(T^U,12),H=H+T|0,F=ve(F^H,8),U=U+F|0,T=ve(T^U,7),G=G+E|0,_=ve(_^G,16),C=C+_|0,E=ve(E^C,12),G=G+E|0,_=ve(_^G,8),C=C+_|0,E=ve(E^C,7),P=P+Q|0,x=ve(x^P,16),v=v+x|0,Q=ve(Q^v,12),P=P+Q|0,x=ve(x^P,8),v=v+x|0,Q=ve(Q^v,7);let K=0;n[K++]=o+M|0,n[K++]=a+H|0,n[K++]=c+G|0,n[K++]=l+P|0,n[K++]=d+Q|0,n[K++]=u+se|0,n[K++]=h+T|0,n[K++]=p+E|0,n[K++]=f+C|0,n[K++]=m+v|0,n[K++]=y+S|0,n[K++]=w+U|0,n[K++]=b+F|0,n[K++]=A+_|0,n[K++]=k+x|0,n[K++]=$+V|0}const fb=lb(pb,{counterRight:!1,counterLength:4,allowShortKeys:!1}),gb=new Uint8Array(16),zl=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(gb.subarray(s))},mb=new Uint8Array(32);function Gl(t,e,s,n,r){const i=t(e,s,mb),o=hb.create(i);r&&zl(o,r),zl(o,n);const a=tb(n.length,r?r.length:0,!0);o.update(a);const c=o.digest();return ar(i,a),c}const yb=t=>(e,s,n)=>({encrypt(r,i){const o=r.length;i=Hl(o+16,i,!1),i.set(r);const a=i.subarray(0,-16);t(e,s,a,a,1);const c=Gl(t,e,s,a,n);return i.set(c,o),ar(c),i},decrypt(r,i){i=Hl(r.length-16,i,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Gl(t,e,s,o,n);if(!Qw(a,c))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),t(e,s,i,i,1),ar(c),i}}),Nh=eb({blockSize:64,nonceLength:12,tagLength:16},yb(fb));let Sh=class extends Uo{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,$o(e);const n=ss(s);if(this.iHash=e.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;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Vt(i)}update(e){return nn(this),this.iHash.update(e),this}digestInto(e){nn(this),ns(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Mo=(t,e,s)=>new Sh(t,e).update(s).digest();Mo.create=(t,e)=>new Sh(t,e);function wb(t,e,s){return $o(t),s===void 0&&(s=new Uint8Array(t.outputLen)),Mo(t,ss(s),ss(e))}const ia=Uint8Array.from([0]),Yl=Uint8Array.of();function bb(t,e,s,n=32){$o(t),xs(n);const r=t.outputLen;if(n>255*r)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/r);s===void 0&&(s=Yl);const o=new Uint8Array(i*r),a=Mo.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)ia[0]=d+1,c.update(d===0?Yl:l).update(s).update(ia).digestInto(l),o.set(l,r*d),a._cloneInto(c);return a.destroy(),c.destroy(),Vt(l,ia),o.slice(0,n)}const Eb=(t,e,s,n,r)=>bb(t,wb(t,e,s),n,r),Lo=Do,Bc=BigInt(0),Qa=BigInt(1);function vo(t,e=""){if(typeof t!="boolean"){const s=e&&`"${e}"`;throw new Error(s+"expected boolean, got type="+typeof t)}return t}function An(t,e,s=""){const n=xo(t),r=t==null?void 0:t.length,i=e!==void 0;if(!n||i&&r!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=n?`length=${r}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function qi(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Th(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Bc:BigInt("0x"+t)}function Fo(t){return Th(Zn(t))}function Ao(t){return ns(t),Th(Zn(Uint8Array.from(t).reverse()))}function jc(t,e){return Eo(t.toString(16).padStart(e*2,"0"))}function qc(t,e){return jc(t,e).reverse()}function ct(t,e,s){let n;if(typeof e=="string")try{n=Eo(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(xo(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const r=n.length;if(typeof s=="number"&&r!==s)throw new Error(t+" of length "+s+" expected, got "+r);return n}const oa=t=>typeof t=="bigint"&&Bc<=t;function Cb(t,e,s){return oa(t)&&oa(e)&&oa(s)&&e<=t&&t<s}function ec(t,e,s,n){if(!Cb(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function Oh(t){let e;for(e=0;t>Bc;t>>=Qa,e+=1);return e}const _i=t=>(Qa<<BigInt(t))-Qa;function vb(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),r=h=>Uint8Array.of(h);let i=n(t),o=n(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...h)=>s(o,i,...h),d=(h=n(0))=>{o=l(r(0),h),i=l(),h.length!==0&&(o=l(r(1),h),i=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const p=[];for(;h<e;){i=l();const f=i.slice();p.push(f),h+=i.length}return zs(...p)};return(h,p)=>{c(),d(h);let f;for(;!(f=p(u()));)d();return c(),f}}function Bo(t,e,s={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(r,i,o){const a=t[r];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${r}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([r,i])=>n(r,i,!1)),Object.entries(s).forEach(([r,i])=>n(r,i,!0))}function Jl(t){const e=new WeakMap;return(s,...n)=>{const r=e.get(s);if(r!==void 0)return r;const i=t(s,...n);return e.set(s,i),i}}const Et=BigInt(0),dt=BigInt(1),_n=BigInt(2),Rh=BigInt(3),Ph=BigInt(4),kh=BigInt(5),Ab=BigInt(7),xh=BigInt(8),_b=BigInt(9),$h=BigInt(16);function Tt(t,e){const s=t%e;return s>=Et?s:e+s}function Zt(t,e,s){let n=t;for(;e-- >Et;)n*=n,n%=s;return n}function Xl(t,e){if(t===Et)throw new Error("invert: expected non-zero number");if(e<=Et)throw new Error("invert: expected positive modulus, got "+e);let s=Tt(t,e),n=e,r=Et,i=dt;for(;s!==Et;){const o=n/s,a=n%s,c=r-i*o;n=s,s=a,r=i,i=c}if(n!==dt)throw new Error("invert: does not exist");return Tt(r,e)}function Wc(t,e,s){if(!t.eql(t.sqr(e),s))throw new Error("Cannot find square root")}function Uh(t,e){const s=(t.ORDER+dt)/Ph,n=t.pow(e,s);return Wc(t,n,e),n}function Ib(t,e){const s=(t.ORDER-kh)/xh,n=t.mul(e,_n),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,_n),r),a=t.mul(i,t.sub(o,t.ONE));return Wc(t,a,e),a}function Nb(t){const e=an(t),s=Dh(t),n=s(e,e.neg(e.ONE)),r=s(e,n),i=s(e,e.neg(n)),o=(t+Ab)/$h;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,n);const u=a.mul(l,r),h=a.mul(l,i),p=a.eql(a.sqr(d),c),f=a.eql(a.sqr(u),c);l=a.cmov(l,d,p),d=a.cmov(h,u,f);const m=a.eql(a.sqr(d),c),y=a.cmov(l,d,m);return Wc(a,y,c),y}}function Dh(t){if(t<Rh)throw new Error("sqrt is not defined for small field");let e=t-dt,s=0;for(;e%_n===Et;)e/=_n,s++;let n=_n;const r=an(t);for(;Zl(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Uh;let i=r.pow(n,e);const o=(e+dt)/_n;return function(a,c){if(a.is0(c))return c;if(Zl(a,c)!==1)throw new Error("Cannot find square root");let l=s,d=a.mul(a.ONE,i),u=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(u,a.ONE);){if(a.is0(u))return a.ZERO;let p=1,f=a.sqr(u);for(;!a.eql(f,a.ONE);)if(p++,f=a.sqr(f),p===l)throw new Error("Cannot find square root");const m=dt<<BigInt(l-p-1),y=a.pow(d,m);l=p,d=a.sqr(y),u=a.mul(u,d),h=a.mul(h,y)}return h}}function Sb(t){return t%Ph===Rh?Uh:t%xh===kh?Ib:t%$h===_b?Nb(t):Dh(t)}const Tb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ob(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},s=Tb.reduce((n,r)=>(n[r]="function",n),e);return Bo(t,s),t}function Rb(t,e,s){if(s<Et)throw new Error("invalid exponent, negatives unsupported");if(s===Et)return t.ONE;if(s===dt)return e;let n=t.ONE,r=e;for(;s>Et;)s&dt&&(n=t.mul(n,r)),r=t.sqr(r),s>>=dt;return n}function Mh(t,e,s=!1){const n=new Array(e.length).fill(s?t.ZERO:void 0),r=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(r);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function Zl(t,e){const s=(t.ORDER-dt)/_n,n=t.pow(e,s),r=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function Lh(t,e){e!==void 0&&xs(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function an(t,e,s=!1,n={}){if(t<=Et)throw new Error("invalid field: expected ORDER > 0, got "+t);let r,i,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||s)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(r=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(s=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(r=e),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=Lh(t,r);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:s,BITS:c,BYTES:l,MASK:_i(c),ZERO:Et,ONE:dt,allowedLengths:a,create:h=>Tt(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Et<=h&&h<t},is0:h=>h===Et,isValidNot0:h=>!u.is0(h)&&u.isValid(h),isOdd:h=>(h&dt)===dt,neg:h=>Tt(-h,t),eql:(h,p)=>h===p,sqr:h=>Tt(h*h,t),add:(h,p)=>Tt(h+p,t),sub:(h,p)=>Tt(h-p,t),mul:(h,p)=>Tt(h*p,t),pow:(h,p)=>Rb(u,h,p),div:(h,p)=>Tt(h*Xl(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Xl(h,t),sqrt:i||(h=>(d||(d=Sb(t)),d(u,h))),toBytes:h=>s?qc(h,l):jc(h,l),fromBytes:(h,p=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const m=new Uint8Array(l);m.set(h,s?0:m.length-h.length),h=m}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let f=s?Ao(h):Fo(h);if(o&&(f=Tt(f,t)),!p&&!u.isValid(f))throw new Error("invalid field element: outside of range 0..ORDER");return f},invertBatch:h=>Mh(u,h),cmov:(h,p,f)=>f?p:h});return Object.freeze(u)}function Fh(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function Bh(t){const e=Fh(t);return e+Math.ceil(e/2)}function Pb(t,e,s=!1){const n=t.length,r=Fh(e),i=Bh(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?Ao(t):Fo(t),a=Tt(o,e-dt)+dt;return s?qc(a,r):jc(a,r)}const cr=BigInt(0),In=BigInt(1);function _o(t,e){const s=e.negate();return t?s:e}function aa(t,e){const s=Mh(t.Fp,e.map(n=>n.Z));return e.map((n,r)=>t.fromAffine(n.toAffine(s[r])))}function jh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ca(t,e){jh(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=_i(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function Ql(t,e,s){const{windowSize:n,mask:r,maxNumber:i,shiftBy:o}=s;let a=Number(t&r),c=t>>o;a>n&&(a-=i,c+=In);const l=e*n,d=l+Math.abs(a)-1,u=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:l}}function kb(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,n)=>{if(!(s instanceof e))throw new Error("invalid point at index "+n)})}function xb(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,n)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+n)})}const la=new WeakMap,qh=new WeakMap;function da(t){return qh.get(t)||1}function ed(t){if(t!==cr)throw new Error("invalid wNAF")}class $b{constructor(e,s){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,n=this.ZERO){let r=e;for(;s>cr;)s&In&&(n=n.add(r)),r=r.double(),s>>=In;return n}precomputeWindow(e,s){const{windows:n,windowSize:r}=ca(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<n;c++){a=o,i.push(a);for(let l=1;l<r;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=ca(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:h,offsetF:p}=Ql(n,a,o);n=c,d?i=i.add(_o(h,s[p])):r=r.add(_o(u,s[l]))}return ed(n),{p:r,f:i}}wNAFUnsafe(e,s,n,r=this.ZERO){const i=ca(e,this.bits);for(let o=0;o<i.windows&&n!==cr;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Ql(n,o,i);if(n=a,!l){const u=s[c];r=r.add(d?u.negate():u)}}return ed(n),r}getPrecomputes(e,s,n){let r=la.get(s);return r||(r=this.precomputeWindow(s,e),e!==1&&(typeof n=="function"&&(r=n(r)),la.set(s,r))),r}cached(e,s,n){const r=da(e);return this.wNAF(r,this.getPrecomputes(r,e,n),s)}unsafe(e,s,n,r){const i=da(e);return i===1?this._unsafeLadder(e,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),s,r)}createCache(e,s){jh(s,this.bits),qh.set(e,s),la.delete(e)}hasCache(e){return da(e)!==1}}function Ub(t,e,s,n){let r=e,i=t.ZERO,o=t.ZERO;for(;s>cr||n>cr;)s&In&&(i=i.add(r)),n&In&&(o=o.add(r)),r=r.double(),s>>=In,n>>=In;return{p1:i,p2:o}}function Db(t,e,s,n){kb(s,t),xb(n,e);const r=s.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Oh(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=_i(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=u;p>=0;p-=c){d.fill(o);for(let m=0;m<i;m++){const y=n[m],w=Number(y>>BigInt(p)&l);d[w]=d[w].add(s[m])}let f=o;for(let m=d.length-1,y=o;m>0;m--)y=y.add(d[m]),f=f.add(y);if(h=h.add(f),p!==0)for(let m=0;m<c;m++)h=h.double()}return h}function td(t,e,s){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ob(e),e}else return an(t,{isLE:s})}function Mb(t,e,s={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>cr))throw new Error(`CURVE.${a} must be positive bigint`)}const r=td(e.p,s.Fp,n),i=td(e.n,s.Fn,n),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:i}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),hh("HashToScalar-");const Er=BigInt(0),Bn=BigInt(1),Wi=BigInt(2);function Lb(t){return Bo(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function Fb(t){const e=Lb(t),{P:s,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:o}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");const c=o||Un,l=a?255:448,d=a?32:56,u=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?Wi**BigInt(254):Wi**BigInt(447),f=a?BigInt(8)*Wi**BigInt(251)-Bn:BigInt(4)*Wi**BigInt(445)-Bn,m=p+f+Bn,y=T=>Tt(T,s),w=b(u);function b(T){return qc(y(T),d)}function A(T){const E=ct("u coordinate",T,d);return a&&(E[31]&=127),y(Ao(E))}function k(T){return Ao(r(ct("scalar",T,d)))}function $(T,E){const C=G(A(E),k(T));if(C===Er)throw new Error("invalid private or public key received");return b(C)}function M(T){return $(T,w)}function H(T,E,C){const v=y(T*(E-C));return E=y(E-v),C=y(C+v),{x_2:E,x_3:C}}function G(T,E){ec("u",T,Er,s),ec("scalar",E,p,m);const C=E,v=T;let S=Bn,U=Er,F=T,_=Bn,x=Er;for(let K=BigInt(l-1);K>=Er;K--){const pe=C>>K&Bn;x^=pe,{x_2:S,x_3:F}=H(x,S,F),{x_2:U,x_3:_}=H(x,U,_),x=pe;const oe=S+U,ne=y(oe*oe),ue=S-U,le=y(ue*ue),Re=ne-le,de=F+_,Le=F-_,Gt=y(Le*oe),$s=y(de*ue),cn=Gt+$s,Mn=Gt-$s;F=y(cn*cn),_=y(v*y(Mn*Mn)),S=y(ne*le),U=y(Re*(ne+y(h*Re)))}({x_2:S,x_3:F}=H(x,S,F)),{x_2:U,x_3:_}=H(x,U,_);const V=i(U);return y(S*V)}const P={secretKey:d,publicKey:d,seed:d},Q=(T=c(d))=>(ns(T,P.seed),T);function se(T){const E=Q(T);return{secretKey:E,publicKey:M(E)}}return{keygen:se,getSharedSecret:(T,E)=>$(T,E),getPublicKey:T=>M(T),scalarMult:$,scalarMultBase:M,utils:{randomSecretKey:Q,randomPrivateKey:Q},GuBytes:w.slice(),lengths:P}}const Bb=BigInt(1),sd=BigInt(2),jb=BigInt(3),qb=BigInt(5),Wb=BigInt(8),Wh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Hb={p:Wh,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Wb,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Kb(t){const e=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=Wh,o=t*t%i*t%i,a=Zt(o,sd,i)*o%i,c=Zt(a,Bb,i)*t%i,l=Zt(c,qb,i)*c%i,d=Zt(l,e,i)*l%i,u=Zt(d,s,i)*d%i,h=Zt(u,n,i)*u%i,p=Zt(h,r,i)*h%i,f=Zt(p,r,i)*h%i,m=Zt(f,e,i)*l%i;return{pow_p_5_8:Zt(m,sd,i)*t%i,b2:o}}function Vb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const zb=an(Hb.p,{isLE:!0}),tc=(()=>{const t=zb.ORDER;return Fb({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:s,b2:n}=Kb(e);return Tt(Zt(s,jb,t)*n,t)},adjustScalarBytes:Vb})})(),nd=(t,e)=>(t+(t>=0?e:-e)/Hh)/e;function Gb(t,e,s){const[[n,r],[i,o]]=e,a=nd(o*t,s),c=nd(-r*t,s);let l=t-a*n-c*i,d=-a*r-c*o;const u=l<Ts,h=d<Ts;u&&(l=-l),h&&(d=-d);const p=_i(Math.ceil(Oh(s)/2))+Qn;if(l<Ts||l>=p||d<Ts||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}function sc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function ua(t,e){const s={};for(let n of Object.keys(e))s[n]=t[n]===void 0?e[n]:t[n];return vo(s.lowS,"lowS"),vo(s.prehash,"prehash"),s.format!==void 0&&sc(s.format),s}class Yb extends Error{constructor(e=""){super(e)}}const Is={Err:Yb,_tlv:{encode:(t,e)=>{const{Err:s}=Is;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const n=e.length/2,r=qi(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?qi(r.length/2|128):"";return qi(t)+i+r+e},decode(t,e){const{Err:s}=Is;let n=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new s("tlv.decode: wrong tlv");const r=e[n++],i=!!(r&128);let o=0;if(!i)o=r;else{const c=r&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(n+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=Is;if(t<Ts)throw new e("integer: negative integers are not allowed");let s=qi(t);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(t){const{Err:e}=Is;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Fo(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=Is,r=ct("signature",t),{v:i,l:o}=n.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=Is,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}},Ts=BigInt(0),Qn=BigInt(1),Hh=BigInt(2),Hi=BigInt(3),Jb=BigInt(4);function Gn(t,e){const{BYTES:s}=t;let n;if(typeof e=="bigint")n=e;else{let r=ct("private key",e);try{n=t.fromBytes(r)}catch{throw new Error(`invalid private key: expected ui8a of size ${s}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Xb(t,e={}){const s=Mb("weierstrass",t,e),{Fp:n,Fn:r}=s;let i=s.CURVE;const{h:o,n:a}=i;Bo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Vh(n,r);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(T,E,C){const{x:v,y:S}=E.toAffine(),U=n.toBytes(v);if(vo(C,"isCompressed"),C){d();const F=!n.isOdd(S);return zs(Kh(F),U)}else return zs(Uint8Array.of(4),U,n.toBytes(S))}function h(T){An(T,void 0,"Point");const{publicKey:E,publicKeyUncompressed:C}=l,v=T.length,S=T[0],U=T.subarray(1);if(v===E&&(S===2||S===3)){const F=n.fromBytes(U);if(!n.isValid(F))throw new Error("bad point: is not on curve, wrong x");const _=m(F);let x;try{x=n.sqrt(_)}catch(K){const pe=K instanceof Error?": "+K.message:"";throw new Error("bad point: is not on curve, sqrt error"+pe)}d();const V=n.isOdd(x);return(S&1)===1!==V&&(x=n.neg(x)),{x:F,y:x}}else if(v===C&&S===4){const F=n.BYTES,_=n.fromBytes(U.subarray(0,F)),x=n.fromBytes(U.subarray(F,F*2));if(!y(_,x))throw new Error("bad point: is not on curve");return{x:_,y:x}}else throw new Error(`bad point: got length ${v}, expected compressed=${E} or uncompressed=${C}`)}const p=e.toBytes||u,f=e.fromBytes||h;function m(T){const E=n.sqr(T),C=n.mul(E,T);return n.add(n.add(C,n.mul(T,i.a)),i.b)}function y(T,E){const C=n.sqr(E),v=m(T);return n.eql(C,v)}if(!y(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const w=n.mul(n.pow(i.a,Hi),Jb),b=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(w,b)))throw new Error("bad curve params: a or b");function A(T,E,C=!1){if(!n.isValid(E)||C&&n.is0(E))throw new Error(`bad point coordinate ${T}`);return E}function k(T){if(!(T instanceof P))throw new Error("ProjectivePoint expected")}function $(T){if(!c||!c.basises)throw new Error("no endo");return Gb(T,c.basises,r.ORDER)}const M=Jl((T,E)=>{const{X:C,Y:v,Z:S}=T;if(n.eql(S,n.ONE))return{x:C,y:v};const U=T.is0();E==null&&(E=U?n.ONE:n.inv(S));const F=n.mul(C,E),_=n.mul(v,E),x=n.mul(S,E);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(x,n.ONE))throw new Error("invZ was invalid");return{x:F,y:_}}),H=Jl(T=>{if(T.is0()){if(e.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}const{x:E,y:C}=T.toAffine();if(!n.isValid(E)||!n.isValid(C))throw new Error("bad point: x or y not field elements");if(!y(E,C))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function G(T,E,C,v,S){return C=new P(n.mul(C.X,T),C.Y,C.Z),E=_o(v,E),C=_o(S,C),E.add(C)}class P{constructor(E,C,v){this.X=A("x",E),this.Y=A("y",C,!0),this.Z=A("z",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(E){const{x:C,y:v}=E||{};if(!E||!n.isValid(C)||!n.isValid(v))throw new Error("invalid affine point");if(E instanceof P)throw new Error("projective point not allowed");return n.is0(C)&&n.is0(v)?P.ZERO:new P(C,v,n.ONE)}static fromBytes(E){const C=P.fromAffine(f(An(E,void 0,"point")));return C.assertValidity(),C}static fromHex(E){return P.fromBytes(ct("pointHex",E))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=8,C=!0){return se.createCache(this,E),C||this.multiply(Hi),this}assertValidity(){H(this)}hasEvenY(){const{y:E}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(E)}equals(E){k(E);const{X:C,Y:v,Z:S}=this,{X:U,Y:F,Z:_}=E,x=n.eql(n.mul(C,_),n.mul(U,S)),V=n.eql(n.mul(v,_),n.mul(F,S));return x&&V}negate(){return new P(this.X,n.neg(this.Y),this.Z)}double(){const{a:E,b:C}=i,v=n.mul(C,Hi),{X:S,Y:U,Z:F}=this;let _=n.ZERO,x=n.ZERO,V=n.ZERO,K=n.mul(S,S),pe=n.mul(U,U),oe=n.mul(F,F),ne=n.mul(S,U);return ne=n.add(ne,ne),V=n.mul(S,F),V=n.add(V,V),_=n.mul(E,V),x=n.mul(v,oe),x=n.add(_,x),_=n.sub(pe,x),x=n.add(pe,x),x=n.mul(_,x),_=n.mul(ne,_),V=n.mul(v,V),oe=n.mul(E,oe),ne=n.sub(K,oe),ne=n.mul(E,ne),ne=n.add(ne,V),V=n.add(K,K),K=n.add(V,K),K=n.add(K,oe),K=n.mul(K,ne),x=n.add(x,K),oe=n.mul(U,F),oe=n.add(oe,oe),K=n.mul(oe,ne),_=n.sub(_,K),V=n.mul(oe,pe),V=n.add(V,V),V=n.add(V,V),new P(_,x,V)}add(E){k(E);const{X:C,Y:v,Z:S}=this,{X:U,Y:F,Z:_}=E;let x=n.ZERO,V=n.ZERO,K=n.ZERO;const pe=i.a,oe=n.mul(i.b,Hi);let ne=n.mul(C,U),ue=n.mul(v,F),le=n.mul(S,_),Re=n.add(C,v),de=n.add(U,F);Re=n.mul(Re,de),de=n.add(ne,ue),Re=n.sub(Re,de),de=n.add(C,S);let Le=n.add(U,_);return de=n.mul(de,Le),Le=n.add(ne,le),de=n.sub(de,Le),Le=n.add(v,S),x=n.add(F,_),Le=n.mul(Le,x),x=n.add(ue,le),Le=n.sub(Le,x),K=n.mul(pe,de),x=n.mul(oe,le),K=n.add(x,K),x=n.sub(ue,K),K=n.add(ue,K),V=n.mul(x,K),ue=n.add(ne,ne),ue=n.add(ue,ne),le=n.mul(pe,le),de=n.mul(oe,de),ue=n.add(ue,le),le=n.sub(ne,le),le=n.mul(pe,le),de=n.add(de,le),ne=n.mul(ue,de),V=n.add(V,ne),ne=n.mul(Le,de),x=n.mul(Re,x),x=n.sub(x,ne),ne=n.mul(Re,ue),K=n.mul(Le,K),K=n.add(K,ne),new P(x,V,K)}subtract(E){return this.add(E.negate())}is0(){return this.equals(P.ZERO)}multiply(E){const{endo:C}=e;if(!r.isValidNot0(E))throw new Error("invalid scalar: out of range");let v,S;const U=F=>se.cached(this,F,_=>aa(P,_));if(C){const{k1neg:F,k1:_,k2neg:x,k2:V}=$(E),{p:K,f:pe}=U(_),{p:oe,f:ne}=U(V);S=pe.add(ne),v=G(C.beta,K,oe,F,x)}else{const{p:F,f:_}=U(E);v=F,S=_}return aa(P,[v,S])[0]}multiplyUnsafe(E){const{endo:C}=e,v=this;if(!r.isValid(E))throw new Error("invalid scalar: out of range");if(E===Ts||v.is0())return P.ZERO;if(E===Qn)return v;if(se.hasCache(this))return this.multiply(E);if(C){const{k1neg:S,k1:U,k2neg:F,k2:_}=$(E),{p1:x,p2:V}=Ub(P,v,U,_);return G(C.beta,x,V,S,F)}else return se.unsafe(v,E)}multiplyAndAddUnsafe(E,C,v){const S=this.multiplyUnsafe(C).add(E.multiplyUnsafe(v));return S.is0()?void 0:S}toAffine(E){return M(this,E)}isTorsionFree(){const{isTorsionFree:E}=e;return o===Qn?!0:E?E(P,this):se.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:E}=e;return o===Qn?this:E?E(P,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(E=!0){return vo(E,"isCompressed"),this.assertValidity(),p(P,this,E)}toHex(E=!0){return Zn(this.toBytes(E))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(E=!0){return this.toBytes(E)}_setWindowSize(E){this.precompute(E)}static normalizeZ(E){return aa(P,E)}static msm(E,C){return Db(P,r,E,C)}static fromPrivateKey(E){return P.BASE.multiply(Gn(r,E))}}P.BASE=new P(i.Gx,i.Gy,n.ONE),P.ZERO=new P(n.ZERO,n.ONE,n.ZERO),P.Fp=n,P.Fn=r;const Q=r.BITS,se=new $b(P,e.endo?Math.ceil(Q/2):Q);return P.BASE.precompute(8),P}function Kh(t){return Uint8Array.of(t?2:3)}function Vh(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Zb(t,e={}){const{Fn:s}=t,n=e.randomBytes||Un,r=Object.assign(Vh(t.Fp,s),{seed:Bh(s.ORDER)});function i(h){try{return!!Gn(s,h)}catch{return!1}}function o(h,p){const{publicKey:f,publicKeyUncompressed:m}=r;try{const y=h.length;return p===!0&&y!==f||p===!1&&y!==m?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(r.seed)){return Pb(An(h,r.seed,"seed"),s.ORDER)}function c(h,p=!0){return t.BASE.multiply(Gn(s,h)).toBytes(p)}function l(h){const p=a(h);return{secretKey:p,publicKey:c(p)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:p,publicKey:f,publicKeyUncompressed:m}=r;if(s.allowedLengths||p===f)return;const y=ct("key",h).length;return y===f||y===m}function u(h,p,f=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(p)===!1)throw new Error("second arg must be public key");const m=Gn(s,h);return t.fromHex(p).multiply(m).toBytes(f)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>Gn(s,h),precompute(h=8,p=t.BASE){return p.precompute(h,!1)}},lengths:r})}function Qb(t,e,s={}){$o(e),Bo(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=s.randomBytes||Un,r=s.hmac||((C,...v)=>Mo(e,C,zs(...v))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p}=Zb(t,s),f={prehash:!1,lowS:typeof s.lowS=="boolean"?s.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function y(C){const v=a>>Qn;return C>v}function w(C,v){if(!o.isValidNot0(v))throw new Error(`invalid signature ${C}: out of range 1..Point.Fn.ORDER`);return v}function b(C,v){sc(v);const S=p.signature,U=v==="compact"?S:v==="recovered"?S+1:void 0;return An(C,U,`${v} signature`)}class A{constructor(v,S,U){this.r=w("r",v),this.s=w("s",S),U!=null&&(this.recovery=U),Object.freeze(this)}static fromBytes(v,S=m){b(v,S);let U;if(S==="der"){const{r:V,s:K}=Is.toSig(An(v));return new A(V,K)}S==="recovered"&&(U=v[0],S="compact",v=v.subarray(1));const F=o.BYTES,_=v.subarray(0,F),x=v.subarray(F,F*2);return new A(o.fromBytes(_),o.fromBytes(x),U)}static fromHex(v,S){return this.fromBytes(Eo(v),S)}addRecoveryBit(v){return new A(this.r,this.s,v)}recoverPublicKey(v){const S=i.ORDER,{r:U,s:F,recovery:_}=this;if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");if(a*Hh<S&&_>1)throw new Error("recovery id is ambiguous for h>1 curve");const x=_===2||_===3?U+a:U;if(!i.isValid(x))throw new Error("recovery id 2 or 3 invalid");const V=i.toBytes(x),K=t.fromBytes(zs(Kh((_&1)===0),V)),pe=o.inv(x),oe=$(ct("msgHash",v)),ne=o.create(-oe*pe),ue=o.create(F*pe),le=t.BASE.multiplyUnsafe(ne).add(K.multiplyUnsafe(ue));if(le.is0())throw new Error("point at infinify");return le.assertValidity(),le}hasHighS(){return y(this.s)}toBytes(v=m){if(sc(v),v==="der")return Eo(Is.hexFromSig(this));const S=o.toBytes(this.r),U=o.toBytes(this.s);if(v==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return zs(Uint8Array.of(this.recovery),S,U)}return zs(S,U)}toHex(v){return Zn(this.toBytes(v))}assertValidity(){}static fromCompact(v){return A.fromBytes(ct("sig",v),"compact")}static fromDER(v){return A.fromBytes(ct("sig",v),"der")}normalizeS(){return this.hasHighS()?new A(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Zn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Zn(this.toBytes("compact"))}}const k=s.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");const v=Fo(C),S=C.length*8-c;return S>0?v>>BigInt(S):v},$=s.bits2int_modN||function(C){return o.create(k(C))},M=_i(c);function H(C){return ec("num < 2^"+c,C,Ts,M),o.toBytes(C)}function G(C,v){return An(C,void 0,"message"),v?An(e(C),void 0,"prehashed message"):C}function P(C,v,S){if(["recovered","canonical"].some(ue=>ue in S))throw new Error("sign() legacy options not supported");const{lowS:U,prehash:F,extraEntropy:_}=ua(S,f);C=G(C,F);const x=$(C),V=Gn(o,v),K=[H(V),H(x)];if(_!=null&&_!==!1){const ue=_===!0?n(p.secretKey):_;K.push(ct("extraEntropy",ue))}const pe=zs(...K),oe=x;function ne(ue){const le=k(ue);if(!o.isValidNot0(le))return;const Re=o.inv(le),de=t.BASE.multiply(le).toAffine(),Le=o.create(de.x);if(Le===Ts)return;const Gt=o.create(Re*o.create(oe+Le*V));if(Gt===Ts)return;let $s=(de.x===Le?0:2)|Number(de.y&Qn),cn=Gt;return U&&y(Gt)&&(cn=o.neg(Gt),$s^=1),new A(Le,cn,$s)}return{seed:pe,k2sig:ne}}function Q(C,v,S={}){C=ct("message",C);const{seed:U,k2sig:F}=P(C,v,S);return vb(e.outputLen,o.BYTES,r)(U,F)}function se(C){let v;const S=typeof C=="string"||xo(C),U=!S&&C!==null&&typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint";if(!S&&!U)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(U)v=new A(C.r,C.s);else if(S){try{v=A.fromBytes(ct("sig",C),"der")}catch(F){if(!(F instanceof Is.Err))throw F}if(!v)try{v=A.fromBytes(ct("sig",C),"compact")}catch{return!1}}return v||!1}function T(C,v,S,U={}){const{lowS:F,prehash:_,format:x}=ua(U,f);if(S=ct("publicKey",S),v=G(ct("message",v),_),"strict"in U)throw new Error("options.strict was renamed to lowS");const V=x===void 0?se(C):A.fromBytes(ct("sig",C),x);if(V===!1)return!1;try{const K=t.fromBytes(S);if(F&&V.hasHighS())return!1;const{r:pe,s:oe}=V,ne=$(v),ue=o.inv(oe),le=o.create(ne*ue),Re=o.create(pe*ue),de=t.BASE.multiplyUnsafe(le).add(K.multiplyUnsafe(Re));return de.is0()?!1:o.create(de.x)===pe}catch{return!1}}function E(C,v,S={}){const{prehash:U}=ua(S,f);return v=G(v,U),A.fromBytes(C,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p,Point:t,sign:Q,verify:T,recoverPublicKey:E,Signature:A,hash:e})}function eE(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},s=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const r=an(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),i={Fp:s,Fn:r,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function tE(t){const{CURVE:e,curveOpts:s}=eE(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:s,hash:t.hash,ecdsaOpts:n}}function sE(t,e){const s=e.Point;return Object.assign({},e,{ProjectivePoint:s,CURVE:Object.assign({},t,Lh(s.Fn.ORDER,s.Fn.BITS))})}function nE(t){const{CURVE:e,curveOpts:s,hash:n,ecdsaOpts:r}=tE(t),i=Xb(e,s),o=Qb(i,n,r);return sE(t,o)}function nc(t,e){const s=n=>nE({...t,hash:n});return{...s(e),create:s}}const zh={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Gh={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Yh={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},rE=an(zh.p),iE=an(Gh.p),oE=an(Yh.p),aE=nc({...zh,Fp:rE,lowS:!1},Do);nc({...Gh,Fp:iE,lowS:!1},pw),nc({...Yh,Fp:oE,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},hw);const cE=aE,Jh="base10",ut="base16",bt="base64pad",Gs="base64url",Ii="utf8",Xh=0,Ps=1,Ni=2,lE=0,rd=1,Mr=12,Hc=32;function dE(){const t=tc.utils.randomPrivateKey(),e=tc.getPublicKey(t);return{privateKey:Ct(t,ut),publicKey:Ct(e,ut)}}function rc(){const t=Un(Hc);return Ct(t,ut)}function uE(t,e){const s=tc.getSharedSecret(Ht(t,ut),Ht(e,ut)),n=Eb(Lo,s,void 0,void 0,Hc);return Ct(n,ut)}function ro(t){const e=Lo(Ht(t,ut));return Ct(e,ut)}function jt(t){const e=Lo(Ht(t,Ii));return Ct(e,ut)}function Zh(t){return Ht(`${t}`,Jh)}function kn(t){return Number(Ct(t,Jh))}function Qh(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ep(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function hE(t){const e=Zh(typeof t.type<"u"?t.type:Xh);if(kn(e)===Ps&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?Ht(t.senderPublicKey,ut):void 0,n=typeof t.iv<"u"?Ht(t.iv,ut):Un(Mr),r=Ht(t.symKey,ut),i=Nh(r,n).encrypt(Ht(t.message,Ii)),o=tp({type:e,sealed:i,iv:n,senderPublicKey:s});return t.encoding===Gs?Qh(o):o}function pE(t){const e=Ht(t.symKey,ut),{sealed:s,iv:n}=fi({encoded:t.encoded,encoding:t.encoding}),r=Nh(e,n).decrypt(s);if(r===null)throw new Error("Failed to decrypt");return Ct(r,Ii)}function fE(t,e){const s=Zh(Ni),n=Un(Mr),r=Ht(t,Ii),i=tp({type:s,sealed:r,iv:n});return e===Gs?Qh(i):i}function gE(t,e){const{sealed:s}=fi({encoded:t,encoding:e});return Ct(s,Ii)}function tp(t){if(kn(t.type)===Ni)return Ct(xr([t.type,t.sealed]),bt);if(kn(t.type)===Ps){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ct(xr([t.type,t.senderPublicKey,t.iv,t.sealed]),bt)}return Ct(xr([t.type,t.iv,t.sealed]),bt)}function fi(t){const e=(t.encoding||bt)===Gs?ep(t.encoded):t.encoded,s=Ht(e,bt),n=s.slice(lE,rd),r=rd;if(kn(n)===Ps){const c=r+Hc,l=c+Mr,d=s.slice(r,c),u=s.slice(c,l),h=s.slice(l);return{type:n,sealed:h,iv:u,senderPublicKey:d}}if(kn(n)===Ni){const c=s.slice(r),l=Un(Mr);return{type:n,sealed:c,iv:l}}const i=r+Mr,o=s.slice(r,i),a=s.slice(i);return{type:n,sealed:a,iv:o}}function mE(t,e){const s=fi({encoded:t,encoding:e==null?void 0:e.encoding});return sp({type:kn(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?Ct(s.senderPublicKey,ut):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function sp(t){const e=(t==null?void 0:t.type)||Xh;if(e===Ps){if(typeof(t==null?void 0:t.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(t==null?void 0:t.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t==null?void 0:t.senderPublicKey,receiverPublicKey:t==null?void 0:t.receiverPublicKey}}function id(t){return t.type===Ps&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function od(t){return t.type===Ni}function yE(t){const e=me.from(t.x,"base64"),s=me.from(t.y,"base64");return xr([new Uint8Array([4]),e,s])}function wE(t,e){const[s,n,r]=t.split("."),i=me.from(ep(r),"base64");if(i.length!==64)throw new Error("Invalid signature length");const o=i.slice(0,32),a=i.slice(32,64),c=`${s}.${n}`,l=Lo(c),d=yE(e);if(!cE.verify(xr([o,a]),l,d))throw new Error("Invalid signature");return xa(t).payload}const bE="irn";function Io(t){return(t==null?void 0:t.relay)||{protocol:bE}}function Yn(t){const e=lf[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var EE=Object.defineProperty,CE=Object.defineProperties,vE=Object.getOwnPropertyDescriptors,ad=Object.getOwnPropertySymbols,AE=Object.prototype.hasOwnProperty,_E=Object.prototype.propertyIsEnumerable,cd=(t,e,s)=>e in t?EE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ha=(t,e)=>{for(var s in e||(e={}))AE.call(e,s)&&cd(t,s,e[s]);if(ad)for(var s of ad(e))_E.call(e,s)&&cd(t,s,e[s]);return t},IE=(t,e)=>CE(t,vE(e));function NE(t,e="-"){const s={},n="relay"+e;return Object.keys(t).forEach(r=>{if(r.startsWith(n)){const i=r.replace(n,""),o=t[r];s[i]=o}}),s}function ld(t){if(!t.includes("wc:")){const l=oh(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),s=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),r=t.substring(e+1,s).split("@"),i=typeof s<"u"?t.substring(s):"",o=new URLSearchParams(i),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:SE(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:NE(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function SE(t){return t.startsWith("//")?t.substring(2):t}function TE(t,e="-"){const s="relay",n={};return Object.keys(t).forEach(r=>{const i=r,o=s+e+i;t[i]&&(n[o]=t[i])}),n}function dd(t){const e=new URLSearchParams,s=ha(ha(IE(ha({},TE(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(s).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!==void 0&&e.append(n,String(r))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function Ki(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var OE=Object.defineProperty,RE=Object.defineProperties,PE=Object.getOwnPropertyDescriptors,ud=Object.getOwnPropertySymbols,kE=Object.prototype.hasOwnProperty,xE=Object.prototype.propertyIsEnumerable,hd=(t,e,s)=>e in t?OE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$E=(t,e)=>{for(var s in e||(e={}))kE.call(e,s)&&hd(t,s,e[s]);if(ud)for(var s of ud(e))xE.call(e,s)&&hd(t,s,e[s]);return t},UE=(t,e)=>RE(t,PE(e));function mr(t){const e=[];return t.forEach(s=>{const[n,r]=s.split(":");e.push(`${n}:${r}`)}),e}function DE(t){const e=[];return Object.values(t).forEach(s=>{e.push(...mr(s.accounts))}),e}function ME(t,e){const s=[];return Object.values(t).forEach(n=>{mr(n.accounts).includes(e)&&s.push(...n.methods)}),s}function LE(t,e){const s=[];return Object.values(t).forEach(n=>{mr(n.accounts).includes(e)&&s.push(...n.events)}),s}function jo(t){return t.includes(":")}function Jn(t){return jo(t)?t.split(":")[0]:t}function pd(t){var e,s,n;const r={};if(!gs(t))return r;for(const[i,o]of Object.entries(t)){const a=jo(i)?[i]:o.chains,c=o.methods||[],l=o.events||[],d=Jn(i);r[d]=UE($E({},r[d]),{chains:fs(a,(e=r[d])==null?void 0:e.chains),methods:fs(c,(s=r[d])==null?void 0:s.methods),events:fs(l,(n=r[d])==null?void 0:n.events)})}return r}function FE(t){const e={};return t==null||t.forEach(s=>{var n;const[r,i]=s.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(s),(n=e[r].chains)==null||n.push(`${r}:${i}`)}),e}function fd(t,e){e=e.map(n=>n.replace("did:pkh:",""));const s=FE(e);for(const[n,r]of Object.entries(s))r.methods?r.methods=fs(r.methods,t):r.methods=t,r.events=["chainChanged","accountsChanged"];return s}function BE(t,e){var s,n,r,i,o,a;const c=pd(t),l=pd(e),d={},u=Object.keys(c).concat(Object.keys(l));for(const h of u)d[h]={chains:fs((s=c[h])==null?void 0:s.chains,(n=l[h])==null?void 0:n.chains),methods:fs((r=c[h])==null?void 0:r.methods,(i=l[h])==null?void 0:i.methods),events:fs((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return d}const jE={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}},qE={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 L(t,e){const{message:s,code:n}=qE[t];return{message:e?`${s} ${e}`:s,code:n}}function Ue(t,e){const{message:s,code:n}=jE[t];return{message:e?`${s} ${e}`:s,code:n}}function ks(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function gs(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Ke(t){return typeof t>"u"}function qe(t,e){return e&&Ke(t)?!0:typeof t=="string"&&!!t.trim().length}function Kc(t,e){return e&&Ke(t)?!0:typeof t=="number"&&!isNaN(t)}function WE(t,e){const{requiredNamespaces:s}=e,n=Object.keys(t.namespaces),r=Object.keys(s);let i=!0;return vn(r,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],d=mr(a),u=s[o];(!vn(th(o,u),d)||!vn(u.methods,c)||!vn(u.events,l))&&(i=!1)}),i):!1}function No(t){return qe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function HE(t){if(qe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&No(s)}}return!1}function KE(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(qe(t,!1)){if(e(t))return!0;const s=oh(t);return e(s)}}catch{}return!1}function VE(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function zE(t){return t==null?void 0:t.topic}function GE(t,e){let s=null;return qe(t==null?void 0:t.publicKey,!1)||(s=L("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function gd(t){let e=!0;return ks(t)?t.length&&(e=t.every(s=>qe(s,!1))):e=!1,e}function YE(t,e,s){let n=null;return ks(e)&&e.length?e.forEach(r=>{n||No(r)||(n=Ue("UNSUPPORTED_CHAINS",`${s}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):No(t)||(n=Ue("UNSUPPORTED_CHAINS",`${s}, 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 JE(t,e,s){let n=null;return Object.entries(t).forEach(([r,i])=>{if(n)return;const o=YE(r,th(r,i),`${e} ${s}`);o&&(n=o)}),n}function XE(t,e){let s=null;return ks(t)?t.forEach(n=>{s||HE(n)||(s=Ue("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):s=Ue("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function ZE(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=XE(n==null?void 0:n.accounts,`${e} namespace`);r&&(s=r)}),s}function QE(t,e){let s=null;return gd(t==null?void 0:t.methods)?gd(t==null?void 0:t.events)||(s=Ue("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=Ue("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function np(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=QE(n,`${e}, namespace`);r&&(s=r)}),s}function e0(t,e,s){let n=null;if(t&&gs(t)){const r=np(t,e);r&&(n=r);const i=JE(t,e,s);i&&(n=i)}else n=L("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return n}function pa(t,e){let s=null;if(t&&gs(t)){const n=np(t,e);n&&(s=n);const r=ZE(t,e);r&&(s=r)}else s=L("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function rp(t){return qe(t.protocol,!0)}function t0(t,e){let s=!1;return e&&!t?s=!0:t&&ks(t)&&t.length&&t.forEach(n=>{s=rp(n)}),s}function s0(t){return typeof t=="number"}function yt(t){return typeof t<"u"&&typeof t!==null}function n0(t){return!(!t||typeof t!="object"||!t.code||!Kc(t.code,!1)||!t.message||!qe(t.message,!1))}function r0(t){return!(Ke(t)||!qe(t.method,!1))}function i0(t){return!(Ke(t)||Ke(t.result)&&Ke(t.error)||!Kc(t.id,!1)||!qe(t.jsonrpc,!1))}function o0(t){return!(Ke(t)||!qe(t.name,!1))}function md(t,e){return!(!No(e)||!DE(t).includes(e))}function a0(t,e,s){return qe(s,!1)?ME(t,e).includes(s):!1}function c0(t,e,s){return qe(s,!1)?LE(t,e).includes(s):!1}function yd(t,e,s){let n=null;const r=l0(t),i=d0(e),o=Object.keys(r),a=Object.keys(i),c=wd(Object.keys(t)),l=wd(Object.keys(e)),d=c.filter(u=>!l.includes(u));return d.length&&(n=L("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
|
|
15
|
+
Required: ${d.toString()}
|
|
16
|
+
Received: ${Object.keys(e).toString()}`)),vn(o,a)||(n=L("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.
|
|
17
|
+
Required: ${o.toString()}
|
|
18
|
+
Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||n)return;const h=mr(e[u].accounts);h.includes(u)||(n=L("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${u}
|
|
19
|
+
Required: ${u}
|
|
20
|
+
Approved: ${h.toString()}`))}),o.forEach(u=>{n||(vn(r[u].methods,i[u].methods)?vn(r[u].events,i[u].events)||(n=L("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${u}`)):n=L("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${u}`))}),n}function l0(t){const e={};return Object.keys(t).forEach(s=>{var n;s.includes(":")?e[s]=t[s]:(n=t[s].chains)==null||n.forEach(r=>{e[r]={methods:t[s].methods,events:t[s].events}})}),e}function wd(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function d0(t){const e={};return Object.keys(t).forEach(s=>{if(s.includes(":"))e[s]=t[s];else{const n=mr(t[s].accounts);n==null||n.forEach(r=>{e[r]={accounts:t[s].accounts.filter(i=>i.includes(`${r}:`)),methods:t[s].methods,events:t[s].events}})}}),e}function u0(t,e){return Kc(t,!1)&&t<=e.max&&t>=e.min}function bd(){const t=vi();return new Promise(e=>{switch(t){case Rt.browser:e(h0());break;case Rt.reactNative:e(p0());break;case Rt.node:e(f0());break;default:e(!0)}})}function h0(){return gr()&&(navigator==null?void 0:navigator.onLine)}async function p0(){if(on()&&typeof ie<"u"&&ie!=null&&ie.NetInfo){const t=await(ie==null?void 0:ie.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function f0(){return!0}function g0(t){switch(vi()){case Rt.browser:m0(t);break;case Rt.reactNative:y0(t);break}}function m0(t){!on()&&gr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function y0(t){var e;on()&&typeof ie<"u"&&ie!=null&&ie.NetInfo&&((e=ie)==null||e.NetInfo.addEventListener(s=>t(s==null?void 0:s.isConnected)))}function w0(){var t;return gr()&&nr()?((t=nr())==null?void 0:t.visibilityState)==="visible":!0}const fa={};class Cr{static get(e){return fa[e]}static set(e,s){fa[e]=s}static delete(e){delete fa[e]}}function b0(t){const e=hr.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function E0({publicKey:t,signature:e,payload:s}){var n;const r=ic(s.method),i=128|parseInt(((n=s.version)==null?void 0:n.toString())||"4"),o=A0(s.address),a=s.era==="00"?new Uint8Array([0]):ic(s.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(s.nonce,16),l=new Uint8Array([c&255,c>>8&255]),d=BigInt(`0x${v0(s.tip)}`),u=I0(d),h=new Uint8Array([0,...t,o,...e,...a,...l,...u,...r]),p=_0(h.length+1);return new Uint8Array([...p,i,...h])}function C0(t){const e=ic(t),s=of.blake2b(e,void 0,32);return"0x"+me.from(s).toString("hex")}function ic(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function v0(t){return t.startsWith("0x")?t.slice(2):t}function A0(t){const e=hr.decode(t)[0];return e===42?0:e===60?2:1}function _0(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function I0(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function N0(t){const e=Uint8Array.from(me.from(t.signature,"hex")),s=b0(t.transaction.address),n=E0({publicKey:s,signature:e,payload:t.transaction}),r=me.from(n).toString("hex");return C0(r)}function Vc({logger:t,name:e}){const s=typeof t=="string"?Ic({opts:{level:t,name:e}}).logger:t;return s.level=typeof t=="string"?t:t.level,s}const ip="wc",op=2,So="core",ms=`${ip}@2:${So}:`,S0={name:So,logger:"error"},T0={database:":memory:"},O0="crypto",Ed="client_ed25519_seed",R0=j.ONE_DAY,P0="keychain",k0="0.3",x0="messages",$0="0.3",U0=j.SIX_HOURS,D0="publisher",ap="irn",M0="error",cp="wss://relay.walletconnect.org",L0="relayer",Fe={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"},F0="_subscription",Ut={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},B0=.1,oc="2.22.4",Pe={link_mode:"link_mode",relay:"relay"},io={inbound:"inbound",outbound:"outbound"},j0="0.3",q0="WALLETCONNECT_CLIENT_ID",Cd="WALLETCONNECT_LINK_MODE_APPS",Nt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},W0="subscription",H0="0.3",K0="pairing",V0="0.3",vr={wc_pairingDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:j.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:j.ONE_DAY,prompt:!1,tag:0},res:{ttl:j.ONE_DAY,prompt:!1,tag:0}}},yn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Jt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},z0="history",G0="0.3",Y0="expirer",Bt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},J0="0.3",X0="verify-api",Z0="https://verify.walletconnect.com",lp="https://verify.walletconnect.org",Lr=lp,Q0=`${Lr}/v3`,eC=[Z0,lp],tC="echo",sC="https://echo.walletconnect.com",as={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"},vs={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"},Xt={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"},un={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"},hn={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"},Ar={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"},nC=.1,rC="event-client",iC=86400,oC="https://pulse.walletconnect.org/batch";function aC(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),n=0;n<s.length;n++)s[n]=255;for(var r=0;r<t.length;r++){var i=t.charAt(r),o=i.charCodeAt(0);if(s[o]!==255)throw new TypeError(i+" is ambiguous");s[o]=r}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var m=0,y=0,w=0,b=f.length;w!==b&&f[w]===0;)w++,m++;for(var A=(b-w)*d+1>>>0,k=new Uint8Array(A);w!==b;){for(var $=f[w],M=0,H=A-1;($!==0||M<y)&&H!==-1;H--,M++)$+=256*k[H]>>>0,k[H]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");y=M,w++}for(var G=A-y;G!==A&&k[G]===0;)G++;for(var P=c.repeat(m);G<A;++G)P+=t.charAt(k[G]);return P}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var m=0;if(f[m]!==" "){for(var y=0,w=0;f[m]===c;)y++,m++;for(var b=(f.length-m)*l+1>>>0,A=new Uint8Array(b);f[m];){var k=s[f.charCodeAt(m)];if(k===255)return;for(var $=0,M=b-1;(k!==0||$<w)&&M!==-1;M--,$++)k+=a*A[M]>>>0,A[M]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");w=$,m++}if(f[m]!==" "){for(var H=b-w;H!==b&&A[H]===0;)H++;for(var G=new Uint8Array(y+(b-H)),P=y;H!==b;)G[P++]=A[H++];return G}}}function p(f){var m=h(f);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:p}}var cC=aC,lC=cC;const dp=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},dC=t=>new TextEncoder().encode(t),uC=t=>new TextDecoder().decode(t);class hC{constructor(e,s,n){this.name=e,this.prefix=s,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class pC{constructor(e,s,n){if(this.name=e,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return up(this,e)}}class fC{constructor(e){this.decoders=e}or(e){return up(this,e)}decode(e){const s=e[0],n=this.decoders[s];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const up=(t,e)=>new fC({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class gC{constructor(e,s,n,r){this.name=e,this.prefix=s,this.baseEncode=n,this.baseDecode=r,this.encoder=new hC(e,s,n),this.decoder=new pC(e,s,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const qo=({name:t,prefix:e,encode:s,decode:n})=>new gC(t,e,s,n),Si=({prefix:t,name:e,alphabet:s})=>{const{encode:n,decode:r}=lC(s,e);return qo({prefix:t,name:e,encode:n,decode:i=>dp(r(i))})},mC=(t,e,s,n)=>{const r={};for(let d=0;d<e.length;++d)r[e[d]]=d;let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*s/8|0);let a=0,c=0,l=0;for(let d=0;d<i;++d){const u=r[t[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<s|u,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},yC=(t,e,s)=>{const n=e[e.length-1]==="=",r=(1<<s)-1;let i="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,i+=e[r&a>>o];if(o&&(i+=e[r&a<<s-o]),n)for(;i.length*s&7;)i+="=";return i},st=({name:t,prefix:e,bitsPerChar:s,alphabet:n})=>qo({prefix:e,name:t,encode(r){return yC(r,n,s)},decode(r){return mC(r,n,s,t)}}),wC=qo({prefix:"\0",name:"identity",encode:t=>uC(t),decode:t=>dC(t)});var bC=Object.freeze({__proto__:null,identity:wC});const EC=st({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var CC=Object.freeze({__proto__:null,base2:EC});const vC=st({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var AC=Object.freeze({__proto__:null,base8:vC});const _C=Si({prefix:"9",name:"base10",alphabet:"0123456789"});var IC=Object.freeze({__proto__:null,base10:_C});const NC=st({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),SC=st({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var TC=Object.freeze({__proto__:null,base16:NC,base16upper:SC});const OC=st({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),RC=st({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),PC=st({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kC=st({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),xC=st({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),$C=st({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),UC=st({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),DC=st({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),MC=st({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var LC=Object.freeze({__proto__:null,base32:OC,base32upper:RC,base32pad:PC,base32padupper:kC,base32hex:xC,base32hexupper:$C,base32hexpad:UC,base32hexpadupper:DC,base32z:MC});const FC=Si({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),BC=Si({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var jC=Object.freeze({__proto__:null,base36:FC,base36upper:BC});const qC=Si({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),WC=Si({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var HC=Object.freeze({__proto__:null,base58btc:qC,base58flickr:WC});const KC=st({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),VC=st({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),zC=st({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),GC=st({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var YC=Object.freeze({__proto__:null,base64:KC,base64pad:VC,base64url:zC,base64urlpad:GC});const hp=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),JC=hp.reduce((t,e,s)=>(t[s]=e,t),[]),XC=hp.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function ZC(t){return t.reduce((e,s)=>(e+=JC[s],e),"")}function QC(t){const e=[];for(const s of t){const n=XC[s.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(n)}return new Uint8Array(e)}const ev=qo({prefix:"🚀",name:"base256emoji",encode:ZC,decode:QC});var tv=Object.freeze({__proto__:null,base256emoji:ev}),sv=pp,vd=128,nv=127,rv=~nv,iv=Math.pow(2,31);function pp(t,e,s){e=e||[],s=s||0;for(var n=s;t>=iv;)e[s++]=t&255|vd,t/=128;for(;t&rv;)e[s++]=t&255|vd,t>>>=7;return e[s]=t|0,pp.bytes=s-n+1,e}var ov=ac,av=128,Ad=127;function ac(t,n){var s=0,n=n||0,r=0,i=n,o,a=t.length;do{if(i>=a)throw ac.bytes=0,new RangeError("Could not decode varint");o=t[i++],s+=r<28?(o&Ad)<<r:(o&Ad)*Math.pow(2,r),r+=7}while(o>=av);return ac.bytes=i-n,s}var cv=Math.pow(2,7),lv=Math.pow(2,14),dv=Math.pow(2,21),uv=Math.pow(2,28),hv=Math.pow(2,35),pv=Math.pow(2,42),fv=Math.pow(2,49),gv=Math.pow(2,56),mv=Math.pow(2,63),yv=function(t){return t<cv?1:t<lv?2:t<dv?3:t<uv?4:t<hv?5:t<pv?6:t<fv?7:t<gv?8:t<mv?9:10},wv={encode:sv,decode:ov,encodingLength:yv},fp=wv;const _d=(t,e,s=0)=>(fp.encode(t,e,s),e),Id=t=>fp.encodingLength(t),cc=(t,e)=>{const s=e.byteLength,n=Id(t),r=n+Id(s),i=new Uint8Array(r+s);return _d(t,i,0),_d(s,i,n),i.set(e,r),new bv(t,s,e,i)};class bv{constructor(e,s,n,r){this.code=e,this.size=s,this.digest=n,this.bytes=r}}const gp=({name:t,code:e,encode:s})=>new Ev(t,e,s);class Ev{constructor(e,s,n){this.name=e,this.code=s,this.encode=n}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?cc(this.code,s):s.then(n=>cc(this.code,n))}else throw Error("Unknown type, must be binary type")}}const mp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Cv=gp({name:"sha2-256",code:18,encode:mp("SHA-256")}),vv=gp({name:"sha2-512",code:19,encode:mp("SHA-512")});var Av=Object.freeze({__proto__:null,sha256:Cv,sha512:vv});const yp=0,_v="identity",wp=dp,Iv=t=>cc(yp,wp(t)),Nv={code:yp,name:_v,encode:wp,digest:Iv};var Sv=Object.freeze({__proto__:null,identity:Nv});new TextEncoder,new TextDecoder;const Nd={...bC,...CC,...AC,...IC,...TC,...LC,...jC,...HC,...YC,...tv};({...Av,...Sv});function bp(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Tv(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?bp(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Ep(t,e,s,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:n}}}const Sd=Ep("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ga=Ep("ascii","a",t=>{let e="a";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return e},t=>{t=t.substring(1);const e=Tv(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),Ov={utf8:Sd,"utf-8":Sd,hex:Nd.base16,latin1:ga,ascii:ga,binary:ga,...Nd};function Rv(t,e="utf8"){const s=Ov[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?bp(globalThis.Buffer.from(t,"utf-8")):s.decoder.decode(`${s.prefix}${t}`)}var Pv=Object.defineProperty,kv=(t,e,s)=>e in t?Pv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,is=(t,e,s)=>kv(t,typeof e!="symbol"?e+"":e,s);class xv{constructor(e,s){this.core=e,this.logger=s,is(this,"keychain",new Map),is(this,"name",P0),is(this,"version",k0),is(this,"initialized",!1),is(this,"storagePrefix",ms),is(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),is(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),is(this,"set",async(n,r)=>{this.isInitialized(),this.keychain.set(n,r),await this.persist()}),is(this,"get",n=>{this.isInitialized();const r=this.keychain.get(n);if(typeof r>"u"){const{message:i}=L("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(i)}return r}),is(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=Pt(s,this.name)}get context(){return kt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Va(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?za(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $v=Object.defineProperty,Uv=(t,e,s)=>e in t?$v(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ve=(t,e,s)=>Uv(t,typeof e!="symbol"?e+"":e,s);class Dv{constructor(e,s,n){this.core=e,this.logger=s,Ve(this,"name",O0),Ve(this,"keychain"),Ve(this,"randomSessionIdentifier",rc()),Ve(this,"initialized",!1),Ve(this,"clientId"),Ve(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ve(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ve(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const r=await this.getClientSeed(),i=sl(r),o=hf(i.publicKey);return this.clientId=o,o}),Ve(this,"generateKeyPair",()=>{this.isInitialized();const r=dE();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ve(this,"signJWT",async r=>{this.isInitialized();const i=await this.getClientSeed(),o=sl(i),a=this.randomSessionIdentifier;return await pf(a,r,R0,o)}),Ve(this,"generateSharedKey",(r,i,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=uE(a,i);return this.setSymKey(c,o)}),Ve(this,"setSymKey",async(r,i)=>{this.isInitialized();const o=i||ro(r);return await this.keychain.set(o,r),o}),Ve(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"encode",async(r,i,o)=>{this.isInitialized();const a=sp(o),c=_c(i);if(od(a))return fE(c,o==null?void 0:o.encoding);if(id(a)){const h=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(h,p)}const l=this.getSymKey(r),{type:d,senderPublicKey:u}=a;return hE({type:d,symKey:l,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Ve(this,"decode",async(r,i,o)=>{this.isInitialized();const a=mE(i,o);if(od(a)){const c=gE(i,o==null?void 0:o.encoding);return uo(c)}if(id(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=pE({symKey:c,encoded:i,encoding:o==null?void 0:o.encoding});return uo(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ve(this,"getPayloadType",(r,i=bt)=>{const o=fi({encoded:r,encoding:i});return kn(o.type)}),Ve(this,"getPayloadSenderPublicKey",(r,i=bt)=>{const o=fi({encoded:r,encoding:i});return o.senderPublicKey?Ct(o.senderPublicKey,ut):void 0}),this.core=e,this.logger=Pt(s,this.name),this.keychain=n||new xv(this.core,this.logger)}get context(){return kt(this.logger)}async setPrivateKey(e,s){return await this.keychain.set(e,s),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ed)}catch{e=rc(),await this.keychain.set(Ed,e)}return Rv(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Mv=Object.defineProperty,Lv=Object.defineProperties,Fv=Object.getOwnPropertyDescriptors,Td=Object.getOwnPropertySymbols,Bv=Object.prototype.hasOwnProperty,jv=Object.prototype.propertyIsEnumerable,lc=(t,e,s)=>e in t?Mv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qv=(t,e)=>{for(var s in e||(e={}))Bv.call(e,s)&&lc(t,s,e[s]);if(Td)for(var s of Td(e))jv.call(e,s)&&lc(t,s,e[s]);return t},Wv=(t,e)=>Lv(t,Fv(e)),_t=(t,e,s)=>lc(t,typeof e!="symbol"?e+"":e,s);class Hv extends Fm{constructor(e,s){super(e,s),this.logger=e,this.core=s,_t(this,"messages",new Map),_t(this,"messagesWithoutClientAck",new Map),_t(this,"name",x0),_t(this,"version",$0),_t(this,"initialized",!1),_t(this,"storagePrefix",ms),_t(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),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}}}),_t(this,"set",async(n,r,i)=>{this.isInitialized();const o=jt(r);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(n,a),i===io.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,Wv(qv({},c),{[o]:r}))}return await this.persist(),o}),_t(this,"get",n=>{this.isInitialized();let r=this.messages.get(n);return typeof r>"u"&&(r={}),r}),_t(this,"getWithoutAck",n=>{this.isInitialized();const r={};for(const i of n){const o=this.messagesWithoutClientAck.get(i)||{};r[i]=Object.values(o)}return r}),_t(this,"has",(n,r)=>{this.isInitialized();const i=this.get(n),o=jt(r);return typeof i[o]<"u"}),_t(this,"ack",async(n,r)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(n);if(typeof i>"u")return;const o=jt(r);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,i),await this.persist()}),_t(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Pt(e,this.name),this.core=s}get context(){return kt(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(e){await this.core.storage.setItem(this.storageKey,Va(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Va(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?za(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?za(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Kv=Object.defineProperty,Vv=Object.defineProperties,zv=Object.getOwnPropertyDescriptors,Od=Object.getOwnPropertySymbols,Gv=Object.prototype.hasOwnProperty,Yv=Object.prototype.propertyIsEnumerable,dc=(t,e,s)=>e in t?Kv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,jn=(t,e)=>{for(var s in e||(e={}))Gv.call(e,s)&&dc(t,s,e[s]);if(Od)for(var s of Od(e))Yv.call(e,s)&&dc(t,s,e[s]);return t},Rd=(t,e)=>Vv(t,zv(e)),Dt=(t,e,s)=>dc(t,typeof e!="symbol"?e+"":e,s);class Jv extends Bm{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Dt(this,"events",new $n.EventEmitter),Dt(this,"name",D0),Dt(this,"queue",new Map),Dt(this,"publishTimeout",j.toMiliseconds(j.ONE_MINUTE)),Dt(this,"initialPublishTimeout",j.toMiliseconds(j.ONE_SECOND*15)),Dt(this,"needsTransportRestart",!1),Dt(this,"publish",async(n,r,i)=>{var o,a,c,l,d;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:r,opts:i}});const u=(i==null?void 0:i.ttl)||U0,h=(i==null?void 0:i.prompt)||!1,p=(i==null?void 0:i.tag)||0,f=(i==null?void 0:i.id)||En().toString(),m=Yn(Io().protocol),y={id:f,method:(i==null?void 0:i.publishMethod)||m.publish,params:jn({topic:n,message:r,ttl:u,prompt:h,tag:p,attestation:i==null?void 0:i.attestation},i==null?void 0:i.tvf)},w=`Failed to publish payload, please try again. id:${f} tag:${p}`;try{Ke((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),Ke((c=y.params)==null?void 0:c.tag)&&((l=y.params)==null||delete l.tag);const b=new Promise(async A=>{const k=({id:M})=>{var H;((H=y.id)==null?void 0:H.toString())===M.toString()&&(this.removeRequestFromQueue(M),this.relayer.events.removeListener(Fe.publish,k),A())};this.relayer.events.on(Fe.publish,k);const $=hs(new Promise((M,H)=>{this.rpcPublish(y,i).then(M).catch(G=>{this.logger.warn(G,G==null?void 0:G.message),H(G)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${f} tag:${p}`);try{await $,this.events.removeListener(Fe.publish,k)}catch(M){this.queue.set(f,{request:y,opts:i,attempt:1}),this.logger.warn(M,M==null?void 0:M.message)}});this.logger.trace({type:"method",method:"publish",params:{id:f,topic:n,message:r,opts:i}}),await hs(b,this.publishTimeout,w)}catch(b){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(b),(d=i==null?void 0:i.internal)!=null&&d.throwOnFailedPublish)throw b}finally{this.queue.delete(f)}}),Dt(this,"publishCustom",async n=>{var r,i,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:l,opts:d={}}=n,{attestation:u,tvf:h,publishMethod:p,prompt:f,tag:m,ttl:y=j.FIVE_MINUTES}=d,w=d.id||En().toString(),b=Yn(Io().protocol),A=p||b.publish,k={id:w,method:A,params:jn(Rd(jn({},l),{ttl:y,prompt:f,tag:m,attestation:u}),h)},$=`Failed to publish custom payload, please try again. id:${w} tag:${m}`;try{Ke((r=k.params)==null?void 0:r.prompt)&&((i=k.params)==null||delete i.prompt),Ke((o=k.params)==null?void 0:o.tag)&&((a=k.params)==null||delete a.tag);const M=new Promise(async H=>{const G=({id:Q})=>{var se;((se=k.id)==null?void 0:se.toString())===Q.toString()&&(this.removeRequestFromQueue(Q),this.relayer.events.removeListener(Fe.publish,G),H())};this.relayer.events.on(Fe.publish,G);const P=hs(new Promise((Q,se)=>{this.rpcPublish(k,d).then(Q).catch(T=>{this.logger.warn(T,T==null?void 0:T.message),se(T)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${A} id:${w} tag:${m}`);try{await P,this.events.removeListener(Fe.publish,G)}catch(Q){this.queue.set(w,{request:k,opts:d,attempt:1}),this.logger.warn(Q,Q==null?void 0:Q.message)}});this.logger.trace({type:"method",method:"publish",params:{id:w,payload:l,opts:d}}),await hs(M,this.publishTimeout,$)}catch(M){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(M),(c=d==null?void 0:d.internal)!=null&&c.throwOnFailedPublish)throw M}finally{this.queue.delete(w)}}),Dt(this,"on",(n,r)=>{this.events.on(n,r)}),Dt(this,"once",(n,r)=>{this.events.once(n,r)}),Dt(this,"off",(n,r)=>{this.events.off(n,r)}),Dt(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.relayer=e,this.logger=Pt(s,this.name),this.registerEventListeners()}get context(){return kt(this.logger)}async rpcPublish(e,s){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(Fe.publish,jn(jn({},e),s)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{var n;const r=e.attempt+1;this.queue.set(s,Rd(jn({},e),{attempt:r})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${r}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(pr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Fe.connection_stalled);return}this.checkQueue()}),this.relayer.on(Fe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Xv=Object.defineProperty,Zv=(t,e,s)=>e in t?Xv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qn=(t,e,s)=>Zv(t,typeof e!="symbol"?e+"":e,s);class Qv{constructor(){qn(this,"map",new Map),qn(this,"set",(e,s)=>{const n=this.get(e);this.exists(e,s)||this.map.set(e,[...n,s])}),qn(this,"get",e=>this.map.get(e)||[]),qn(this,"exists",(e,s)=>this.get(e).includes(s)),qn(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,s))return;const r=n.filter(i=>i!==s);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),qn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var e1=Object.defineProperty,t1=Object.defineProperties,s1=Object.getOwnPropertyDescriptors,Pd=Object.getOwnPropertySymbols,n1=Object.prototype.hasOwnProperty,r1=Object.prototype.propertyIsEnumerable,uc=(t,e,s)=>e in t?e1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_r=(t,e)=>{for(var s in e||(e={}))n1.call(e,s)&&uc(t,s,e[s]);if(Pd)for(var s of Pd(e))r1.call(e,s)&&uc(t,s,e[s]);return t},ma=(t,e)=>t1(t,s1(e)),Te=(t,e,s)=>uc(t,typeof e!="symbol"?e+"":e,s);class i1 extends Wm{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Te(this,"subscriptions",new Map),Te(this,"topicMap",new Qv),Te(this,"events",new $n.EventEmitter),Te(this,"name",W0),Te(this,"version",H0),Te(this,"pending",new Map),Te(this,"cached",[]),Te(this,"initialized",!1),Te(this,"storagePrefix",ms),Te(this,"subscribeTimeout",j.toMiliseconds(j.ONE_MINUTE)),Te(this,"initialSubscribeTimeout",j.toMiliseconds(j.ONE_SECOND*15)),Te(this,"clientId"),Te(this,"batchSubscribeTopicsLimit",500),Te(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Te(this,"subscribe",async(n,r)=>{var i;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}});try{const o=Io(r),a={topic:n,relay:o,transportType:r==null?void 0:r.transportType};(i=r==null?void 0:r.internal)!=null&&i.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,r);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:r}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),Te(this,"unsubscribe",async(n,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(n,r.id,r):await this.unsubscribeByTopic(n,r)}),Te(this,"isSubscribed",n=>new Promise(r=>{r(this.topicMap.topics.includes(n))})),Te(this,"isKnownTopic",n=>new Promise(r=>{r(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(i=>i.topic===n))})),Te(this,"on",(n,r)=>{this.events.on(n,r)}),Te(this,"once",(n,r)=>{this.events.once(n,r)}),Te(this,"off",(n,r)=>{this.events.off(n,r)}),Te(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),Te(this,"start",async()=>{await this.onConnect()}),Te(this,"stop",async()=>{await this.onDisconnect()}),Te(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Te(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(r=>{n.push(r)}),await this.batchSubscribe(n)}),Te(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(pr.pulse,async()=>{await this.checkPending()}),this.events.on(Nt.created,async n=>{const r=Nt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()}),this.events.on(Nt.deleted,async n=>{const r=Nt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()})}),this.relayer=e,this.logger=Pt(s,this.name),this.clientId=""}get context(){return kt(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(e,s){let n=!1;try{n=this.getSubscription(e).topic===s}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(e,s){const n=this.topicMap.get(e);await Promise.all(n.map(async r=>await this.unsubscribeById(e,r,s)))}async unsubscribeById(e,s,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}});try{const r=Io(n);await this.restartToComplete({topic:e,id:s,relay:r}),await this.rpcUnsubscribe(e,s,r);const i=Ue("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,s,n){var r,i;const o=await this.getSubscriptionId(e);if((r=n==null?void 0:n.internal)!=null&&r.skipSubscribe)return o;(!n||(n==null?void 0:n.transportType)===Pe.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const a={method:Yn(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(i=n==null?void 0:n.internal)==null?void 0:i.throwOnFailedPublish;try{if((n==null?void 0:n.transportType)===Pe.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(u=>this.logger.warn(u))},j.toMiliseconds(j.ONE_SECOND)),o;const l=new Promise(async u=>{const h=p=>{p.topic===e&&(this.events.removeListener(Nt.created,h),u(p.id))};this.events.on(Nt.created,h);try{const p=await hs(new Promise((f,m)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y==null?void 0:y.message),m(y)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Nt.created,h),u(p)}catch{}}),d=await hs(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!d&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return d?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Fe.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,n={method:Yn(s.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await hs(new Promise(r=>{this.relayer.request(n).catch(i=>this.logger.warn(i)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Fe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,n={method:Yn(s.protocol).batchFetchMessages,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let r;try{r=await await hs(new Promise((i,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Fe.connection_stalled)}return r}rpcUnsubscribe(e,s,n){const r={method:Yn(n.protocol).unsubscribe,params:{topic:e,id:s}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,s){this.setSubscription(e,ma(_r({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,_r({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,n){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,s){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:s}),this.addSubscription(e,s)}addSubscription(e,s){this.subscriptions.set(e,_r({},s)),this.topicMap.set(s.topic,e),this.events.emit(Nt.created,s)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const s=this.subscriptions.get(e);if(!s){const{message:n}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Nt.deleted,ma(_r({},n),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Nt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<s;n++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(Nt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(s=>{var n;return s.topic===((n=this.subscriptions.get(s.id))==null?void 0:n.topic)})){const{message:s}=L("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async s=>ma(_r({},s),{id:await this.getSubscriptionId(s.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const s=await this.rpcBatchFetchMessages(e);s&&s.messages&&(await Py(j.toMiliseconds(j.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(s.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return jt(e+await this.getClientId())}}var o1=Object.defineProperty,kd=Object.getOwnPropertySymbols,a1=Object.prototype.hasOwnProperty,c1=Object.prototype.propertyIsEnumerable,hc=(t,e,s)=>e in t?o1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xd=(t,e)=>{for(var s in e||(e={}))a1.call(e,s)&&hc(t,s,e[s]);if(kd)for(var s of kd(e))c1.call(e,s)&&hc(t,s,e[s]);return t},Ae=(t,e,s)=>hc(t,typeof e!="symbol"?e+"":e,s);class l1 extends jm{constructor(e){var s;super(e),Ae(this,"protocol","wc"),Ae(this,"version",2),Ae(this,"core"),Ae(this,"logger"),Ae(this,"events",new $n.EventEmitter),Ae(this,"provider"),Ae(this,"messages"),Ae(this,"subscriber"),Ae(this,"publisher"),Ae(this,"name",L0),Ae(this,"transportExplicitlyClosed",!1),Ae(this,"initialized",!1),Ae(this,"connectionAttemptInProgress",!1),Ae(this,"relayUrl"),Ae(this,"projectId"),Ae(this,"packageName"),Ae(this,"bundleId"),Ae(this,"hasExperiencedNetworkDisruption",!1),Ae(this,"pingTimeout"),Ae(this,"heartBeatTimeout",j.toMiliseconds(j.THIRTY_SECONDS+j.FIVE_SECONDS)),Ae(this,"reconnectTimeout"),Ae(this,"connectPromise"),Ae(this,"reconnectInProgress",!1),Ae(this,"requestsInFlight",[]),Ae(this,"connectTimeout",j.toMiliseconds(j.ONE_SECOND*15)),Ae(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const o=n.id||En().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const a=`${o}:${((i=n.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),Ae(this,"resetPingTimeout",()=>{bo()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,i,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||o.call(i)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),Ae(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),Ae(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Fe.connect)}),Ae(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ae(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(Fe.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ae(this,"registerProviderListeners",()=>{this.provider.on(Ut.payload,this.onPayloadHandler),this.provider.on(Ut.connect,this.onConnectHandler),this.provider.on(Ut.disconnect,this.onDisconnectHandler),this.provider.on(Ut.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Vc({logger:(s=e.logger)!=null?s:M0,name:this.name}),this.messages=new Hv(this.logger,e.core),this.subscriber=new i1(this,this.logger),this.publisher=new Jv(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||cp,gy()?this.packageName=Sl():my()&&(this.bundleId=Sl()),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(e=>this.logger.warn(e,e==null?void 0:e.message))}get context(){return kt(this.logger)}get connected(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,n){this.isInitialized(),await this.publisher.publish(e,s,n),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:Pe.relay},io.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,s){var n,r,i;this.isInitialized(),(!(s!=null&&s.transportType)||(s==null?void 0:s.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((n=s==null?void 0:s.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(r=s==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",c;const l=d=>{d.topic===e&&(this.subscriber.off(Nt.created,l),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(Nt.created,l)}),new Promise(async(d,u)=>{a=await this.subscriber.subscribe(e,xd({internal:{throwOnFailedPublish:o}},s)).catch(h=>{o&&u(h)})||a,d()})]),a}async unsubscribe(e,s){this.isInitialized(),await this.subscriber.unsubscribe(e,s)}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}off(e,s){this.events.off(e,s)}removeListener(e,s){this.events.removeListener(e,s)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await hs(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){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(s,n)=>{await this.connect(e).then(s).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(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await bd())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const s=e.sort((n,r)=>n.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const n of s)try{await this.onMessageEvent(n)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:n}=e;if(!s.sessionExists){const r=je(j.FIVE_MINUTES),i={topic:n,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,i)}this.events.emit(Fe.message,e),await this.recordMessageEvent(e,io.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let s=1;for(;s<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${s}...`),await this.createProvider(),await new Promise(async(n,r)=>{const i=()=>{r(new Error("Connection interrupted while trying to connect"))};this.provider.once(Ut.disconnect,i),await hs(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(Ut.disconnect,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ut.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Ut.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const r=n;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${s}`);break}await new Promise(n=>setTimeout(n,j.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,n,r,i;if(bo())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null||i.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Nc(new uf(Cy({sdkVersion:oc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,s){const{topic:n,message:r}=e;await this.messages.set(n,r,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const r=this.messages.has(s,n);return r&&this.logger.warn(`Ignoring duplicate message: ${n}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Sc(e)){if(!e.method.endsWith(F0))return;const s=e.params,{topic:n,message:r,publishedAt:i,attestation:o}=s.data,a={topic:n,message:r,publishedAt:i,transportType:Pe.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(xd({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Tc(e)&&this.events.emit(Fe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,io.inbound),this.events.emit(Fe.message,e))}async acknowledgePayload(e){const s=qr(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Ut.payload,this.onPayloadHandler),this.provider.off(Ut.connect,this.onConnectHandler),this.provider.off(Ut.disconnect,this.onDisconnectHandler),this.provider.off(Ut.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await bd();g0(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(n=>this.logger.error(n,n==null?void 0:n.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(pr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&w0())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s==null?void 0:s.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Fe.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(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},j.toMiliseconds(B0)))))}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function d1(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function $d(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Ud(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const u1="[object RegExp]",h1="[object String]",p1="[object Number]",f1="[object Boolean]",Dd="[object Arguments]",g1="[object Symbol]",m1="[object Date]",y1="[object Map]",w1="[object Set]",b1="[object Array]",E1="[object Function]",C1="[object ArrayBuffer]",ya="[object Object]",v1="[object Error]",A1="[object DataView]",_1="[object Uint8Array]",I1="[object Uint8ClampedArray]",N1="[object Uint16Array]",S1="[object Uint32Array]",T1="[object BigUint64Array]",O1="[object Int8Array]",R1="[object Int16Array]",P1="[object Int32Array]",k1="[object BigInt64Array]",x1="[object Float32Array]",$1="[object Float64Array]";function U1(){}function Md(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function D1(t,e,s){return Pr(t,e,void 0,void 0,void 0,void 0,s)}function Pr(t,e,s,n,r,i,o){const a=o(t,e,s,n,r,i);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Fr(t,e,i,o)}return Fr(t,e,i,o)}function Fr(t,e,s,n){if(Object.is(t,e))return!0;let r=Ud(t),i=Ud(e);if(r===Dd&&(r=ya),i===Dd&&(i=ya),r!==i)return!1;switch(r){case h1:return t.toString()===e.toString();case p1:{const c=t.valueOf(),l=e.valueOf();return d1(c,l)}case f1:case m1:case g1:return Object.is(t.valueOf(),e.valueOf());case u1:return t.source===e.source&&t.flags===e.flags;case E1:return t===e}s=s??new Map;const o=s.get(t),a=s.get(e);if(o!=null&&a!=null)return o===e;s.set(t,e),s.set(e,t);try{switch(r){case y1:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Pr(l,e.get(c),c,t,e,s,n))return!1;return!0}case w1:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let d=0;d<c.length;d++){const u=c[d],h=l.findIndex(p=>Pr(u,p,void 0,t,e,s,n));if(h===-1)return!1;l.splice(h,1)}return!0}case b1:case _1:case I1:case N1:case S1:case T1:case O1:case R1:case P1:case k1:case x1:case $1:{if(typeof me<"u"&&me.isBuffer(t)!==me.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Pr(t[c],e[c],c,t,e,s,n))return!1;return!0}case C1:return t.byteLength!==e.byteLength?!1:Fr(new Uint8Array(t),new Uint8Array(e),s,n);case A1:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Fr(new Uint8Array(t),new Uint8Array(e),s,n);case v1:return t.name===e.name&&t.message===e.message;case ya:{if(!(Fr(t.constructor,e.constructor,s,n)||Md(t)&&Md(e)))return!1;const c=[...Object.keys(t),...$d(t)],l=[...Object.keys(e),...$d(e)];if(c.length!==l.length)return!1;for(let d=0;d<c.length;d++){const u=c[d],h=t[u];if(!Object.hasOwn(e,u))return!1;const p=e[u];if(!Pr(h,p,u,t,e,s,n))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function M1(t,e){return D1(t,e,U1)}var L1=Object.defineProperty,Ld=Object.getOwnPropertySymbols,F1=Object.prototype.hasOwnProperty,B1=Object.prototype.propertyIsEnumerable,pc=(t,e,s)=>e in t?L1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Fd=(t,e)=>{for(var s in e||(e={}))F1.call(e,s)&&pc(t,s,e[s]);if(Ld)for(var s of Ld(e))B1.call(e,s)&&pc(t,s,e[s]);return t},gt=(t,e,s)=>pc(t,typeof e!="symbol"?e+"":e,s);class Dn extends qm{constructor(e,s,n,r=ms,i=void 0){super(e,s,n,r),this.core=e,this.logger=s,this.name=n,gt(this,"map",new Map),gt(this,"version",j0),gt(this,"cached",[]),gt(this,"initialized",!1),gt(this,"getKey"),gt(this,"storagePrefix",ms),gt(this,"recentlyDeleted",[]),gt(this,"recentlyDeletedLimit",200),gt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ke(o)?this.map.set(this.getKey(o),o):VE(o)?this.map.set(o.id,o):zE(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),gt(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),gt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),gt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>M1(a[c],o[c]))):this.values)),gt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Fd(Fd({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),gt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Pt(s,this.name),this.storagePrefix=r,this.getKey=i}get context(){return kt(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(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const s=this.map.get(e);if(!s){if(this.recentlyDeleted.includes(e)){const{message:r}=L("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:n}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return s}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:s}=L("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var j1=Object.defineProperty,q1=(t,e,s)=>e in t?j1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fe=(t,e,s)=>q1(t,typeof e!="symbol"?e+"":e,s);class W1{constructor(e,s){this.core=e,this.logger=s,fe(this,"name",K0),fe(this,"version",V0),fe(this,"events",new Ac),fe(this,"pairings"),fe(this,"initialized",!1),fe(this,"storagePrefix",ms),fe(this,"ignoredPayloadTypes",[Ps]),fe(this,"registeredMethods",[]),fe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),fe(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),fe(this,"create",async n=>{this.isInitialized();const r=rc(),i=await this.core.crypto.setSymKey(r),o=je(j.FIVE_MINUTES),a={protocol:ap},c={topic:i,expiry:o,relay:a,active:!1,methods:n==null?void 0:n.methods},l=dd({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:r,relay:a,expiryTimestamp:o,methods:n==null?void 0:n.methods});return this.events.emit(yn.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:n==null?void 0:n.transportType,internal:n==null?void 0:n.internal}),{topic:i,uri:l}}),fe(this,"pair",async n=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:n==null?void 0:n.uri,trace:[as.pairing_started]}});this.isValidPair(n,r);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=ld(n.uri);r.props.properties.topic=i,r.addTrace(as.pairing_uri_validation_success),r.addTrace(as.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(i)){if(d=this.pairings.get(i),r.addTrace(as.existing_pairing),d.active)throw r.setError(vs.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);r.addTrace(as.pairing_not_expired)}const u=c||je(j.FIVE_MINUTES),h={topic:i,relay:a,expiry:u,active:!1,methods:l};this.core.expirer.set(i,u),await this.pairings.set(i,h),r.addTrace(as.store_new_pairing),n.activatePairing&&await this.activate({topic:i}),this.events.emit(yn.create,h),r.addTrace(as.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),r.addTrace(as.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(vs.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(p){throw r.setError(vs.subscribe_pairing_topic_failure),p}return r.addTrace(as.subscribe_pairing_topic_success),h}),fe(this,"activate",async({topic:n})=>{this.isInitialized();const r=je(j.FIVE_MINUTES);this.core.expirer.set(n,r),await this.pairings.update(n,{active:!0,expiry:r})}),fe(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.");const{topic:r}=n;if(this.pairings.keys.includes(r)){const i=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=mn();this.events.once(Ne("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}}),fe(this,"updateExpiry",async({topic:n,expiry:r})=>{this.isInitialized(),await this.pairings.update(n,{expiry:r})}),fe(this,"updateMetadata",async({topic:n,metadata:r})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:r})}),fe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),fe(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:r}=n;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Ue("USER_DISCONNECTED")),await this.deletePairing(r))}),fe(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:r,relay:i,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(r);return dd({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:i,expiryTimestamp:o,methods:a})}),fe(this,"sendRequest",async(n,r,i)=>{const o=ls(r,i),a=await this.core.crypto.encode(n,o),c=vr[r].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),fe(this,"sendResult",async(n,r,i)=>{const o=qr(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=vr[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"sendError",async(n,r,i)=>{const o=Tu(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=vr[c]?vr[c].res:vr.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"deletePairing",async(n,r)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Ue("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),r?Promise.resolve():this.core.expirer.del(n)])}),fe(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(r=>ds(r.expiry));await Promise.all(n.map(r=>this.deletePairing(r.topic)))}),fe(this,"onRelayEventRequest",async n=>{const{topic:r,payload:i}=n;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,i);default:return await this.onUnknownRpcMethodRequest(r,i)}}),fe(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i}=n,o=(await this.core.history.get(r,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,i);default:return this.onUnknownRpcMethodResponse(o)}}),fe(this,"onPairingPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult(i,n,!0),this.events.emit(yn.ping,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),fe(this,"onPairingPingResponse",(n,r)=>{const{id:i}=r;setTimeout(()=>{Es(r)?this.events.emit(Ne("pairing_ping",i),{}):cs(r)&&this.events.emit(Ne("pairing_ping",i),{error:r.error})},500)}),fe(this,"onPairingDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(yn.delete,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),fe(this,"onUnknownRpcMethodRequest",async(n,r)=>{const{id:i,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Ue("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,n,a),this.logger.error(a)}catch(a){await this.sendError(i,n,a),this.logger.error(a)}}),fe(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(Ue("WC_METHOD_UNSUPPORTED",n))}),fe(this,"isValidPair",(n,r)=>{var i;if(!yt(n)){const{message:a}=L("MISSING_OR_INVALID",`pair() params: ${n}`);throw r.setError(vs.malformed_pairing_uri),new Error(a)}if(!KE(n.uri)){const{message:a}=L("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw r.setError(vs.malformed_pairing_uri),new Error(a)}const o=ld(n==null?void 0:n.uri);if(!((i=o==null?void 0:o.relay)!=null&&i.protocol)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(vs.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(vs.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&j.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(vs.pairing_expired);const{message:a}=L("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),fe(this,"isValidPing",async n=>{if(!yt(n)){const{message:i}=L("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),fe(this,"isValidDisconnect",async n=>{if(!yt(n)){const{message:i}=L("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),fe(this,"isValidPairingTopic",async n=>{if(!qe(n,!1)){const{message:r}=L("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(r)}if(!this.pairings.keys.includes(n)){const{message:r}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(r)}if(ds(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:r}=L("EXPIRED",`pairing topic: ${n}`);throw new Error(r)}}),this.core=e,this.logger=Pt(s,this.name),this.pairings=new Dn(this.core,this.logger,this.name,this.storagePrefix)}get context(){return kt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Fe.message,async e=>{const{topic:s,message:n,transportType:r}=e;if(this.pairings.keys.includes(s)&&r!==Pe.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const i=await this.core.crypto.decode(s,n);Sc(i)?(this.core.history.set(s,i),await this.onRelayEventRequest({topic:s,payload:i})):Tc(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:s,payload:i}),this.core.history.delete(s,i.id)),await this.core.relayer.messages.ack(s,n)}catch(i){this.logger.error(i)}})}registerExpirerEvents(){this.core.expirer.on(Bt.expired,async e=>{const{topic:s}=ih(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(yn.expire,{topic:s}))})}}var H1=Object.defineProperty,K1=(t,e,s)=>e in t?H1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Xe=(t,e,s)=>K1(t,typeof e!="symbol"?e+"":e,s);class V1 extends Lm{constructor(e,s){super(e,s),this.core=e,this.logger=s,Xe(this,"records",new Map),Xe(this,"events",new $n.EventEmitter),Xe(this,"name",z0),Xe(this,"version",G0),Xe(this,"cached",[]),Xe(this,"initialized",!1),Xe(this,"storagePrefix",ms),Xe(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)}),Xe(this,"set",(n,r,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:r,chainId:i}),this.records.has(r.id))return;const o={id:r.id,topic:n,request:{method:r.method,params:r.params||null},chainId:i,expiry:je(j.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Jt.created,o)}),Xe(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;const r=await this.getRecord(n.id);typeof r.response>"u"&&(r.response=cs(n)?{error:n.error}:{result:n.result},this.records.set(r.id,r),this.persist(),this.events.emit(Jt.updated,r))}),Xe(this,"get",async(n,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:r}),await this.getRecord(r))),Xe(this,"delete",(n,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(i=>{if(i.topic===n){if(typeof r<"u"&&i.id!==r)return;this.records.delete(i.id),this.events.emit(Jt.deleted,i)}}),this.persist()}),Xe(this,"exists",async(n,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===n:!1)),Xe(this,"on",(n,r)=>{this.events.on(n,r)}),Xe(this,"once",(n,r)=>{this.events.once(n,r)}),Xe(this,"off",(n,r)=>{this.events.off(n,r)}),Xe(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=Pt(s,this.name)}get context(){return kt(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(){const e=[];return this.values.forEach(s=>{if(typeof s.response<"u")return;const n={topic:s.topic,request:ls(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const s=this.records.get(e);if(!s){const{message:n}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Jt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=L("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Jt.created,e=>{const s=Jt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Jt.updated,e=>{const s=Jt.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Jt.deleted,e=>{const s=Jt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(pr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{j.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(Jt.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var z1=Object.defineProperty,G1=(t,e,s)=>e in t?z1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ot=(t,e,s)=>G1(t,typeof e!="symbol"?e+"":e,s);class Y1 extends Hm{constructor(e,s){super(e,s),this.core=e,this.logger=s,ot(this,"expirations",new Map),ot(this,"events",new $n.EventEmitter),ot(this,"name",Y0),ot(this,"version",J0),ot(this,"cached",[]),ot(this,"initialized",!1),ot(this,"storagePrefix",ms),ot(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)}),ot(this,"has",n=>{try{const r=this.formatTarget(n);return typeof this.getExpiration(r)<"u"}catch{return!1}}),ot(this,"set",(n,r)=>{this.isInitialized();const i=this.formatTarget(n),o={target:i,expiry:r};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(Bt.created,{target:i,expiration:o})}),ot(this,"get",n=>{this.isInitialized();const r=this.formatTarget(n);return this.getExpiration(r)}),ot(this,"del",n=>{if(this.isInitialized(),this.has(n)){const r=this.formatTarget(n),i=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Bt.deleted,{target:r,expiration:i})}}),ot(this,"on",(n,r)=>{this.events.on(n,r)}),ot(this,"once",(n,r)=>{this.events.once(n,r)}),ot(this,"off",(n,r)=>{this.events.off(n,r)}),ot(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=Pt(s,this.name)}get context(){return kt(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(e){if(typeof e=="string")return vy(e);if(typeof e=="number")return Ay(e);const{message:s}=L("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(s)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Bt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=L("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const s=this.expirations.get(e);if(!s){const{message:n}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return s}checkExpiry(e,s){const{expiry:n}=s;j.toMiliseconds(n)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(Bt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(pr.pulse,()=>this.checkExpirations()),this.events.on(Bt.created,e=>{const s=Bt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Bt.expired,e=>{const s=Bt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Bt.deleted,e=>{const s=Bt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var J1=Object.defineProperty,X1=(t,e,s)=>e in t?J1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Be=(t,e,s)=>X1(t,typeof e!="symbol"?e+"":e,s);class Z1 extends Km{constructor(e,s,n){super(e,s,n),this.core=e,this.logger=s,this.store=n,Be(this,"name",X0),Be(this,"abortController"),Be(this,"isDevEnv"),Be(this,"verifyUrlV3",Q0),Be(this,"storagePrefix",ms),Be(this,"version",op),Be(this,"publicKey"),Be(this,"fetchPromise"),Be(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&j.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Be(this,"register",async r=>{if(!gr()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=nr(),d=this.startAbortTimer(j.ONE_SECOND*5),u=await new Promise((h,p)=>{const f=()=>{window.removeEventListener("message",y),l.body.removeChild(m),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const m=l.createElement("iframe");m.src=c,m.style.display="none",m.addEventListener("error",f,{signal:this.abortController.signal});const y=w=>{if(w.data&&typeof w.data=="string")try{const b=JSON.parse(w.data);if(b.type==="verify_attestation"){if(xa(b.attestation).payload.id!==o)return;clearInterval(d),l.body.removeChild(m),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",y),h(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};l.body.appendChild(m),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug(u,"jwt attestation"),u}catch(l){this.logger.warn(l)}return""}),Be(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=r;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(xa(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),Be(this,"fetchAttestation",async(r,i)=>{this.logger.debug(`resolving attestation: ${r} from url: ${i}`);const o=this.startAbortTimer(j.ONE_SECOND*5),a=await fetch(`${i}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),Be(this,"getVerifyUrl",r=>{let i=r||Lr;return eC.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Lr}`),i=Lr),i}),Be(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(j.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await i.json()}catch(r){this.logger.warn(r)}}),Be(this,"persistPublicKey",async r=>{this.logger.debug(r,"persisting public key to local storage"),await this.store.setItem(this.storeKey,r),this.publicKey=r}),Be(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Be(this,"isValidJwtAttestation",async r=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(r,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Be(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Be(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),Be(this,"validateAttestation",(r,i)=>{const o=wE(r,i.publicKey),a={hasExpired:j.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Pt(s,this.name),this.abortController=new AbortController,this.isDevEnv=$c(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return kt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),j.toMiliseconds(e))}}var Q1=Object.defineProperty,eA=(t,e,s)=>e in t?Q1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Bd=(t,e,s)=>eA(t,typeof e!="symbol"?e+"":e,s);class tA extends Vm{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,Bd(this,"context",tC),Bd(this,"registerDeviceToken",async n=>{const{clientId:r,token:i,notificationType:o,enableEncrypted:a=!1}=n,c=`${sC}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:i,always_raw:a})})}),this.logger=Pt(s,this.context)}}var sA=Object.defineProperty,jd=Object.getOwnPropertySymbols,nA=Object.prototype.hasOwnProperty,rA=Object.prototype.propertyIsEnumerable,fc=(t,e,s)=>e in t?sA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ir=(t,e)=>{for(var s in e||(e={}))nA.call(e,s)&&fc(t,s,e[s]);if(jd)for(var s of jd(e))rA.call(e,s)&&fc(t,s,e[s]);return t},ze=(t,e,s)=>fc(t,typeof e!="symbol"?e+"":e,s);class iA extends zm{constructor(e,s,n=!0){super(e,s,n),this.core=e,this.logger=s,ze(this,"context",rC),ze(this,"storagePrefix",ms),ze(this,"storageVersion",nC),ze(this,"events",new Map),ze(this,"shouldPersist",!1),ze(this,"init",async()=>{if(!$c())try{const r={eventId:Ol(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:nh(this.core.relayer.protocol,this.core.relayer.version,oc)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),ze(this,"createEvent",r=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=Ol(),d=this.core.projectId||"",u=Date.now(),h=Ir({eventId:l,timestamp:u,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),ze(this,"getEvent",r=>{const{eventId:i,topic:o}=r;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Ir(Ir({},a),this.setMethods(a.eventId))}),ze(this,"deleteEvent",r=>{const{eventId:i}=r;this.events.delete(i),this.shouldPersist=!0}),ze(this,"setEventListeners",()=>{this.core.heartbeat.on(pr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{j.fromMiliseconds(Date.now())-j.fromMiliseconds(r.timestamp)>iC&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),ze(this,"setMethods",r=>({addTrace:i=>this.addTrace(r,i),setError:i=>this.setError(r,i)})),ze(this,"addTrace",(r,i)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(i),this.events.set(r,o),this.shouldPersist=!0)}),ze(this,"setError",(r,i)=>{const o=this.events.get(r);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),ze(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ze(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(i=>{this.events.set(i.eventId,Ir(Ir({},i),this.setMethods(i.eventId)))})}catch(r){this.logger.warn(r)}}),ze(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[i,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const i of r)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}}),ze(this,"sendEvent",async r=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${oC}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${oc}${i}`,{method:"POST",body:JSON.stringify(r)})}),ze(this,"getAppDomain",()=>sh().url),this.logger=Pt(s,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}}var oA=Object.defineProperty,qd=Object.getOwnPropertySymbols,aA=Object.prototype.hasOwnProperty,cA=Object.prototype.propertyIsEnumerable,gc=(t,e,s)=>e in t?oA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Wd=(t,e)=>{for(var s in e||(e={}))aA.call(e,s)&&gc(t,s,e[s]);if(qd)for(var s of qd(e))cA.call(e,s)&&gc(t,s,e[s]);return t},Oe=(t,e,s)=>gc(t,typeof e!="symbol"?e+"":e,s);let lA=class Cp extends $m{constructor(e){var s;super(e),Oe(this,"protocol",ip),Oe(this,"version",op),Oe(this,"name",So),Oe(this,"relayUrl"),Oe(this,"projectId"),Oe(this,"customStoragePrefix"),Oe(this,"events",new $n.EventEmitter),Oe(this,"logger"),Oe(this,"heartbeat"),Oe(this,"relayer"),Oe(this,"crypto"),Oe(this,"storage"),Oe(this,"history"),Oe(this,"expirer"),Oe(this,"pairing"),Oe(this,"verify"),Oe(this,"echoClient"),Oe(this,"linkModeSupportedApps"),Oe(this,"eventClient"),Oe(this,"initialized",!1),Oe(this,"logChunkController"),Oe(this,"on",(a,c)=>this.events.on(a,c)),Oe(this,"once",(a,c)=>this.events.once(a,c)),Oe(this,"off",(a,c)=>this.events.off(a,c)),Oe(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Oe(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const d={topic:a,message:c,publishedAt:Date.now(),transportType:Pe.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:l})});const n=this.getGlobalCore(e==null?void 0:e.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=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||cp,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Su({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:S0.logger,name:So}),{logger:i,chunkLoggerController:o}=Ic({opts:r,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(s=this.logChunkController)!=null&&s.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=Pt(i,this.name),this.heartbeat=new df,this.crypto=new Dv(this,this.logger,e==null?void 0:e.keychain),this.history=new V1(this,this.logger),this.expirer=new Y1(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Pm(Wd(Wd({},T0),e==null?void 0:e.storageOptions)),this.relayer=new l1({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new W1(this,this.logger),this.verify=new Z1(this,this.logger,this.storage),this.echoClient=new tA(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new iA(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new Cp(e);await s.initialize();const n=await s.crypto.getClientId();return await s.storage.setItem(q0,n),s}get context(){return kt(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Cd,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(Cd)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${e}`,n=`${s}_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[s]}catch(s){console.warn("Failed to get global WalletConnect core",s);return}}setGlobalCore(e){var s;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof Os<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const dA=lA,vp="wc",Ap=2,_p="client",zc=`${vp}@${Ap}:${_p}:`,wa={name:_p,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Hd="WALLETCONNECT_DEEPLINK_CHOICE",uA="proposal",Kd="Proposal expired",hA="session",Wn=j.SEVEN_DAYS,pA="engine",Ze={wc_sessionPropose:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1104},res:{ttl:j.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1106},res:{ttl:j.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1112},res:{ttl:j.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1114},res:{ttl:j.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:j.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:j.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1119}}},ba={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},os={idle:"IDLE",active:"ACTIVE"},fA={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:""}},gA="request",mA=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],yA="wc",wA="auth",bA="authKeys",EA="pairingTopics",CA="requests",Wo=`${yA}@${1.5}:${wA}:`,oo=`${Wo}:PUB_KEY`;var vA=Object.defineProperty,AA=Object.defineProperties,_A=Object.getOwnPropertyDescriptors,Vd=Object.getOwnPropertySymbols,IA=Object.prototype.hasOwnProperty,NA=Object.prototype.propertyIsEnumerable,mc=(t,e,s)=>e in t?vA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Se=(t,e)=>{for(var s in e||(e={}))IA.call(e,s)&&mc(t,s,e[s]);if(Vd)for(var s of Vd(e))NA.call(e,s)&&mc(t,s,e[s]);return t},at=(t,e)=>AA(t,_A(e)),O=(t,e,s)=>mc(t,typeof e!="symbol"?e+"":e,s);class SA extends Xm{constructor(e){super(e),O(this,"name",pA),O(this,"events",new Ac),O(this,"initialized",!1),O(this,"requestQueue",{state:os.idle,queue:[]}),O(this,"sessionRequestQueue",{state:os.idle,queue:[]}),O(this,"emittedSessionRequests",new ky({limit:500})),O(this,"requestQueueDelay",j.ONE_SECOND),O(this,"expectedPairingMethodMap",new Map),O(this,"recentlyDeletedMap",new Map),O(this,"recentlyDeletedLimit",200),O(this,"relayMessageCache",[]),O(this,"pendingSessions",new Map),O(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(Ze)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay)))}),O(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=at(Se({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=BE(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=n;let d=r,u,h=!1;try{if(d){const M=this.client.core.pairing.pairings.get(d);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=M.active}}catch(M){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),M}if(!d||!h){const{topic:M,uri:H}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});d=M,u=H}if(!d){const{message:M}=L("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(M)}const p=await this.client.core.crypto.generateKeyPair(),f=Ze.wc_sessionPropose.req.ttl||j.FIVE_MINUTES,m=je(f),y=at(Se(Se({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:ap}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:d},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Ds()}),w=Ne("session_connect",y.id),{reject:b,resolve:A,done:k}=mn(f,Kd),$=({id:M})=>{M===y.id&&(this.client.events.off("proposal_expire",$),this.pendingSessions.delete(y.id),this.events.emit(w,{error:{message:Kd,code:0}}))};return this.client.events.on("proposal_expire",$),this.events.once(w,({error:M,session:H})=>{this.client.events.off("proposal_expire",$),M?b(M):H&&A(H)}),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}),await this.setProposal(y.id,y),{uri:u,approval:k}}),O(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(n){throw this.client.logger.error("pair() failed"),n}}),O(this,"approve",async s=>{var n,r,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=s==null?void 0:s.id)==null?void 0:n.toString(),trace:[Xt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(P){throw o.setError(un.no_internet_connection),P}try{await this.isValidProposalId(s==null?void 0:s.id)}catch(P){throw this.client.logger.error(`approve() -> proposal.get(${s==null?void 0:s.id}) failed`),o.setError(un.proposal_not_found),P}try{await this.isValidApprove(s)}catch(P){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(un.session_approve_namespace_validation_failure),P}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=s,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:m,requiredNamespaces:y,optionalNamespaces:w}=p;let b=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});b||(b=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:Xt.session_approve_started,properties:{topic:f,trace:[Xt.session_approve_started,Xt.session_namespaces_validation_success]}}));const A=await this.client.core.crypto.generateKeyPair(),k=m.publicKey,$=await this.client.core.crypto.generateSharedKey(A,k),M=Se(Se(Se({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:A,metadata:this.client.metadata},expiry:je(Wn)},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),H=Pe.relay;b.addTrace(Xt.subscribing_session_topic);try{await this.client.core.relayer.subscribe($,{transportType:H,internal:{skipSubscribe:!0}})}catch(P){throw b.setError(un.subscribe_session_topic_failure),P}b.addTrace(Xt.subscribe_session_topic_success);const G=at(Se({},M),{topic:$,requiredNamespaces:y,optionalNamespaces:w,pairingTopic:f,acknowledged:!1,self:M.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:A,transportType:Pe.relay});await this.client.session.set($,G),b.addTrace(Xt.store_session);try{await this.sendApproveSession({sessionTopic:$,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:A},sessionSettleRequest:M,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),b.addTrace(Xt.session_approve_publish_success)}catch(P){throw this.client.logger.error(P),this.client.session.delete($,Ue("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe($),P}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:f}),await this.setExpiry($,je(Wn)),{topic:$,acknowledged:()=>Promise.resolve(this.client.session.get($))}}),O(this,"reject",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(s)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:r}=s;let i;try{i=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}i&&await this.sendError({id:n,topic:i,error:r,rpcOpts:Ze.wc_sessionPropose.reject}),await this.deleteProposal(n)}),O(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:n,namespaces:r}=s,{done:i,resolve:o,reject:a}=mn(),c=Ds(),l=En().toString(),d=this.client.session.get(n).namespaces;return this.events.once(Ne("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(n,{namespaces:r}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(u=>{this.client.logger.error(u),this.client.session.update(n,{namespaces:d}),a(u)}),{acknowledged:i}}),O(this,"extend",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(s)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=s,r=Ds(),{done:i,resolve:o,reject:a}=mn();return this.events.once(Ne("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,je(Wn)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),O(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:n,request:r,topic:i,expiry:o=Ze.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(i);(a==null?void 0:a.transportType)===Pe.relay&&await this.confirmOnlineStateOrThrow();const c=Ds(),l=En().toString(),{done:d,resolve:u,reject:h}=mn(o,"Request expired. Please try again.");this.events.once(Ne("session_request",c),({error:y,result:w})=>{y?h(y):u(w)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:{request:at(Se({},r),{expiryTimestamp:je(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),await d();const m={request:at(Se({},r),{expiryTimestamp:je(o)}),chainId:n};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:m,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,m)}).catch(w=>h(w)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),y()}),new Promise(async y=>{var w;if(!((w=a.sessionConfig)!=null&&w.disableDeepLink)){const b=await Sy(this.client.core.storage,Hd);await _y({id:c,topic:i,wcDeepLink:b})}y()}),d()]).then(y=>y[2])}),O(this,"respond",async s=>{var n,r;this.isInitialized();const i=this.client.core.eventClient.createEvent({properties:{topic:(s==null?void 0:s.topic)||((r=(n=s==null?void 0:s.response)==null?void 0:n.id)==null?void 0:r.toString()),trace:[Xt.session_request_response_started]}});try{await this.isValidRespond(s)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(un.session_request_response_validation_failure),u}i.addTrace(Xt.session_request_response_validation_success);const{topic:o,response:a}=s,{id:c}=a,l=this.client.session.get(o);l.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const d=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{i.addTrace(Xt.session_request_response_publish_started),Es(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:d}):cs(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:d}),this.cleanupAfterResponse(s)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(un.session_request_response_publish_failure),u}}),O(this,"ping",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(s)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:n}=s;if(this.client.session.keys.includes(n)){const r=Ds(),i=En().toString(),{done:o,resolve:a,reject:c}=mn();this.events.once(Ne("session_ping",r),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:i}),o()])}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}))}),O(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:n,event:r,chainId:i}=s,o=En().toString(),a=Ds();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:r,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),O(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:n}=s;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Ue("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{const{message:r}=L("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(r)}}),O(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(n=>WE(n,s)))),O(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),O(this,"authenticate",async(s,n)=>{var r;this.isInitialized(),this.isValidAuthenticate(s);const i=n&&this.client.core.linkModeSupportedApps.includes(n)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=i?Pe.link_mode:Pe.relay;o===Pe.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:d,nonce:u,type:h,exp:p,nbf:f,methods:m=[],expiry:y}=s,w=[...s.resources||[]],{topic:b,uri:A}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:A}});const k=await this.client.core.crypto.generateKeyPair(),$=ro(k);if(await Promise.all([this.client.auth.authKeys.set(oo,{responseTopic:$,publicKey:k}),this.client.auth.pairingTopics.set($,{topic:$,pairingTopic:b})]),await this.client.core.relayer.subscribe($,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),m.length>0){const{namespace:_}=Rs(a[0]);let x=Ww(_,"request",m);no(w)&&(x=Kw(x,w.pop())),w.push(x)}const M=y&&y>Ze.wc_sessionAuthenticate.req.ttl?y:Ze.wc_sessionAuthenticate.req.ttl,H={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:d,version:"1",nonce:u,iat:new Date().toISOString(),exp:p,nbf:f,resources:w},requester:{publicKey:k,metadata:this.client.metadata},expiryTimestamp:je(M)},G={eip155:{chains:a,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},P={requiredNamespaces:{},optionalNamespaces:G,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:k,metadata:this.client.metadata},expiryTimestamp:je(Ze.wc_sessionPropose.req.ttl),id:Ds()},{done:Q,resolve:se,reject:T}=mn(M,"Request expired"),E=Ds(),C=Ne("session_connect",P.id),v=Ne("session_request",E),S=async({error:_,session:x})=>{this.events.off(v,U),_?T(_):x&&se({session:x})},U=async _=>{var x,V,K;if(await this.deletePendingAuthRequest(E,{message:"fulfilled",code:0}),_.error){const de=Ue("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return _.error.code===de.code?void 0:(this.events.off(C,S),T(_.error.message))}await this.deleteProposal(P.id),this.events.off(C,S);const{cacaos:pe,responder:oe}=_.result,ne=[],ue=[];for(const de of pe){await Bl({cacao:de,projectId:this.client.core.projectId})||(this.client.logger.error(de,"Signature verification failed"),T(Ue("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Le}=de,Gt=no(Le.resources),$s=[Ga(Le.iss)],cn=Co(Le.iss);if(Gt){const Mn=jl(Gt),Gp=ql(Gt);ne.push(...Mn),$s.push(...Gp)}for(const Mn of $s)ue.push(`${Mn}:${cn}`)}const le=await this.client.core.crypto.generateSharedKey(k,oe.publicKey);let Re;ne.length>0&&(Re={topic:le,acknowledged:!0,self:{publicKey:k,metadata:this.client.metadata},peer:oe,controller:oe.publicKey,expiry:je(Wn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:fd([...new Set(ne)],[...new Set(ue)]),transportType:o},await this.client.core.relayer.subscribe(le,{transportType:o}),await this.client.session.set(le,Re),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:oe.metadata}),Re=this.client.session.get(le)),(x=this.client.metadata.redirect)!=null&&x.linkMode&&(V=oe.metadata.redirect)!=null&&V.linkMode&&(K=oe.metadata.redirect)!=null&&K.universal&&n&&(this.client.core.addLinkModeSupportedApp(oe.metadata.redirect.universal),this.client.session.update(le,{transportType:Pe.link_mode})),se({auths:pe,session:Re})};this.events.once(C,S),this.events.once(v,U);let F;try{if(i){const _=ls("wc_sessionAuthenticate",H,E);this.client.core.history.set(b,_);const x=await this.client.core.crypto.encode("",_,{type:Ni,encoding:Gs});F=Ki(n,b,x)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:H,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:E}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:P,expiry:Ze.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:P.id})])}catch(_){throw this.events.off(C,S),this.events.off(v,U),_}return await this.setProposal(P.id,P),await this.setAuthRequest(E,{request:at(Se({},H),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:F??A,response:Q}}),O(this,"approveSessionAuthenticate",async s=>{const{id:n,auths:r}=s,i=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[hn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw i.setError(Ar.no_internet_connection),y}const o=this.getPendingAuthRequest(n);if(!o)throw i.setError(Ar.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||Pe.relay;a===Pe.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=ro(c),u={type:Ps,receiverPublicKey:c,senderPublicKey:l},h=[],p=[];for(const y of r){if(!await Bl({cacao:y,projectId:this.client.core.projectId})){i.setError(Ar.invalid_cacao);const $=Ue("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:$,encodeOpts:u}),new Error($.message)}i.addTrace(hn.cacaos_verified);const{p:w}=y,b=no(w.resources),A=[Ga(w.iss)],k=Co(w.iss);if(b){const $=jl(b),M=ql(b);h.push(...$),A.push(...M)}for(const $ of A)p.push(`${$}:${k}`)}const f=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(hn.create_authenticated_session_topic);let m;if((h==null?void 0:h.length)>0){m={topic:f,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:je(Wn),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:fd([...new Set(h)],[...new Set(p)]),transportType:a},i.addTrace(hn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(y){throw i.setError(Ar.subscribe_authenticated_session_topic_failure),y}i.addTrace(hn.subscribe_authenticated_session_topic_success),await this.client.session.set(f,m),i.addTrace(hn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(hn.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw i.setError(Ar.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:m}}),O(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:n,reason:r}=s,i=this.getPendingAuthRequest(n);if(!i)throw new Error(`Could not find pending auth request with id ${n}`);i.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ro(o),l={type:Ps,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:r,encodeOpts:l,rpcOpts:Ze.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),O(this,"formatAuthMessage",s=>{this.isInitialized();const{request:n,iss:r}=s;return Ch(n,r)}),O(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const s=this.relayMessageCache.shift();s&&await this.onRelayMessage(s)}catch(s){this.client.logger.error(s)}},50)}),O(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const n=this.client.core.pairing.pairings.get(s.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter(i=>{var o,a;return((o=i.peerMetadata)==null?void 0:o.url)&&((a=i.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&i.topic&&i.topic!==n.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),O(this,"deleteSession",async s=>{var n;const{topic:r,expirerHasDeleted:i=!1,emitEvent:o=!0,id:a=0}=s,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Ue("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),i||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Hd).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,Ue("USER_DISCONNECTED"))}),r===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=os.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),O(this,"deleteProposal",async(s,n)=>{if(n)try{const r=this.client.proposal.get(s),i=this.client.core.eventClient.getEvent({topic:r.pairingTopic});i==null||i.setError(un.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,Ue("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),O(this,"deletePendingSessionRequest",async(s,n,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==s),r&&(this.sessionRequestQueue.state=os.idle,this.client.events.emit("session_request_expire",{id:s}))}),O(this,"deletePendingAuthRequest",async(s,n,r=!1)=>{await Promise.all([this.client.auth.requests.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)])}),O(this,"setExpiry",async(s,n)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,n),await this.client.session.update(s,{expiry:n}))}),O(this,"setProposal",async(s,n)=>{this.client.core.expirer.set(s,je(Ze.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,n)}),O(this,"setAuthRequest",async(s,n)=>{const{request:r,pairingTopic:i,transportType:o=Pe.relay}=n;this.client.core.expirer.set(s,r.expiryTimestamp),await this.client.auth.requests.set(s,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:s,pairingTopic:i,verifyContext:r.verifyContext,transportType:o})}),O(this,"setPendingSessionRequest",async s=>{const{id:n,topic:r,params:i,verifyContext:o}=s,a=i.request.expiryTimestamp||je(Ze.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:r,params:i,verifyContext:o})}),O(this,"sendRequest",async s=>{const{topic:n,method:r,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:d,tvf:u,publishOpts:h={}}=s,p=ls(r,i,c);let f;const m=!!d;try{const b=m?Gs:bt;f=await this.client.core.crypto.encode(n,p,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),b}let y;if(mA.includes(r)){const b=jt(JSON.stringify(p)),A=jt(f);y=await this.client.core.verify.register({id:A,decryptedId:b})}const w=Se(Se({},Ze[r].req),h);if(w.attestation=y,o&&(w.ttl=o),a&&(w.id=a),this.client.core.history.set(n,p),m){const b=Ki(d,n,f);await ie.Linking.openURL(b,this.client.name)}else w.tvf=at(Se({},u),{correlationId:p.id}),l?(w.internal=at(Se({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,f,w)):this.client.core.relayer.publish(n,f,w).catch(b=>this.client.logger.error(b));return p.id}),O(this,"sendProposeSession",async s=>{const{proposal:n,publishOpts:r}=s,i=ls("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,i);const o=await this.client.core.crypto.encode(n.pairingTopic,i,{encoding:bt}),a=jt(JSON.stringify(i)),c=jt(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:o},opts:at(Se({},r),{publishMethod:"wc_proposeSession",attestation:l})})}),O(this,"sendApproveSession",async s=>{const{sessionTopic:n,pairingProposalResponse:r,proposal:i,sessionSettleRequest:o,publishOpts:a}=s,c=qr(i.id,r),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:bt}),d=ls("wc_sessionSettle",o,a==null?void 0:a.id),u=await this.client.core.crypto.encode(n,d,{encoding:bt});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:u},opts:at(Se({},a),{publishMethod:"wc_approveSession"})})}),O(this,"sendResult",async s=>{const{id:n,topic:r,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=qr(n,i);let d;const u=c&&typeof(ie==null?void 0:ie.Linking)<"u";try{const f=u?Gs:bt;d=await this.client.core.crypto.encode(r,l,at(Se({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),f}let h,p;try{h=await this.client.core.history.get(r,n);const f=h.request;try{p=this.getTVFParams(n,f.params,i)}catch(m){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${m==null?void 0:m.message}`)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${n}) failed`),f}if(u){const f=Ki(c,r,d);await ie.Linking.openURL(f,this.client.name)}else{const f=h.request.method,m=Ze[f].res;m.tvf=at(Se({},p),{correlationId:n}),o?(m.internal=at(Se({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,d,m)):this.client.core.relayer.publish(r,d,m).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)}),O(this,"sendError",async s=>{const{id:n,topic:r,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=Tu(n,i);let d;const u=c&&typeof(ie==null?void 0:ie.Linking)<"u";try{const p=u?Gs:bt;d=await this.client.core.crypto.encode(r,l,at(Se({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),p}let h;try{h=await this.client.core.history.get(r,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${r}, ${n}) failed`),p}if(u){const p=Ki(c,r,d);await ie.Linking.openURL(p,this.client.name)}else{const p=h.request.method,f=a||Ze[p].res;this.client.core.relayer.publish(r,d,f)}await this.client.core.history.resolve(l)}),O(this,"cleanup",async()=>{const s=[],n=[];this.client.session.getAll().forEach(r=>{let i=!1;ds(r.expiry)&&(i=!0),this.client.core.crypto.keychain.has(r.topic)||(i=!0),i&&s.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{ds(r.expiryTimestamp)&&n.push(r.id)}),await Promise.all([...s.map(r=>this.deleteSession({topic:r})),...n.map(r=>this.deleteProposal(r))])}),O(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),O(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),O(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===os.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=os.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=os.idle}),O(this,"processRequest",async s=>{const{topic:n,payload:r,attestation:i,transportType:o,encryptedId:a}=s,c=r.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:r,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,r);case"wc_sessionPing":return await this.onSessionPingRequest(n,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),O(this,"onRelayEventResponse",async s=>{const{topic:n,payload:r,transportType:i}=s,o=(await this.client.core.history.get(n,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,r,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,r);case"wc_sessionExtend":return this.onSessionExtendResponse(n,r);case"wc_sessionPing":return this.onSessionPingResponse(n,r);case"wc_sessionRequest":return this.onSessionRequestResponse(n,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),O(this,"onRelayEventUnknownPayload",s=>{const{topic:n}=s,{message:r}=L("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),O(this,"shouldIgnorePairingRequest",s=>{const{topic:n,requestMethod:r}=s,i=this.expectedPairingMethodMap.get(n);return!i||i.includes(r)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),O(this,"onSessionProposeRequest",async s=>{const{topic:n,payload:r,attestation:i,encryptedId:o}=s,{params:a,id:c}=r;try{const l=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(vs.proposal_listener_not_found)),this.isValidConnect(Se({},r.params));const d=a.expiryTimestamp||je(Ze.wc_sessionPropose.req.ttl),u=Se({id:c,pairingTopic:n,expiryTimestamp:d,attestation:i,encryptedId:o},a);await this.setProposal(c,u);const h=await this.getVerifyContext({attestationId:i,hash:jt(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});l==null||l.addTrace(as.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:h})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:Ze.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),O(this,"onSessionProposeResponse",async(s,n,r)=>{const{id:i}=n;if(Es(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const d=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(i,{sessionTopic:d,pairingTopic:s,proposalId:i,publicKey:c});const u=await this.client.core.relayer.subscribe(d,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:s})}else if(cs(n)){await this.deleteProposal(i);const o=Ne("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),O(this,"onSessionSettleRequest",async(s,n)=>{const{id:r,params:i}=n;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=n.params,p=[...this.pendingSessions.values()].find(y=>y.sessionTopic===s);if(!p)return this.client.logger.error(`Pending session not found for topic ${s}`);const f=this.client.proposal.get(p.proposalId),m=at(Se(Se(Se({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),{transportType:Pe.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(Ne("session_connect",p.proposalId),{session:m}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:n.id,topic:s,result:!0})}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),O(this,"onSessionSettleResponse",async(s,n)=>{const{id:r}=n;Es(n)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(Ne("session_approve",r),{})):cs(n)&&(await this.client.session.delete(s,Ue("USER_DISCONNECTED")),this.events.emit(Ne("session_approve",r),{error:n.error}))}),O(this,"onSessionUpdateRequest",async(s,n)=>{const{params:r,id:i}=n;try{const o=`${s}_session_update`,a=Cr.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:s,error:Ue("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Se({topic:s},r));try{Cr.set(o,i),await this.client.session.update(s,{namespaces:r.namespaces}),await this.sendResult({id:i,topic:s,result:!0})}catch(c){throw Cr.delete(o),c}this.client.events.emit("session_update",{id:i,topic:s,params:r})}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),O(this,"isRequestOutOfSync",(s,n)=>n.toString().slice(0,-3)<s.toString().slice(0,-3)),O(this,"onSessionUpdateResponse",(s,n)=>{const{id:r}=n,i=Ne("session_update",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);Es(n)?this.events.emit(Ne("session_update",r),{}):cs(n)&&this.events.emit(Ne("session_update",r),{error:n.error})}),O(this,"onSessionExtendRequest",async(s,n)=>{const{id:r}=n;try{this.isValidExtend({topic:s}),await this.setExpiry(s,je(Wn)),await this.sendResult({id:r,topic:s,result:!0}),this.client.events.emit("session_extend",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),O(this,"onSessionExtendResponse",(s,n)=>{const{id:r}=n,i=Ne("session_extend",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);Es(n)?this.events.emit(Ne("session_extend",r),{}):cs(n)&&this.events.emit(Ne("session_extend",r),{error:n.error})}),O(this,"onSessionPingRequest",async(s,n)=>{const{id:r}=n;try{this.isValidPing({topic:s}),await this.sendResult({id:r,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),O(this,"onSessionPingResponse",(s,n)=>{const{id:r}=n,i=Ne("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);Es(n)?this.events.emit(Ne("session_ping",r),{}):cs(n)&&this.events.emit(Ne("session_ping",r),{error:n.error})},500)}),O(this,"onSessionDeleteRequest",async(s,n)=>{const{id:r}=n;try{this.isValidDisconnect({topic:s,reason:n.params}),await Promise.all([new Promise(i=>{this.client.core.relayer.once(Fe.publish,async()=>{i(await this.deleteSession({topic:s,id:r}))})}),this.sendResult({id:r,topic:s,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:Ue("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),O(this,"onSessionRequest",async s=>{var n,r,i;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:d}=s,{id:u,params:h}=a;try{await this.isValidRequest(Se({topic:o},h));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:jt(JSON.stringify(ls("wc_sessionRequest",h,u))),encryptedId:l,metadata:p.peer.metadata,transportType:d}),m={id:u,topic:o,params:h,verifyContext:f};await this.setPendingSessionRequest(m),d===Pe.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((r=p.peer.metadata.redirect)==null?void 0:r.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(p){await this.sendError({id:u,topic:o,error:p}),this.client.logger.error(p)}}),O(this,"onSessionRequestResponse",(s,n)=>{const{id:r}=n,i=Ne("session_request",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);Es(n)?this.events.emit(Ne("session_request",r),{result:n.result}):cs(n)&&this.events.emit(Ne("session_request",r),{error:n.error})}),O(this,"onSessionEventRequest",async(s,n)=>{const{id:r,params:i}=n;try{const o=`${s}_session_event_${i.event.name}`,a=Cr.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Se({topic:s},i)),this.client.events.emit("session_event",{id:r,topic:s,params:i}),Cr.set(o,r)}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),O(this,"onSessionAuthenticateResponse",(s,n)=>{const{id:r}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:n}),Es(n)?this.events.emit(Ne("session_request",r),{result:n.result}):cs(n)&&this.events.emit(Ne("session_request",r),{error:n.error})}),O(this,"onSessionAuthenticateRequest",async s=>{var n;const{topic:r,payload:i,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:d,expiryTimestamp:u}=i.params,h=await this.getVerifyContext({attestationId:o,hash:jt(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:r,id:i.id,authPayload:d,verifyContext:h,expiryTimestamp:u};await this.setAuthRequest(i.id,{request:p,pairingTopic:r,transportType:c}),c===Pe.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:i.params,id:i.id,verifyContext:h})}catch(l){this.client.logger.error(l);const d=i.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(i.params.requester.metadata,c),p={type:Ps,receiverPublicKey:d,senderPublicKey:u};await this.sendError({id:i.id,topic:r,error:l,encodeOpts:p,rpcOpts:Ze.wc_sessionAuthenticate.autoReject,appLink:h})}}),O(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),O(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=os.idle,this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay))}),O(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:n})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(i=>i.topic===s&&i.request.method==="wc_sessionRequest").forEach(i=>{const o=i.request.id,a=Ne("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ne("session_request",i.request.id),{error:n})})}),O(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===os.active){this.client.logger.info("session request queue is already active.");return}const s=this.sessionRequestQueue.queue[0];if(!s){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(s)}catch(n){this.client.logger.error(n)}}),O(this,"emitSessionRequest",s=>{if(this.emittedSessionRequests.has(s.id)){this.client.logger.warn({id:s.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${s.id}`);return}this.sessionRequestQueue.state=os.active,this.emittedSessionRequests.add(s.id),this.client.events.emit("session_request",s)}),O(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const n=this.client.proposal.getAll().find(r=>r.pairingTopic===s.topic);n&&this.onSessionProposeRequest({topic:s.topic,payload:ls("wc_sessionPropose",at(Se({},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})}),O(this,"isValidConnect",async s=>{if(!yt(s)){const{message:l}=L("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:n,requiredNamespaces:r,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=s;if(Ke(n)||await this.isValidPairingTopic(n),!t0(c,!0)){const{message:l}=L("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(r&&!Ke(r)&&gs(r)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(r,"requiredNamespaces")}if(i&&!Ke(i)&&gs(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),o&&!Ke(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ke(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(r||{}).concat(Object.keys(i||{}));if(!Object.keys(a).every(d=>l.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(l)}`)}}),O(this,"validateNamespaces",(s,n)=>{const r=e0(s,"connect()",n);if(r)throw new Error(r.message)}),O(this,"isValidApprove",async s=>{if(!yt(s))throw new Error(L("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:n,namespaces:r,relayProtocol:i,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),l=pa(r,"approve()");if(l)throw new Error(l.message);const d=yd(c.requiredNamespaces,r,"approve()");if(d)throw new Error(d.message);if(!qe(i,!0)){const{message:u}=L("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(u)}if(o&&!Ke(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ke(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(h=>u.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),O(this,"isValidReject",async s=>{if(!yt(s)){const{message:i}=L("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(i)}const{id:n,reason:r}=s;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!n0(r)){const{message:i}=L("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(i)}}),O(this,"isValidSessionSettleRequest",s=>{if(!yt(s)){const{message:l}=L("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:n,controller:r,namespaces:i,expiry:o}=s;if(!rp(n)){const{message:l}=L("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=GE(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=pa(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ds(o)){const{message:l}=L("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),O(this,"isValidUpdate",async s=>{if(!yt(s)){const{message:c}=L("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:n,namespaces:r}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const i=this.client.session.get(n),o=pa(r,"update()");if(o)throw new Error(o.message);const a=yd(i.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),O(this,"isValidExtend",async s=>{if(!yt(s)){const{message:r}=L("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(r)}const{topic:n}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),O(this,"isValidRequest",async s=>{if(!yt(s)){const{message:c}=L("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:n,request:r,chainId:i,expiry:o}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!md(a,i)){const{message:c}=L("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!r0(r)){const{message:c}=L("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!a0(a,i,r.method)){const{message:c}=L("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!u0(o,ba)){const{message:c}=L("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${ba.min} and ${ba.max}`);throw new Error(c)}}),O(this,"isValidRespond",async s=>{var n;if(!yt(s)){const{message:a}=L("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(a)}const{topic:r,response:i}=s;try{await this.isValidSessionTopic(r)}catch(a){throw(n=s==null?void 0:s.response)!=null&&n.id&&this.cleanupAfterResponse(s),a}if(!i0(i)){const{message:a}=L("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(a)}const o=this.client.pendingRequest.get(i.id);if(o.topic!==r){const{message:a}=L("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${i.id}, expected topic: ${o.topic}, received topic: ${r}`);throw new Error(a)}}),O(this,"isValidPing",async s=>{if(!yt(s)){const{message:r}=L("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),O(this,"isValidEmit",async s=>{if(!yt(s)){const{message:a}=L("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}const{topic:n,event:r,chainId:i}=s;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!md(o,i)){const{message:a}=L("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!o0(r)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!c0(o,i,r.name)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),O(this,"isValidDisconnect",async s=>{if(!yt(s)){const{message:r}=L("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),O(this,"isValidAuthenticate",s=>{const{chains:n,uri:r,domain:i,nonce:o}=s;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!qe(r,!1))throw new Error("uri is required parameter");if(!qe(i,!1))throw new Error("domain is required parameter");if(!qe(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Rs(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Rs(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),O(this,"getVerifyContext",async s=>{const{attestationId:n,hash:r,encryptedId:i,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||Lr,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Pe.link_mode){const d=this.getAppLinkIfEnabled(o,a);return c.verified.validation=d&&new URL(d).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:n,hash:r,encryptedId:i,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),O(this,"validateSessionProps",(s,n)=>{Object.values(s).forEach((r,i)=>{if(r==null){const{message:o}=L("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${r} for key ${Object.keys(s)[i]}`);throw new Error(o)}})}),O(this,"getPendingAuthRequest",s=>{const n=this.client.auth.requests.get(s);return typeof n=="object"?n:void 0}),O(this,"addToRecentlyDeleted",(s,n)=>{if(this.recentlyDeletedMap.set(s,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=i)break;this.recentlyDeletedMap.delete(o)}}}),O(this,"checkRecentlyDeleted",s=>{const n=this.recentlyDeletedMap.get(s);if(n){const{message:r}=L("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${s}`);throw new Error(r)}}),O(this,"isLinkModeEnabled",(s,n)=>{var r,i,o,a,c,l,d,u,h;return!s||n!==Pe.link_mode?!1:((i=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:i.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((d=s==null?void 0:s.redirect)==null?void 0:d.universal)!==void 0&&((u=s==null?void 0:s.redirect)==null?void 0:u.universal)!==""&&((h=s==null?void 0:s.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(ie==null?void 0:ie.Linking)<"u"}),O(this,"getAppLinkIfEnabled",(s,n)=>{var r;return this.isLinkModeEnabled(s,n)?(r=s==null?void 0:s.redirect)==null?void 0:r.universal:void 0}),O(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const n=Tl(s,"topic")||"",r=decodeURIComponent(Tl(s,"wc_ev")||""),i=this.client.session.keys.includes(n);i&&this.client.session.update(n,{transportType:Pe.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:r,sessionExists:i})}),O(this,"registerLinkModeListeners",async()=>{var s;if($c()||on()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const n=ie==null?void 0:ie.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await n.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),O(this,"getTVFParams",(s,n,r)=>{var i,o,a;if(!((i=n.request)!=null&&i.method))return{};const c={correlationId:s,rpcMethods:[n.request.method],chainId:n.chainId};try{const l=this.extractTxHashesFromResult(n.request,r);c.txHashes=l,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(o=n.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),O(this,"isValidContractData",s=>{var n;if(!s)return!1;try{const r=(s==null?void 0:s.data)||((n=s==null?void 0:s[0])==null?void 0:n.data);if(!r.startsWith("0x"))return!1;const i=r.slice(2);return/^[0-9a-fA-F]*$/.test(i)?i.length%2===0:!1}catch{}return!1}),O(this,"extractTxHashesFromResult",(s,n)=>{var r;try{if(!n)return[];const i=s.method,o=fA[i];if(i==="sui_signTransaction")return[Nw(n.transactionBytes)];if(i==="near_signTransaction")return[Dl(n)];if(i==="near_signTransactions")return n.map(c=>Dl(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(r=n.tx_json)==null?void 0:r.hash];if(i==="polkadot_signTransaction")return[N0({transaction:s.params.transactionPayload,signature:n.signature})];if(i==="algo_signTxn")return ks(n)?n.map(c=>Ml(c)):[Ml(n)];if(i==="cosmos_signDirect")return[Tw(n)];if(i==="wallet_sendCalls")return Ow(n);if(typeof n=="string")return[n];const a=n[o.key];if(ks(a))return i==="solana_signAllTransactions"?a.map(c=>Iw(c)):a;if(typeof a=="string")return[a]}catch(i){this.client.logger.warn(i,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,s=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,r]of Object.entries(s))for(const i of r)try{await this.onProviderMessageEvent({topic:n,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${i}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Fe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:n,attestation:r,transportType:i}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(oo)?this.client.auth.authKeys.get(oo):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,n,{receiverPublicKey:o,encoding:i===Pe.link_mode?Gs:bt});Sc(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:r,transportType:i,encryptedId:jt(n)})):Tc(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:i}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:i}),await this.client.core.relayer.messages.ack(s,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Bt.expired,async e=>{const{topic:s,id:n}=ih(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,L("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,L("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(yn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(yn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!qe(e,!1)){const{message:s}=L("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(s)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:s}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(ds(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=L("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!qe(e,!1)){const{message:s}=L("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(s)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:s}=L("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(ds(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=L("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=L("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(s)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(qe(e,!1)){const{message:s}=L("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=L("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!s0(e)){const{message:s}=L("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=L("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(ds(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=L("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class TA extends Dn{constructor(e,s){super(e,s,uA,zc),this.core=e,this.logger=s}}let OA=class extends Dn{constructor(e,s){super(e,s,hA,zc),this.core=e,this.logger=s}};class RA extends Dn{constructor(e,s){super(e,s,gA,zc,n=>n.id),this.core=e,this.logger=s}}class PA extends Dn{constructor(e,s){super(e,s,bA,Wo,()=>oo),this.core=e,this.logger=s}}class kA extends Dn{constructor(e,s){super(e,s,EA,Wo),this.core=e,this.logger=s}}class xA extends Dn{constructor(e,s){super(e,s,CA,Wo,n=>n.id),this.core=e,this.logger=s}}var $A=Object.defineProperty,UA=(t,e,s)=>e in t?$A(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ea=(t,e,s)=>UA(t,typeof e!="symbol"?e+"":e,s);class DA{constructor(e,s){this.core=e,this.logger=s,Ea(this,"authKeys"),Ea(this,"pairingTopics"),Ea(this,"requests"),this.authKeys=new PA(this.core,this.logger),this.pairingTopics=new kA(this.core,this.logger),this.requests=new xA(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var MA=Object.defineProperty,LA=(t,e,s)=>e in t?MA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ge=(t,e,s)=>LA(t,typeof e!="symbol"?e+"":e,s);let FA=class Ip extends Jm{constructor(e){super(e),ge(this,"protocol",vp),ge(this,"version",Ap),ge(this,"name",wa.name),ge(this,"metadata"),ge(this,"core"),ge(this,"logger"),ge(this,"events",new $n.EventEmitter),ge(this,"engine"),ge(this,"session"),ge(this,"proposal"),ge(this,"pendingRequest"),ge(this,"auth"),ge(this,"signConfig"),ge(this,"on",(n,r)=>this.events.on(n,r)),ge(this,"once",(n,r)=>this.events.once(n,r)),ge(this,"off",(n,r)=>this.events.off(n,r)),ge(this,"removeListener",(n,r)=>this.events.removeListener(n,r)),ge(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),ge(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"update",async n=>{try{return await this.engine.update(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"request",async n=>{try{return await this.engine.request(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"find",n=>{try{return this.engine.find(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),ge(this,"authenticate",async(n,r)=>{try{return await this.engine.authenticate(n,r)}catch(i){throw this.logger.error(i.message),i}}),ge(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||wa.name,this.metadata=wy(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const s=Vc({logger:(e==null?void 0:e.logger)||wa.logger,name:this.name});this.logger=s,this.core=(e==null?void 0:e.core)||new dA(e),this.session=new OA(this.core,this.logger),this.proposal=new TA(this.core,this.logger),this.pendingRequest=new RA(this.core,this.logger),this.engine=new SA(this),this.auth=new DA(this.core,this.logger)}static async init(e){const s=new Ip(e);return await s.initialize(),s}get context(){return kt(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(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const BA=FA;function Gc(t){return t==null||typeof t!="object"&&typeof t!="function"}function Np(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Sp(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const jA="[object RegExp]",Tp="[object String]",Op="[object Number]",Rp="[object Boolean]",Pp="[object Arguments]",qA="[object Symbol]",WA="[object Date]",HA="[object Map]",KA="[object Set]",VA="[object Array]",zA="[object ArrayBuffer]",GA="[object Object]",YA="[object DataView]",JA="[object Uint8Array]",XA="[object Uint8ClampedArray]",ZA="[object Uint16Array]",QA="[object Uint32Array]",e_="[object Int8Array]",t_="[object Int16Array]",s_="[object Int32Array]",n_="[object Float32Array]",r_="[object Float64Array]";function Yc(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function i_(t,e){return Xn(t,void 0,t,new Map,e)}function Xn(t,e,s,n=new Map,r=void 0){const i=r==null?void 0:r(t,e,s,n);if(i!=null)return i;if(Gc(t))return t;if(n.has(t))return n.get(t);if(Array.isArray(t)){const o=new Array(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=Xn(t[a],a,s,n,r);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;n.set(t,o);for(const[a,c]of t)o.set(a,Xn(c,a,s,n,r));return o}if(t instanceof Set){const o=new Set;n.set(t,o);for(const a of t)o.add(Xn(a,void 0,s,n,r));return o}if(typeof me<"u"&&me.isBuffer(t))return t.subarray();if(Yc(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=Xn(t[a],a,s,n,r);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return n.set(t,o),wn(o,t,s,n,r),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return n.set(t,o),wn(o,t,s,n,r),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),wn(o,t,s,n,r),o}if(t instanceof Error){const o=new t.constructor;return n.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,wn(o,t,s,n,r),o}if(typeof t=="object"&&o_(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),wn(o,t,s,n,r),o}return t}function wn(t,e,s=t,n,r){const i=[...Object.keys(e),...Np(e)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Xn(e[a],a,s,n,r))}}function o_(t){switch(Sp(t)){case Pp:case VA:case zA:case YA:case Rp:case WA:case n_:case r_:case e_:case t_:case s_:case HA:case Op:case GA:case jA:case KA:case Tp:case qA:case JA:case XA:case ZA:case QA:return!0;default:return!1}}function a_(t,e){return i_(t,(s,n,r,i)=>{const o=e==null?void 0:e(s,n,r,i);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Op:case Tp:case Rp:{const a=new t.constructor(t==null?void 0:t.valueOf());return wn(a,t),a}case Pp:{const a={};return wn(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function zd(t){return a_(t)}function Gd(t){return t!==null&&typeof t=="object"&&Sp(t)==="[object Arguments]"}function Yd(t){return typeof t=="object"&&t!==null}function c_(){}function l_(t){return Yc(t)}function d_(t){var s;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const n=t[Symbol.toStringTag];return n==null||!((s=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&s.writable)?!1:t.toString()===`[object ${n}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function u_(t){if(Gc(t))return t;if(Array.isArray(t)||Yc(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),s=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new s(t);if(t instanceof RegExp){const n=new s(t);return n.lastIndex=t.lastIndex,n}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const n=new s(t.message);return n.stack=t.stack,n.name=t.name,n.cause=t.cause,n}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const n=Object.create(e);return Object.assign(n,t)}return t}function h_(t,...e){const s=e.slice(0,-1),n=e[e.length-1];let r=t;for(let i=0;i<s.length;i++){const o=s[i];r=yc(r,o,n,new Map)}return r}function yc(t,e,s,n){if(Gc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return u_(n.get(e));if(n.set(e,t),Array.isArray(e)){e=e.slice();for(let i=0;i<e.length;i++)e[i]=e[i]??void 0}const r=[...Object.keys(e),...Np(e)];for(let i=0;i<r.length;i++){const o=r[i];let a=e[o],c=t[o];if(Gd(a)&&(a={...a}),Gd(c)&&(c={...c}),typeof me<"u"&&me.isBuffer(a)&&(a=zd(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const d=[],u=Reflect.ownKeys(c);for(let h=0;h<u.length;h++){const p=u[h];d[p]=c[p]}c=d}else c=[];const l=s(c,a,o,t,e,n);l!=null?t[o]=l:Array.isArray(a)||Yd(c)&&Yd(a)?t[o]=yc(c,a,s,n):c==null&&d_(a)?t[o]=yc({},a,s,n):c==null&&l_(a)?t[o]=zd(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function p_(t,...e){return h_(t,...e,c_)}const Jd="error",f_="wss://relay.walletconnect.org",g_="wc",kp="universal_provider",Vi=`${g_}@2:${kp}:`,xp="https://rpc.walletconnect.org/v1/",$p="generic",m_=`${xp}bundler`,er="call_status",y_=86400,Jc={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var w_=Object.defineProperty,b_=Object.defineProperties,E_=Object.getOwnPropertyDescriptors,Xd=Object.getOwnPropertySymbols,C_=Object.prototype.hasOwnProperty,v_=Object.prototype.propertyIsEnumerable,Zd=(t,e,s)=>e in t?w_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,zi=(t,e)=>{for(var s in e||(e={}))C_.call(e,s)&&Zd(t,s,e[s]);if(Xd)for(var s of Xd(e))v_.call(e,s)&&Zd(t,s,e[s]);return t},A_=(t,e)=>b_(t,E_(e));function Up(t,e,s){var n;const r=Rs(t);return((n=e.rpcMap)==null?void 0:n[r.reference])||`${xp}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function __(t){return t.includes(":")?t.split(":")[1]:t}function Dp(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function I_(t,e){const s=Object.keys(e.namespaces).filter(r=>r.includes(t));if(!s.length)return[];const n=[];return s.forEach(r=>{const i=e.namespaces[r].accounts;n.push(...i)}),n}function Qd(t){return Object.fromEntries(Object.entries(t).filter(([e,s])=>{var n,r;return((n=s==null?void 0:s.chains)==null?void 0:n.length)&&((r=s==null?void 0:s.chains)==null?void 0:r.length)>0}))}function Gi(t={},e={}){const s=Qd(eu(t)),n=Qd(eu(e));return p_(s,n)}function eu(t){var e,s,n,r,i;const o={};if(!gs(t))return o;for(const[a,c]of Object.entries(t)){const l=jo(a)?[a]:c.chains,d=c.methods||[],u=c.events||[],h=c.rpcMap||{},p=Jn(a);o[p]=A_(zi(zi({},o[p]),c),{chains:fs(l,(e=o[p])==null?void 0:e.chains),methods:fs(d,(s=o[p])==null?void 0:s.methods),events:fs(u,(n=o[p])==null?void 0:n.events)}),(gs(h)||gs(((r=o[p])==null?void 0:r.rpcMap)||{}))&&(o[p].rpcMap=zi(zi({},h),(i=o[p])==null?void 0:i.rpcMap))}return o}function tu(t){return t.includes(":")?t.split(":")[2]:t}function su(t){const e={};for(const[s,n]of Object.entries(t)){const r=n.methods||[],i=n.events||[],o=n.accounts||[],a=jo(s)?[s]:n.chains?n.chains:Dp(n.accounts);e[s]={chains:a,methods:r,events:i,accounts:o}}return e}function Ca(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function N_(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const Mp={},tr=t=>Mp[t],va=(t,e)=>{Mp[t]=e};var S_=Object.defineProperty,nu=Object.getOwnPropertySymbols,T_=Object.prototype.hasOwnProperty,O_=Object.prototype.propertyIsEnumerable,ru=(t,e,s)=>e in t?S_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,iu=(t,e)=>{for(var s in e||(e={}))T_.call(e,s)&&ru(t,s,e[s]);if(nu)for(var s of nu(e))O_.call(e,s)&&ru(t,s,e[s]);return t};const ou="eip155",R_=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],P_=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,Aa=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,au=t=>Object.keys(t).filter(e=>R_.includes(e)).reduce((e,s)=>(e[s]=k_(t[s]),e),{}),k_=t=>typeof t=="string"&&N_(t)?JSON.parse(t):t,x_=(t,e,s)=>{const{sessionProperties:n={},scopedProperties:r={}}=t,i={};if(!gs(r)&&!gs(n))return;const o=au(n);for(const a of s){const c=P_(a);if(!c)continue;i[Aa(c)]=o;const l=r==null?void 0:r[`${ou}:${c}`];if(l){const d=l==null?void 0:l[`${ou}:${c}:${e}`];i[Aa(c)]=iu(iu({},i[Aa(c)]),au(d||l))}}for(const[a,c]of Object.entries(i))Object.keys(c).length===0&&delete i[a];return Object.keys(i).length>0?i:void 0};var $_=Object.defineProperty,U_=(t,e,s)=>e in t?$_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,D_=(t,e,s)=>U_(t,typeof e!="symbol"?e+"":e,s);let _a;class Xc{constructor(e){D_(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,s){return await this.storage.setItem(e,s)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return _a||(_a=new Xc(e)),_a}}var M_=Object.defineProperty,L_=Object.defineProperties,F_=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,B_=Object.prototype.hasOwnProperty,j_=Object.prototype.propertyIsEnumerable,lu=(t,e,s)=>e in t?M_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,q_=(t,e)=>{for(var s in e||(e={}))B_.call(e,s)&&lu(t,s,e[s]);if(cu)for(var s of cu(e))j_.call(e,s)&&lu(t,s,e[s]);return t},W_=(t,e)=>L_(t,F_(e));async function H_(t,e){const s=Rs(t.result.capabilities.caip345.caip2),n=t.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(n.map(u=>K_(s.reference,u,e))),i=r.filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u);r.filter(u=>u.status==="rejected").forEach(u=>console.warn("Failed to fetch transaction receipt:",u.reason));const o=!i.length||i.some(u=>!u),a=i.every(u=>(u==null?void 0:u.status)==="0x1"),c=i.every(u=>(u==null?void 0:u.status)==="0x0"),l=i.some(u=>(u==null?void 0:u.status)==="0x0");let d;return o?d=100:a?d=200:c?d=500:l&&(d=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:i,status:d}}async function K_(t,e,s){return await s(parseInt(t)).request(ls("eth_getTransactionReceipt",[e]))}async function V_({sendCalls:t,storage:e}){const s=await e.getItem(er);await e.setItem(er,W_(q_({},s),{[t.result.id]:{request:t.request,result:t.result,expiry:je(y_)}}))}async function z_({resultId:t,storage:e}){const s=await e.getItem(er);if(s){delete s[t],await e.setItem(er,s);for(const n in s)ds(s[n].expiry)&&delete s[n];await e.setItem(er,s)}}async function G_({resultId:t,storage:e}){const s=await e.getItem(er),n=s==null?void 0:s[t];if(n&&!ds(n.expiry))return n;await z_({resultId:t,storage:e})}var Y_=Object.defineProperty,J_=Object.defineProperties,X_=Object.getOwnPropertyDescriptors,du=Object.getOwnPropertySymbols,Z_=Object.prototype.hasOwnProperty,Q_=Object.prototype.propertyIsEnumerable,wc=(t,e,s)=>e in t?Y_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ia=(t,e)=>{for(var s in e||(e={}))Z_.call(e,s)&&wc(t,s,e[s]);if(du)for(var s of du(e))Q_.call(e,s)&&wc(t,s,e[s]);return t},Na=(t,e)=>J_(t,X_(e)),pn=(t,e,s)=>wc(t,typeof e!="symbol"?e+"":e,s);class eI{constructor(e){pn(this,"name","eip155"),pn(this,"client"),pn(this,"chainId"),pn(this,"namespace"),pn(this,"httpProviders"),pn(this,"events"),pn(this,"storage"),this.namespace=e.namespace,this.events=tr("events"),this.client=tr("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=Xc.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s);const n=this.chainId;this.chainId=parseInt(e),this.events.emit(Jc.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,s){const n=s||Up(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Nc(new Ou(n,tr("disableProviderPing")))}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var n;const r=parseInt(__(s));e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[s])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}getHttpProvider(e){const s=e||this.chainId;return this.httpProviders[s]||(this.httpProviders=Na(Ia({},this.httpProviders),{[s]:this.createHttpProvider(s)}),this.httpProviders[s])}async handleSwitchChain(e){var s,n;let r=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const i=parseInt(r,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${i}`);else throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,n,r,i,o;const a=(n=(s=e.request)==null?void 0:s.params)==null?void 0:n[0],c=((i=(r=e.request)==null?void 0:r.params)==null?void 0:i[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),d=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{},u=`${a}${c.join(",")}`,h=d==null?void 0:d[u];if(h)return h;let p;try{p=x_(l,a,c)}catch(m){console.warn("Failed to extract capabilities from session",m)}if(p)return p;const f=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Na(Ia({},l.sessionProperties||{}),{capabilities:Na(Ia({},d||{}),{[u]:f})})})}catch(m){console.warn("Failed to update session with capabilities",m)}return f}async getCallStatus(e){var s,n,r;const i=this.client.session.get(e.topic),o=(s=i.sessionProperties)==null?void 0:s.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(d){console.warn("Failed to fetch call status from bundler",d,l)}}const a=(n=i.sessionProperties)==null?void 0:n.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await G_({resultId:(r=e.request.params)==null?void 0:r[0],storage:this.storage});if(c)try{return await H_(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,s){var n;const r=new URL(e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ls("eth_getUserOperationReceipt",[(n=s.request.params)==null?void 0:n[0]]))});if(!i.ok)throw new Error(`Failed to fetch user operation receipt - ${i.status}`);return await i.json()}getBundlerUrl(e,s){return`${m_}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}async sendCalls(e){var s,n,r;const i=await this.client.request(e),o=(s=e.request.params)==null?void 0:s[0],a=i==null?void 0:i.id,c=(i==null?void 0:i.capabilities)||{},l=(n=c==null?void 0:c.caip345)==null?void 0:n.caip2,d=(r=c==null?void 0:c.caip345)==null?void 0:r.transactionHashes;return!a||!l||!(d!=null&&d.length)||await V_({sendCalls:{request:o,result:i},storage:this.storage}),i}}var tI=Object.defineProperty,sI=(t,e,s)=>e in t?tI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Hn=(t,e,s)=>sI(t,typeof e!="symbol"?e+"":e,s);class nI{constructor(e){Hn(this,"name",$p),Hn(this,"client"),Hn(this,"httpProviders"),Hn(this,"events"),Hn(this,"namespace"),Hn(this,"chainId"),this.namespace=e.namespace,this.events=tr("events"),this.client=tr("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s);const n=this.chainId;this.chainId=e,this.events.emit(Jc.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return Rs(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){var e,s;const n={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(r=>{var i,o;const a=Rs(r),c=(o=(i=this.namespace)==null?void 0:i.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];n[a.reference]=this.createHttpProvider(r,c)}),n}getHttpProvider(e){const s=Rs(e).reference,n=this.httpProviders[s];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProvider(e,s){const n=s||Up(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Nc(new Ou(n,tr("disableProviderPing")))}}var rI=Object.defineProperty,iI=Object.defineProperties,oI=Object.getOwnPropertyDescriptors,uu=Object.getOwnPropertySymbols,aI=Object.prototype.hasOwnProperty,cI=Object.prototype.propertyIsEnumerable,bc=(t,e,s)=>e in t?rI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Nr=(t,e)=>{for(var s in e||(e={}))aI.call(e,s)&&bc(t,s,e[s]);if(uu)for(var s of uu(e))cI.call(e,s)&&bc(t,s,e[s]);return t},Yi=(t,e)=>iI(t,oI(e)),Mt=(t,e,s)=>bc(t,typeof e!="symbol"?e+"":e,s);let lI=class Lp{constructor(e){Mt(this,"client"),Mt(this,"namespaces"),Mt(this,"optionalNamespaces"),Mt(this,"sessionProperties"),Mt(this,"scopedProperties"),Mt(this,"events",new Ac),Mt(this,"rpcProviders",{}),Mt(this,"session"),Mt(this,"providerOpts"),Mt(this,"logger"),Mt(this,"uri"),Mt(this,"disableProviderPing",!1);var s,n;this.providerOpts=e,this.logger=Vc({logger:(s=e.logger)!=null?s:Jd,name:(n=this.providerOpts.name)!=null?n:kp}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const s=new Lp(e);return await s.initialize(),s}async request(e,s,n){const[r,i]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Nr({},e),chainId:`${r}:${i}`,topic:this.session.topic,expiry:n})}sendAsync(e,s,n,r){const i=new Date().getTime();this.request(e,n,r).then(o=>s(null,qr(i,o))).catch(o=>s(o,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 e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Ue("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,s){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:r}=await this.client.authenticate(e,s);n&&(this.uri=n,this.events.emit("display_uri",n));const i=await r();if(this.session=i.session,this.session){const o=su(this.session.namespaces);this.namespaces=Gi(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return i}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}removeListener(e,s){this.events.removeListener(e,s)}off(e,s){this.events.off(e,s)}get isWalletConnect(){return!0}async pair(e){const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});s&&(this.uri=s,this.events.emit("display_uri",s));const r=await n();this.session=r;const i=su(r.namespaces);return this.namespaces=Gi(this.namespaces,i),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,s){try{if(!this.session)return;const[n,r]=this.validateChain(e);this.getProvider(n).setDefaultChain(r,s)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(!ks(s))return;for(const n of s)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}catch(s){this.logger.warn(s,"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 e,s;if(this.client=this.providerOpts.client||await BA.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Jd,relayUrl:this.providerOpts.relayUrl||f_,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: ${(s=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:s.topic} doesn't exist in the Sign client`)}else{const 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()");const e=[...new Set(Object.keys(this.session.namespaces).map(s=>Jn(s)))];va("client",this.client),va("events",this.events),va("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const n=I_(s,this.session);if((n==null?void 0:n.length)===0)return;const r=Dp(n),i=Gi(this.namespaces,this.optionalNamespaces),o=Yi(Nr({},i[s]),{accounts:n,chains:r});switch(s){case"eip155":this.rpcProviders[s]=new eI({namespace:o});break;default:this.rpcProviders[s]=new nI({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var s;const{topic:n}=e;n===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:n,topic:r}=e;if(r!==((s=this.session)==null?void 0:s.topic))return;const{event:i}=n;if(i.name==="accountsChanged"){const o=i.data;o&&ks(o)&&this.events.emit("accountsChanged",o.map(tu))}else if(i.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Jn(o),l=Ca(o)!==Ca(a)?`${c}:${Ca(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var n,r;if(e!==((n=this.session)==null?void 0:n.topic))return;const{namespaces:i}=s,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Yi(Nr({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:s})}),this.client.on("session_delete",async e=>{var s;e.topic===((s=this.session)==null?void 0:s.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Yi(Nr({},Ue("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Jc.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(Yi(Nr({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[$p]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var s;this.getProvider(e).updateNamespace((s=this.session)==null?void 0:s.namespaces[e])})}setNamespaces(e){const{namespaces:s={},optionalNamespaces:n={},sessionProperties:r,scopedProperties:i}=e;this.optionalNamespaces=Gi(s,n),this.sessionProperties=r,this.scopedProperties=i}validateChain(e){const[s,n]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,n];if(s&&!Object.keys(this.namespaces||{}).map(o=>Jn(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&n)return[s,n];const r=Jn(Object.keys(this.namespaces)[0]),i=this.rpcProviders[r].getDefaultChain();return[r,i]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:s,internal:n=!1}){if(!this.namespaces)return;const[r,i]=this.validateChain(e);i&&(this.updateNamespaceChain(r,i),n?(this.events.emit("chainChanged",i),this.emitAccountsChangedOnChainChange({namespace:r,currentCaipChainId:e,previousCaipChainId:s})):this.getProvider(r).setDefaultChain(i),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:s,previousCaipChainId:n}){var r,i;try{if(n===s)return;const o=(i=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:i.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(tu);if(!ks(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,s){if(!this.namespaces)return;const n=this.namespaces[e]?e:`${e}:${s}`,r={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=s):this.namespaces[n]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){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(e,s){var n;const r=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${Vi}/${e}${r}`,s)}async getFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${Vi}/${e}${n}`)}async deleteFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${Vi}/${e}${n}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const s=await this.client.core.storage.getKeys();for(const n of s)n.startsWith(Vi)&&await this.client.core.storage.removeItem(n)}catch(s){this.logger.warn(s,"Failed to cleanup storage")}}};const Me={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",EIP155:N.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(t,e){return`
|
|
21
|
+
@@@@@@@ @@@@@@@@@@@@@@@@@@
|
|
22
|
+
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
|
|
23
|
+
@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@
|
|
24
|
+
@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
|
|
25
|
+
@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@
|
|
26
|
+
@@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@
|
|
27
|
+
@@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@
|
|
28
|
+
@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@
|
|
29
|
+
@@@@@@ @@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@
|
|
30
|
+
@@@@@@ @@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@
|
|
31
|
+
@@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@
|
|
32
|
+
@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
|
|
33
|
+
@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@
|
|
34
|
+
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
|
|
35
|
+
@@@@@ @@@@@@@@@@@@@@@@@@
|
|
36
|
+
|
|
37
|
+
AppKit SDK version ${t} is outdated. Latest version is ${e}. Please update to the latest version for bug fixes and new features.
|
|
38
|
+
|
|
39
|
+
Changelog: https://github.com/reown-com/appkit/releases
|
|
40
|
+
NPM Registry: https://www.npmjs.com/package/@reown/appkit`}},dI={ConnectorExplorerIds:{[N.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[N.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[N.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[N.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[N.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[Me.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[Me.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[Me.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[Me.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[Me.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[Me.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[Me.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[Me.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[Me.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[Me.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[Me.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[Me.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709"},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"},ConnectorImageIds:{[N.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[N.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[N.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[N.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[N.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[N.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[N.CONNECTOR_ID.INJECTED]:"Browser Wallet",[N.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[N.CONNECTOR_ID.COINBASE]:"Coinbase",[N.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[N.CONNECTOR_ID.LEDGER]:"Ledger",[N.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[N.CONNECTOR_ID.INJECTED]:"INJECTED",[N.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[N.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[N.CONNECTOR_ID.AUTH]:"AUTH",[Me.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]},gi={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,n])=>{e[`${Me.EIP155}:${s}`]=n}),e},isLowerCaseMatch(t,e){return(t==null?void 0:t.toLowerCase())===(e==null?void 0:e.toLowerCase())},getActiveNamespaceConnectedToAuth(){const t=g.state.activeChain;return N.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(e=>D.getConnectorId(e)===N.CONNECTOR_ID.AUTH&&e===t)},withRetry({conditionFn:t,intervalMs:e,maxRetries:s}){let n=0;return new Promise(r=>{async function i(){return n+=1,await t()?r(!0):n>=s?r(!1):(setTimeout(i,e),null)}i()})},userChainIdToChainNamespace(t){if(typeof t=="number")return N.CHAIN.EVM;const[e]=t.split(":");return e},getOtherAuthNamespaces(t){return t?N.AUTH_CONNECTOR_SUPPORTED_CHAINS.filter(n=>n!==t):[]},getConnectorStorageInfo(t,e){const n=R.getConnections()[e]??[];return{hasDisconnected:R.isConnectorDisconnected(t,e),hasConnected:n.some(r=>gi.isLowerCaseMatch(r.connectorId,t))}}},uI=new AbortController,Lt={EmbeddedWalletAbortController:uI,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 ${Tr()?window.origin:"unknown"} is not in your allow list. Please update your allowed domains at https://dashboard.reown.com. [PID: ${I.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’s 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:t=>`Unable to fetch App Configuration. ${t}. 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:t=>`[Reown Config Notice] ${t}`},INACTIVE_NAMESPACE_NOT_CONNECTED:{code:"APKTW001",displayMessage:"Inactive Namespace Not Connected",debugMessage:(t,e)=>`An error occurred while connecting an inactive namespace ${t}: "${e}"`},INVALID_EMAIL:{code:"APKTW002",displayMessage:"Invalid Email Address",debugMessage:"Please enter a valid email address"}}},Fp={TOKEN_ADDRESSES_BY_SYMBOL:{USDC:{8453:om.asset,84532:am.asset}},getTokenSymbolByAddress(t){if(!t)return;const[e]=Object.entries(Fp.TOKEN_ADDRESSES_BY_SYMBOL).find(([s,n])=>Object.values(n).includes(t))??[];return e}},hI={createLogger(t,e="error"){const s=Su({level:e}),{logger:n}=Ic({opts:s});return n.error=(...r)=>{for(const i of r)if(i instanceof Error){t(i,...r);return}t(void 0,...r)},n}},pI="rpc.walletconnect.org";function hu(t,e){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",t),s.searchParams.set("projectId",e),s.toString()}const Sa=["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"],Vn={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===pI}catch{s=!1}if(s){const n=new URL(t);return n.searchParams.has("projectId")||n.searchParams.set("projectId",e),n.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:N.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${N.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){var r,i,o;const n=(o=(i=(r=t.rpcUrls)==null?void 0:r.default)==null?void 0:i.http)==null?void 0:o[0];return Sa.includes(e)?hu(e,s):n||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){var h,p,f,m,y,w,b;const r=this.getChainNamespace(t),i=this.getCaipNetworkId(t),o=(f=(p=(h=t.rpcUrls)==null?void 0:h.default)==null?void 0:p.http)==null?void 0:f[0],a=this.getDefaultRpcUrl(t,i,s),c=((w=(y=(m=t==null?void 0:t.rpcUrls)==null?void 0:m.chainDefault)==null?void 0:y.http)==null?void 0:w[0])||o,l=((b=n==null?void 0:n[i])==null?void 0:b.map(A=>A.url))||[],d=[...l,...a?[a]:[]],u=[...l];return c&&!u.includes(c)&&u.push(c),{...t,chainNamespace:r,caipNetworkId:i,assets:{imageId:dI.NetworkImageIds[t.id],imageUrl:e==null?void 0:e[t.id]},rpcUrls:{...t.rpcUrls,default:{http:d},chainDefault:{http:u}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){return t.map(r=>Vn.extendCaipNetwork(r,{customNetworkImageUrls:e,customRpcUrls:n,projectId:s}))},getViemTransport(t,e,s){var r,i,o;const n=[];return s==null||s.forEach(a=>{n.push(Di(a.url,a.config))}),Sa.includes(t.caipNetworkId)&&n.push(Di(hu(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),(o=(i=(r=t==null?void 0:t.rpcUrls)==null?void 0:r.default)==null?void 0:i.http)==null||o.forEach(a=>{n.push(Di(a))}),hl(n)},extendWagmiTransports(t,e,s){if(Sa.includes(t.caipNetworkId)){const n=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return hl([s,Di(n)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:N.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){var c;const e=R.getActiveCaipNetworkId(),s=g.getAllRequestedCaipNetworks(),n=Array.from(((c=g.state.chains)==null?void 0:c.keys())||[]),r=e==null?void 0:e.split(":")[0],i=r?n.includes(r):!1,o=s==null?void 0:s.find(l=>l.caipNetworkId===e);return i&&!o&&e?this.getUnsupportedNetwork(e):o||t||(s==null?void 0:s[0])}},fI={ACCOUNT_TABS:[{label:"Tokens"},{label:"Activity"}],SECURE_SITE_ORIGIN:(typeof Os<"u"&&typeof{}<"u"?{}.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150},VIEWS_WITH_LEGAL_FOOTER:["Connect","ConnectWallets","OnRampTokenSelect","OnRampFiatSelect","OnRampProviders"],VIEWS_WITH_DEFAULT_FOOTER:["Networks"]},kr={filterOutDuplicatesByRDNS(t){const e=I.state.enableEIP6963?D.state.connectors:[],s=R.getRecentWallets(),n=e.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}).filter(Boolean),r=s.map(a=>a.rdns).filter(Boolean),i=n.concat(r);if(i.includes("io.metamask.mobile")&&z.isMobile()){const a=i.indexOf("io.metamask.mobile");i[a]="io.metamask"}return t.filter(a=>!(a!=null&&a.rdns&&i.includes(String(a.rdns))||!(a!=null&&a.rdns)&&e.some(l=>l.name===a.name)))},filterOutDuplicatesByIds(t){const e=D.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=R.getRecentWallets(),n=e.map(a=>a.explorerId),r=s.map(a=>a.id),i=n.concat(r);return t.filter(a=>!i.includes(a==null?void 0:a.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=D.state,{featuredWalletIds:s}=I.state,n=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>{var c;return(c=a.info)!=null&&c.rdns&&(o[a.info.rdns]=!0),o},{});return t.map(o=>({...o,installed:!!o.rdns&&!!n[o.rdns??""]})).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(s!=null&&s.length){const l=s.indexOf(o.id),d=s.indexOf(a.id);if(l!==-1&&d!==-1)return l-d;if(l!==-1)return-1;if(d!==-1)return 1}return 0})},getConnectOrderMethod(t,e){var c;const s=(t==null?void 0:t.connectMethodsOrder)||((c=I.state.features)==null?void 0:c.connectMethodsOrder),n=e||D.state.connectors;if(s)return s;const{injected:r,announced:i}=Ta.getConnectorsByType(n,J.state.recommended,J.state.featured),o=r.filter(Ta.showConnector),a=i.filter(Ta.showConnector);return o.length||a.length?["wallet","email","social"]:fI.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&J.state.excludedWallets.some(n=>n.rdns===t.rdns),s=!!t.name&&J.state.excludedWallets.some(n=>gi.isLowerCaseMatch(n.name,t.name));return e||s},markWalletsWithDisplayIndex(t){return t.map((e,s)=>({...e,display_index:s}))}},Ta={getConnectorsByType(t,e,s){const{customWallets:n}=I.state,r=R.getRecentWallets(),i=kr.filterOutDuplicateWallets(e),o=kr.filterOutDuplicateWallets(s),a=t.filter(u=>u.type==="MULTI_CHAIN"),c=t.filter(u=>u.type==="ANNOUNCED"),l=t.filter(u=>u.type==="INJECTED"),d=t.filter(u=>u.type==="EXTERNAL");return{custom:n,recent:r,external:d,multiChain:a,announced:c,injected:l,recommended:i,featured:o}},showConnector(t){var r;const e=(r=t.info)==null?void 0:r.rdns,s=!!e&&J.state.excludedWallets.some(i=>!!i.rdns&&i.rdns===e),n=!!t.name&&J.state.excludedWallets.some(i=>gi.isLowerCaseMatch(i.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!z.isMobile()||z.isMobile()&&!e&&!B.checkInstalled())||s||n)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||n))},getIsConnectedWithWC(){return Array.from(g.state.chains.values()).some(s=>D.getConnectorId(s.namespace)===N.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:n,announced:r,injected:i,multiChain:o,external:a,overriddenConnectors:c=(l=>(l=I.state.features)==null?void 0:l.connectorTypeOrder)()??[]}){const u=[{type:"walletConnect",isEnabled:!0},{type:"recent",isEnabled:n.length>0},{type:"injected",isEnabled:[...i,...r,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(m=>m.isEnabled),h=new Set(u.map(m=>m.type)),p=c.filter(m=>h.has(m)).map(m=>({type:m,isEnabled:!0})),f=u.filter(({type:m})=>!p.some(({type:w})=>w===m));return Array.from(new Set([...p,...f].map(({type:m})=>m)))},sortConnectorsByExplorerWallet(t){return[...t].sort((e,s)=>e.explorerWallet&&s.explorerWallet?(e.explorerWallet.order??0)-(s.explorerWallet.order??0):e.explorerWallet?-1:s.explorerWallet?1:0)},getAuthName({email:t,socialUsername:e,socialProvider:s}){return e?s&&s==="discord"&&e.endsWith("0")?e.slice(0,-1):e:t.length>30?`${t.slice(0,-3)}...`:t},async fetchProviderData(t){var e,s;try{if(t.name==="Browser Wallet"&&!z.isMobile())return{accounts:[],chainId:void 0};if(t.id===N.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};const[n,r]=await Promise.all([(e=t.provider)==null?void 0:e.request({method:"eth_accounts"}),(s=t.provider)==null?void 0:s.request({method:"eth_chainId"}).then(i=>Number(i))]);return{accounts:n,chainId:r}}catch(n){return console.warn(`Failed to fetch provider data for ${t.name}`,n),{accounts:[],chainId:void 0}}},getFilteredCustomWallets(t){const e=R.getRecentWallets(),s=D.state.connectors.map(o=>{var a;return(a=o.info)==null?void 0:a.rdns}).filter(Boolean),n=e.map(o=>o.rdns).filter(Boolean),r=s.concat(n);if(r.includes("io.metamask.mobile")&&z.isMobile()){const o=r.indexOf("io.metamask.mobile");r[o]="io.metamask"}return t.filter(o=>!r.includes(String(o==null?void 0:o.rdns)))},hasWalletConnector(t){return D.state.connectors.some(e=>e.id===t.id||e.name===t.name)},isWalletCompatibleWithCurrentChain(t){const e=g.state.activeChain;return e&&t.chains?t.chains.some(s=>{const n=s.split(":")[0];return e===n}):!0},getFilteredRecentWallets(){return R.getRecentWallets().filter(s=>!kr.isExcluded(s)).filter(s=>!this.hasWalletConnector(s)).filter(s=>this.isWalletCompatibleWithCurrentChain(s))},getCappedRecommendedWallets(t){const{connectors:e}=D.state,{customWallets:s,featuredWalletIds:n}=I.state,r=e.find(b=>b.id==="walletConnect"),i=e.filter(b=>b.type==="INJECTED"||b.type==="ANNOUNCED"||b.type==="MULTI_CHAIN");if(!r&&!i.length&&!(s!=null&&s.length))return[];const o=La.isEmailEnabled(),a=La.isSocialsEnabled(),c=i.filter(b=>b.name!=="Browser Wallet"),l=(n==null?void 0:n.length)||0,d=(s==null?void 0:s.length)||0,u=c.length||0,h=o?1:0,p=a?1:0,f=l+d+u+h+p,y=Math.max(0,4-f);return y<=0?[]:kr.filterOutDuplicateWallets(t).slice(0,y)}};/**
|
|
41
|
+
* @license
|
|
42
|
+
* Copyright 2019 Google LLC
|
|
43
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
44
|
+
*/const ao=globalThis,Zc=ao.ShadowRoot&&(ao.ShadyCSS===void 0||ao.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Qc=Symbol(),pu=new WeakMap;let Bp=class{constructor(e,s,n){if(this._$cssResult$=!0,n!==Qc)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=s}get styleSheet(){let e=this.o;const s=this.t;if(Zc&&e===void 0){const n=s!==void 0&&s.length===1;n&&(e=pu.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&pu.set(s,e))}return e}toString(){return this.cssText}};const es=t=>new Bp(typeof t=="string"?t:t+"",void 0,Qc),Ys=(t,...e)=>{const s=t.length===1?t[0]:e.reduce((n,r,i)=>n+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+t[i+1],t[0]);return new Bp(s,t,Qc)},gI=(t,e)=>{if(Zc)t.adoptedStyleSheets=e.map(s=>s instanceof CSSStyleSheet?s:s.styleSheet);else for(const s of e){const n=document.createElement("style"),r=ao.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=s.cssText,t.appendChild(n)}},fu=Zc?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const n of e.cssRules)s+=n.cssText;return es(s)})(t):t;/**
|
|
45
|
+
* @license
|
|
46
|
+
* Copyright 2017 Google LLC
|
|
47
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
48
|
+
*/const{is:mI,defineProperty:yI,getOwnPropertyDescriptor:wI,getOwnPropertyNames:bI,getOwnPropertySymbols:EI,getPrototypeOf:CI}=Object,tn=globalThis,gu=tn.trustedTypes,vI=gu?gu.emptyScript:"",Oa=tn.reactiveElementPolyfillSupport,Br=(t,e)=>t,Ec={toAttribute(t,e){switch(e){case Boolean:t=t?vI:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,e){let s=t;switch(e){case Boolean:s=t!==null;break;case Number:s=t===null?null:Number(t);break;case Object:case Array:try{s=JSON.parse(t)}catch{s=null}}return s}},jp=(t,e)=>!mI(t,e),mu={attribute:!0,type:String,converter:Ec,reflect:!1,useDefault:!1,hasChanged:jp};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),tn.litPropertyMetadata??(tn.litPropertyMetadata=new WeakMap);let zn=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,s=mu){if(s.state&&(s.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((s=Object.create(s)).wrapped=!0),this.elementProperties.set(e,s),!s.noAccessor){const n=Symbol(),r=this.getPropertyDescriptor(e,n,s);r!==void 0&&yI(this.prototype,e,r)}}static getPropertyDescriptor(e,s,n){const{get:r,set:i}=wI(this.prototype,e)??{get(){return this[s]},set(o){this[s]=o}};return{get:r,set(o){const a=r==null?void 0:r.call(this);i==null||i.call(this,o),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??mu}static _$Ei(){if(this.hasOwnProperty(Br("elementProperties")))return;const e=CI(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Br("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Br("properties"))){const s=this.properties,n=[...bI(s),...EI(s)];for(const r of n)this.createProperty(r,s[r])}const e=this[Symbol.metadata];if(e!==null){const s=litPropertyMetadata.get(e);if(s!==void 0)for(const[n,r]of s)this.elementProperties.set(n,r)}this._$Eh=new Map;for(const[s,n]of this.elementProperties){const r=this._$Eu(s,n);r!==void 0&&this._$Eh.set(r,s)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const s=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const r of n)s.unshift(fu(r))}else e!==void 0&&s.push(fu(e));return s}static _$Eu(e,s){const n=s.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(s=>this.enableUpdating=s),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(s=>s(this))}addController(e){var s;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((s=e.hostConnected)==null||s.call(e))}removeController(e){var s;(s=this._$EO)==null||s.delete(e)}_$E_(){const e=new Map,s=this.constructor.elementProperties;for(const n of s.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return gI(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(s=>{var n;return(n=s.hostConnected)==null?void 0:n.call(s)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(s=>{var n;return(n=s.hostDisconnected)==null?void 0:n.call(s)})}attributeChangedCallback(e,s,n){this._$AK(e,n)}_$ET(e,s){var i;const n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&n.reflect===!0){const o=(((i=n.converter)==null?void 0:i.toAttribute)!==void 0?n.converter:Ec).toAttribute(s,n.type);this._$Em=e,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(e,s){var i,o;const n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const a=n.getPropertyOptions(r),c=typeof a.converter=="function"?{fromAttribute:a.converter}:((i=a.converter)==null?void 0:i.fromAttribute)!==void 0?a.converter:Ec;this._$Em=r;const l=c.fromAttribute(s,a.type);this[r]=l??((o=this._$Ej)==null?void 0:o.get(r))??l,this._$Em=null}}requestUpdate(e,s,n){var r;if(e!==void 0){const i=this.constructor,o=this[e];if(n??(n=i.getPropertyOptions(e)),!((n.hasChanged??jp)(o,s)||n.useDefault&&n.reflect&&o===((r=this._$Ej)==null?void 0:r.get(e))&&!this.hasAttribute(i._$Eu(e,n))))return;this.C(e,s,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,s,{useDefault:n,reflect:r,wrapped:i},o){n&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,o??s??this[e]),i!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(s=void 0),this._$AL.set(e,s)),r===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(s){Promise.reject(s)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var n;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[i,o]of this._$Ep)this[i]=o;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[i,o]of r){const{wrapped:a}=o,c=this[i];a!==!0||this._$AL.has(i)||c===void 0||this.C(i,void 0,o,c)}}let e=!1;const s=this._$AL;try{e=this.shouldUpdate(s),e?(this.willUpdate(s),(n=this._$EO)==null||n.forEach(r=>{var i;return(i=r.hostUpdate)==null?void 0:i.call(r)}),this.update(s)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(s)}willUpdate(e){}_$AE(e){var s;(s=this._$EO)==null||s.forEach(n=>{var r;return(r=n.hostUpdated)==null?void 0:r.call(n)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(s=>this._$ET(s,this[s]))),this._$EM()}updated(e){}firstUpdated(e){}};zn.elementStyles=[],zn.shadowRootOptions={mode:"open"},zn[Br("elementProperties")]=new Map,zn[Br("finalized")]=new Map,Oa==null||Oa({ReactiveElement:zn}),(tn.reactiveElementVersions??(tn.reactiveElementVersions=[])).push("2.1.1");/**
|
|
49
|
+
* @license
|
|
50
|
+
* Copyright 2017 Google LLC
|
|
51
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
52
|
+
*/const jr=globalThis,To=jr.trustedTypes,yu=To?To.createPolicy("lit-html",{createHTML:t=>t}):void 0,qp="$lit$",Js=`lit$${Math.random().toFixed(9).slice(2)}$`,Wp="?"+Js,AI=`<${Wp}>`,xn=document,mi=()=>xn.createComment(""),yi=t=>t===null||typeof t!="object"&&typeof t!="function",el=Array.isArray,_I=t=>el(t)||typeof(t==null?void 0:t[Symbol.iterator])=="function",Ra=`[
|
|
53
|
+
\f\r]`,Sr=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,wu=/-->/g,bu=/>/g,fn=RegExp(`>|${Ra}(?:([^\\s"'>=/]+)(${Ra}*=${Ra}*(?:[^
|
|
54
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Eu=/'/g,Cu=/"/g,Hp=/^(?:script|style|textarea|title)$/i,Kp=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),zN=Kp(1),GN=Kp(2),lr=Symbol.for("lit-noChange"),Ye=Symbol.for("lit-nothing"),vu=new WeakMap,Nn=xn.createTreeWalker(xn,129);function Vp(t,e){if(!el(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return yu!==void 0?yu.createHTML(e):e}const II=(t,e)=>{const s=t.length-1,n=[];let r,i=e===2?"<svg>":e===3?"<math>":"",o=Sr;for(let a=0;a<s;a++){const c=t[a];let l,d,u=-1,h=0;for(;h<c.length&&(o.lastIndex=h,d=o.exec(c),d!==null);)h=o.lastIndex,o===Sr?d[1]==="!--"?o=wu:d[1]!==void 0?o=bu:d[2]!==void 0?(Hp.test(d[2])&&(r=RegExp("</"+d[2],"g")),o=fn):d[3]!==void 0&&(o=fn):o===fn?d[0]===">"?(o=r??Sr,u=-1):d[1]===void 0?u=-2:(u=o.lastIndex-d[2].length,l=d[1],o=d[3]===void 0?fn:d[3]==='"'?Cu:Eu):o===Cu||o===Eu?o=fn:o===wu||o===bu?o=Sr:(o=fn,r=void 0);const p=o===fn&&t[a+1].startsWith("/>")?" ":"";i+=o===Sr?c+AI:u>=0?(n.push(l),c.slice(0,u)+qp+c.slice(u)+Js+p):c+Js+(u===-2?a:p)}return[Vp(t,i+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class wi{constructor({strings:e,_$litType$:s},n){let r;this.parts=[];let i=0,o=0;const a=e.length-1,c=this.parts,[l,d]=II(e,s);if(this.el=wi.createElement(l,n),Nn.currentNode=this.el.content,s===2||s===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(r=Nn.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const u of r.getAttributeNames())if(u.endsWith(qp)){const h=d[o++],p=r.getAttribute(u).split(Js),f=/([.?@])?(.*)/.exec(h);c.push({type:1,index:i,name:f[2],strings:p,ctor:f[1]==="."?SI:f[1]==="?"?TI:f[1]==="@"?OI:Ho}),r.removeAttribute(u)}else u.startsWith(Js)&&(c.push({type:6,index:i}),r.removeAttribute(u));if(Hp.test(r.tagName)){const u=r.textContent.split(Js),h=u.length-1;if(h>0){r.textContent=To?To.emptyScript:"";for(let p=0;p<h;p++)r.append(u[p],mi()),Nn.nextNode(),c.push({type:2,index:++i});r.append(u[h],mi())}}}else if(r.nodeType===8)if(r.data===Wp)c.push({type:2,index:i});else{let u=-1;for(;(u=r.data.indexOf(Js,u+1))!==-1;)c.push({type:7,index:i}),u+=Js.length-1}i++}}static createElement(e,s){const n=xn.createElement("template");return n.innerHTML=e,n}}function dr(t,e,s=t,n){var o,a;if(e===lr)return e;let r=n!==void 0?(o=s._$Co)==null?void 0:o[n]:s._$Cl;const i=yi(e)?void 0:e._$litDirective$;return(r==null?void 0:r.constructor)!==i&&((a=r==null?void 0:r._$AO)==null||a.call(r,!1),i===void 0?r=void 0:(r=new i(t),r._$AT(t,s,n)),n!==void 0?(s._$Co??(s._$Co=[]))[n]=r:s._$Cl=r),r!==void 0&&(e=dr(t,r._$AS(t,e.values),r,n)),e}class NI{constructor(e,s){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=s}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:s},parts:n}=this._$AD,r=((e==null?void 0:e.creationScope)??xn).importNode(s,!0);Nn.currentNode=r;let i=Nn.nextNode(),o=0,a=0,c=n[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new Ti(i,i.nextSibling,this,e):c.type===1?l=new c.ctor(i,c.name,c.strings,this,e):c.type===6&&(l=new RI(i,this,e)),this._$AV.push(l),c=n[++a]}o!==(c==null?void 0:c.index)&&(i=Nn.nextNode(),o++)}return Nn.currentNode=xn,r}p(e){let s=0;for(const n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,s),s+=n.strings.length-2):n._$AI(e[s])),s++}}class Ti{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,s,n,r){this.type=2,this._$AH=Ye,this._$AN=void 0,this._$AA=e,this._$AB=s,this._$AM=n,this.options=r,this._$Cv=(r==null?void 0:r.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const s=this._$AM;return s!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=s.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,s=this){e=dr(this,e,s),yi(e)?e===Ye||e==null||e===""?(this._$AH!==Ye&&this._$AR(),this._$AH=Ye):e!==this._$AH&&e!==lr&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):_I(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==Ye&&yi(this._$AH)?this._$AA.nextSibling.data=e:this.T(xn.createTextNode(e)),this._$AH=e}$(e){var i;const{values:s,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=wi.createElement(Vp(n.h,n.h[0]),this.options)),n);if(((i=this._$AH)==null?void 0:i._$AD)===r)this._$AH.p(s);else{const o=new NI(r,this),a=o.u(this.options);o.p(s),this.T(a),this._$AH=o}}_$AC(e){let s=vu.get(e.strings);return s===void 0&&vu.set(e.strings,s=new wi(e)),s}k(e){el(this._$AH)||(this._$AH=[],this._$AR());const s=this._$AH;let n,r=0;for(const i of e)r===s.length?s.push(n=new Ti(this.O(mi()),this.O(mi()),this,this.options)):n=s[r],n._$AI(i),r++;r<s.length&&(this._$AR(n&&n._$AB.nextSibling,r),s.length=r)}_$AR(e=this._$AA.nextSibling,s){var n;for((n=this._$AP)==null?void 0:n.call(this,!1,!0,s);e!==this._$AB;){const r=e.nextSibling;e.remove(),e=r}}setConnected(e){var s;this._$AM===void 0&&(this._$Cv=e,(s=this._$AP)==null||s.call(this,e))}}class Ho{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,n,r,i){this.type=1,this._$AH=Ye,this._$AN=void 0,this.element=e,this.name=s,this._$AM=r,this.options=i,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=Ye}_$AI(e,s=this,n,r){const i=this.strings;let o=!1;if(i===void 0)e=dr(this,e,s,0),o=!yi(e)||e!==this._$AH&&e!==lr,o&&(this._$AH=e);else{const a=e;let c,l;for(e=i[0],c=0;c<i.length-1;c++)l=dr(this,a[n+c],s,c),l===lr&&(l=this._$AH[c]),o||(o=!yi(l)||l!==this._$AH[c]),l===Ye?e=Ye:e!==Ye&&(e+=(l??"")+i[c+1]),this._$AH[c]=l}o&&!r&&this.j(e)}j(e){e===Ye?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class SI extends Ho{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Ye?void 0:e}}class TI extends Ho{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Ye)}}class OI extends Ho{constructor(e,s,n,r,i){super(e,s,n,r,i),this.type=5}_$AI(e,s=this){if((e=dr(this,e,s,0)??Ye)===lr)return;const n=this._$AH,r=e===Ye&&n!==Ye||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==Ye&&(n===Ye||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var s;typeof this._$AH=="function"?this._$AH.call(((s=this.options)==null?void 0:s.host)??this.element,e):this._$AH.handleEvent(e)}}class RI{constructor(e,s,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=s,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){dr(this,e)}}const Pa=jr.litHtmlPolyfillSupport;Pa==null||Pa(wi,Ti),(jr.litHtmlVersions??(jr.litHtmlVersions=[])).push("3.3.1");const PI=(t,e,s)=>{const n=(s==null?void 0:s.renderBefore)??e;let r=n._$litPart$;if(r===void 0){const i=(s==null?void 0:s.renderBefore)??null;n._$litPart$=r=new Ti(e.insertBefore(mi(),i),i,void 0,s??{})}return r._$AI(t),r};/**
|
|
55
|
+
* @license
|
|
56
|
+
* Copyright 2017 Google LLC
|
|
57
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
|
58
|
+
*/const On=globalThis;class co extends zn{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var s;const e=super.createRenderRoot();return(s=this.renderOptions).renderBefore??(s.renderBefore=e.firstChild),e}update(e){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=PI(s,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return lr}}var Iu;co._$litElement$=!0,co.finalized=!0,(Iu=On.litElementHydrateSupport)==null||Iu.call(On,{LitElement:co});const ka=On.litElementPolyfillSupport;ka==null||ka({LitElement:co});(On.litElementVersions??(On.litElementVersions=[])).push("4.2.1");const kI={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)"},Oo={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"}},xI={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"},$I={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"},UI={regular:"KHTeka",mono:"KHTekaMono"},DI={regular:"400",medium:"500"},MI={h1:"50px",h2:"44px",h3:"38px",h4:"32px",h5:"26px",h6:"20px",large:"16px",medium:"14px",small:"12px"},LI={"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"}},FI={"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)"},BI={xl:"400ms",lg:"200ms",md:"125ms",sm:"75ms"},Cc={colors:kI,fontFamily:UI,fontWeight:DI,textSize:MI,typography:LI,tokens:{core:Oo.core,theme:Oo.dark},borderRadius:xI,spacing:$I,durations:BI,easings:FI},Au="--apkt",_s={createCSSVariables(t){const e={},s={};function n(i,o,a=""){for(const[c,l]of Object.entries(i)){const d=a?`${a}-${c}`:c;l&&typeof l=="object"&&Object.keys(l).length?(o[c]={},n(l,o[c],d)):typeof l=="string"&&(o[c]=`${Au}-${d}`)}}function r(i,o){for(const[a,c]of Object.entries(i))c&&typeof c=="object"?(o[a]={},r(c,o[a])):typeof c=="string"&&(o[a]=`var(${c})`)}return n(t,e),r(e,s),{cssVariables:e,cssVariablesVarPrefix:s}},assignCSSVariables(t,e){const s={};function n(r,i,o){for(const[a,c]of Object.entries(r)){const l=o?`${o}-${a}`:a,d=i[a];c&&typeof c=="object"?n(c,d,l):typeof d=="string"&&(s[`${Au}-${l}`]=d)}}return n(t,e),s},createRootStyles(t,e){const s={...Cc,tokens:{...Cc.tokens,theme:t==="light"?Oo.light:Oo.dark}},{cssVariables:n}=_s.createCSSVariables(s),r=_s.assignCSSVariables(n,s),i=_s.generateW3MVariables(e),o=_s.generateW3MOverrides(e),a=_s.generateScaledVariables(e),c=_s.generateBaseVariables(r),l={...r,...c,...i,...o,...a},d=_s.applyColorMixToVariables(e,l),u={...l,...d};return`:root {${Object.entries(u).map(([p,f])=>`${p}:${f.replace("/[:;{}</>]/g","")};`).join("")}}`},generateW3MVariables(t){if(!t)return{};const e={};return e["--w3m-font-family"]=t["--w3m-font-family"]||"KHTeka",e["--w3m-accent"]=t["--w3m-accent"]||"#0988F0",e["--w3m-color-mix"]=t["--w3m-color-mix"]||"#000",e["--w3m-color-mix-strength"]=`${t["--w3m-color-mix-strength"]||0}%`,e["--w3m-font-size-master"]=t["--w3m-font-size-master"]||"10px",e["--w3m-border-radius-master"]=t["--w3m-border-radius-master"]||"4px",e},generateW3MOverrides(t){if(!t)return{};const e={};if(t["--w3m-accent"]){const s=t["--w3m-accent"];e["--apkt-tokens-core-iconAccentPrimary"]=s,e["--apkt-tokens-core-borderAccentPrimary"]=s,e["--apkt-tokens-core-textAccentPrimary"]=s,e["--apkt-tokens-core-backgroundAccentPrimary"]=s}return t["--w3m-font-family"]&&(e["--apkt-fontFamily-regular"]=t["--w3m-font-family"]),t["--w3m-z-index"]&&(e["--apkt-tokens-core-zIndex"]=`${t["--w3m-z-index"]}`),e},generateScaledVariables(t){if(!t)return{};const e={};if(t["--w3m-font-size-master"]){const s=parseFloat(t["--w3m-font-size-master"].replace("px",""));e["--apkt-textSize-h1"]=`${Number(s)*5}px`,e["--apkt-textSize-h2"]=`${Number(s)*4.4}px`,e["--apkt-textSize-h3"]=`${Number(s)*3.8}px`,e["--apkt-textSize-h4"]=`${Number(s)*3.2}px`,e["--apkt-textSize-h5"]=`${Number(s)*2.6}px`,e["--apkt-textSize-h6"]=`${Number(s)*2}px`,e["--apkt-textSize-large"]=`${Number(s)*1.6}px`,e["--apkt-textSize-medium"]=`${Number(s)*1.4}px`,e["--apkt-textSize-small"]=`${Number(s)*1.2}px`}if(t["--w3m-border-radius-master"]){const s=parseFloat(t["--w3m-border-radius-master"].replace("px",""));e["--apkt-borderRadius-1"]=`${Number(s)}px`,e["--apkt-borderRadius-2"]=`${Number(s)*2}px`,e["--apkt-borderRadius-3"]=`${Number(s)*3}px`,e["--apkt-borderRadius-4"]=`${Number(s)*4}px`,e["--apkt-borderRadius-5"]=`${Number(s)*5}px`,e["--apkt-borderRadius-6"]=`${Number(s)*6}px`,e["--apkt-borderRadius-8"]=`${Number(s)*8}px`,e["--apkt-borderRadius-16"]=`${Number(s)*16}px`,e["--apkt-borderRadius-20"]=`${Number(s)*20}px`,e["--apkt-borderRadius-32"]=`${Number(s)*32}px`,e["--apkt-borderRadius-64"]=`${Number(s)*64}px`,e["--apkt-borderRadius-128"]=`${Number(s)*128}px`}return e},generateColorMixCSS(t,e){if(!(t!=null&&t["--w3m-color-mix"])||!t["--w3m-color-mix-strength"])return"";const s=t["--w3m-color-mix"],n=t["--w3m-color-mix-strength"];if(!n||n===0)return"";const r=Object.keys(e||{}).filter(o=>{const a=o.includes("-tokens-core-background")||o.includes("-tokens-core-text")||o.includes("-tokens-core-border")||o.includes("-tokens-core-foreground")||o.includes("-tokens-core-icon")||o.includes("-tokens-theme-background")||o.includes("-tokens-theme-text")||o.includes("-tokens-theme-border")||o.includes("-tokens-theme-foreground")||o.includes("-tokens-theme-icon"),c=o.includes("-borderRadius-")||o.includes("-spacing-")||o.includes("-textSize-")||o.includes("-fontFamily-")||o.includes("-fontWeight-")||o.includes("-typography-")||o.includes("-duration-")||o.includes("-ease-")||o.includes("-path-")||o.includes("-width-")||o.includes("-height-")||o.includes("-visual-size-")||o.includes("-modal-width")||o.includes("-cover");return a&&!c});return r.length===0?"":` @supports (background: color-mix(in srgb, white 50%, black)) {
|
|
59
|
+
:root {
|
|
60
|
+
${r.map(o=>{const a=(e==null?void 0:e[o])||"";return a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?`${o}: color-mix(in srgb, ${s} ${n}%, ${a});`:`${o}: color-mix(in srgb, ${s} ${n}%, var(${o}-base, ${a}));`}).join("")}
|
|
61
|
+
}
|
|
62
|
+
}`},generateBaseVariables(t){const e={},s=t["--apkt-tokens-theme-backgroundPrimary"];s&&(e["--apkt-tokens-theme-backgroundPrimary-base"]=s);const n=t["--apkt-tokens-core-backgroundAccentPrimary"];return n&&(e["--apkt-tokens-core-backgroundAccentPrimary-base"]=n),e},applyColorMixToVariables(t,e){const s={};if(e!=null&&e["--apkt-tokens-theme-backgroundPrimary"]&&(s["--apkt-tokens-theme-backgroundPrimary"]="var(--apkt-tokens-theme-backgroundPrimary-base)"),e!=null&&e["--apkt-tokens-core-backgroundAccentPrimary"]&&(s["--apkt-tokens-core-backgroundAccentPrimary"]="var(--apkt-tokens-core-backgroundAccentPrimary-base)"),!(t!=null&&t["--w3m-color-mix"])||!t["--w3m-color-mix-strength"])return s;const n=t["--w3m-color-mix"],r=t["--w3m-color-mix-strength"];if(!r||r===0)return s;const i=Object.keys(e||{}).filter(o=>{const a=o.includes("-tokens-core-background")||o.includes("-tokens-core-text")||o.includes("-tokens-core-border")||o.includes("-tokens-core-foreground")||o.includes("-tokens-core-icon")||o.includes("-tokens-theme-background")||o.includes("-tokens-theme-text")||o.includes("-tokens-theme-border")||o.includes("-tokens-theme-foreground")||o.includes("-tokens-theme-icon")||o.includes("-tokens-theme-overlay"),c=o.includes("-borderRadius-")||o.includes("-spacing-")||o.includes("-textSize-")||o.includes("-fontFamily-")||o.includes("-fontWeight-")||o.includes("-typography-")||o.includes("-duration-")||o.includes("-ease-")||o.includes("-path-")||o.includes("-width-")||o.includes("-height-")||o.includes("-visual-size-")||o.includes("-modal-width")||o.includes("-cover");return a&&!c});return i.length===0||i.forEach(o=>{const a=(e==null?void 0:e[o])||"";o.endsWith("-base")||(o==="--apkt-tokens-theme-backgroundPrimary"||o==="--apkt-tokens-core-backgroundAccentPrimary"?s[o]=`color-mix(in srgb, ${n} ${r}%, var(${o}-base))`:a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?s[o]=`color-mix(in srgb, ${n} ${r}%, ${a})`:s[o]=`color-mix(in srgb, ${n} ${r}%, var(${o}-base, ${a}))`)}),s}},{cssVariablesVarPrefix:jI}=_s.createCSSVariables(Cc);function YN(t,...e){return Ys(t,...e.map(s=>es(typeof s=="function"?s(jI):s)))}let bn,Sn,ps,Ot,Ro;const As={"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"};function Po(t,e="dark"){bn&&document.head.removeChild(bn),bn=document.createElement("style"),bn.textContent=_s.createRootStyles(e,t),document.head.appendChild(bn)}function JN(t,e="dark"){if(Ro=t,Sn=document.createElement("style"),ps=document.createElement("style"),Ot=document.createElement("style"),Sn.textContent=sr(t).core.cssText,ps.textContent=sr(t).dark.cssText,Ot.textContent=sr(t).light.cssText,document.head.appendChild(Sn),document.head.appendChild(ps),document.head.appendChild(Ot),Po(t,e),vc(e),!(t!=null&&t["--w3m-font-family"]))for(const[s,n]of Object.entries(As)){const r=document.createElement("link");r.rel="preload",r.href=n,r.as="font",r.type=s.includes("woff2")?"font/woff2":"font/woff",r.crossOrigin="anonymous",document.head.appendChild(r)}vc(e)}function vc(t="dark"){ps&&Ot&&bn&&(t==="light"?(Po(Ro,t),ps.removeAttribute("media"),Ot.media="enabled"):(Po(Ro,t),Ot.removeAttribute("media"),ps.media="enabled"))}function qI(t){var e,s,n;if(Ro=t,Sn&&ps&&Ot&&(Sn.textContent=sr(t).core.cssText,ps.textContent=sr(t).dark.cssText,Ot.textContent=sr(t).light.cssText,t!=null&&t["--w3m-font-family"])){const r=t["--w3m-font-family"];Sn.textContent=(e=Sn.textContent)==null?void 0:e.replace("font-family: KHTeka",`font-family: ${r}`),ps.textContent=(s=ps.textContent)==null?void 0:s.replace("font-family: KHTeka",`font-family: ${r}`),Ot.textContent=(n=Ot.textContent)==null?void 0:n.replace("font-family: KHTeka",`font-family: ${r}`)}if(bn){const r=(Ot==null?void 0:Ot.media)==="enabled"?"light":"dark";Po(t,r)}}function sr(t){const e=!!(t!=null&&t["--w3m-font-family"]);return{core:Ys`
|
|
63
|
+
${e?Ys``:Ys`
|
|
64
|
+
@font-face {
|
|
65
|
+
font-family: 'KHTeka';
|
|
66
|
+
src:
|
|
67
|
+
url(${es(As["KHTeka-400-woff2"])}) format('woff2'),
|
|
68
|
+
url(${es(As["KHTeka-400-woff"])}) format('woff');
|
|
69
|
+
font-weight: 400;
|
|
70
|
+
font-style: normal;
|
|
71
|
+
font-display: swap;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
@font-face {
|
|
75
|
+
font-family: 'KHTeka';
|
|
76
|
+
src:
|
|
77
|
+
url(${es(As["KHTeka-300-woff2"])}) format('woff2'),
|
|
78
|
+
url(${es(As["KHTeka-300-woff"])}) format('woff');
|
|
79
|
+
font-weight: 300;
|
|
80
|
+
font-style: normal;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
@font-face {
|
|
84
|
+
font-family: 'KHTekaMono';
|
|
85
|
+
src:
|
|
86
|
+
url(${es(As["KHTekaMono-400-woff2"])}) format('woff2'),
|
|
87
|
+
url(${es(As["KHTekaMono-400-woff"])}) format('woff');
|
|
88
|
+
font-weight: 400;
|
|
89
|
+
font-style: normal;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
@font-face {
|
|
93
|
+
font-family: 'KHTeka';
|
|
94
|
+
src:
|
|
95
|
+
url(${es(As["KHTeka-400-woff2"])}) format('woff2'),
|
|
96
|
+
url(${es(As["KHTeka-400-woff"])}) format('woff');
|
|
97
|
+
font-weight: 400;
|
|
98
|
+
font-style: normal;
|
|
99
|
+
}
|
|
100
|
+
`}
|
|
101
|
+
|
|
102
|
+
@keyframes w3m-shake {
|
|
103
|
+
0% {
|
|
104
|
+
transform: scale(1) rotate(0deg);
|
|
105
|
+
}
|
|
106
|
+
20% {
|
|
107
|
+
transform: scale(1) rotate(-1deg);
|
|
108
|
+
}
|
|
109
|
+
40% {
|
|
110
|
+
transform: scale(1) rotate(1.5deg);
|
|
111
|
+
}
|
|
112
|
+
60% {
|
|
113
|
+
transform: scale(1) rotate(-1.5deg);
|
|
114
|
+
}
|
|
115
|
+
80% {
|
|
116
|
+
transform: scale(1) rotate(1deg);
|
|
117
|
+
}
|
|
118
|
+
100% {
|
|
119
|
+
transform: scale(1) rotate(0deg);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
@keyframes w3m-iframe-fade-out {
|
|
123
|
+
0% {
|
|
124
|
+
opacity: 1;
|
|
125
|
+
}
|
|
126
|
+
100% {
|
|
127
|
+
opacity: 0;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
@keyframes w3m-iframe-zoom-in {
|
|
131
|
+
0% {
|
|
132
|
+
transform: translateY(50px);
|
|
133
|
+
opacity: 0;
|
|
134
|
+
}
|
|
135
|
+
100% {
|
|
136
|
+
transform: translateY(0px);
|
|
137
|
+
opacity: 1;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
@keyframes w3m-iframe-zoom-in-mobile {
|
|
141
|
+
0% {
|
|
142
|
+
transform: scale(0.95);
|
|
143
|
+
opacity: 0;
|
|
144
|
+
}
|
|
145
|
+
100% {
|
|
146
|
+
transform: scale(1);
|
|
147
|
+
opacity: 1;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
:root {
|
|
151
|
+
--apkt-modal-width: 370px;
|
|
152
|
+
|
|
153
|
+
--apkt-visual-size-inherit: inherit;
|
|
154
|
+
--apkt-visual-size-sm: 40px;
|
|
155
|
+
--apkt-visual-size-md: 55px;
|
|
156
|
+
--apkt-visual-size-lg: 80px;
|
|
157
|
+
|
|
158
|
+
--apkt-path-network-sm: path(
|
|
159
|
+
'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'
|
|
160
|
+
);
|
|
161
|
+
|
|
162
|
+
--apkt-path-network-md: path(
|
|
163
|
+
'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'
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
--apkt-path-network-lg: path(
|
|
167
|
+
'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'
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
--apkt-width-network-sm: 36px;
|
|
171
|
+
--apkt-width-network-md: 48px;
|
|
172
|
+
--apkt-width-network-lg: 86px;
|
|
173
|
+
|
|
174
|
+
--apkt-duration-dynamic: 0ms;
|
|
175
|
+
--apkt-height-network-sm: 40px;
|
|
176
|
+
--apkt-height-network-md: 54px;
|
|
177
|
+
--apkt-height-network-lg: 96px;
|
|
178
|
+
}
|
|
179
|
+
`,dark:Ys`
|
|
180
|
+
:root {
|
|
181
|
+
}
|
|
182
|
+
`,light:Ys`
|
|
183
|
+
:root {
|
|
184
|
+
}
|
|
185
|
+
`}}const XN=Ys`
|
|
186
|
+
div,
|
|
187
|
+
span,
|
|
188
|
+
iframe,
|
|
189
|
+
a,
|
|
190
|
+
img,
|
|
191
|
+
form,
|
|
192
|
+
button,
|
|
193
|
+
label,
|
|
194
|
+
*::after,
|
|
195
|
+
*::before {
|
|
196
|
+
margin: 0;
|
|
197
|
+
padding: 0;
|
|
198
|
+
box-sizing: border-box;
|
|
199
|
+
font-style: normal;
|
|
200
|
+
text-rendering: optimizeSpeed;
|
|
201
|
+
-webkit-font-smoothing: antialiased;
|
|
202
|
+
-moz-osx-font-smoothing: grayscale;
|
|
203
|
+
-webkit-tap-highlight-color: transparent;
|
|
204
|
+
backface-visibility: hidden;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
:host {
|
|
208
|
+
font-family: var(--apkt-fontFamily-regular);
|
|
209
|
+
}
|
|
210
|
+
`,ZN=Ys`
|
|
211
|
+
button,
|
|
212
|
+
a {
|
|
213
|
+
cursor: pointer;
|
|
214
|
+
display: flex;
|
|
215
|
+
justify-content: center;
|
|
216
|
+
align-items: center;
|
|
217
|
+
position: relative;
|
|
218
|
+
|
|
219
|
+
will-change: background-color, color, border, box-shadow, width, height, transform, opacity;
|
|
220
|
+
outline: none;
|
|
221
|
+
border: none;
|
|
222
|
+
text-decoration: none;
|
|
223
|
+
transition:
|
|
224
|
+
background-color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
|
|
225
|
+
color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
|
|
226
|
+
border var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
|
|
227
|
+
box-shadow var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
|
|
228
|
+
width var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
|
|
229
|
+
height var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
|
|
230
|
+
transform var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
|
|
231
|
+
opacity var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
|
|
232
|
+
scale var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
|
|
233
|
+
border-radius var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2);
|
|
234
|
+
will-change:
|
|
235
|
+
background-color, color, border, box-shadow, width, height, transform, opacity, scale,
|
|
236
|
+
border-radius;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
a:active:not([disabled]),
|
|
240
|
+
button:active:not([disabled]) {
|
|
241
|
+
scale: 0.975;
|
|
242
|
+
transform-origin: center;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
button:disabled {
|
|
246
|
+
cursor: default;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
input {
|
|
250
|
+
border: none;
|
|
251
|
+
outline: none;
|
|
252
|
+
appearance: none;
|
|
253
|
+
}
|
|
254
|
+
`,Ji={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};class WI extends sm{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new nm({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit("disconnect")}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}return{connections:[]}}syncConnections(){return Promise.resolve()}async getAccounts({namespace:e}){var r,i,o,a;const s=this.provider,n=((a=(o=(i=(r=s==null?void 0:s.session)==null?void 0:r.namespaces)==null?void 0:i[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const[,,l]=c.split(":");return l}).filter((c,l,d)=>d.indexOf(c)===l))||[];return Promise.resolve({accounts:n.map(c=>z.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var o,a,c,l,d;if(!(e.caipNetwork&&be.BALANCE_SUPPORTED_CHAINS.includes((o=e.caipNetwork)==null?void 0:o.chainNamespace))||(a=e.caipNetwork)!=null&&a.testnet)return{balance:"0.00",symbol:((c=e.caipNetwork)==null?void 0:c.nativeCurrency.symbol)||""};const n=g.getAccountData();if(n!=null&&n.balanceLoading&&e.chainId===((l=g.state.activeCaipNetwork)==null?void 0:l.id))return{balance:(n==null?void 0:n.balance)||"0.00",symbol:(n==null?void 0:n.balanceSymbol)||""};const i=(await g.fetchTokenBalance()).find(u=>{var h,p;return u.chainId===`${(h=e.caipNetwork)==null?void 0:h.chainNamespace}:${e.chainId}`&&u.symbol===((p=e.caipNetwork)==null?void 0:p.nativeCurrency.symbol)});return{balance:(i==null?void 0:i.quantity.numeric)||"0.00",symbol:(i==null?void 0:i.symbol)||((d=e.caipNetwork)==null?void 0:d.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:s,message:n,address:r}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let i="";return((o=g.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===N.CHAIN.SOLANA?i=(await s.request({method:"solana_signMessage",params:{message:hr.encode(new TextEncoder().encode(n)),pubkey:r}},(a=g.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:i=await s.request({method:"personal_sign",params:[n,r]},(c=g.state.activeCaipNetwork)==null?void 0:c.caipNetworkId),{signature:i}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){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(e){var r,i,o,a,c,l;const{caipNetwork:s}=e,n=this.getWalletConnectConnector();if(s.chainNamespace===N.CHAIN.EVM)try{await((r=n.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:cl(s.id)}]}))}catch(d){if(d.code===Ji.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||d.code===Ji.ERROR_INVALID_CHAIN_ID||d.code===Ji.ERROR_CODE_DEFAULT||((o=(i=d==null?void 0:d.data)==null?void 0:i.originalError)==null?void 0:o.code)===Ji.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=n.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:cl(s.id),rpcUrls:[(a=s==null?void 0:s.rpcUrls.chainDefault)==null?void 0:a.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[(c=s.blockExplorers)==null?void 0:c.default.url]}]}))}catch{throw new Error("Chain is not supported")}}n.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(n=>n.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}const HI=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication"],Xi={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(s=>s!=="email"):!1},processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?be.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?be.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?be.DEFAULT_REMOTE_FEATURES.onramp:!1:t},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.activity:!!t},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?be.DEFAULT_REMOTE_FEATURES.reownBranding:!!t},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>t.isEnabled&&(t.config??[]),processFallback:t=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>be.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>be.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>be.DEFAULT_REMOTE_FEATURES.payments},reownAuthentication:{apiFeatureName:"reown_authentication",localFeatureName:"reownAuthentication",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>typeof t>"u"?be.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!t}},KI={localSettingsOverridden:new Set,getApiConfig(t,e){return e==null?void 0:e.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=Xi[e],n=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(n)}},processFeature(t,e,s,n,r){const i=Xi[t],o=e[i.localFeatureName];if(r&&!i.isAvailableOnBasic)return!1;if(n){const a=this.getApiConfig(i.apiFeatureName,s);return(a==null?void 0:a.config)===null?this.processFallbackFeature(t,o):a!=null&&a.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return Xi[t].processApi(e)},processFallbackFeature(t,e){return Xi[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let n=null,r=!1;try{n=await J.fetchProjectConfig(),r=n!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const i=r&&!e?be.DEFAULT_REMOTE_FEATURES:be.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of HI){const a=this.processFeature(o,s,n,r,e);Object.assign(i,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),be.DEFAULT_REMOTE_FEATURES}if(r&&this.localSettingsOverridden.size>0){const o=`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.`;It.open({debugMessage:Lt.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(o)},"warning")}return i}};class VI{constructor(e){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,n)=>{var r,i,o;if(s){const a=(r=g.getCaipNetworks(s))==null?void 0:r.find(d=>d.id===n);if(a)return a;const c=(i=g.getNetworkData(s))==null?void 0:i.caipNetwork;return c||((o=g.getRequestedCaipNetworks(s).filter(d=>d.chainNamespace===s))==null?void 0:o[0])}return g.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>g.getCaipNetworks(s),this.getActiveChainNamespace=()=>g.state.activeChain,this.setRequestedCaipNetworks=(s,n)=>{g.setRequestedCaipNetworks(s,n)},this.getApprovedCaipNetworkIds=()=>g.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>{var n,r;return g.state.activeChain===s||!s?g.state.activeCaipAddress:(r=(n=g.state.chains.get(s))==null?void 0:n.accountState)==null?void 0:r.caipAddress},this.setClientId=s=>{te.setClientId(s)},this.getProvider=s=>$e.getProvider(s),this.getProviderType=s=>$e.getProviderId(s),this.getPreferredAccountType=s=>Kt(s),this.setCaipAddress=(s,n,r=!1)=>{g.setAccountProp("caipAddress",s,n,r),g.setAccountProp("address",z.getPlainAddress(s),n,r)},this.setBalance=(s,n,r)=>{g.setAccountProp("balance",s,r),g.setAccountProp("balanceSymbol",n,r)},this.setProfileName=(s,n)=>{g.setAccountProp("profileName",s,n)},this.setProfileImage=(s,n)=>{g.setAccountProp("profileImage",s,n)},this.setUser=(s,n)=>{g.setAccountProp("user",s,n)},this.resetAccount=s=>{g.resetAccount(s)},this.setCaipNetwork=s=>{g.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,n)=>{g.setChainNetworkData(n,{caipNetwork:s})},this.setStatus=(s,n)=>{g.setAccountProp("status",s,n),D.isConnected()?R.setConnectionStatus("connected"):R.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>{var n;return(n=g.getAccountData(s))==null?void 0:n.address},this.setConnectors=s=>{const n=[...D.state.allConnectors,...s];D.setConnectors(n)},this.setConnections=(s,n)=>{R.setConnections(s,n),B.setConnections(s,n)},this.fetchIdentity=s=>te.fetchIdentity(s),this.getReownName=s=>Dr.getNamesForAddress(s),this.getConnectors=()=>D.getConnectors(),this.getConnectorImage=s=>Gu.getConnectorImage(s),this.getConnections=s=>this.remoteFeatures.multiWallet?fo.getConnectionsData(s).connections:(It.open(N.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=s=>this.remoteFeatures.multiWallet?fo.getConnectionsData(s).recentConnections:(It.open(N.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async s=>{if(!this.remoteFeatures.multiWallet){It.open(N.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await B.switchConnection(s)},this.deleteConnection=s=>{if(!this.remoteFeatures.multiWallet){It.open(N.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}R.deleteAddressFromConnection(s),B.syncStorageConnections()},this.setConnectedWalletInfo=(s,n)=>{const r=$e.getProviderId(n),i=s?{...s,type:r}:void 0;g.setAccountProp("connectedWalletInfo",i,n)},this.getIsConnectedState=()=>!!g.state.activeCaipAddress,this.addAddressLabel=(s,n,r)=>{var o;const i=((o=g.getAccountData(r))==null?void 0:o.addressLabels)||{};g.setAccountProp("addressLabels",{...i,[s]:n},r)},this.removeAddressLabel=(s,n)=>{var i;const r=((i=g.getAccountData(n))==null?void 0:i.addressLabels)||{};g.setAccountProp("addressLabels",{...r,[s]:void 0},n)},this.getAddress=s=>{var r;const n=s||g.state.activeChain;return(r=g.getAccountData(n))==null?void 0:r.address},this.resetNetwork=s=>{g.resetNetwork(s)},this.addConnector=s=>{D.addConnector(s)},this.resetWcConnection=()=>{B.resetWcConnection()},this.setAddressExplorerUrl=(s,n)=>{g.setAccountProp("addressExplorerUrl",s,n)},this.setSmartAccountDeployed=(s,n)=>{g.setAccountProp("smartAccountDeployed",s,n)},this.setPreferredAccountType=(s,n)=>{g.setAccountProp("preferredAccountType",s,n)},this.setEIP6963Enabled=s=>{I.setEIP6963Enabled(s)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,s){const n=e==null?void 0:e.map(i=>i.namespace).filter(i=>!!i);if(n!=null&&n.length)return[...new Set(n)];const r=s==null?void 0:s.map(i=>i.chainNamespace);return[...new Set(r)]}async initialize(e){var s,n,r,i,o;if(this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),I.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),this.remoteFeatures=await KI.fetchRemoteFeatures(e),await J.fetchUsage(),I.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&qa.setOnrampProviders(this.remoteFeatures.onramp),((s=I.state.remoteFeatures)!=null&&s.email||Array.isArray((n=I.state.remoteFeatures)==null?void 0:n.socials)&&((r=I.state.remoteFeatures)==null?void 0:r.socials.length)>0)&&await this.checkAllowedOrigins(),(i=I.state.features)!=null&&i.reownAuthentication||(o=I.state.remoteFeatures)!=null&&o.reownAuthentication){const{ReownAuthentication:a}=await lo(()=>import("./features-21cad012.js"),["assets/features-21cad012.js","assets/index-fec77d48.js","assets/index-91d98a83.css","assets/index-516a1ffc.js"]),c=I.state.siwx;c instanceof a||(c&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),I.setSIWX(new a))}}async openSend(e){var i;const s=e.namespace||g.state.activeChain,n=this.getCaipAddress(s),r=(i=this.getCaipNetwork(s))==null?void 0:i.id;if(!n)throw new Error("openSend: caipAddress not found");if((r==null?void 0:r.toString())!==e.chainId.toString()){const o=g.getCaipNetworkById(e.chainId,s);if(!o)throw new Error(`openSend: caipNetwork with chainId ${e.chainId} not found`);await this.switchNetwork(o,{throwOnFailure:!0})}try{const o=Fp.getTokenSymbolByAddress(e.assetAddress);o&&await J.fetchTokenImages([o])}catch{}return await he.open({view:"WalletSend",data:{send:e}}),new Promise((o,a)=>{const c=ae.subscribeKey("hash",u=>{u&&(d(),o({hash:u}))}),l=he.subscribe(u=>{u.open||(d(),a(new Error("Modal closed")))}),d=this.createCleanupHandler([c,l])})}toModalOptions(){function e(n){return(n==null?void 0:n.view)==="Swap"}function s(n){return(n==null?void 0:n.view)==="WalletSend"}return{isSwap:e,isSend:s}}async checkAllowedOrigins(){try{const e=await J.fetchAllowedOrigins();if(!z.isClient())return;const s=window.location.origin;Qs.isOriginAllowed(s,e,N.DEFAULT_ALLOWED_ANCESTORS)||It.open(Lt.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error))return;switch(e.message){case"RATE_LIMITED":It.open(Lt.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const s=e.cause instanceof Error?e.cause:e;It.open({displayMessage:Lt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:Lt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(s.message)},"error");break}}}}createCleanupHandler(e){return()=>{e.forEach(s=>{try{s()}catch{}})}}sendInitializeEvent(e){var n;const{...s}=e;delete s.adapters,delete s.universalProvider,ce.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(r=>r.id),siweConfig:{options:((n=e.siweConfig)==null?void 0:n.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initAdapterController(){Xu.initialize(this.chainAdapters)}initializeThemeController(e){e.themeMode&&St.setThemeMode(e.themeMode),e.themeVariables&&St.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");g.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});const s=this.getDefaultNetwork();s&&g.setActiveCaipNetwork(s)}initializeConnectionController(e){B.initialize(e.adapters??[]),B.setWcBasic(e.basic??!1)}initializeConnectorController(){D.initialize(this.chainNamespaces)}initializeProjectSettings(e){I.setProjectId(e.projectId),I.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var r;I.setDebug(e.debug!==!1),I.setEnableWalletGuide(e.enableWalletGuide!==!1),I.setEnableWallets(e.enableWallets!==!1),I.setEIP6963Enabled(e.enableEIP6963!==!1),I.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),I.setEnableReconnect(e.enableReconnect!==!1),I.setEnableMobileFullScreen(e.enableMobileFullScreen===!0),I.setCoinbasePreference(e.coinbasePreference),I.setEnableAuthLogger(e.enableAuthLogger!==!1),I.setCustomRpcUrls(e.customRpcUrls),I.setEnableEmbedded(e.enableEmbedded),I.setAllWallets(e.allWallets),I.setIncludeWalletIds(e.includeWalletIds),I.setExcludeWalletIds(e.excludeWalletIds),I.setFeaturedWalletIds(e.featuredWalletIds),I.setTokens(e.tokens),I.setTermsConditionsUrl(e.termsConditionsUrl),I.setPrivacyPolicyUrl(e.privacyPolicyUrl),I.setCustomWallets(e.customWallets),I.setFeatures(e.features),I.setAllowUnsupportedChain(e.allowUnsupportedChain),I.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),I.setPreferUniversalLinks(e.experimental_preferUniversalLinks),I.setDefaultAccountTypes(e.defaultAccountTypes);const s=this.getDefaultMetaData();if(!e.metadata&&s&&(e.metadata=s),I.setMetadata(e.metadata),I.setDisableAppend(e.disableAppend),I.setEnableEmbedded(e.enableEmbedded),I.setSIWX(e.siwx),this.features=I.state.features??{},!e.projectId){It.open(Lt.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(i=>i.namespace===N.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");I.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,s,n,r;return z.isClient()?{name:((s=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:s.textContent)||"",description:((n=document.querySelector('meta[property="og:description"]'))==null?void 0:n.content)||"",url:window.location.origin,icons:[((r=document.querySelector('link[rel~="icon"]'))==null?void 0:r.href)||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const n=Vn.getUnsupportedNetwork(`${s}:${e}`);g.setActiveCaipNetwork(n)}}getDefaultNetwork(){return Vn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,s){return Vn.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return Vn.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(r=>{var i;return r.id===((i=e.defaultNetwork)==null?void 0:i.id)});return s?Vn.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectConnector(e,s){var n,r;try{this.setLoading(!0,e);let i={connections:[]};const o=this.getAdapter(e);return(((r=(n=g.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.caipAddress)||!I.state.enableReconnect)&&(o!=null&&o.disconnect)&&(i=await o.disconnect({id:s})),this.setLoading(!1,e),i}catch(i){throw this.setLoading(!1,e),new Error(`Failed to disconnect chains: ${i.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var l;const e=g.state.activeChain,s=this.getAdapter(e),n=(l=this.getCaipNetwork(e))==null?void 0:l.id,r=B.getConnections(e),i=this.remoteFeatures.multiWallet,o=r.length>0;if(!s)throw new Error("Adapter not found");const a=await s.connectWalletConnect(n);(!o||!i)&&this.close(),this.setClientId((a==null?void 0:a.clientId)||null),R.setConnectedNamespaces([...g.state.chains.keys()]),await this.syncWalletConnectAccount(),await ts.initializeIfEnabled()},connectExternal:async e=>{const s=await this.onConnectExternal(e);return await this.connectInactiveNamespaces(e,s),s?{address:s.address}:void 0},reconnectExternal:async({id:e,info:s,type:n,provider:r})=>{var a;const i=g.state.activeChain,o=this.getAdapter(i);if(!i)throw new Error("reconnectExternal: namespace not found");if(!o)throw new Error("reconnectExternal: adapter not found");o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:s,type:n,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),R.addConnectedNamespace(i),this.syncConnectedWalletInfo(i))},disconnectConnector:async e=>{await this.disconnectConnector(e.namespace,e.id)},disconnect:async e=>{var l;const{id:s,chainNamespace:n,initialDisconnect:r}=e||{},i=n||g.state.activeChain,o=D.getConnectorId(i),a=s===N.CONNECTOR_ID.AUTH||o===N.CONNECTOR_ID.AUTH,c=s===N.CONNECTOR_ID.WALLET_CONNECT||o===N.CONNECTOR_ID.WALLET_CONNECT;try{const d=Array.from(g.state.chains.keys());let u=n?[n]:d;(c||a)&&(u=d);const h=u.map(async m=>{const y=D.getConnectorId(m),w=s||y,b=await this.disconnectConnector(m,w);b&&(a&&R.deleteConnectedSocialProvider(),b.connections.forEach(A=>{R.addDisconnectedConnectorId(A.connectorId,m)})),r&&this.onDisconnectNamespace({chainNamespace:m,closeModal:!1})}),p=await Promise.allSettled(h);ae.resetSend(),B.resetWcConnection(),(l=ts.getSIWX())!=null&&l.signOutOnDisconnect&&await ts.clearSessions(),D.setFilterByNamespace(void 0),B.syncStorageConnections();const f=p.filter(m=>m.status==="rejected");if(f.length>0)throw new Error(f.map(m=>m.reason.message).join(", "));ce.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:n||"all"}})}catch(d){throw new Error(`Failed to disconnect chains: ${d.message}`)}},checkInstalled:e=>e?e.some(s=>{var n;return!!((n=window.ethereum)!=null&&n[String(s)])}):!!window.ethereum,signMessage:async e=>{const s=g.state.activeChain,n=this.getAdapter(g.state.activeChain);if(!s)throw new Error("signMessage: namespace not found");if(!n)throw new Error("signMessage: adapter not found");const r=this.getAddress(s);if(!r)throw new Error("signMessage: address not found");const i=await(n==null?void 0:n.signMessage({message:e,address:r,provider:$e.getProvider(s)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{const s=e.chainNamespace;if(!s)throw new Error("sendTransaction: namespace not found");if(be.SEND_SUPPORTED_NAMESPACES.includes(s)){const n=this.getAdapter(s);if(!n)throw new Error("sendTransaction: adapter not found");const r=$e.getProvider(s),i=await(n==null?void 0:n.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:r}));return(i==null?void 0:i.hash)||""}return""},estimateGas:async e=>{const s=e.chainNamespace;if(s===N.CHAIN.EVM){const n=this.getAdapter(s);if(!n)throw new Error("estimateGas: adapter is required but got undefined");const r=$e.getProvider(s),i=this.getCaipNetwork();if(!i)throw new Error("estimateGas: caipNetwork is required but got undefined");const o=await(n==null?void 0:n.estimateGas({...e,provider:r,caipNetwork:i}));return(o==null?void 0:o.gas)||0n}return 0n},getEnsAvatar:async()=>{var r;const e=g.state.activeChain;if(!e)throw new Error("getEnsAvatar: namespace is required but got undefined");const s=this.getAddress(e);if(!s)throw new Error("getEnsAvatar: address not found");await this.syncIdentity({address:s,chainId:Number((r=this.getCaipNetwork())==null?void 0:r.id),chainNamespace:e});const n=g.getAccountData();return(n==null?void 0:n.profileImage)||!1},getEnsAddress:async e=>await Qs.resolveReownName(e),writeContract:async e=>{const s=g.state.activeChain,n=this.getAdapter(s);if(!s)throw new Error("writeContract: namespace is required but got undefined");if(!n)throw new Error("writeContract: adapter is required but got undefined");const r=this.getCaipNetwork(),i=this.getCaipAddress(),o=$e.getProvider(s);if(!r||!i)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");const a=await(n==null?void 0:n.writeContract({...e,caipNetwork:r,provider:o,caipAddress:i}));return a==null?void 0:a.hash},parseUnits:(e,s)=>{const n=this.getAdapter(g.state.activeChain);if(!n)throw new Error("parseUnits: adapter is required but got undefined");return(n==null?void 0:n.parseUnits({value:e,decimals:s}))??0n},formatUnits:(e,s)=>{const n=this.getAdapter(g.state.activeChain);if(!n)throw new Error("formatUnits: adapter is required but got undefined");return(n==null?void 0:n.formatUnits({value:e,decimals:s}))??"0"},getCapabilities:async e=>{const s=this.getAdapter(g.state.activeChain);if(!s)throw new Error("getCapabilities: adapter is required but got undefined");return await(s==null?void 0:s.getCapabilities(e))},grantPermissions:async e=>{const s=this.getAdapter(g.state.activeChain);if(!s)throw new Error("grantPermissions: adapter is required but got undefined");return await(s==null?void 0:s.grantPermissions(e))},revokePermissions:async e=>{const s=this.getAdapter(g.state.activeChain);if(!s)throw new Error("revokePermissions: adapter is required but got undefined");return s!=null&&s.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(g.state.activeChain);if(!s)throw new Error("walletGetAssets: adapter is required but got undefined");return await(s==null?void 0:s.walletGetAssets(e))??{}},updateBalance:e=>{const s=this.getAddress(e),n=this.getCaipNetwork(e);!n||!s||this.updateNativeBalance(s,n==null?void 0:n.id,e)}},B.setClient(this.connectionControllerClient)}async onConnectExternal(e){var l,d,u,h,p,f,m,y;const s=g.state.activeChain,n=e.chain||s,r=this.getAdapter(n);let i=!0;if(e.type===Me.CONNECTOR_TYPE_AUTH&&N.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(A=>D.getConnectorId(A)===N.CONNECTOR_ID.AUTH)&&e.chain!==s&&(i=!1),e.chain&&e.chain!==s&&!e.caipNetwork){const w=this.getCaipNetworks().find(b=>b.chainNamespace===e.chain);w&&i&&this.setCaipNetwork(w)}if(!n)throw new Error("connectExternal: namespace not found");if(!r)throw new Error("connectExternal: adapter not found");const o=this.getCaipNetwork(n),a=e.caipNetwork||o,c=await r.connect({id:e.id,address:e.address,info:e.info,type:e.type,provider:e.provider,socialUri:e.socialUri,chainId:((l=e.caipNetwork)==null?void 0:l.id)||(o==null?void 0:o.id),rpcUrl:((p=(h=(u=(d=e.caipNetwork)==null?void 0:d.rpcUrls)==null?void 0:u.default)==null?void 0:h.http)==null?void 0:p[0])||((y=(m=(f=o==null?void 0:o.rpcUrls)==null?void 0:f.default)==null?void 0:m.http)==null?void 0:y[0])});if(c)return R.addConnectedNamespace(n),this.syncProvider({...c,chainNamespace:n}),this.setStatus("connected",n),this.syncConnectedWalletInfo(n),R.removeDisconnectedConnectorId(e.id,n),{address:c.address,connectedCaipNetwork:a}}async connectInactiveNamespaces(e,s){var a;const n=e.type===Me.CONNECTOR_TYPE_AUTH,r=gi.getOtherAuthNamespaces((a=s==null?void 0:s.connectedCaipNetwork)==null?void 0:a.chainNamespace),i=g.state.activeCaipNetwork,o=this.getAdapter(i==null?void 0:i.chainNamespace);n&&(await Promise.all(r.map(async c=>{var l,d,u;try{const h=$e.getProvider(c),p=this.getCaipNetwork(c),f=this.getAdapter(c);await(f==null?void 0:f.connect({...e,provider:h,socialUri:void 0,chainId:p==null?void 0:p.id,rpcUrl:(u=(d=(l=p==null?void 0:p.rpcUrls)==null?void 0:l.default)==null?void 0:d.http)==null?void 0:u[0]}))&&(R.addConnectedNamespace(c),R.removeDisconnectedConnectorId(e.id,c),this.setStatus("connected",c),this.syncConnectedWalletInfo(c))}catch(h){It.warn(Lt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,Lt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(c,h instanceof Error?h.message:void 0),Lt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),i&&await(o==null?void 0:o.switchNetwork({caipNetwork:i})))}getApprovedCaipNetworksData(){var s,n,r,i,o;if($e.getProviderId(g.state.activeChain)===Me.CONNECTOR_TYPE_WALLET_CONNECT){const a=(n=(s=this.universalProvider)==null?void 0:s.session)==null?void 0:n.namespaces;return{supportsAllNetworks:((o=(i=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:i.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=$e.getProviderId(s);if(e.chainNamespace===g.state.activeChain){const i=this.getAdapter(s);await(i==null?void 0:i.switchNetwork({caipNetwork:e}))}else if(this.setCaipNetwork(e),r===Me.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const i=this.getAddressByChainNamespace(s);i&&this.syncAccount({address:i,chainId:e.id,chainNamespace:s})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(s=>{const n=s.chains||[],r=s.accounts.map(i=>{const{chainId:o,chainNamespace:a}=Qe.parseCaipAddress(i);return`${a}:${o}`});return Array.from(new Set([...n,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,n)=>{var i,o;const r=e==null?void 0:e.find(a=>a.namespace===n);return r?(r.construct({namespace:n,projectId:(i=this.options)==null?void 0:i.projectId,networks:(o=this.caipNetworks)==null?void 0:o.filter(({chainNamespace:a})=>a===n)}),s[n]=r):s[n]=new WI({namespace:n,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e);const s=this.getAdapter(e);if(!s)throw new Error("adapter not found");await s.syncConnectors(),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)})),this.initAdapterController()}onConnectors(e){const s=this.getAdapter(e);s==null||s.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const n=R.getConnectionStatus();I.state.enableReconnect===!1?this.setStatus("disconnected",e):n==="connected"?this.setStatus("connecting",e):n==="disconnected"?(R.clearAddressCache(),this.setStatus(n,e)):this.setStatus(n,e),s.on("switchNetwork",({address:r,chainId:i})=>{var l,d;const o=this.getCaipNetworks().find(u=>u.id.toString()===i.toString()||u.caipNetworkId.toString()===i.toString()),a=g.state.activeChain===e,c=(d=(l=g.state.chains.get(e))==null?void 0:l.accountState)==null?void 0:d.address;if(o){const u=a&&r?r:c;u&&this.syncAccount({address:u,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(i)}),s.on("disconnect",()=>{const r=this.remoteFeatures.multiWallet,i=Array.from(B.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:e,closeModal:!r||i.length===0})}),s.on("connections",r=>{this.setConnections(r,e)}),s.on("pendingTransactions",()=>{const r=this.getAddress(e),i=g.state.activeCaipNetwork;!r||!(i!=null&&i.id)||this.updateNativeBalance(r,i.id,i.chainNamespace)}),s.on("accountChanged",({address:r,chainId:i,connector:o})=>{var d,u;this.handlePreviousConnectorConnection(o);const a=g.state.activeChain===e;o!=null&&o.provider&&(this.syncProvider({id:o.id,type:o.type,provider:o==null?void 0:o.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e));const c=(u=(d=g.getNetworkData(e))==null?void 0:d.caipNetwork)==null?void 0:u.id,l=i||c;a&&l?this.syncAccount({address:r,chainId:l,chainNamespace:e}):!a&&l?(this.syncAccountInfo(r,l,e),this.syncBalance({address:r,chainId:l,chainNamespace:e})):this.syncAccountInfo(r,i,e),R.addConnectedNamespace(e)})}async handlePreviousConnectorConnection(e){var c;const s=e==null?void 0:e.chain,n=e==null?void 0:e.id,r=D.getConnectorId(s),i=(c=I.state.remoteFeatures)==null?void 0:c.multiWallet,a=s&&n&&r&&r!==n&&!i;try{a&&await B.disconnect({id:r,namespace:s})}catch(l){console.warn("Error disconnecting previous connector",l)}}async createUniversalProviderForAdapter(e){var s,n,r;await this.getUniversalProvider(),this.universalProvider&&await((r=(n=(s=this.chainAdapters)==null?void 0:s[e])==null?void 0:n.setUniversalProvider)==null?void 0:r.call(n,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(e=>B.disconnect({namespace:e,initialDisconnect:!0})))}catch(e){console.error("Error disconnecting existing connections:",e)}}async reconnectWalletConnect(){await this.syncWalletConnectAccount();const e=this.getAddress();this.getCaipAddress()||R.deleteRecentWallet();const s=R.getRecentWallet();ce.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:z.isMobile()?"mobile":"qrcode",name:(s==null?void 0:s.name)||"Unknown",reconnect:!0,view:ee.state.view,walletRank:s==null?void 0:s.order}})}async syncNamespaceConnection(e){try{e===N.CHAIN.EVM&&z.isSafeApp()&&D.setConnectorId(N.CONNECTOR_ID.SAFE,e);const s=D.getConnectorId(e);switch(this.setStatus("connecting",e),s){case N.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case N.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}onDisconnectNamespace(e){const{chainNamespace:s,closeModal:n}=e||{};g.resetAccount(s),g.resetNetwork(s),R.removeConnectedNamespace(s);const r=Array.from(g.state.chains.keys());(s?[s]:r).forEach(o=>R.addDisconnectedConnectorId(D.getConnectorId(o)||"",o)),D.removeConnectorId(s),$e.resetChain(s),this.setUser(null,s),this.setStatus("disconnected",s),this.setConnectedWalletInfo(null,s),n!==!1&&he.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(e=>{const s=this.getAdapter(e),n=this.getCaipAddress(e),r=this.getCaipNetwork(e);return s==null?void 0:s.syncConnections({connectToFirstConnector:!n,caipNetwork:r})}))}async syncAdapterConnection(e){var a,c,l,d;const s=this.getAdapter(e),n=this.getCaipNetwork(e),r=D.getConnectorId(e),o=D.getConnectors(e).find(u=>u.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(n!=null&&n.id))throw new Error("CaipNetwork not found");const u=await(s==null?void 0:s.syncConnection({namespace:e,id:o.id,chainId:n.id,rpcUrl:(l=(c=(a=n==null?void 0:n.rpcUrls)==null?void 0:a.default)==null?void 0:c.http)==null?void 0:l[0]}));u?(this.syncProvider({...u,chainNamespace:e}),await this.syncAccount({...u,chainNamespace:e}),this.setStatus("connected",e),ce.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:u.address,properties:{method:"browser",name:((d=o.info)==null?void 0:d.name)||o.name||"Unknown",reconnect:!0,view:ee.state.view,walletRank:void 0}})):this.setStatus("disconnected",e)}catch{this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})}}async syncWalletConnectAccount(){var n,r;const e=Object.keys(((r=(n=this.universalProvider)==null?void 0:n.session)==null?void 0:r.namespaces)||{}),s=this.chainNamespaces.map(async i=>{var u,h,p,f,m;const o=this.getAdapter(i);if(!o)return;const a=((f=(p=(h=(u=this.universalProvider)==null?void 0:u.session)==null?void 0:h.namespaces)==null?void 0:p[i])==null?void 0:f.accounts)||[],c=(m=g.state.activeCaipNetwork)==null?void 0:m.id,l=a.find(y=>{const{chainId:w}=Qe.parseCaipAddress(y);return w===(c==null?void 0:c.toString())})||a[0];if(l){const y=Qe.validateCaipAddress(l),{chainId:w,address:b}=Qe.parseCaipAddress(y);if($e.setProviderId(i,Me.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&g.state.activeCaipNetwork&&o.namespace!==N.CHAIN.EVM){const A=o.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:g.state.activeCaipNetwork});$e.setProvider(i,A)}else $e.setProvider(i,this.universalProvider);D.setConnectorId(N.CONNECTOR_ID.WALLET_CONNECT,i),R.addConnectedNamespace(i),await this.syncAccount({address:b,chainId:w,chainNamespace:i})}else e.includes(i)&&this.setStatus("disconnected",i);const d=this.getApprovedCaipNetworksData();this.syncConnectedWalletInfo(i),g.setApprovedCaipNetworksData(i,{approvedCaipNetworkIds:d.approvedCaipNetworkIds,supportsAllNetworks:d.supportsAllNetworks})});await Promise.all(s)}syncProvider({type:e,provider:s,id:n,chainNamespace:r}){$e.setProviderId(r,e),$e.setProvider(r,s),D.setConnectorId(n,r)}async syncAccount(e){var u,h;const s=e.chainNamespace===g.state.activeChain,n=g.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:i,chainNamespace:o}=e,{chainId:a}=R.getActiveNetworkProps(),c=(n==null?void 0:n.id)||a,l=((u=g.state.activeCaipNetwork)==null?void 0:u.name)===N.UNSUPPORTED_NETWORK_NAME,d=g.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!d)&&c){let p=this.getCaipNetworks().find(w=>w.id.toString()===c.toString()),f=this.getCaipNetworks().find(w=>w.chainNamespace===o);if(!d&&!p&&!f){const w=this.getApprovedCaipNetworkIds()||[],b=w.find(k=>{var $;return(($=Qe.parseCaipNetworkId(k))==null?void 0:$.chainId)===c.toString()}),A=w.find(k=>{var $;return(($=Qe.parseCaipNetworkId(k))==null?void 0:$.chainNamespace)===o});p=this.getCaipNetworks().find(k=>k.caipNetworkId===b),f=this.getCaipNetworks().find(k=>k.caipNetworkId===A||"deprecatedCaipNetworkId"in k&&k.deprecatedCaipNetworkId===A)}const m=p||f;(m==null?void 0:m.chainNamespace)===g.state.activeChain?I.state.enableNetworkSwitch&&!I.state.allowUnsupportedChain&&((h=g.state.activeCaipNetwork)==null?void 0:h.name)===N.UNSUPPORTED_NETWORK_NAME?g.showUnsupportedChainUI():this.setCaipNetwork(m):s||n&&this.setCaipNetworkOfNamespace(n,o),this.syncConnectedWalletInfo(o);const y=this.getAddress(o);gi.isLowerCaseMatch(r,y)||this.syncAccountInfo(r,m==null?void 0:m.id,o),s?await this.syncBalance({address:r,chainId:m==null?void 0:m.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:n==null?void 0:n.id,chainNamespace:o}),this.syncIdentity({address:r,chainId:i,chainNamespace:o})}}async syncAccountInfo(e,s,n){const r=this.getCaipAddress(n),i=s||(r==null?void 0:r.split(":")[1]);if(!i)return;const o=`${n}:${i}:${e}`;this.setCaipAddress(o,n,!0),await this.syncIdentity({address:e,chainId:i,chainNamespace:n})}async syncReownName(e,s){try{const n=await this.getReownName(e);if(n[0]){const r=n[0];this.setProfileName(r.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){var r;const s=D.getConnectorId(e),n=$e.getProviderId(e);if(n===Me.CONNECTOR_TYPE_ANNOUNCED||n===Me.CONNECTOR_TYPE_INJECTED){if(s){const o=this.getConnectors().find(a=>{var u,h;const c=a.id===s,l=((u=a.info)==null?void 0:u.rdns)===s,d=(h=a.connectors)==null?void 0:h.some(p=>{var f;return p.id===s||((f=p.info)==null?void 0:f.rdns)===s});return c||l||!!d});if(o){const{info:a,name:c,imageUrl:l}=o,d=l||this.getConnectorImage(o);this.setConnectedWalletInfo({name:c,icon:d,...a},e)}}}else if(n===Me.CONNECTOR_TYPE_WALLET_CONNECT){const i=$e.getProvider(e);i!=null&&i.session&&this.setConnectedWalletInfo({...i.session.peer.metadata,name:i.session.peer.metadata.name,icon:(r=i.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(s&&(s===N.CONNECTOR_ID.COINBASE_SDK||s===N.CONNECTOR_ID.COINBASE)){const i=this.getConnectors().find(l=>l.id===s),o=(i==null?void 0:i.name)||"Coinbase Wallet",a=(i==null?void 0:i.imageUrl)||this.getConnectorImage(i),c=i==null?void 0:i.info;this.setConnectedWalletInfo({...c,name:o,icon:a},e)}}async syncBalance(e){!Ru.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(n=>{var r;return n.id.toString()===((r=e.chainId)==null?void 0:r.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,n){const r=this.getAdapter(n),i=g.getCaipNetworkByNamespace(n,s);if(r){const o=await r.getBalance({address:e,chainId:s,caipNetwork:i,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,n),o}}async initializeUniversalAdapter(){var n,r,i,o,a,c,l,d,u,h;const e=hI.createLogger((p,...f)=>{p&&this.handleAlertError(p),console.error(...f)}),s={projectId:(n=this.options)==null?void 0:n.projectId,metadata:{name:(r=this.options)!=null&&r.metadata?(i=this.options)==null?void 0:i.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(c=this.options)!=null&&c.metadata?(l=this.options)==null?void 0:l.metadata.url:"",icons:(d=this.options)!=null&&d.metadata?(u=this.options)==null?void 0:u.metadata.icons:[""]},logger:e};I.setManualWCControl(!!((h=this.options)!=null&&h.manualWCControl)),this.universalProvider=this.options.universalProvider??await lI.init(s),I.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(e=>{Qs.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:s=>{B.setUri(s)},onConnect:s=>{const{address:n}=z.getAccount(s[0]);B.finalizeWcConnection(n)},onDisconnect:()=>{g.state.noAdapters&&this.resetAccount(e),B.resetWcConnection()},onChainChanged:s=>{const n=g.state.activeChain,r=n&&D.state.activeConnectorIds[n]===N.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(g.state.noAdapters||r)){const i=this.getCaipNetworks().find(a=>a.id.toString()===s.toString()||a.caipNetworkId.toString()===s.toString()),o=this.getCaipNetwork();if(!i){this.setUnsupportedNetwork(s);return}(o==null?void 0:o.id.toString())!==(i==null?void 0:i.id.toString())&&(o==null?void 0:o.chainNamespace)===(i==null?void 0:i.chainNamespace)&&this.setCaipNetwork(i)}},onAccountsChanged:s=>{const n=g.state.activeChain,r=n&&D.state.activeConnectorIds[n]===N.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(g.state.noAdapters||r)){const i=s==null?void 0:s[0];i&&this.syncAccount({address:i.address,chainId:i.chainId,chainNamespace:i.chainNamespace})}}})})}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&z.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){ce.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}getDisabledCaipNetworks(){const e=g.getAllApprovedCaipNetworkIds(),s=g.getAllRequestedCaipNetworks();return z.sortRequestedNetworks(e,s).filter(r=>g.isCaipNetworkDisabled(r))}handleAlertError(e){const s=Object.entries(Lt.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[n,r]=s??[],{message:i,alertErrorKey:o}=r??{};if(n&&i&&!this.reportedAlertErrors[n]){const a=Lt.ALERT_ERRORS[o];a&&(It.open(a,"error"),this.reportedAlertErrors[n]=!0)}}getAdapter(e){var s;if(e)return(s=this.chainAdapters)==null?void 0:s[e]}createAdapter(e){var r,i;if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const n=e;n.namespace=s,n.construct({namespace:s,projectId:(r=this.options)==null?void 0:r.projectId,networks:(i=this.caipNetworks)==null?void 0:i.filter(({chainNamespace:o})=>o===s)}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=n)}async open(e){await this.injectModalUi(),e!=null&&e.uri&&B.setUri(e.uri);const{isSwap:s,isSend:n}=this.toModalOptions();return s(e)?he.open({...e,data:{swap:e.arguments}}):n(e)&&e.arguments?this.openSend(e.arguments):he.open(e)}async close(){await this.injectModalUi(),he.close()}setLoading(e,s){he.setLoading(e,s)}async disconnect(e){await B.disconnect({namespace:e})}getSIWX(){return I.state.siwx}getError(){return""}getChainId(){var e;return(e=g.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e,{throwOnFailure:s=!1}={}){const n=this.getCaipNetworks().find(r=>r.id===e.id);if(!n){It.open(Lt.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await g.switchActiveNetwork(n,{throwOnFailure:s})}getWalletProvider(){return g.state.activeChain?$e.state.providers[g.state.activeChain]:null}getWalletProviderType(){return $e.getProviderId(g.state.activeChain)}subscribeProviders(e){return $e.subscribeProviders(e)}getThemeMode(){return St.state.themeMode}getThemeVariables(){return St.state.themeVariables}setThemeMode(e){St.setThemeMode(e),vc(St.state.themeMode)}setTermsConditionsUrl(e){I.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){I.setPrivacyPolicyUrl(e)}setThemeVariables(e){St.setThemeVariables(e),qI(St.state.themeVariables)}subscribeTheme(e){return St.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?B.subscribe(e):(It.open(N.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){var n,r;if(e)return(r=(n=g.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.connectedWalletInfo;const s=g.getAccountData();return s==null?void 0:s.connectedWalletInfo}getAccount(e){const s=e||g.state.activeChain,n=D.getAuthConnector(s),r=g.getAccountData(s),i=R.getConnectedConnectorId(g.state.activeChain),o=B.getConnections(s);if(!s)throw new Error("AppKit:getAccount - namespace is required");const a=o.flatMap(c=>c.accounts.map(({address:l,type:d,publicKey:u})=>z.createAccount(s,l,d||"eoa",u)));if(r)return{allAccounts:a,caipAddress:r.caipAddress,address:z.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:n&&i===N.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:R.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:Kt(s),isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const n=()=>{const r=this.getAccount(s);r&&e(r)};s?g.subscribeChainProp("accountState",n,s):g.subscribe(n),D.subscribe(n)}subscribeNetwork(e){return g.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s==null?void 0:s.id,caipNetworkId:s==null?void 0:s.caipNetworkId})})}subscribeWalletInfo(e,s){return s?g.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo),s):g.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo))}subscribeShouldUpdateToAddress(e){g.subscribeChainProp("accountState",s=>e(s==null?void 0:s.shouldUpdateToAddress))}subscribeCaipNetworkChange(e){g.subscribeKey("activeCaipNetwork",e)}getState(){return Ss.state}getRemoteFeatures(){return I.state.remoteFeatures}subscribeState(e){return Ss.subscribe(e)}subscribeRemoteFeatures(e){return I.subscribeKey("remoteFeatures",e)}showErrorMessage(e){us.showError(e)}showSuccessMessage(e){us.showSuccess(e)}getEvent(){return{...ce.state}}subscribeEvents(e){return ce.subscribe(e)}replace(e){ee.replace(e)}redirect(e){ee.push(e)}popTransactionStack(e){ee.popTransactionStack(e)}isOpen(){return he.state.open}isTransactionStackEmpty(){return ee.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){I.setFeatures(e)}updateRemoteFeatures(e){I.setRemoteFeatures(e)}updateOptions(e){const n={...I.state||{},...e};I.setOptions(n)}setConnectMethodsOrder(e){I.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){I.setWalletFeaturesOrder(e)}setCollapseWallets(e){I.setCollapseWallets(e)}setSocialsOrder(e){I.setSocialsOrder(e)}getConnectMethodsOrder(){return kr.getConnectOrderMethod(I.state.features,D.getConnectors())}addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const n=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(r=>r.id===n.id)||g.addNetwork(n)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(r=>r.id===s)&&g.removeNetwork(e,s)}}let _u=!1;class zp extends VI{async open(e){D.isConnected()||await super.open(e)}async close(){var e;if(await super.close(),this.options.manualWCControl){const s=(e=g.getAccountData(this.activeChainNamespace))==null?void 0:e.address;B.finalizeWcConnection(s)}}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!_u&&z.isClient()){if(await lo(()=>import("./basic-eeeaaaeb.js"),["assets/basic-eeeaaaeb.js","assets/index-388893ce.js","assets/index-fec77d48.js","assets/index-91d98a83.css","assets/index-516a1ffc.js"]),await lo(()=>import("./w3m-modal-4a2f6c0b.js"),["assets/w3m-modal-4a2f6c0b.js","assets/index-388893ce.js","assets/index-fec77d48.js","assets/index-91d98a83.css","assets/index-516a1ffc.js"]),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!I.state.disableAppend&&!I.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}_u=!0}}}const zI="1.8.11";function GI(t){return new zp({...t,basic:!0,sdkVersion:`html-core-${zI}`})}const QN=Object.freeze(Object.defineProperty({__proto__:null,AppKit:zp,createAppKit:GI},Symbol.toStringTag,{value:"Module"}));export{_e as $,J as A,te as B,D as C,kc as D,ce as E,It as F,Kt as G,gi as H,Wt as I,ts as J,jI as K,fI as L,he as M,ff as N,I as O,JN as P,Ec as Q,ee as R,us as S,St as T,jp as U,lr as V,kr as W,Ru as X,Z as Y,Mi as Z,Y as _,z as a,wN as a$,al as a0,Uu as a1,iN as a2,cl as a3,Gf as a4,Yf as a5,eN as a6,ju as a7,$f as a8,Wf as a9,ag as aA,cg as aB,uN as aC,tN as aD,dg as aE,hN as aF,Ku as aG,ii as aH,ui as aI,lg as aJ,ug as aK,hg as aL,pN as aM,yN as aN,fN as aO,mN as aP,gN as aQ,fr as aR,Ei as aS,$r as aT,nN as aU,ul as aV,mg as aW,dl as aX,dN as aY,lN as aZ,Jf as a_,Df as aa,qu as ab,Bu as ac,rn as ad,Fu as ae,Qi as af,sN as ag,Bf as ah,ko as ai,Zs as aj,Rc as ak,oN as al,po as am,cN as an,rr as ao,Jr as ap,Wu as aq,Pc as ar,Qf as as,eg as at,tg as au,sg as av,ng as aw,rg as ax,ig as ay,og as az,B as b,bN as b0,Ff as b1,Vu as b2,Cg as b3,hl as b4,bg as b5,Di as b6,ki as b7,EN as b8,vN as b9,ci as bA,Zf as bB,oi as bC,ti as bD,Tn as bE,Uf as bF,rN as bG,jf as bH,Vf as bI,zf as bJ,QN as bK,CN as ba,AN as bb,aN as bc,QI as bd,Lu as be,Mf as bf,Lf as bg,di as bh,li as bi,ni as bj,ai as bk,Yr as bl,zr as bm,Qr as bn,or as bo,Gr as bp,Cn as bq,Vr as br,si as bs,xt as bt,Xr as bu,Zr as bv,vt as bw,ri as bx,ir as by,ei as bz,N as c,YN as d,qt as e,Ta as f,Gu as g,ZN as h,co as i,Rn as j,Ns as k,be as l,GN as m,g as n,Vn as o,R as p,Ye as q,XN as r,Ys as s,ke as t,et as u,tt as v,zt as w,zN as x,Ju as y,Vg as z};
|