PageSourceSearch

https://protocol.art/assets/core-4b5951b1.js

js protocol.art collected 2026-10-06 19:11:29 UTC 473,416 bytes, 889 lines download raw bytes

1import{iy as $i,ix as hd,d8 as _i,a7 as $n,c_ as pd,c$ as U,d0 as wi,d1 as kc,d2 as xc,d3 as gd,d4 as fd,d5 as Un,d6 as md,bh as js,d9 as wd,da as yd,db as _t,dc as bd,dd as mo,de as wo,df as Gr,dg as Si,dh as yo,di as $s,dj as Ro,dk as vd,dl as Ed,d7 as Cd,dm as $o,dn as di,dp as Rc,dq as es,dr as jt,ds as os,dt as Dt,eB as Cr,eA as Uo,o as gi,iz as Pt,aE as Do}from"./index-c2fc66f8.js";import{k as Id,h as At,i as lt,j as Ji,E as tt,y as yt,l as ur,A as $c,O as bo}from"./index.es-7ecd5e33.js";const B={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:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"}
1,CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},Uc={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(n=>n.caipNetworkId===e);if(s)return s.name;const[i]=e.split(":");return((r=B.CHAIN_NAME_MAP)==null?void 0:r[i])||void 0}},Nd={bigNumber(t){return t?new $i(t):new $i(0)},multiply(t,e){if(t===void 0||e===void 0)return new $i(0);const s=new $i(t),i=new $i(e);return s.times(i)},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(t){return t===void 0?0:parseFloat(t.replace(/,/gu,""))}},Ad=[{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"}]}],_d=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Sd=[{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"}]}],Pd={getERC20Abi:t=>B.USDT_CONTRACT_ADDRESSES.includes(t)?Sd:Ad,getSwapAbi:()=>_d},as={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,i,r]=e;if(!s||!i||!r)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:i,address:r}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,i]=e;if(!s||!i)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:i}}},ee={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",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_cac
1he",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections"};function rn(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Z={setItem(t,e){Wi()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(Wi())return localStorage.getItem(t)||void 0},removeItem(t){Wi()&&localStorage.removeItem(t)},clear(){Wi()&&localStorage.clear()}};function Wi(){return typeof window<"u"&&typeof localStorage<"u"}function fs(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":"#121313"}}const Od=Symbol(),Lo=Object.getPrototypeOf,Dn=new WeakMap,Td=t=>t&&(Dn.has(t)?Dn.get(t):Lo(t)===Object.prototype||Lo(t)===Array.prototype),kd=t=>Td(t)&&t[Od]||null,Mo=(t,e=!0)=>{Dn.set(t,e)},nn=t=>typeof t=="object"&&t!==null,hs=new WeakMap,zi=new WeakSet,xd=(t=Object.is,e=(l,d)=>new Proxy(l,d),s=l=>nn(l)&&!zi.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),i=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},r=new WeakMap,n=(l,d,u=i)=>{const h=r.get(l);if((h==null?void 0:h[0])===d)return h[1];const g=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return Mo(g,!0),r.set(l,[d,g]),Reflect.ownKeys(l).forEach(w=>{if(Object.getOwnPropertyDescriptor(g,w))return;const m=Reflect.get(l,w),{enumerable:f}=Reflect.getOwnPropertyDescriptor(l,w),y={value:m,enumerable:f,configurable:!0};if(zi.has(m))Mo(m,!1);else if(m instanceof Promise)delete y.value,y.get=()=>u(m);else if(hs.has(m)){const[b,E]=hs.get(m);y.value=n(b,E(),u)}Object.defineProperty(g,w,y)}),Object.preventExtensions(g)},o=new WeakMap,a=[1,1],c=l=>{if(!nn(l))throw new Error("object required");const d=o.get(l);if(d)return d;let u=a[0];const h=new Set,g=(v,R=++a[0])=>{u!==R&&(u=R,h.forEach(C=>C(v,R)))};let w=a[1];const m=(v=++a[1])=>(w!==v&&!h.size&&(w=v,y.forEach(([R])=>{const C=R[1](v);C>u&&(u=C)})),u),f=v=>(R,C)=>{const L=[...R];L[1]=[v,...L[1]],g(L,C)},y=new Map,b=(v,R)=>{if(h.size){const C=R[3](f(v));y.set(v,[R,C])}else y.set(v,[R])},E=v=>{var R;const C=y.get(v);C&&(y.delete(v),(R=C[1])==null||R.call(C))},_=v=>
1(h.add(v),h.size===1&&y.forEach(([C,L],H)=>{const I=C[3](f(H));y.set(H,[C,I])}),()=>{h.delete(v),h.size===0&&y.forEach(([C,L],H)=>{L&&(L(),y.set(H,[C]))})}),x=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),S=e(x,{deleteProperty(v,R){const C=Reflect.get(v,R);E(R);const L=Reflect.deleteProperty(v,R);return L&&g(["delete",[R],C]),L},set(v,R,C,L){const H=Reflect.has(v,R),I=Reflect.get(v,R,L);if(H&&(t(I,C)||o.has(C)&&t(I,o.get(C))))return!0;E(R),nn(C)&&(C=kd(C)||C);let T=C;if(C instanceof Promise)C.then(A=>{C.status="fulfilled",C.value=A,g(["resolve",[R],A])}).catch(A=>{C.status="rejected",C.reason=A,g(["reject",[R],A])});else{!hs.has(C)&&s(C)&&(T=c(C));const A=!zi.has(T)&&hs.get(T);A&&b(R,A)}return Reflect.set(v,R,T,L),g(["set",[R],C,I]),!0}});o.set(l,S);const D=[x,m,n,_];return hs.set(S,D),Reflect.ownKeys(l).forEach(v=>{const R=Object.getOwnPropertyDescriptor(l,v);"value"in R&&(S[v]=l[v],delete R.value,delete R.writable),Object.defineProperty(x,v,R)}),S})=>[c,hs,zi,t,e,s,i,r,n,o,a],[Rd]=xd();function Ae(t={}){return Rd(t)}function Xe(t,e,s){const i=hs.get(t);let r;const n=[],o=i[3];let a=!1;const l=o(d=>{if(n.push(d),s){e(n.splice(0));return}r||(r=Promise.resolve().then(()=>{r=void 0,a&&e(n.splice(0))}))});return a=!0,()=>{a=!1,l()}}function rr(t,e){const s=hs.get(t),[i,r,n]=s;return n(i,r(),e)}function Ls(t){return zi.add(t),t}function Ze(t,e,s,i){let r=t[e];return Xe(t,()=>{const n=t[e];Object.is(r,n)||s(r=n)},i)}function $d(t){const e=Ae({data:Array.from(t||[]),has(s){return this.data.some(i=>i[0]===s)},set(s,i){const r=this.data.find(n=>n[0]===s);return r?r[1]=i:this.data.push([s,i]),this},get(s){var i;return(i=this.data.find(r=>r[0]===s))==null?void 0:i[1]},delete(s){const i=this.data.findIndex(r=>r[0]===s);return i===-1?!1:(this.data.splice(i,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)},forEach(s){this.data.forEach(i=>{s(i[1],i[0],this)})},keys(){return this.data.map(s=>s[0]).values()},values(){return this.data.map(s=>s[1]).values()},entries(){return new Map(this.data).entries()},get[Symbol.toStringTag](){return"Map"},[Symbol.iterator](){return this.entries()}});return Object.defineProperties(e,{data:{enumerable:!1},size:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(e),e}const on=(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Dc=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Ud="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",ve={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:on,SECURE_SITE_DASHBOARD:`${on}/dashboard`,SECURE_SITE_FAVICON:`${on}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",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"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:
156","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"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:["eip155","solana"],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["coinbase","meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!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},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"}},W={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=W.getActiveNamespace(),e=W.getActiveCaipNetworkId(),s=e?e.split(":")[1]:void 0,i=s?isNaN(Number(s))?s:Number(s):void 0;return{namespace:t,caipNetworkId:e,chainId:i}},setWalletConnectDeepLink({name:t,href:e}){try{Z.setItem(ee.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Z.getItem(ee.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Z.removeItem(ee.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Z.setItem(ee.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Z.setItem(ee.ACTIVE_CAIP_NETWORK_ID,t),W.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Z.getItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Z.removeItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=rn(t);Z.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=W.getRecentWallets();e.find(i=>i.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Z.setItem(ee.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Z.getItem(ee.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const s=rn(t);Z.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Z.getItem(ee.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=rn(t);return Z.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",t)}},setConnectedSocialProvider(t){try{Z.setItem(ee.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Z.getItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Z.removeItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Z.getItem(ee.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var s;const t=Z.getItem(ee.ACTIVE_CAIP_NETWORK_ID);return(s=t==null?void 0:t.split(":"))==null?void 0:s[1]},setConnectionStatus(t){try{Z.setItem(ee.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Z.getItem(ee.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Z.getItem(ee.CONNECTED_NAMESPACES);return t!=null&&t.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Z.setItem(ee.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=W.getConnectedNamespaces();e.includes(t)||(e.push(t),W.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=W.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),W.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Z.getItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Z.setItem(ee.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Z.removeItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Z.getItem(ee.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=W.getBalanceCache();Z.setItem(ee.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=W.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;W.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=W.getBalanceCache();e[t.caipAddress]=t,Z.setItem(ee.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Z.getItem(ee.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=W.getBalanceCache();Z.setItem(ee.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=W.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),W.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=W.getNativeBalanceCache();e[t.caipAddress]=t,Z.setItem(ee.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Z.getItem(ee.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t}
1,getEnsFromCacheForAddress(t){try{const s=W.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;W.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=W.getEnsCache();e[t.address]=t,Z.setItem(ee.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=W.getEnsCache();Z.setItem(ee.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=Z.getItem(ee.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=W.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;W.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=W.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Z.setItem(ee.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=W.getIdentityCache();Z.setItem(ee.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Z.removeItem(ee.PORTFOLIO_CACHE),Z.removeItem(ee.NATIVE_BALANCE_CACHE),Z.removeItem(ee.ENS_CACHE),Z.removeItem(ee.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Z.setItem(ee.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Z.getItem(ee.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s={...W.getConnections(),[e]:t};Z.setItem(ee.CONNECTIONS,JSON.stringify(s))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=Z.getItem(ee.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}}},X={isMobile(){var t;return this.isClient()?!!(typeof(window==null?void 0:window.matchMedia)=="function"&&((t=window==null?void 0: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 X.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()<=ve.TEN_SEC_MS:!0},isAllowedRetry(t,e=ve.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(X.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],i="https://app.safe.global";if(s){const r=new URL(s),n=new URL(i);return r.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+ve.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(...i)=>{function r(){t(...i)}s&&clearTimeout(s),s=setTimeout(r,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(X.isHttpUrl(t))return this.formatUniversalUrl(t,e);let i=t,r=s;i.includes("://")||(i=t.replaceAll("/","").replaceAll(":",""),i=`${i}://`),i.endsWith("/")||(i=`${i}/`),r&&!(r!=null&&r.endsWith("/"))&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const n=encodeURIComponent(e);return{redirect:`${i}wc?uri=${n}`,redirectUniversalLink:r?`${r}wc?uri=${n}`:void 0,href:i}},formatUniversalUrl(t,e){if(!X.isHttpUrl(t))return this.formatNativeUrl(t,e);let s=t;s.endsWith("/")||(s=`${s}/`);const i=encodeURIComponent(e);return{redirect:`${s}wc?uri=${i}`,href:s}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?W.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,i,r;if(typeof window>"u")return!1;const t=(i=(s=window.matchMedia)==null?void 0:s.call(window,"(display-mode: standalone)"))==null?void 0:i.matches,e=(r=window==null?void 0:window.navigator)==null?void 0:r.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,i)=>{const r=new Image;r.onload=s,r.onerror=i,r.crossOrigin="anonymous",r.src=t});return Promise.race([e,X.wait(2e3)])},formatBalance(t,e){let s="0.000";if(typeof t=="string"){const i=Number(t);if(i){const r=Math.floor(i*1e3)/1e3;r&&(s=r.toString())}}return`${s}${e?` ${e}`:""}`},formatBalance2(t,e){var i;let s;if(t==="0")s="0";else if(typeof t=="string"){const r=Number(t);r&&(s=(i=r.toString().match(/^-?\d+(?:\.\d{0,3})?/u))==null?void 0:i[0])}
1return{value:s??"0",rest:s==="0"?"000":"",symbol:e}},getApiUrl(){return B.W3M_API_URL},getBlockchainApiUrl(){return B.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return B.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((i,r)=>{s[i]=r}),e.sort((i,r)=>{const n=s[i.id],o=s[r.id];return n!==void 0&&o!==void 0?n-o:n!==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,i]=e.split(".");return{dollars:s,pennies:i}},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(i=>{const r=i[e];return s.has(r)?!1:(s.add(r),!0)})},generateSdkVersion(t,e,s){const r=t.length===0?ve.ADAPTER_TYPES.UNIVERSAL:t.map(n=>n.adapterType).join(",");return`${e}-${r}-${s}`},createAccount(t,e,s,i,r){return{namespace:t,address:e,type:s,publicKey:i,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 B.CHAIN_NAME_MAP},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=",n=t.substring(t.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(n),s,e);return t.replace(n,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const i=t.indexOf(e);if(i===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const r=t.indexOf("&",i),n=e.length,o=r!==-1?r:t.length,a=t.substring(0,i+n),c=t.substring(i+n,o),l=t.substring(r),d=c+s;return a+d+l}};async function Ui(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class hr{constructor({baseUrl:e,clientId:s}){this.baseUrl=e,this.clientId=s}async get({headers:e,signal:s,cache:i,...r}){const n=this.createUrl(r);return(await Ui(n,{method:"GET",headers:e,signal:s,cache:i})).json()}async getBlob({headers:e,signal:s,...i}){const r=this.createUrl(i);return(await Ui(r,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:i,...r}){const n=this.createUrl(r);return(await Ui(n,{method:"POST",headers:s,body:e?JSON.stringify(e):void 0,signal:i})).json()}async put({body:e,headers:s,signal:i,...r}){const n=this.createUrl(r);return(await Ui(n,{method:"PUT",headers:s,body:e?JSON.stringify(e):void 0,signal:i})).json()}async delete({body:e,headers:s,signal:i,...r}){const n=this.createUrl(r);return(await Ui(n,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:i})).json()}createUrl({path:e,params:s}){const i=new URL(e,this.baseUrl);return s&&Object.entries(s).forEach(([r,n])=>{n&&i.searchParams.append(r,n)}),this.clientId&&i.searchParams.append("clientId",this.clientId),i}}const Dd={getFeatureValue(t,e){const s=e==null?void 0:e[t];return s===void 0?ve.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(X.isTelegram()){if(X.isIos())return t.filter(e=>e!=="google");if(X.isMac())return t.filter(e=>e!=="x");if(X.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},V=Ae({features:ve.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:ve.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),O={state:V,subscribeKey(t,e){return Ze(V,t,e)},setOptions(t){Object.assign(V,t)},setRemoteFeatures(t){var s;if(!t)return;const e={...V.remoteFeatures,...t};V.remoteFeatures=e,(s=V.remoteFeatures)!=null&&s.socials&&(V.remoteFeatures.socials=Dd.filterS
vendor: 2,858 bytes, line 1
1ocialsByPlatform(V.remoteFeatures.socials))},setFeatures(t){if(!t)return;V.features||(V.features=ve.DEFAULT_FEATURES);const e={...V.features,...t};V.features=e},setProjectId(t){V.projectId=t},setCustomRpcUrls(t){V.customRpcUrls=t},setAllWallets(t){V.allWallets=t},setIncludeWalletIds(t){V.includeWalletIds=t},setExcludeWalletIds(t){V.excludeWalletIds=t},setFeaturedWalletIds(t){V.featuredWalletIds=t},setTokens(t){V.tokens=t},setTermsConditionsUrl(t){V.termsConditionsUrl=t},setPrivacyPolicyUrl(t){V.privacyPolicyUrl=t},setCustomWallets(t){V.customWallets=t},setIsSiweEnabled(t){V.isSiweEnabled=t},setIsUniversalProvider(t){V.isUniversalProvider=t},setSdkVersion(t){V.sdkVersion=t},setMetadata(t){V.metadata=t},setDisableAppend(t){V.disableAppend=t},setEIP6963Enabled(t){V.enableEIP6963=t},setDebug(t){V.debug=t},setEnableWalletConnect(t){V.enableWalletConnect=t},setEnableWalletGuide(t){V.enableWalletGuide=t},setEnableAuthLogger(t){V.enableAuthLogger=t},setEnableWallets(t){V.enableWallets=t},setPreferUniversalLinks(t){V.experimental_preferUniversalLinks=t},setHasMultipleAddresses(t){V.hasMultipleAddresses=t},setSIWX(t){V.siwx=t},setConnectMethodsOrder(t){V.features={...V.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){V.features={...V.features,walletFeaturesOrder:t}},setSocialsOrder(t){V.remoteFeatures={...V.remoteFeatures,socials:t}},setCollapseWallets(t){V.features={...V.features,collapseWallets:t}},setEnableEmbedded(t){V.enableEmbedded=t},setAllowUnsupportedChain(t){V.allowUnsupportedChain=t},setManualWCControl(t){V.manualWCControl=t},setEnableNetworkSwitch(t){V.enableNetworkSwitch=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(V.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){V.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return V.universalProviderConfigOverride},getSnapshot(){return rr(V)}},Ld=Object.freeze({enabled:!0,events:[]}),Md=new hr({baseUrl:X.getAnalyticsUrl(),clientId:null}),Fd=5,Bd=60*1e3,cs=Ae({...Ld}),qd={state:cs,subscribeKey(t,e){return Ze(cs,t,e)},async sendError(t,e){if(!cs.enabled)return;const s=Date.now();if(cs.events.filter(n=>{const o=new Date(n.properties.timestamp||"").getTime();return s-o<Bd}).length>=Fd)return;const r={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};cs.events.push(r);try{if(typeof window>"u")return;const{projectId:n,sdkType:o,sdkVersion:a}=O.state;await Md.post({path:"/e",params:{projectId:n,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:X.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(){cs.enabled=!0},disable(){cs.enabled=!1},clearEvents(){cs.events=[]}};
1class yi extends Error{constructor(e,s,i){super(e),this.name="AppKitError",this.category=s,this.originalError=i,Object.setPrototypeOf(this,yi.prototype);let r=!1;if(i instanceof Error&&typeof i.stack=="string"&&i.stack){const n=i.stack,o=n.indexOf(`
2`);if(o>-1){const a=n.substring(o+1);this.stack=`${this.name}: ${this.message}
3${a}`,r=!0}}r||(Error.captureStackTrace?Error.captureStackTrace(this,yi):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Fo(t,e){const s=t instanceof yi?t:new yi(t instanceof Error?t.message:String(t),e,t);throw qd.sendError(s,s.category),s}function bt(t,e="INTERNAL_SDK_ERROR"){const s={};return Object.keys(t).forEach(i=>{const r=t[i];if(typeof r=="function"){let n=r;r.constructor.name==="AsyncFunction"?n=async(...o)=>{try{return await r(...o)}catch(a){return Fo(a,e)}}:n=(...o)=>{try{return r(...o)}catch(a){return Fo(a,e)}},s[i]=n}else s[i]=r}),s}const Wt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},jd={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,i=encodeURIComponent(s);if(t===Wt.PHANTOM.id&&!("phantom"in window)){const r=s.startsWith("https")?"https":"http",n=s.split("/")[2],o=encodeURIComponent(`${r}://${n}`);window.location.href=`${Wt.PHANTOM.url}/ul/browse/${i}?ref=${o}`}t===Wt.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Wt.SOLFLARE.url}/ul/v1/browse/${i}?ref=${i}`),e===B.CHAIN.SOLANA&&t===Wt.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Wt.COINBASE.url}/dapp?cb_url=${i}`)}},dt=Ae({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Wd={state:dt,subscribeNetworkImages(t){return Xe(dt.networkImages,()=>t(dt.networkImages))},subscribeKey(t,e){return Ze(dt,t,e)},subscribe(t){return Xe(dt,()=>t(dt))},setWalletImage(t,e){dt.walletImages[t]=e},setNetworkImage(t,e){dt.networkImages[t]=e},setChainImage(t,e){dt.chainImages[t]=e},setConnectorImage(t,e){dt.connectorImages={...dt.connectorImages,[t]:e}},setTokenImage(t,e){dt.tokenImages[t]=e},setCurrencyImage(t,e){dt.currencyImages[t]=e}},Rt=bt(Wd),zd={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},an=Ae({networkImagePromises:{}}),Lc={async fetchWalletImage(t){if(t)return await K._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(an.networkImagePromises[t]||(an.networkImagePromises[t]=K._fetchNetworkImage(t)),await an.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return Rt.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 Rt.state.walletImages[t.image_id]},getNetworkImage(t){var e,s,i;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((i=t==null?void 0:t.assets)!=null&&i.imageId)return Rt.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return Rt.state.networkImages[t]},getConnectorImage(t){if(t!=null&&t.imageUrl)return t.imageUrl;if(t!=null&&t.imageId)return Rt.state.connectorImages[t.imageId]},getChainImage(t){return Rt.state.networkImages[zd[t]]}},ls=Ae({message:"",variant:"info",open:!1}),Hd={state:ls,subscribeKey(t,e){return Ze(ls,t,e)},open(t,e){const{debug:s}=O.state,{shortMessage:i,longMessage:r}=t;s&&(ls.message=i,ls.variant=e,ls.open=!0),r&&console.error(typeof r=="function"?r():r)},close(){ls.open=!1,ls.message="",ls.variant="info"}},Ts=bt(Hd),Kd=X.getAnalyticsUrl(),Vd=new hr({baseUrl:Kd,clientId:null}),Gd=["MODAL_CREATED"],Yt=Ae({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Se={state:Yt,subscribe(t){return Xe(Yt,()=>t(Yt))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=O.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(t){try{const e=z.state.address;if(Gd.includes(t.data.event)||typeof window>"u")return;await Vd.post({path:"/e",params:Se.getSdkProperties(),body:{eventId:X.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e}}}),Yt.reportedErrors.FORBIDDEN=!1}
3catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===B.HTTP_STATUS_CODES.FORBIDDEN&&!Yt.reportedErrors.FORBIDDEN&&(Ts.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${Wi()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),Yt.reportedErrors.FORBIDDEN=!0)}},sendEvent(t){var e;Yt.timestamp=Date.now(),Yt.data=t,(e=O.state.features)!=null&&e.analytics&&Se._sendAnalyticsEvent(Yt)}},Jd=X.getApiUrl(),st=new hr({baseUrl:Jd,clientId:null}),Yd=40,Bo=4,Xd=20,te=Ae({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),K={state:te,subscribeKey(t,e){return Ze(te,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=O.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return O.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${st.baseUrl}/getWalletImage/${t}`,s=await st.getBlob({path:e,params:K._getSdkProperties()});Rt.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${st.baseUrl}/public/getAssetImage/${t}`,s=await st.getBlob({path:e,params:K._getSdkProperties()});Rt.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${st.baseUrl}/public/getAssetImage/${t}`,s=await st.getBlob({path:e,params:K._getSdkProperties()});Rt.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${st.baseUrl}/public/getCurrencyImage/${t}`,s=await st.getBlob({path:e,params:K._getSdkProperties()});Rt.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${st.baseUrl}/public/getTokenImage/${t}`,s=await st.getBlob({path:e,params:K._getSdkProperties()});Rt.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){return X.isMobile()?t==null?void 0:t.filter(s=>s.mobile_link||s.id===Wt.COINBASE.id?!0:p.state.activeChain==="solana"&&(s.id===Wt.SOLFLARE.id||s.id===Wt.PHANTOM.id)):t},async fetchProjectConfig(){return(await st.get({path:"/appkit/v1/config",params:K._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await st.get({path:"/projects/v1/origins",params:K._getSdkProperties()});return t}catch{return[]}},async fetchNetworkImages(){const t=p.getAllRequestedCaipNetworks(),e=t==null?void 0:t.map(({assets:s})=>s==null?void 0:s.imageId).filter(Boolean).filter(s=>!Lc.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>K._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=q.state,e=t.map(({imageId:s}
3)=>s).filter(Boolean);await Promise.allSettled(e.map(s=>K._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>K._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>K._fetchTokenImage(e)))},async fetchWallets(t){var n;const e=t.exclude??[];K._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Wt).map(o=>o.id));const i=await st.get({path:"/getWallets",params:{...K._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:(n=t.include)==null?void 0:n.join(","),exclude:e.join(",")}});return{data:K._filterWalletsByPlatform(i==null?void 0:i.data)||[],count:i==null?void 0:i.count}},async fetchFeaturedWallets(){const{featuredWalletIds:t}=O.state;if(t!=null&&t.length){const e={...K._getSdkProperties(),page:1,entries:(t==null?void 0:t.length)??Bo,include:t},{data:s}=await K.fetchWallets(e),i=[...s].sort((n,o)=>t.indexOf(n.id)-t.indexOf(o.id)),r=i.map(n=>n.image_id).filter(Boolean);await Promise.allSettled(r.map(n=>K._fetchWalletImage(n))),te.featured=i,te.allFeatured=i}},async fetchRecommendedWallets(){try{te.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=O.state,i=[...e??[],...s??[]].filter(Boolean),r=p.getRequestedCaipNetworkIds().join(","),n={page:1,entries:Bo,include:t,exclude:i,chains:r},{data:o,count:a}=await K.fetchWallets(n),c=W.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=>K._fetchWalletImage(u))),te.recommended=o,te.allRecommended=o,te.count=a??0}catch{}finally{te.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:i}=O.state,r=p.getRequestedCaipNetworkIds().join(","),n=[...te.recommended.map(({id:d})=>d),...s??[],...i??[]].filter(Boolean),o={page:t,entries:Yd,include:e,exclude:n,chains:r},{data:a,count:c}=await K.fetchWallets(o),l=a.slice(0,Xd).map(d=>d.image_id).filter(Boolean);await Promise.allSettled(l.map(d=>K._fetchWalletImage(d))),te.wallets=X.uniqueBy([...te.wallets,...K._filterOutExtensions(a)],"id").filter(d=>{var u;return(u=d.chains)==null?void 0:u.some(h=>r.includes(h))}),te.count=c>te.count?c:te.count,te.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await K.fetchWallets(e);s&&s.forEach(i=>{te.excludedWallets.push({rdns:i.rdns,name:i.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:i}=O.state,r=p.getRequestedCaipNetworkIds().join(",");te.search=[];const n={page:1,entries:100,search:t==null?void 0:t.trim(),badge_type:e,include:s,exclude:i,chains:r},{data:o}=await K.fetchWallets(n);Se.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=>K._fetchWalletImage(c)),X.wait(300)]),te.search=K._filterOutExtensions(o)},initPromise(t,e){const s=te.promises[t];return s||(te.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:i=!0}={}){const r=[t&&K.initPromise("connectorImages",K.fetchConnectorImages),e&&K.initPromise("featuredWallets",K.fetchFeaturedWallets),s&&K.initPromise("recommendedWallets",K.fetchRecommendedWallets),i&&K.initPromise("networkImages",K.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){var t;(t=O.state.features)!=null&&t.analytics&&K.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await st.get({path:"/getAnalyticsConfig",params:K._getSdkProperties()});O.setFeatures({analytics:t})}catch{O.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!(t!=null&&t.length)){te.featured=te.allFeatured,te.recommended=te.allRecommended;return}const e=p.getRequestedCaipNetworkIds().join(",");te.featured=te.allFeatured.filter(s=>{var i;return(i=s.chains)==null?void 0:i.some(r=>e.includes(r))}),te.recommended=te.allRecommended.filter(s=>{var i;return(i=s.chains)==null?void 0:i.some(r=>e.includes(r))}),te.filteredWallets=te.wallets.filter(s=>{var i;return(i=s.chains)==null?void 0:i.some(r=>e.includes(r))})},clearFilterByNamespaces(){te.filteredWallets=[]},setFilterByNamespace(t){if(!t){te.featured=te.allFeatured,te.recommended=te.allRecommended;return}const e=p.getRequestedCaipNetworkIds().join(",");te.featured=te.allFeatured.filter(s=>{var i;return(i=s.chains)==null?void 0:i.some(r=>e.includes(r))}),te.recommended=te.allRecommended.filter(s=>{var i;return(i=s.chains)==null?void 0:i.some(r=>e.includes(r))}),te.filteredWallets=te.wallets.filter(s=>{var i;return(i=s.chains)==null?void 0:i.some(r=>e.includes(r))})}},fe=Ae({view:"Connect",history:["Connect"],transactionStack:[]}),Zd={state:fe,subscribeKey(t,e){return Ze(fe,t,e)},pushTransactionStack(t){fe.transactionStack.push(t)},popTransactionStack(t){const e=fe.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:i,onCancel:r}=e;switch(t){case"success":s==null||s();break;case"error":i==null||i(),ie.goBack();break;case"cancel":r==null||r(),ie.goBack();break}},push(t,e){t!==fe.view&&(fe.view=t,fe.history.push(t),fe.data=e)},reset(t,e){fe.view=t,fe.history=[t],fe.data=e},replace(t,e){fe.history.at(-1)===t||(fe.view=t,fe.history[fe.history.length-1]=t,fe.data=e)},goBack(){var i;const t=p.state.activeCaipAddress,e=ie.state.view==="ConnectingFarcaster",s=!t&&e;if(fe.history.length>1){fe.history.pop();const[r]=fe.history.slice(-1);r&&(t&&r==="Connect"?fe.view="Account":fe.view=r)}else je.close();(i=fe.data)!=null&&i.wallet&&(fe.data.wallet=void 0),setTimeout(()=>{var r,n,o;if(s){z.setFarcasterUrl(void 0,p.state.activeChain);const a=q.getAuthConnector();(r=a==null?void 0:a.provider)==null||r.reload();const c=rr(O.state);(o=(n=a==null?void 0:a.provider)==null?void 0:n.syncDappData)==null||o.call(n,{metadata:c.metadata,sdkVersion:c.sdkVersion,projectId:c.projectId,sdkType:c.sdkType})}},100)},goBackToIndex(t){if(fe.history.length>1){fe.history=fe.history.slice(0,t+1);const[e]=fe.history.slice(-1);e&&(fe.view=e)}},goBackOrCloseModal(){ie.state.history.length>1?ie.goBack():je.close()}},ie=bt(Zd),Xt=Ae({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Ln={state:Xt,subscribe(t){return Xe(Xt,()=>t(Xt))},setThemeMode(t){Xt.themeMode=t;try{const e=q.getAuthConnector();
3if(e){const s=Ln.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:fs(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){Xt.themeVariables={...Xt.themeVariables,...t};try{const e=q.getAuthConnector();if(e){const s=Ln.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:fs(Xt.themeVariables,Xt.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return rr(Xt)}},pt=bt(Ln),Mc={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},ae=Ae({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...Mc},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),Qd={state:ae,subscribe(t){return Xe(ae,()=>{t(ae)})},subscribeKey(t,e){return Ze(ae,t,e)},initialize(t){t.forEach(e=>{const s=W.getConnectedConnectorId(e);s&&q.setConnectorId(s,e)})},setActiveConnector(t){t&&(ae.activeConnector=Ls(t))},setConnectors(t){t.filter(r=>!ae.allConnectors.some(n=>n.id===r.id&&q.getConnectorName(n.name)===q.getConnectorName(r.name)&&n.chain===r.chain)).forEach(r=>{r.type!=="MULTI_CHAIN"&&ae.allConnectors.push(Ls(r))});const s=q.getEnabledNamespaces(),i=q.getEnabledConnectors(s);ae.connectors=q.mergeMultiChainConnectors(i)},filterByNamespaces(t){Object.keys(ae.filterByNamespaceMap).forEach(e=>{ae.filterByNamespaceMap[e]=!1}),t.forEach(e=>{ae.filterByNamespaceMap[e]=!0}),q.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){ae.filterByNamespaceMap[t]=e,q.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=q.getEnabledNamespaces(),e=q.getEnabledConnectors(t),s=q.areAllNamespacesEnabled();ae.connectors=q.mergeMultiChainConnectors(e),s?K.clearFilterByNamespaces():K.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(ae.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return ae.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(ae.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=q.generateConnectorMapByName(t),s=[];return e.forEach(i=>{const r=i[0],n=(r==null?void 0:r.id)===B.CONNECTOR_ID.AUTH;i.length>1&&r?s.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...i],type:n?"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:i}=s,r=q.getConnectorName(i);if(!r)return;const n=e.get(r)||[];n.find(a=>a.chain===s.chain)||n.push(s),e.set(r,n)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(s=>{e.find(i=>i.chain===s.chain)||e.push(s)}),e},addConnector(t){var e,s,i;if(t.id===B.CONNECTOR_ID.AUTH){const r=t,n=rr(O.state),o=pt.getSnapshot().themeMode,a=pt.getSnapshot().themeVariables;(s=(e=r==null?void 0:r.provider)==null?void 0:e.syncDappData)==null||s.call(e,{metadata:n.metadata,sdkVersion:n.sdkVersion,projectId:n.projectId,sdkType:n.sdkType}),(i=r==null?void 0:r.provider)==null||i.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:fs(a,o)}),q.setConnectors([t])}else q.setConnectors([t])},getAuthConnector(t){var i;const e=t||p.state.activeChain,s=ae.connectors.find(r=>r.id===B.CONNECTOR_ID.AUTH);if(s)return(i=s==null?void 0:s.connectors)!=null&&i.length?s.connectors.find(n=>n.chain===e):s},getAnnouncedConnectorRdns(){return ae.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>{var e;return(e=t.info)==null?void 0:e.rdns})},getConnectorById(t){return ae.allConnectors.find(e=>e.id===t)},getConnector(t,e){return ae.allConnectors.filter(i=>i.chain===p.state.activeChain).find(i=>{var r;return i.explorerId===t||((r=i.info)==null?void 0:r.rdns)===e})},syncIfAuthConnector(t){var n,o;if(t.id!=="ID_AUTH")return;const e=t,s=rr(O.state),i=pt.getSnapshot().themeMode,r=pt.getSnapshot().themeVariables;(o=(n=e==null?void 0:e.provider)==null?void 0:n.syncDappData)==null||o.call(n,{metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:i,themeVariables:r,w3mThemeVariables:fs(r,i)})},getConnectorsByNamespace(t){const e=ae.allConnectors.filter(s=>s.chain===t);return q.mergeMultiChainConnectors(e)},selectWalletConnector(t){const e=q.getConnector(t.id,t.rdns),s=p.state.activeChain;jd.handleMobileDeeplinkRedirect((e==null?void 0:e.explorerId)||t.id,s),e?ie.push("ConnectingExter
3nal",{connector:e}):ie.push("ConnectingWalletConnect",{wallet:t})},getConnectors(t){return t?q.getConnectorsByNamespace(t):q.mergeMultiChainConnectors(ae.allConnectors)},setFilterByNamespace(t){ae.filterByNamespace=t,ae.connectors=q.getConnectors(t),K.setFilterByNamespace(t)},setConnectorId(t,e){t&&(ae.activeConnectorIds={...ae.activeConnectorIds,[e]:t},W.setConnectedConnectorId(e,t))},removeConnectorId(t){ae.activeConnectorIds={...ae.activeConnectorIds,[t]:void 0},W.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return ae.activeConnectorIds[t]},isConnected(t){return t?!!ae.activeConnectorIds[t]:Object.values(ae.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){ae.activeConnectorIds={...Mc}}},q=bt(Qd),eu="https://secure.walletconnect.org/sdk";typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL;typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL;typeof process<"u"&&typeof process.env<"u"&&process.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const Yi={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"}},Ps=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),$e=Ae({...Ps}),tu={state:$e,subscribeKey(t,e){return Ze($e,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=X.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){$e.message=Ps.message,$e.variant=Ps.variant,$e.svg=Ps.svg,$e.open=Ps.open,$e.autoClose=Ps.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:i=Ps.autoClose}){$e.open?($e.open=!1,setTimeout(()=>{$e.message=t,$e.variant=s,$e.svg=e,$e.open=!0,$e.autoClose=i},150)):($e.message=t,$e.variant=s,$e.svg=e,$e.open=!0,$e.autoClose=i)}},$t=tu,Ce=Ae({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),su={state:Ce,subscribe(t){return Xe(Ce,()=>t(Ce))},setLastNetworkInView(t){Ce.lastNetworkInView=t},async fetchTransactions(t,e){var s,i;if(!t)throw new Error("Transactions can't be fetched without an accountAddress");Ce.loading=!0;try{const r=await J.fetchTransactions({account:t,cursor:Ce.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:(s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId}),n=Hi.filterSpamTransactions(r.data),o=Hi.filterByConnectedChain(n),a=[...Ce.transactions,...o];Ce.loading=!1,e==="coinbase"?Ce.coinbaseTransactions=Hi.groupTransactionsByYearAndMonth(Ce.coinbaseTransactions,r.data):(Ce.transactions=a,Ce.transactionsByYear=Hi.groupTransactionsByYearAndMonth(Ce.transactionsByYear,o)),Ce.empty=a.length===0,Ce.next=r.next?r.next:void 0}catch{const n=p.state.activeChain;Se.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:O.state.projectId,cursor:Ce.next,isSmartAccount:((i=z.state.preferredAccountTypes)==null?void 0:i[n])===Yi.ACCOUNT_TYPES.SMART_ACCOUNT}}),$t.showError("Failed to fetch transactions"),Ce.loading=!1,Ce.empty=!0,Ce.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const s=t;return e.forEach(i=>
3{const r=new Date(i.metadata.minedAt).getFullYear(),n=new Date(i.metadata.minedAt).getMonth(),o=s[r]??{},c=(o[n]??[]).filter(l=>l.id!==i.id);s[r]={...o,[n]:[...c,i].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(i=>{var r;return((r=i.nft_info)==null?void 0:r.flags.is_spam)===!0}))},filterByConnectedChain(t){var i;const e=(i=p.state.activeCaipNetwork)==null?void 0:i.caipNetworkId;return t.filter(r=>r.metadata.chain===e)},clearCursor(){Ce.next=void 0},resetTransactions(){Ce.transactions=[],Ce.transactionsByYear={},Ce.lastNetworkInView=void 0,Ce.loading=!1,Ce.empty=!1,Ce.next=void 0}},Hi=bt(su,"API_ERROR"),we=Ae({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let As;const iu={state:we,subscribeKey(t,e){return Ze(we,t,e)},_getClient(){return we._client},setClient(t){we._client=Ls(t)},async connectWalletConnect(){var t,e,s,i;if(X.isTelegram()||X.isSafari()&&X.isIos()){if(As){await As,As=void 0;return}if(!X.isPairingExpired(we==null?void 0:we.wcPairingExpiry)){const r=we.wcUri;we.wcUri=r;return}As=(e=(t=Y._getClient())==null?void 0:t.connectWalletConnect)==null?void 0:e.call(t).catch(()=>{}),Y.state.status="connecting",await As,As=void 0,we.wcPairingExpiry=void 0,Y.state.status="connected"}else await((i=(s=Y._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:i.call(s))},async connectExternal(t,e,s=!0){var i,r;await((r=(i=Y._getClient())==null?void 0:i.connectExternal)==null?void 0:r.call(i,t)),s&&p.setActiveNamespace(e)},async reconnectExternal(t){var s,i;await((i=(s=Y._getClient())==null?void 0:s.reconnectExternal)==null?void 0:i.call(s,t));const e=t.chain||p.state.activeChain;e&&q.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){var i;je.setLoading(!0,p.state.activeChain);const s=q.getAuthConnector();s&&(z.setPreferredAccountType(t,e),await s.provider.setPreferredAccount(t),W.setPreferredAccountTypes(z.state.preferredAccountTypes??{[e]:t}),await Y.reconnectExternal(s),je.setLoading(!1,p.state.activeChain),Se.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:((i=p.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||""}}))},async signMessage(t){var e;return(e=Y._getClient())==null?void 0:e.signMessage(t)},parseUnits(t,e){var s;return(s=Y._getClient())==null?void 0:s.parseUnits(t,e)},formatUnits(t,e){var s;return(s=Y._getClient())==null?void 0:s.formatUnits(t,e)},async sendTransaction(t){var e;return(e=Y._getClient())==null?void 0:e.sendTransaction(t)},async getCapabilities(t){var e;return(e=Y._getClient())==null?void 0:e.getCapabilities(t)},async grantPermissions(t){var e;return(e=Y._getClient())==null?void 0:e.grantPermissions(t)},async walletGetAssets(t){var e;return((e=Y._getClient())==null?void 0:e.walletGetAssets(t))??{}},async estimateGas(t){var e;return(e=Y._getClient())==null?void 0:e.estimateGas(t)},async writeContract(t){var e;return(e=Y._getClient())==null?void 0:e.writeContract(t)},async getEnsAddress(t){var e;return(e=Y._getClient())==null?void 0:e.getEnsAddress(t)},async getEnsAvatar(t){var e;return(e=Y._getClient())==null?void 0:e.getEnsAvatar(t)},checkInstalled(t){var e,s;return((s=(e=Y._getClient())==null?void 0:e.checkInstalled)==null?void 0:s.call(e,t))||!1},resetWcConnection(){we.wcUri=void 0,we.wcPairingExpiry=void 0,we.wcLinking=void 0,we.recentWallet=void 0,we.status="disconnected",Hi.resetTransactions(),W.deleteWalletConnectDeepLink()},resetUri(){we.wcUri=void 0,we.wcPairingExpiry=void 0,As=void 0},finalizeWcConnection(){var s,i;const{wcLinking:t,recentWallet:e}=Y.state;t&&W.setWalletConnectDeepLink(t),e&&W.setAppKitRecent(e),Se.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:t?"mobile":"qrcode",name:((i=(s=ie.state.data)==null?void 0:s.wallet)==null?void 0:i.name)||"Unknown"}})},setWcBasic(t){we.wcBasic=t},setUri(t){we.wcUri=t,we.wcPairingExpiry=X.getPairingExpiry()},setWcLinking(t){we.wcLinking=t},setWcError(t){we.wcError=t,we.buffering=!1},setRecentWallet(t){we.recentWallet=t},setBuffering(t){we.buffering=t},setStatus(t){we.status=t},async disconnect(t){var e;try{await((e=Y._getClient())==null?void 0:e.disconnect(t))}catch(s){throw new yi("Failed to disconnect","INTERNAL_SDK_ERROR",s)}},setConnections(t,e){we.connections.set(e,t)},switchAccount({connection:t,address:e,namespace:s}){if(q.state.activeConnectorIds[s]===t.connectorId){const n=p.state.activeCaipNetwork;if(n){const o=`${s}:${n.id}:${e}`;z.setCaipAddress(o,s)}else console.warn(`No current network found for namespace "${s}"`)}else{const n=q.getConnector(t.connectorId);n?Y.connectExternal(n,s):console.warn(`No connector found for namespace "${s}"`)}}},Y=bt(iu),Hs=Ae({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),ws={state:Hs,subscribe(t){return Xe(Hs,()=>t(Hs))},subscribeOpen(t){return Ze(Hs,"open",t)},set(t){Object.assign(Hs,{...Hs,...t})}},cn={createBalance(t,e){const s={name:t.metadata.name||"",symbol
3: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 hd(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],i=parseInt(s,10);return isNaN(i)?"0x0":`0x${i.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"}},qo={async getMyTokensWithBalance(t){const e=z.state.address,s=p.state.activeCaipNetwork;if(!e||!s)return[];if(s.chainNamespace==="eip155"){const r=await this.getEIP155Balances(e,s);if(r)return this.filterLowQualityTokens(r)}const i=await J.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(i.balances)},async getEIP155Balances(t,e){var s,i;try{const r=cn.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),n=await Y.getCapabilities(t);if(!((i=(s=n==null?void 0:n[r])==null?void 0:s.assetDiscovery)!=null&&i.supported))return null;const o=await Y.walletGetAssets({account:t,chainFilter:[r]});return cn.isWalletGetAssetsResponse(o)?(o[r]||[]).map(c=>cn.createBalance(c,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(t){return(t==null?void 0:t.map(e=>({...e,address:e!=null&&e.address?e.address:p.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]}},ge=Ae({tokenBalances:[],loading:!1}),ru={state:ge,subscribe(t){return Xe(ge,()=>t(ge))},subscribeKey(t,e){return Ze(ge,t,e)},setToken(t){t&&(ge.token=Ls(t))},setTokenAmount(t){ge.sendTokenAmount=t},setReceiverAddress(t){ge.receiverAddress=t},setReceiverProfileImageUrl(t){ge.receiverProfileImageUrl=t},setReceiverProfileName(t){ge.receiverProfileName=t},setNetworkBalanceInUsd(t){ge.networkBalanceInUSD=t},setLoading(t){ge.loading=t},async sendToken(){var t;try{switch(ue.setLoading(!0),(t=p.state.activeCaipNetwork)==null?void 0:t.chainNamespace){case"eip155":await ue.sendEvmToken();return;case"solana":await ue.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}finally{ue.setLoading(!1)}},async sendEvmToken(){var s,i,r,n;const t=p.state.activeChain,e=(s=z.state.preferredAccountTypes)==null?void 0:s[t];if(!ue.state.sendTokenAmount||!ue.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!ue.state.token)throw new Error("A token is required");(i=ue.state.token)!=null&&i.address?(Se.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Yi.ACCOUNT_TYPES.SMART_ACCOUNT,token:ue.state.token.address,amount:ue.state.sendTokenAmount,network:((r=p.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}}),await ue.sendERC20Token({receiverAddress:ue.state.receiverAddress,tokenAddress:ue.state.token.address,sendTokenAmount:ue.state.sendTokenAmount,decimals:ue.state.token.quantity.decimals})):(Se.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Yi.ACCOUNT_TYPES.SMART_ACCOUNT,token:ue.state.token.symbol||"",amount:ue.state.sendTokenAmount,network:((n=p.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}}),await ue.sendNativeToken({receiverAddress:ue.state.receiverAddress,sendTokenAmount:ue.state.sendTokenAmount,decimals:ue.state.token.quantity.decimals}))},async fetchTokenBalance(t){var n,o;ge.loading=!0;const e=(n=p.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,s=(o=p.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=p.state.activeCaipAddress,r=i?X.getPlainAddress(i):void 0;if(ge.lastRetry&&!X.isAllowedRetry(ge.lastRetry,30*ve.ONE_SEC_MS))return ge.loading=!1,[];try{if(r&&e&&s){const a=await qo.getMyTokensWithBalance();return ge.tokenBalances=a,ge.lastRetry=void 0,a}}catch(a){ge.lastRetry=Date.now(),t==null||t(a),$t.showError("Token Balance Unavailable")}finally{ge.loading=!1}return[]},fetchNetworkBalance(){if(ge.tokenBalances.length===0)return;const t=qo.mapBalancesToSwapTokens(ge.tokenBalances);if(!t)return;const e=t.find(s=>
3s.address===p.getActiveNetworkTokenAddress());e&&(ge.networkBalanceInUSD=e?Nd.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){var n,o,a,c;ie.pushTransactionStack({});const e=t.receiverAddress,s=z.state.address,i=Y.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),r="0x";await Y.sendTransaction({chainNamespace:"eip155",to:e,address:s,data:r,value:i??BigInt(0)}),Se.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:((n=z.state.preferredAccountTypes)==null?void 0:n.eip155)===Yi.ACCOUNT_TYPES.SMART_ACCOUNT,token:((o=ue.state.token)==null?void 0:o.symbol)||"",amount:t.sendTokenAmount,network:((a=p.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)||""}}),(c=Y._getClient())==null||c.updateBalance("eip155"),ue.resetSend()},async sendERC20Token(t){ie.pushTransactionStack({onSuccess(){ie.replace("Account")}});const e=Y.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));if(z.state.address&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const s=X.getPlainAddress(t.tokenAddress);await Y.writeContract({fromAddress:z.state.address,tokenAddress:s,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:Pd.getERC20Abi(s),chainNamespace:"eip155"}),ue.resetSend()}},async sendSolanaToken(){var t;if(!ue.state.sendTokenAmount||!ue.state.receiverAddress)throw new Error("An amount and receiver address are required");ie.pushTransactionStack({onSuccess(){ie.replace("Account")}}),await Y.sendTransaction({chainNamespace:"solana",to:ue.state.receiverAddress,value:ue.state.sendTokenAmount}),(t=Y._getClient())==null||t.updateBalance("solana"),ue.resetSend()},resetSend(){ge.token=void 0,ge.sendTokenAmount=void 0,ge.receiverAddress=void 0,ge.receiverProfileImageUrl=void 0,ge.receiverProfileName=void 0,ge.loading=!1,ge.tokenBalances=[]}},ue=bt(ru),ln={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},Ir={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},M=Ae({chains:$d(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),nu={state:M,subscribe(t){return Xe(M,()=>{t(M)})},subscribeKey(t,e){return Ze(M,t,e)},subscribeChainProp(t,e,s){let i;return Xe(M.chains,()=>{var n;const r=s||M.activeChain;if(r){const o=(n=M.chains.get(r))==null?void 0:n[t];i!==o&&(i=o,e(o))}})},initialize(t,e,s){const{chainId:i,namespace:r}=W.getActiveNetworkProps(),n=e==null?void 0:e.find(d=>d.id.toString()===(i==null?void 0:i.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=O.state.enableEmbedded?new Set([...c]):new Set([...(e==null?void 0:e.map(d=>d.chainNamespace))??[]]);((t==null?void 0:t.length)===0||!a)&&(M.noAdapters=!0),M.noAdapters||(M.activeChain=a==null?void 0:a.namespace,M.activeCaipNetwork=n,p.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:n}),M.activeChain&&ws.set({activeChain:a==null?void 0:a.namespace})),l.forEach(d=>{const u=e==null?void 0:e.filter(h=>h.chainNamespace===d);p.state.chains.set(d,{namespace:d,networkState:Ae({...Ir,caipNetwork:u==null?void 0:u[0]}),accountState:Ae(ln),caipNetworks:u??[],...s}),p.setRequestedCaipNetworks(u??[],d)})},removeAdapter(t){var e,s;if(M.activeChain===t){const i=Array.from(M.chains.entries()).find(([r])=>r!==t);if(i){const r=(s=(e=i[1])==null?void 0:e.caipNetworks)==null?void 0:s[0];r&&p.setActiveCaipNetwork(r)}}M.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:s},i){M.chains.set(t.namespace,{namespace:t.namespace,networkState:{...Ir,caipNetwork:i[0]},accountState:ln,caipNetworks:i,connectionControllerClient:s,networkControllerClient:e}),p.setRequestedCaipNetworks((i==null?void 0:i.filter(r=>r.chainNamespace===t.namespace))??[],t.namespace)},addNetwork(t){var s;const e=M.chains.get(t.chainNamespace);if(e){const i=[...e.caipNetworks||[]];(s=e.caipNetworks)!=null&&s.find(r=>r.id===t.id)||i.push(t),M.chains.set(t.chainNamespace,{...e,caipNetworks:i}),p.setRequestedCaipNetworks(i,t.chainNamespace),q.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){var i,r,n;const s=M.chains.get(t);if(s){const o=((i=M.activeCaipNetwork)==null?void 0:i.id)===e,a=[...((r=s.caipNetworks)==null?void 0:r.filter(c=>c.id!==e))||[]];o&&((n=s==null?void 0:s.caipNetworks)!=null&&n[0])&&p.setActiveCaipNetwork(s.caipNetworks[0]),M.chains.set(t,{...s,caipNetworks:a}),p.setRequestedCaipNetworks(a||[],t),a.length===0&&q.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=M.chains.get(t);s&&(s.networkState={...s.networkState||Ir,...e},M.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const i=M.chains.get(t);if(i){const r={...i.accountState||ln,...e};M.chains.set(t,{...i,accountState:r}),(M.chains.size===1||M.activeChain===t)&&(e.caipAddress&&(M.activeCaipAddress=e.caipAddress),z.replaceState(r))}},setChainNetworkData(t,e){if(!t)return;const s=M.chains.get(t);if(s){const i={...s.networkState||Ir,...e};M.chains.set(t,{...s,networkState:i})}}
3,setAccountProp(t,e,s,i=!0){p.setChainAccountData(s,{[t]:e},i),t==="status"&&e==="disconnected"&&s&&q.removeConnectorId(s)},setActiveNamespace(t){var i,r;M.activeChain=t;const e=t?M.chains.get(t):void 0,s=(i=e==null?void 0:e.networkState)==null?void 0:i.caipNetwork;s!=null&&s.id&&t&&(M.activeCaipAddress=(r=e==null?void 0:e.accountState)==null?void 0:r.caipAddress,M.activeCaipNetwork=s,p.setChainNetworkData(t,{caipNetwork:s}),W.setActiveCaipNetworkId(s==null?void 0:s.caipNetworkId),ws.set({activeChain:t,selectedNetworkId:s==null?void 0:s.caipNetworkId}))},setActiveCaipNetwork(t){var i,r,n;if(!t)return;M.activeChain!==t.chainNamespace&&p.setIsSwitchingNamespace(!0);const e=M.chains.get(t.chainNamespace);M.activeChain=t.chainNamespace,M.activeCaipNetwork=t,p.setChainNetworkData(t.chainNamespace,{caipNetwork:t}),(i=e==null?void 0:e.accountState)!=null&&i.address?M.activeCaipAddress=`${t.chainNamespace}:${t.id}:${(r=e==null?void 0:e.accountState)==null?void 0:r.address}`:M.activeCaipAddress=void 0,p.setAccountProp("caipAddress",M.activeCaipAddress,t.chainNamespace),e&&z.replaceState(e.accountState),ue.resetSend(),ws.set({activeChain:M.activeChain,selectedNetworkId:(n=M.activeCaipNetwork)==null?void 0:n.caipNetworkId}),W.setActiveCaipNetworkId(t.caipNetworkId),!p.checkIfSupportedNetwork(t.chainNamespace)&&O.state.enableNetworkSwitch&&!O.state.allowUnsupportedChain&&!Y.state.wcBasic&&p.showUnsupportedChainUI()},addCaipNetwork(t){var s;if(!t)return;const e=M.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!==p.state.activeChain,s=(r=p.getNetworkData(t))==null?void 0:r.caipNetwork,i=p.getCaipNetworkByNamespace(t,s==null?void 0:s.id);e&&i&&await p.switchActiveNetwork(i)},async switchActiveNetwork(t){var r;const e=p.state.chains.get(p.state.activeChain),s=!((r=e==null?void 0:e.caipNetworks)!=null&&r.some(n=>{var o;return n.id===((o=M.activeCaipNetwork)==null?void 0:o.id)})),i=p.getNetworkControllerClient(t.chainNamespace);if(i){try{await i.switchCaipNetwork(t),s&&je.close()}catch{ie.goBack()}Se.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})}},getNetworkControllerClient(t){const e=t||M.activeChain,s=M.chains.get(e);if(!s)throw new Error("Chain adapter not found");if(!s.networkControllerClient)throw new Error("NetworkController client not set");return s.networkControllerClient},getConnectionControllerClient(t){const e=t||M.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=M.chains.get(e);if(!(s!=null&&s.connectionControllerClient))throw new Error("ConnectionController client not set");return s.connectionControllerClient},getAccountProp(t,e){var r;let s=M.activeChain;if(e&&(s=e),!s)return;const i=(r=M.chains.get(s))==null?void 0:r.accountState;if(i)return i[t]},getNetworkProp(t,e){var i;const s=(i=M.chains.get(e))==null?void 0:i.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=M.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:i=[]}=(e==null?void 0:e.networkState)||{};return X.sortRequestedNetworks(s,i)},getAllRequestedCaipNetworks(){const t=[];return M.chains.forEach(e=>{const s=p.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){p.setAdapterNetworkState(e,{requestedCaipNetworks:t});const i=p.getAllRequestedCaipNetworks().map(n=>n.chainNamespace),r=Array.from(new Set(i));q.filterByNamespaces(r)},getAllApprovedCaipNetworkIds(){const t=[];return M.chains.forEach(e=>{const s=p.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(){return M.activeCaipNetwork},getActiveCaipAddress(){return M.activeCaipAddress},getApprovedCaipNetworkIds(t){var i;const e=M.chains.get(t);return((i=e==null?void 0:e.networkState)==null?void 0:i.approvedCaipNetworkIds)||[]},async setApprovedCaipNetworksData(t){const e=p.getNetworkControllerClient(),s=await(e==null?void 0:e.getApprovedCaipNetworksData());p.setAdapterNetworkState(t,{approvedCaipNetworkIds:s==null?void 0:s.approvedCaipNetworkIds,supportsAllNetworks:s==null?void 0:s.supportsAllNetworks})},checkIfSupportedNetwork(t,e){const s=e||M.activeCaipNetwork,i=p.getRequestedCaipNetworks(t);return i.length?i==null?void 0:i.some(r=>r.id===(s==null?void 0:s.id)):!0},checkIfSupportedChainId(t){if(!M.activeChain)return!0;const e=p.getRequestedCaipNetworks(M.activeChain);return e==null?void 0:e.some(s=>s.id===t)},setSmartAccountEnabledNetworks(t,e){p.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){var i;const t=Uc.caipNetworkIdToNumber((i=M.activeCaipNetwork)==null?void 0:i.caipNetworkId),e=M.activeChain;if(!e||!t)return!1;const s=p.getNetworkProp("smartAccountEnabledNetworks",e);return!!(s!=null&&s.includes(Number(t)))},getActiveNetworkTokenAddress(){var i,r;const t=((i=M.activeCaipNetwork)==null?void 0:i.chainNamespace)||"eip155",e=((r=M.activeCaipNetwork)==null?void 0:r.id)||1,s=ve.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`},showUnsupportedChainUI(){je.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=M.activeCaipNetwork;return!!(t!=null&&t.chainNamespace&&ve.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){p.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(t){const e=t;if(!e)throw new Error("Chain is required to set account prop");M.activeCaipAddress=void 0,p.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol
3:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountTypes:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),q.removeConnectorId(e)},setIsSwitchingNamespace(t){M.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){var s,i;const t=[];let e;if(M.chains.forEach(r=>{B.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===r.namespace)&&r.namespace&&t.push(r.namespace)}),t.length>0){const r=t[0];return e=r?(i=(s=M.chains.get(r))==null?void 0:s.caipNetworks)==null?void 0:i[0]:void 0,e}},getAccountData(t){var e;return t?(e=p.state.chains.get(t))==null?void 0:e.accountState:z.state},getNetworkData(t){var s;const e=t||M.activeChain;if(e)return(s=p.state.chains.get(e))==null?void 0:s.networkState},getCaipNetworkByNamespace(t,e){var r,n,o;if(!t)return;const s=p.state.chains.get(t),i=(r=s==null?void 0:s.caipNetworks)==null?void 0:r.find(a=>a.id===e);return i||((n=s==null?void 0:s.networkState)==null?void 0:n.caipNetwork)||((o=s==null?void 0:s.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const t=q.state.filterByNamespace;return(t?[M.chains.get(t)]:Array.from(M.chains.values())).flatMap(s=>(s==null?void 0:s.caipNetworks)||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?p.getRequestedCaipNetworks(t):p.getAllRequestedCaipNetworks()}},p=bt(nu),ou={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"}]}]},Fc=X.getBlockchainApiUrl(),it=Ae({clientId:null,api:new hr({baseUrl:Fc,clientId:null}),supportedChains:{http:[],ws:[]}}),J={state:it,async get(t){const{st:e,sv:s}=J.getSdkProperties(),i=O.state.projectId,r={...t.params||{},st:e,sv:s,projectId:i};return it.api.get({...t,params:r})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=O.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{it.supportedChains.http.length||await J.getSupportedNetworks()}catch{return!1}return it.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await J.get({path:"v1/supported-chains"});return it.supportedChains=t,t}catch{return it.supportedChains}},async fetchIdentity({address:t,caipNetworkId:e}){if(!await J.isNetworkSupported(e))return{avatar:"",name:""};const i=W.getIdentityFromCacheForAddress(t);if(i)return i;const r=await J.get({path:`/v1/identity/${t}`,params:{sender:p.state.activeCaipAddress?X.getPlainAddress(p.state.activeCaipAddress):void 0}});return W.updateIdentityCache({address:t,identity:r,timestamp:Date.now()}),r},async fetchTransactions({account:t,cursor:e,onramp:s,signal:i,cache:r,chainId:n}){var a;return await J.isNetworkSupported((a=p.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?J.get({path:`/v1/account/${t}/history`,params:{cursor:e,onramp:s,chainId:n},signal:i,cache:r}):{data:[],next:void 0}},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:i,gasPrice:r}){var o;return await J.isNetworkSupported((o=p.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?J.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:s,to:i,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){var s;return await J.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){var s;return await J.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?it.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:O.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){var i;return await J.isNetworkSupported((i=p.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?J.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}=J.getSdkProperties();if(!await J.isNetworkSupported((r=p.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))throw new Error("Network not supported for Gas Price");return J.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:i,disableEstimate:r}){var o;if(!await J.isNetworkSupported((o=p.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return it.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:ve.CONVERT_SLIPPAGE_TOLERANCE},projectId:O.state.projectId,from:e,to:s,userAddress:i,disableEstimate:r}}
3)},async generateApproveCalldata({from:t,to:e,userAddress:s}){var o;const{st:i,sv:r}=J.getSdkProperties();if(!await J.isNetworkSupported((o=p.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return J.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:t,to:e,st:i,sv:r}})},async getBalance(t,e,s){var l;const{st:i,sv:r}=J.getSdkProperties();if(!await J.isNetworkSupported((l=p.state.activeCaipNetwork)==null?void 0:l.caipNetworkId))return $t.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=W.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await J.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:i,sv:r}});return W.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){var s;return await J.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){var s;return await J.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:`/v1/profile/reverse/${t}`,params:{sender:z.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(t){var s;return await J.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:i}){var n;return await J.isNetworkSupported((n=p.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?it.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:s,signature:i},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:s,purchaseAmount:i,paymentAmount:r}){var a;return await J.isNetworkSupported((a=p.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await it.api.post({path:"/v1/generators/onrampurl",params:{projectId:O.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url:""},async getOnrampOptions(){var e;if(!await J.isNetworkSupported((e=p.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await J.get({path:"/v1/onramp/options"})}catch{return ou}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:i}){var r;try{return await J.isNetworkSupported((r=p.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?await it.api.post({path:"/v1/onramp/quote",params:{projectId:O.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:s,network:i}}):null}catch{return{coinbaseFee:{amount:s,currency:e.id},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 J.isNetworkSupported((s=p.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){var r;return await J.isNetworkSupported((r=p.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?it.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:O.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){it.clientId=t,it.api=new hr({baseUrl:Fc,clientId:t})}},vt=Ae({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),au={state:vt,replaceState(t){t&&Object.assign(vt,Ls(t))},subscribe(t){return p.subscribeChainProp("accountState",e=>{if(e)return t(e)})},subscribeKey(t,e,s){let i;return p.subscribeChainProp("accountState",r=>{if(r){const n=r[t];i!==n&&(i=n,e(n))}},s)},setStatus(t,e){p.setAccountProp("status",t,e)},getCaipAddress(t){return p.getAccountProp("caipAddress",t)},setCaipAddress(t,e){const s=t?X.getPlainAddress(t):void 0;e===p.state.activeChain&&(p.state.activeCaipAddress=t),p.setAccountProp("caipAddress",t,e),p.setAccountProp("address",s,e)},setBalance(t,e,s){p.setAccountProp("balance",t,s),p.setAccountProp("balanceSymbol",e,s)},setProfileName(t,e){p.setAccountProp("profileName",t,e)},setProfileImage(t,e){p.setAccountProp("profileImage",t,e)},setUser(t,e){p.setAccountProp("user",t,e)},setAddressExplorerUrl(t,e){p.setAccountProp("addressExplorerUrl",t,e)},setSmartAccountDeployed(t,e){p.setAccountProp("smartAccountDeployed",t,e)},setCurrentTab(t){p.setAccountProp("currentTab",t,p.state.activeChain)},setTokenBalance(t,e){t&&p.setAccountProp("tokenBalance",t,e)},setShouldUpdateToAddress(t,e){p.setAccountProp("shouldUpdateToAddress",t,e)},setAllAccounts(t,e){p.setAccountProp("allAccounts",t,e)},addAddressLabel(t,e,s){const i=p.getAccountProp("addressLabels",s)||new Map;i.set(t,e),p.setAccountProp("addressLabels",i,s)},removeAddressLabel(t,e){const s=p.getAccountProp("addressLabels",e)||new Map;s.delete(t),p.setAccountProp("addressLabels",s,e)},setConnectedWalletInfo(t,e){p.setAccountProp("connectedWalletInfo",t,e,!1)},setPreferredAccountType(t,e){p.setAccountProp("preferredAccountTypes",{...vt.preferredAccountTypes,[e]:t},e)},setPreferredAccountTypes(t){vt.preferredAccountTypes=t},setSocialProvider(t,e){t&&p.setAccountProp("socialProvider",t,e)},setSocialWindow(t,e){p.setAccountProp("socialWindow",t?Ls(t):void 0,e)},setFarcasterUrl(t,e){p.setAccountProp("farcasterUrl",t,e)},async fetchTokenBalance(t){var n,o;vt.balanceLoading=!0;const e=(n=p.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,s=(o=p.state.activeCaipNetwork)==null?void 0:o.chainNamespace,i=p.state.activeCaipAddress,r=i?X.getPlainAddress(i):void 0;if(vt.lastRetry&&!X.isAllowedRetry(vt.lastRetry,30*ve.ONE_SEC_MS))return vt.balanceLoading=!1,[];try{if(r&&e&&s){const c=(await J.getBalance(r,e)).balances.filter(l=>l.quantity.decimals!=="0");return z.setTokenBalance(c,s),vt.lastRetry=void 0,vt.balanceLoading=!1,c}}catch(a){vt.lastRetry=Date.now(),t==null||t(a),$t.showError("Token Balance Unavailable")}finally{vt.balanceLoading=!1}return[]},resetAccount(t){p.resetAccount(t)}},z=bt(au),cu={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const s=p.state.activeCaipNetwork,i=ie.state.data;if(t.id===(s==null?void 0:s.id))return;const n=z.getCaipAddress(p.state.activeChain),o=t.chainNamespace!==p.state.activeChain,a=z.getCaipAddress(t.chainNamespace),l=q.getConnectorId(p.state.activeChain)===B.CONNECTOR_ID.AUTH,d=B.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(u=>u===t.chainNamespace);e||l&&d?ie.push("SwitchNetwork",{...i,network:t}):n&&o&&!a?ie.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):ie.push("SwitchNetwork",{...i,network:t})}},rt=Ae({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),lu={state:rt,subscribe(t){return Xe(rt,()=>t(rt))},subscribeKey(t,e){return Ze(rt,t,e)},async open(t){var o,a;const e=z.state.status==="connected",s=t==null?void 0:t.namespace,i=p.state.activeChain,r=s&&s!==i,n=(o=p.getAccountData(t==null?void 0:t.namespace))==null?void 0:o.caipAddress;if(Y.state.wcBasic?K.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await K.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),q.setFilterByNamespace(t==null?void 0:t.namespace),je.setLoading(!0,s),s&&r){const c=((a=p.getNetworkData(s))==null?void 0:a.caipNetwork)||p.getRequestedCaipNetworks(s)[0];c&&cu.onSwitchNetwork({network:c,ignoreSwitchConfirmation:!0})}else{const c=p.state.noAdapters;O.state.manualWCControl||c&&!n?X.isMobile()?ie.reset("AllWallets"):ie.reset("ConnectingWalletConnectBasic"):t!=null&&t.view?ie.reset(t.view,t.data):n?ie.reset("Account"):ie.reset("Connect")}rt.open=!0,ws.set({open:!0}),Se.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!n}})},close(){const t=O.state.enableEmbedded,e=!!p.state.activeCaipAddress;rt.open&&Se.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),rt.open=!1,ie.reset("Connect"),je.clearLoading(),t?e?ie.replace("Account"):ie.push("Connect"):ws.set({open:!1}),Y.resetUri()}
3,setLoading(t,e){e&&rt.loadingNamespaceMap.set(e,t),rt.loading=t,ws.set({loading:t})},clearLoading(){rt.loadingNamespaceMap.clear(),rt.loading=!1},shake(){rt.shake||(rt.shake=!0,setTimeout(()=>{rt.shake=!1},500))}},je=bt(lu),Xi={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"}]},Mn={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},du={providers:Dc,selectedProvider:null,error:null,purchaseCurrency:Xi,paymentCurrency:Mn,purchaseCurrencies:[Xi],paymentCurrencies:[],quotesLoading:!1},oe=Ae(du),uu={state:oe,subscribe(t){return Xe(oe,()=>t(oe))},subscribeKey(t,e){return Ze(oe,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=p.state.activeChain===B.CHAIN.SOLANA?"SOL":"USDC",s=z.state.address??"",i=new URL(t.url);i.searchParams.append("publicKey",Ud),i.searchParams.append("destinationCurrencyCode",e),i.searchParams.append("walletAddress",s),i.searchParams.append("externalCustomerId",O.state.projectId),oe.selectedProvider={...t,url:i.toString()}}else oe.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=Dc.filter(i=>e.includes(i.name));oe.providers=s}else oe.providers=[]},setPurchaseCurrency(t){oe.purchaseCurrency=t},setPaymentCurrency(t){oe.paymentCurrency=t},setPurchaseAmount(t){Fn.state.purchaseAmount=t},setPaymentAmount(t){Fn.state.paymentAmount=t},async getAvailableCurrencies(){const t=await J.getOnrampOptions();oe.purchaseCurrencies=t.purchaseCurrencies,oe.paymentCurrencies=t.paymentCurrencies,oe.paymentCurrency=t.paymentCurrencies[0]||Mn,oe.purchaseCurrency=t.purchaseCurrencies[0]||Xi,await K.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await K.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){var t,e;oe.quotesLoading=!0;try{const s=await J.getOnrampQuote({purchaseCurrency:oe.purchaseCurrency,paymentCurrency:oe.paymentCurrency,amount:((t=oe.paymentAmount)==null?void 0:t.toString())||"0",network:(e=oe.purchaseCurrency)==null?void 0:e.symbol});return oe.quotesLoading=!1,oe.purchaseAmount=Number(s==null?void 0:s.purchaseAmount.amount),s}catch(s){return oe.error=s.message,oe.quotesLoading=!1,null}finally{oe.quotesLoading=!1}},resetState(){oe.selectedProvider=null,oe.error=null,oe.purchaseCurrency=Xi,oe.paymentCurrency=Mn,oe.purchaseCurrencies=[Xi],oe.paymentCurrencies=[],oe.paymentAmount=void 0,oe.purchaseAmount=void 0,oe.quotesLoading=!1}},Fn=bt(uu),jo=2147483648,hu={convertEVMChainIdToCoinType(t){if(t>=jo)throw new Error("Invalid chainId");return(jo|t)>>>0}},Et=Ae({suggestions:[],loading:!1}),pu={state:Et,subscribe(t){return Xe(Et,()=>t(Et))},subscribeKey(t,e){return Ze(Et,t,e)},async resolveName(t){var e,s;try{return await J.lookupEnsName(t)}catch(i){const r=i;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 J.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{Et.loading=!0,Et.suggestions=[];const e=await J.getEnsNameSuggestions(t);return Et.suggestions=e.suggestions.map(s=>({...s,name:s.name}))||[],Et.suggestions}catch(e){const s=Zi.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{Et.loading=!1}},async getNamesForAddress(t){try{if(!p.state.activeCaipNetwork)return[];const s=W.getEnsFromCacheForAddress(t);if(s)return s;const i=await J.reverseLookupEnsName({address:t});return W.updateEnsCache({address:t,ens:i,timestamp:Date.now()}),i}catch(e){const s=Zi.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){const e=p.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const s=z.state.address,i=q.getAuthConnector();if(!s||!i)throw new Error("Address or auth connector not found");Et.loading=!0;try{const r=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});ie.pushTransactionStack({onCancel(){ie.replace("RegisterAccountName")}});const n=await Y.signMessage(r);Et.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=hu.convertEVMChainIdToCoinType(Number(o));await J.registerEnsName({coinType:a,address:s,signature:n,message:r}),z.setProfileName(t,e.chainNamespace),ie.replace("RegisterAccountNameSuccess")}catch(r){const n=Zi.parseEnsApiError(r,`Error registering name ${t}`);throw ie.replace("RegisterAccountName"),new Error(n)}finally{Et.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){var i,r;const s=t;return((r=(i=s==null?void 0:s.reasons)==null?void 0:i[0])==null?void 0:r.description)||e}},Zi=bt(pu),Qi={getSIWX(){return O.state.siwx},async initializeIfEnabled(){var n;const t=O.state.siwx,e=p.getActiveCaipAddress();if(!(t&&e))return;const[s,i,r]=e.split(":");
3if(p.checkIfSupportedNetwork(s))try{if((await t.getSessions(`${s}:${i}`,r)).length)return;await je.open({view:"SIWXSignMessage"})}catch(o){console.error("SIWXUtil:initializeIfEnabled",o),Se.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await((n=Y._getClient())==null?void 0:n.disconnect().catch(console.error)),ie.reset("Connect"),$t.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=O.state.siwx,e=X.getPlainAddress(p.getActiveCaipAddress()),s=p.getActiveCaipNetwork(),i=Y._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(!i)throw new Error("No ConnectionController client found");try{const r=await t.createMessage({chainId:s.caipNetworkId,accountAddress:e}),n=r.toString();q.getConnectorId(s.chainNamespace)===B.CONNECTOR_ID.AUTH&&ie.pushTransactionStack({});const a=await i.signMessage(n);await t.addSession({data:r,message:n,signature:a}),je.close(),Se.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){const n=this.getSIWXEventProperties();(!je.state.open||ie.state.view==="ApproveTransaction")&&await je.open({view:"SIWXSignMessage"}),n.isSmartAccount?$t.showError("This application might not support Smart Accounts"):$t.showError("Signature declined"),Se.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:n}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){var t;try{const e=this.getSIWX();((t=e==null?void 0:e.getRequired)==null?void 0:t.call(e))?await Y.disconnect():je.close(),ie.reset("Connect"),Se.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getSessions(){const t=O.state.siwx,e=X.getPlainAddress(p.getActiveCaipAddress()),s=p.getActiveCaipNetwork();return t&&e&&s?t.getSessions(s.caipNetworkId,e):[]},async isSIWXCloseDisabled(){var e;const t=this.getSIWX();if(t){const s=ie.state.view==="ApproveTransaction",i=ie.state.view==="SIWXSignMessage";if(s||i)return((e=t.getRequired)==null?void 0:e.call(t))&&(await this.get
3Sessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){var a,c,l;const i=Qi.getSIWX(),r=new Set(e.map(d=>d.split(":")[0]));if(!i||r.size!==1||!r.has("eip155"))return!1;const n=await i.createMessage({chainId:((a=p.getActiveCaipNetwork())==null?void 0:a.caipNetworkId)||"",accountAddress:""}),o=await t.authenticate({nonce:n.nonce,domain:n.domain,uri:n.uri,exp:n.expirationTime,iat:n.issuedAt,nbf:n.notBefore,requestId:n.requestId,version:n.version,resources:n.resources,statement:n.statement,chainId:n.chainId,methods:s,chains:[n.chainId,...e.filter(d=>d!==n.chainId)]});if($t.showLoading("Authenticating...",{autoClose:!1}),z.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:(c=o.session.peer.metadata.icons)==null?void 0:c[0],type:"WALLET_CONNECT"},Array.from(r)[0]),(l=o==null?void 0:o.auths)!=null&&l.length){const d=o.auths.map(u=>{const h=t.client.formatAuthMessage({request:u.p,iss:u.p.iss});return{data:{...u.p,accountAddress:u.p.iss.split(":").slice(-1).join(""),chainId:u.p.iss.split(":").slice(2,4).join(":"),uri:u.p.aud,version:u.p.version||n.version,expirationTime:u.p.exp,issuedAt:u.p.iat,notBefore:u.p.nbf},message:h,signature:u.s.s,cacao:u}});try{await i.setSessions(d),Se.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:Qi.getSIWXEventProperties()})}catch(u){throw console.error("SIWX:universalProviderAuth - failed to set sessions",u),Se.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:Qi.getSIWXEventProperties()}),await t.disconnect().catch(console.error),u}finally{$t.hide()}}return!0},getSIWXEventProperties(){var e,s;const t=p.state.activeChain;return{network:((e=p.state.activeCaipNetwork)==null?void 0:e.caipNetworkId)||"",isSmartAccount:((s=z.state.preferredAccountTypes)==null?void 0:s[t])===Yi.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};var gu=Object.defineProperty,fu=(t,e,s)=>e in t?gu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Wo=(t,e,s)=>fu(t,typeof e!="symbol"?e+"":e,s);let mu=class extends _i{constructor(e){super(),this.opts=e,Wo(this,"protocol","wc"),Wo(this,"version",2)}};var wu=Object.defineProperty,yu=(t,e,s)=>e in t?wu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,bu=(t,e,s)=>yu(t,typeof e!="symbol"?e+"":e,s);let vu=class extends _i{constructor(e,s){super(),this.core=e,this.logger=s,bu(this,"records",new Map)}},Eu=class{constructor(e,s){this.logger=e,this.core=s}};class Cu extends _i{constructor(e,s){super(),this.relayer=e,this.logger=s}}let Iu=class extends _i{constructor(e){super()}},Nu=class{constructor(e,s,i,r){this.core=e,this.logger=s,this.name=i}},Au=class extends _i{constructor(e,s){super(),this.relayer=e,this.logger=s}},_u=class extends _i{constructor(e,s){super(),this.core=e,this.logger=s}},Su=class{constructor(e,s,i){this.core=e,this.logger=s,this.store=i}},Pu=class{constructor(e,s){this.projectId=e,this.logger=s}},Ou=class{constructor(e,s,i){this.core=e,this.logger=s,this.telemetryEnabled=i}};var Tu=Object.defineProperty,ku=(t,e,s)=>e in t?Tu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,zo=(t,e,s)=>ku(t,typeof e!="symbol"?e+"":e,s);let xu=class{constructor(e){this.opts=e,zo(this,"protocol","wc"),zo(this,"version",2)}},Ru=class{constructor(e){this.client=e}};function nr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Ho(t){return nr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Bc="2.23.2";let Di={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${Bc}`};class Ms extends Error{constructor(e,s={}){var a;const i=(()=>{var c;return s.cause instanceof Ms?s.cause.details:(c=s.cause)!=null&&c.message?s.cause.message:s.details})(),r=(()=>s.cause instanceof Ms&&s.cause.docsPath||s.docsPath)(),n=(a=Di.getDocsUrl)==null?void 0:a.call(Di,{...s,docsPath:r}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...Di.version?[`Version: ${Di.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=i,this.docsPath=r,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=Bc}walk(e){return qc(this,e)}}function qc(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?qc(t.cause,e):e?null:t}class jc extends Ms{constructor({size:e,targetSize:s,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}}function Pi(t,{dir:e,size:s=32}={}){return typeof t=="string"?$u(t,{dir:e,size:s}):Uu(t,{dir:e,size:s})}function $u(t,{dir:e,size:s=32}={}){if(s===null)return t;const i=t.replace("0x","");if(i.length>s*2)throw new jc({size:Math.ceil(i.length/2),targetSize:s,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function Uu(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new jc({size:t.length,targetSize:s,type:"bytes"});const i=new Uint8Array(s);for(let r=0;r<s;r++){const n=e==="right";i[n?r:s-r-1]=t[n?r:t.length-r-1]}return i}class Du extends Ms{constructor({max:e,min:s,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${s} to ${e})`:`(above ${s})`}`,{name:"IntegerOutOfRangeError"})}}class Lu extends Ms{constructor({givenSize:e,maxSize:s}
4){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Oi(t,{size:e}){if(Ho(t)>e)throw new Lu({givenSize:Ho(t),maxSize:e})}function Bn(t,e={}){const{signed:s}=e;e.size&&Oi(t,{size:e.size});const i=BigInt(t);if(!s)return i;const r=(t.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function Mu(t,e={}){return Number(Bn(t,e))}const Fu=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function qn(t,e={}){return typeof t=="number"||typeof t=="bigint"?zc(t,e):typeof t=="string"?ju(t,e):typeof t=="boolean"?Bu(t,e):Wc(t,e)}function Bu(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(Oi(s,{size:e.size}),Pi(s,{size:e.size})):s}function Wc(t,e={}){let s="";for(let r=0;r<t.length;r++)s+=Fu[t[r]];const i=`0x${s}`;return typeof e.size=="number"?(Oi(i,{size:e.size}),Pi(i,{dir:"right",size:e.size})):i}function zc(t,e={}){const{signed:s,size:i}=e,r=BigInt(t);let n;i?s?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&s?-n-1n:0;if(n&&r>n||r<o){const c=typeof t=="bigint"?"n":"";throw new Du({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:s,size:i,value:`${t}${c}`})}const a=`0x${(s&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?Pi(a,{size:i}):a}const qu=new TextEncoder;function ju(t,e={}){const s=qu.encode(t);return Wc(s,e)}const Wu=new TextEncoder;function zu(t,e={}){return typeof t=="number"||typeof t=="bigint"?Ku(t,e):typeof t=="boolean"?Hu(t,e):nr(t)?Hc(t,e):Kc(t,e)}function Hu(t,e={}){const s=new Uint8Array(1);return s[0]=Number(t),typeof e.size=="number"?(Oi(s,{size:e.size}),Pi(s,{size:e.size})):s}const Zt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ko(t){if(t>=Zt.zero&&t<=Zt.nine)return t-Zt.zero;if(t>=Zt.A&&t<=Zt.F)return t-(Zt.A-10);if(t>=Zt.a&&t<=Zt.f)return t-(Zt.a-10)}function Hc(t,e={}){let s=t;e.size&&(Oi(s,{size:e.size}),s=Pi(s,{dir:"right",size:e.size}));let i=s.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Ko(i.charCodeAt(a++)),l=Ko(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new Ms(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function Ku(t,e){const s=zc(t,e);return Hc(s)}function Kc(t,e={}){const s=Wu.encode(t);return typeof e.size=="number"?(Oi(s,{size:e.size}),Pi(s,{dir:"right",size:e.size})):s}function Vc(t,e){const s=e||"hex",i=Id(nr(t,{strict:!1})?zu(t):t);return s==="bytes"?i:qn(i)}class Vu 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 i=this.keys().next().value;i&&this.delete(i)}return this}}const dn=new Vu(8192);function Gu(t,e){if(dn.has(`${t}.${e}`))return dn.get(`${t}.${e}`);const s=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),i=Vc(Kc(s),"bytes"),r=(e?s.substring(`${e}0x`.length):s).split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return dn.set(`${t}.${e}`,n),n}function Ju(t){const e=Vc(`0x${t.substring(4)}`).substring(26);return Gu(`0x${e}`)}async function Yu({hash:t,signature:e}){const s=nr(t)?t:qn(t),{secp256k1:i}=await $n(()=>import("./secp256k1-b8c3c050.js"),["assets/secp256k1-b8c3c050.js","assets/index.es-7ecd5e33.js","assets/index-c2fc66f8.js","assets/index-401e0e46.css"]);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:d,v:u,yParity:h}=e,g=Number(h??u),w=Vo(g);return new i.Signature(Bn(l),Bn(d)).addRecoveryBit(w)}const o=nr(e)?e:qn(e),a=Mu(`0x${o.slice(130)}`),c=Vo(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(s.substring(2)).toHex(!1)}`}function Vo(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Xu({hash:t,signature:e}){return Ju(await Yu({hash:t,signature:e}))}const Zu=":";function fi(t){const[e,s]=t.split(Zu);return{namespace:e,reference:s}}function Gc(t,e){return t.includes(":")?[t]:e.chains||[]}var Qu=Object.defineProperty,eh=Object.defineProperties,th=Object.getOwnPropertyDescriptors,Go=Object.getOwnPropertySymbols,sh=Object.prototype.hasOwnProperty,ih=Object.prototype.propertyIsEnumerable,Jo=(t,e,s)=>e in t?Qu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Yo=(t,e)=>{for(var s in e||(e={}))sh.call(e,s)&&Jo(t,s,e[s]);if(Go)for(var s of Go(e))ih.call(e,s)&&Jo(t,s,e[s]);return t},rh=(t,e)=>eh(t,th(e));const nh="ReactNative",mt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},oh="js";function qr(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Is(){return!wi()&&!!kc()&&navigator.product===nh}function ah(){return Is()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function ch(){return Is()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}
4function Ti(){return!qr()&&!!kc()&&!!wi()}function pr(){return Is()?mt.reactNative:qr()?mt.node:Ti()?mt.browser:mt.unknown}function Xo(){var t;try{return Is()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function lh(t,e){const s=new URLSearchParams(t);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&s.set(i,r)}return s.toString()}function dh(t){var e,s;const i=Jc();try{return t!=null&&t.url&&i.url&&new URL(t.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),t.url=i.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(r=>r!=="")),rh(Yo(Yo({},i),t),{url:(t==null?void 0:t.url)||i.url,name:(t==null?void 0:t.name)||i.name,description:(t==null?void 0:t.description)||i.description,icons:(s=t==null?void 0:t.icons)!=null&&s.length&&t.icons.length>0?t.icons:i.icons})}catch(r){return console.warn("Error populating app metadata",r),t||i}}function Jc(){return pd()||{name:"",description:"",url:"",icons:[""]}}function uh(){if(pr()===mt.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:s,Version:i}=global.Platform;return[s,i].join("-")}const t=gd();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 hh(){var t;const e=pr();return e===mt.browser?[e,((t=fd())==null?void 0:t.host)||"unknown"].join(":"):e}function Yc(t,e,s){const i=uh(),r=hh();return[[t,e].join("-"),[oh,s].join("-"),i,r].join("/")}function ph({protocol:t,version:e,relayUrl:s,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d=Yc(t,e,i),u={auth:r,ua:d,projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=lh(l[1]||"",u);return l[0]+"?"+h}function Us(t,e){return t.filter(s=>e.includes(s)).length===t.length}function jn(t){return Object.fromEntries(t.entries())}function Wn(t){return new Map(Object.entries(t))}function Os(t=U.FIVE_MINUTES,e){const s=U.toMiliseconds(t||U.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),i=a,r=c})}}function ms(t,e,s){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(s)),e);try{const o=await t;i(o)}catch(o){r(o)}clearTimeout(n)})}function Xc(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 gh(t){return Xc("topic",t)}function fh(t){return Xc("id",t)}function Zc(t){const[e,s]=t.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")i.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))i.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return i}function Ue(t,e){return U.fromMiliseconds((e||Date.now())+U.toMiliseconds(t))}function ps(t){return Date.now()>=U.toMiliseconds(t)}function pe(t,e){return`${t}${e?`:${e}`:""}`}function Ht(t=[],e=[]){return[...new Set([...t,...e])]}async function mh({id:t,topic:e,wcDeepLink:s}){var i;try{if(!s)return;const r=typeof s=="string"?JSON.parse(s):s,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=wh(n,t,e),a=pr();if(a===mt.browser){if(!((i=wi())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}yh(o)}else a===mt.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(r){console.error(r)}}function wh(t,e,s){const i=`requestId=${e}&sessionTopic=${s}`;
vendor: 4,322 bytes, line 4
4t.endsWith("/")&&(t=t.slice(0,-1));let r=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${Ch(i,!0)}`}else r=`${r}/wc?${i}`;return r}function yh(t){let e="_self";Eh()?e="_top":(vh()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function bh(t,e){let s="";try{if(Ti()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(i){console.error(i)}return s}function Zo(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),i=s.indexOf(e);return s[i+2]}function Qo(){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 vo(){return typeof process<"u"&&{}.IS_VITEST==="true"}function vh(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Eh(){try{return window.self!==window.top}catch{return!1}}function Ch(t,e=!1){const s=Buffer.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function Qc(t){return Buffer.from(t,"base64").toString("utf-8")}function Ih(t){return new Promise(e=>setTimeout(e,t))}function or(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Nh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function gr(t,...e){if(!Nh(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 Eo(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");or(t.outputLen),or(t.blockLen)}function bi(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 el(t,e){gr(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const Nr=BigInt(2**32-1),ea=BigInt(32);function Ah(t,e=!1){return e?{h:Number(t&Nr),l:Number(t>>ea&Nr)}:{h:Number(t>>ea&Nr)|0,l:Number(t&Nr)|0}}function _h(t,e=!1){let s=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let r=0;r<t.length;r++){const{h:n,l:o}=Ah(t[r],e);[s[r],i[r]]=[n,o]}return[s,i]}const Sh=(t,e,s)=>t<<s|e>>>32-s,Ph=(t,e,s)=>e<<s|t>>>32-s,Oh=(t,e,s)=>e<<s-32|t>>>64-s,Th=(t,e,s)=>t<<s-32|e>>>64-s,Ks=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function kh(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function un(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Mt(t,e){return t<<32-e|t>>>e}const ta=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xh(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function sa(t){for(let e=0;e<t.length;e++)t[e]=xh(t[e])}function Rh(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function vi(t){return typeof t=="string"&&(t=Rh(t)),gr(t),t}function $h(...t){let e=0;for(let i=0;i<t.length;i++){const r=t[i];gr(r),e+=r.length}const s=new Uint8Array(e);for(let i=0,r=0;i<t.length;i++){const n=t[i];s.set(n,r),r+=n.length}return s}let Co=class{clone(){return this._cloneInto()}};function tl(t){const e=i=>t().update(vi(i)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function ki(t=32){if(Ks&&typeof Ks.getRandomValues=="function")return Ks.getRandomValues(new Uint8Array(t));if(Ks&&typeof Ks.randomBytes=="function")return Ks.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const sl=[],il=[],rl=[],Uh=BigInt(0),Li=BigInt(1),Dh=BigInt(2),Lh=BigInt(7),Mh=BigInt(256),Fh=BigInt(113);for(let t=0,e=Li,s=1,i=0;t<24;t++){[s,i]=[i,(2*s+3*i)%5],sl.push(2*(5*i+s)),il.push((t+1)*(t+2)/2%64);let r=Uh;for(let n=0;n<7;n++)e=(e<<Li^(e>>Lh)*Fh)%Mh,e&Dh&&(r^=Li<<(Li<<BigInt(n))-Li);rl.push(r)}const[Bh,qh]=_h(rl,!0),ia=(t,e,s)=>s>32?Oh(t,e,s):Sh(t,e,s),ra=(t,e,s)=>s>32?Th(t,e,s):Ph(t,e,s);function jh(t,e=24){const s=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;
4o++)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=ia(l,d,1)^s[a],h=ra(l,d,1)^s[a+1];for(let g=0;g<50;g+=10)t[o+g]^=u,t[o+g+1]^=h}let r=t[2],n=t[3];for(let o=0;o<24;o++){const a=il[o],c=ia(r,n,a),l=ra(r,n,a),d=sl[o];r=t[d],n=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]^=Bh[i],t[1]^=qh[i]}s.fill(0)}let Wh=class nl extends Co{constructor(e,s,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=s,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,or(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=kh(this.state)}keccak(){ta||sa(this.state32),jh(this.state32,this.rounds),ta||sa(this.state32),this.posOut=0,this.pos=0}update(e){bi(this);const{blockLen:s,state:i}=this;e=vi(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:i,blockLen:r}=this;e[i]^=s,s&128&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){bi(this,!1),gr(e),this.finish();const s=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-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 or(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(el(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,this.state.fill(0)}_cloneInto(e){const{blockLen:s,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new nl(s,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const zh=(t,e,s)=>tl(()=>new Wh(e,t,s)),Hh=zh(1,136,256/8),Kh="https://rpc.walletconnect.org/v1";function ol(t){const e=`�Ethereum Signed Message:
5${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Hh(s)).toString("hex")}async function Vh(t,e,s,i,r,n){switch(s.t){case"eip191":return await Gh(t,e,s.s);case"eip1271":return await Jh(t,e,s.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}async function Gh(t,e,s){return(await Xu({hash:ol(e),signature:s})).toLowerCase()===t.toLowerCase()}async function Jh(t,e,s,i,r,n){const o=fi(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l="0000000000000000000000000000000000000000000000000000000000000041",d=s.substring(2),u=ol(e).substring(2),h=a+u+c+l+d,g=await fetch(`${n||Kh}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:Yh(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:w}=await g.json();return w?w.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Yh(){return Date.now()+Math.floor(Math.random()*1e3)}function Xh(t){const e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);const i=s[0];if(i===0)throw new Error("No signatures found");const r=1+i*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 n=Buffer.from(t,"base64").slice(1,65);return xc.encode(n)}var Zh=Object.defineProperty,Qh=Object.defineProperties,ep=Object.getOwnPropertyDescriptors,na=Object.getOwnPropertySymbols,tp=Object.prototype.hasOwnProperty,sp=Object.prototype.propertyIsEnumerable,oa=(t,e,s)=>e in t?Zh(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ip=(t,e)=>{for(var s in e||(e={}))tp.call(e,s)&&oa(t,s,e[s]);if(na)for(var s of na(e))sp.call(e,s)&&oa(t,s,e[s]);return t},rp=(t,e)=>Qh(t,ep(e));const np="did:pkh:",Io=t=>t==null?void 0:t.split(":"),op=t=>{const e=t&&Io(t);if(e)return t.includes(np)?e[3]:e[1]},zn=t=>{const e=t&&Io(t);if(e)return e[2]+":"+e[3]},jr=t=>{const e=t&&Io(t);if(e)return e.pop()};async function aa(t){const{cacao:e,projectId:s}=t,{s:i,p:r}=e,n=al(r,r.iss),o=jr(r.iss);return await Vh(o,n,i,zn(r.iss),s)}const al=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,i=jr(e);
vendor: 28,842 bytes, lines 5-7
5if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=t.statement||void 0;const n=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${op(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,g=t.resources?`Resources:${t.resources.map(m=>`
6- ${m}`).join("")}`:void 0,w=Ur(t.resources);if(w){const m=ar(w);r=fp(r,m)}return[s,i,"",r,"",n,o,a,c,l,d,u,h,g].filter(m=>m!=null).join(`
7`)};function ap(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function cp(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function Fs(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 i=t.att[s];if(Array.isArray(i))throw new Error(`Resource must be an object: ${s}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${s}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${s}`);Object.keys(i).forEach(r=>{const n=i[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function lp(t,e,s,i={}){return s==null||s.sort((r,n)=>r.localeCompare(n)),{att:{[t]:dp(e,s,i)}}}function dp(t,e,s={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const i=e.map(r=>({[`${t}/${r}`]:[s]}));return Object.assign({},...i)}function cl(t){return Fs(t),`urn:recap:${ap(t).replace(/=/g,"")}`}function ar(t){const e=cp(t.replace("urn:recap:",""));return Fs(e),e}function up(t,e,s){const i=lp(t,e,s);return cl(i)}function hp(t){return t&&t.includes("urn:recap:")}function pp(t,e){const s=ar(t),i=ar(e),r=gp(s,i);return cl(r)}function gp(t,e){Fs(t),Fs(e);const s=Object.keys(t.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),i={att:{}};return s.forEach(r=>{var n,o;Object.keys(((n=t.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;i.att[r]=rp(ip({},i.att[r]),{[a]:((c=t.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),i}function fp(t="",e){Fs(e);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(s))return t;const i=[];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}'.`));i.push(d.join(", ").replace(".,","."))});const n=i.join(" "),o=`${s}${n}`;return`${t?t+" ":""}${o}`}function ca(t){var e;const s=ar(t);Fs(s);const i=(e=s.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function la(t){const e=ar(t);Fs(e);const s=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&s.push(r[0].chains)})}),[...new Set(s.flat())]}function Ur(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return hp(e)?e:void 0}function hn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ll(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ft(t,...e){if(!ll(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 da(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 mp(t,e){ft(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function ua(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const ys=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),wp=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),yp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!yp)throw new Error("Non little-endian hardware is not supported");function bp(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Hn(t){if(typeof t=="string")t=bp(t);else if(ll(t))t=Kn(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function vp(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Ep(t,e){if(t.length!==e.length)return!1;let s=0;for(let i=0;i<t.length;i++)s|=t[i]^e[i];return s===0}const Cp=(t,e)=>{function s(i,...r){if(ft(i),t.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?ft(l):ft(l,t.nonceLength)}const n=t.tagLength;n&&r[1]!==void 0&&ft(r[1]);const o=e(i,...r),a=(l,d)=>{if(d!==void 0){if(l!==2)throw new Error("cipher output not supported");ft(d)}};let c=!1;return{encrypt(l,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ft(l),a(o.encrypt.length,d),o.encrypt(l,d)},decrypt(l,d){if(ft(l),n&&l.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,d),o.decrypt(l,d)}}}return Object.assign(s,t),s};function ha(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&&!Ip(e))throw new Error("invalid output, must be aligned");return e}function pa(t,e,s,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(s>>r&n),a=Number(s&n),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}function Ip(t){return t.byteOffset%4===0}function Kn(t){return Uint8Array.from(t)}function Ei(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const dl=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),Np=dl("expand 16-byte k"),Ap=dl("expand 32-byte k"),_p=ys(Np),Sp=ys(Ap);function ce(t,e){return t<<e|t>>>32-e}function Vn(t){return t.byteOffset%4===0}const Ar=64,Pp=16,ul=2**32-1,ga=new Uint32Array;function Op(t,e,s,i,r,n,o,a){const c=r.length,l=new Uint8Array(Ar),d=ys(l),u=Vn(r)&&Vn(n),h=u?ys(r):ga,g=u?ys(n):ga;for(let w=0;w<c;o++){if(t(e,s,i,d,o,a),o>=ul)throw new Error("arx: counter overflow");const m=Math.min(Ar,c-w);if(u&&m===Ar){const f=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<Pp;y++)b=f+y,g[b]=h[b]^d[y];w+=Ar;continue}for(let f=0,y;f<m;f++)y=w+f,n[y]=r[y]^l[f];w+=m}}function Tp(t,e){const{allowShortKeys:s,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=vp({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return hn(r),hn(o),ua(n),ua(s),(a,c,l,d,u=0)=>{ft(a),ft(c),ft(l);const h=l.length;if(d===void 0&&(d=new Uint8Array(h)),ft(d),hn(u),u<0||u>=ul)throw new Error("arx: counter overflow");if(d.length<h)throw new Error(`arx: output (${d.length}) is shorter than data (${h})`);const g=[];let w=a.length,m,f;if(w===32)g.push(m=Kn(a)),f=Sp;else if(w===16&&s)m=new Uint8Array(32),m.set(a),m.set(a,16),f=_p,g.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);Vn(c)||g.push(c=Kn(c));const y=ys(m);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(f,y,ys(c.subarray(0,16)),y),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 _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,g.push(c)}const E=ys(c);return Op(t,f,y,E,l,d,u,o),Ei(...g),d}}const ze=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class kp{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=Hn(e),ft(e,32);const s=ze(e,0),i=ze(e,2),r=ze(e,4),n=ze(e,6),o=ze(e,8),a=ze(e,10),c=ze(e,12),l=ze(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>7|n<<9)&8191,this.r[4]=(n>>>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]=ze(e,16+2*d)}process(e,s,i=!1){const r=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],l=o[2],d=o[3],u=o[4],h=o[5],g=o[6],w=o[7],m=o[8],f=o[9],y=ze(e,s+0),b=ze(e,s+2),E=ze(e,s+4),_=ze(e,s+6),x=ze(e,s+8),P=ze(e,s+10),S=ze(e,s+12),D=ze(e,s+14);let v=n[0]+(y&8191),R=n[1]+((y>>>13|b<<3)&8191),C=n[2]+((b>>>10|E<<6)&8191),L=n[3]+((E>>>7|_<<9)&8191),H=n[4]+((_>>>4|x<<12)&8191),I=n[5]+(x>>>1&8191),T=n[6]+((x>>>14|P<<2)&8191),A=n[7]+((P>>>11|S<<5)&8191),F=n[8]+((S>>>8|D<<8)&8191),j=n[9]+(D>>>5|r),k=0,G=k+v*a+R*(5*f)+C*(5*m)+L*(5*w)+H*(5*g);k=G>>>13,G&=8191,G+=I*(5*h)+T*(5*u)+A*(5*d)+F*(5*l)+j*(5*c),k+=G>>>13,G&=8191;let Q=k+v*c+R*a+C*(5*f)+L*(5*m)+H*(5*w);k=Q>>>13,Q&=8191,Q+=I*(5*g)+T*(5*h)+A*(5*u)+F*(5*d)+j*(5*l),k+=Q>>>13,Q&=8191;let se=k+v*l+R*c+C*a+L*(5*f)+H*(5*m);k=se>>>13,se&=8191,se+=I*(5*w)+T*(5*g)+A*(5*h)+F*(5*u)+j*(5*d),k+=se>>>13,se&=8191;let Ee=k+v*d+R*l+C*c+L*a+H*(5*f);k=Ee>>>13,Ee&=8191,Ee+=I*(5*m)+T*(5*w)+A*(5*g)+F*(5*h)+j*(5*u),k+=Ee>>>13,Ee&=8191;let he=k+v*u+R*d+C*l+L*c+H*a;k=he>>>13,he&=8191,he+=I*(5*f)+T*(5*m)+A*(5*w)+F*(5*g)+j*(5*h),k+=he>>>13,he&=8191;let Oe=k+v*h+R*u+C*d+L*l+H*c;k=Oe>>>13,Oe&=8191,Oe+=I*a+T*(5*f)+A*(5*m)+F*(5*w)+j*(5*g),k+=Oe>>>13,Oe&=8191;let Le=k+v*g+R*h+C*u+L*d+H*l;k=Le>>>13,Le&=8191,Le+=I*c+T*a+A*(5*f)+F*(5*m)+j*(5*w),k+=Le>>>13,Le&=8191;let Je=k+v*w+R*g+C*h+L*u+H*d;k=Je>>>13,Je&=8191,Je+=I*l+T*c+A*a+F*(5*f)+j*(5*m),k+=Je>>>13,Je&=8191;let xe=k+v*m+R*w+C*g+L*h+H*u;k=xe>>>13,xe&=8191,xe+=I*d+T*l+A*c+F*a+j*(5*f),k+=xe>>>13,xe&=8191;let Re=k+v*f+R*m+C*w+L*g+H*h;k=Re>>>13,Re&=8191,Re+=I*u+T*d+A*l+F*c+j*a,k+=Re>>>13,Re&=8191,k=(k<<2)+k|0,k=k+G|0,G=k&8191,k=k>>>13,Q+=k,n[0]=G,n[1]=Q,n[2]=se,n[3]=Ee,n[4]=he,n[5]=Oe,n[6]=Le,n[7]=Je,n[8]=xe,n[9]=Re}finalize(){const{h:e,pad:s}=this,i=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,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+r,r=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[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;Ei(i)}update(e){da(this);const{buffer:s,blockLen:i}=this;e=Hn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){for(;i<=r-n;n+=i)this.process(e,n);continue}s.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){Ei(this.h,this.r,this.buffer,this.pad)}digestInto(e){da(this),mp(e,this),this.finished=!0;const{buffer:s,h:i}=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 n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const i=e.slice(0,s);return this.destroy(),i}}function xp(t){const e=(i,r)=>t(r).update(Hn(i)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=i=>t(i),e}const Rp=xp(t=>new kp(t));function $p(t,e,s,i,r,n=20){let o=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],h=e[2],g=e[3],w=e[4],m=e[5],f=e[6],y=e[7],b=r,E=s[0],_=s[1],x=s[2],P=o,S=a,D=c,v=l,R=d,C=u,L=h,H=g,I=w,T=m,A=f,F=y,j=b,k=E,G=_,Q=x;for(let Ee=0;Ee<n;Ee+=2)P=P+R|0,j=ce(j^P,16),I=I+j|0,R=ce(R^I,12),P=P+R|0,j=ce(j^P,8),I=I+j|0,R=ce(R^I,7),S=S+C|0,k=ce(k^S,16),T=T+k|0,C=ce(C^T,12),S=S+C|0,k=ce(k^S,8),T=T+k|0,C=ce(C^T,7),D=D+L|0,G=ce(G^D,16),A=A+G|0,L=ce(L^A,12),D=D+L|0,G=ce(G^D,8),A=A+G|0,L=ce(L^A,7),v=v+H|0,Q=ce(Q^v,16),F=F+Q|0,H=ce(H^F,12),v=v+H|0,Q=ce(Q^v,8),F=F+Q|0,H=ce(H^F,7),P=P+C|0,Q=ce(Q^P,16),A=A+Q|0,C=ce(C^A,12),P=P+C|0,Q=ce(Q^P,8),A=A+Q|0,C=ce(C^A,7),S=S+L|0,j=ce(j^S,16),F=F+j|0,L=ce(L^F,12),S=S+L|0,j=ce(j^S,8),F=F+j|0,L=ce(L^F,7),D=D+H|0,k=ce(k^D,16),I=I+k|0,H=ce(H^I,12),D=D+H|0,k=ce(k^D,8),I=I+k|0,H=ce(H^I,7),v=v+R|0,G=ce(G^v,16),T=T+G|0,R=ce(R^T,12),v=v+R|0,G=ce(G^v,8),T=T+G|0,R=ce(R^T,7);let se=0;i[se++]=o+P|0,i[se++]=a+S|0,i[se++]=c+D|0,i[se++]=l+v|0,i[se++]=d+R|0,i[se++]=u+C|0,i[se++]=h+L|0,i[se++]=g+H|0,i[se++]=w+I|0,i[se++]=m+T|0,i[se++]=f+A|0,i[se++]=y+F|0,i[se++]=b+j|0,i[se++]=E+k|0,i[se++]=_+G|0,i[se++]=x+Q|0}const Up=Tp($p,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Dp=new Uint8Array(16),fa=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(Dp.subarray(s))},Lp=new Uint8Array(32);function ma(t,e,s,i,r){const n=t(e,s,Lp),o=Rp.create(n);r&&fa(o,r),fa(o,i);const a=new Uint8Array(16),c=wp(a);pa(c,0,BigInt(r?r.length:0),!0),pa(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return Ei(n,a),l}const Mp=t=>(e,s,i)=>({encrypt(r,n){const o=r.length;n=ha(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);t(e,s,a,a,1);const c=ma(t,e,s,a,i);return n.set(c,o),Ei(c),n},decrypt(r,n){n=ha(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=ma(t,e,s,o,i);if(!Ep(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),t(e,s,n,n,1),Ei(c),n}}),hl=Cp({blockSize:64,nonceLength:12,tagLength:16},Mp(Up));let pl=class extends Co{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,Eo(e);const i=vi(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,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return bi(this),this.iHash.update(e),this}digestInto(e){bi(this),gr(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:i,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Jr=(t,e,s)=>new pl(t,e).update(s).digest();Jr.create=(t,e)=>new pl(t,e);function Fp(t,e,s){return Eo(t),s===void 0&&(s=new Uint8Array(t.outputLen)),Jr(t,vi(s),vi(e))}const pn=new Uint8Array([0]),wa=new Uint8Array;function Bp(t,e,s,i=32){if(Eo(t),or(i),i>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/t.outputLen);s===void 0&&(s=wa);const n=new Uint8Array(r*t.outputLen),o=Jr.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)pn[0]=l+1,a.update(l===0?wa:c).update(s).update(pn).digestInto(c),n.set(c,t.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),pn.fill(0),n.slice(0,i)}const qp=(t,e,s,i,r)=>Bp(t,Fp(t,e,s),i,r);function jp(t,e,s,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(s>>r&n),a=Number(s&n),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}function Wp(t,e,s){return t&e^~t&s}function zp(t,e,s){return t&e^t&s^e&s}let Hp=class extends Co{constructor(e,s,i,r){super(),this.blockLen=e,this.outputLen=s,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=un(this.buffer)}update(e){bi(this);const{view:s,buffer:i,blockLen:r}=this;e=vi(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=un(e);for(;r<=n-o;o+=r)this.process(c,o);continue}i.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){bi(this),el(e,this),this.finished=!0;const{buffer:s,view:i,blockLen:r,isLE:n}=this;let{pos:o}=this;s[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(i,0),o=0);for(let u=o;u<r;u++)s[u]=0;jp(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=un(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],n)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const i=e.slice(0,s);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:i,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%s&&e.buffer.set(i),e}};const Kp=new Uint32Array([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]),ds=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),us=new Uint32Array(64);class Vp extends Hp{constructor(){super(64,32,8,!1),this.A=ds[0]|0,this.B=ds[1]|0,this.C=ds[2]|0,this.D=ds[3]|0,this.E=ds[4]|0,this.F=ds[5]|0,this.G=ds[6]|0,this.H=ds[7]|0}get(){const{A:e,B:s,C:i,D:r,E:n,F:o,G:a,H:c}=this;return[e,s,i,r,n,o,a,c]}set(e,s,i,r,n,o,a,c){this.A=e|0,this.B=s|0,this.C=i|0,this.D=r|0,this.E=n|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)us[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const h=us[u-15],g=us[u-2],w=Mt(h,7)^Mt(h,18)^h>>>3,m=Mt(g,17)^Mt(g,19)^g>>>10;us[u]=m+us[u-7]+w+us[u-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=Mt(a,6)^Mt(a,11)^Mt(a,25),g=d+h+Wp(a,c,l)+Kp[u]+us[u]|0,w=(Mt(i,2)^Mt(i,13)^Mt(i,22))+zp(i,r,n)|0;d=l,l=c,c=a,a=o+g|0,o=n,n=r,r=i,i=g+w|0}i=i+this.A|0,r=r+this.B|0,n=n+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(i,r,n,o,a,c,l,d)}roundClean(){us.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const fr=tl(()=>new Vp);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Yr=BigInt(0),Xr=BigInt(1),Gp=BigInt(2);function Bs(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function mr(t){if(!Bs(t))throw new Error("Uint8Array expected")}function Ci(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Jp=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ii(t){mr(t);let e="";for(let s=0;s<t.length;s++)e+=Jp[t[s]];return e}function ui(t){const e=t.toString(16);return e.length&1?"0"+e:e}function No(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Yr:BigInt("0x"+t)}const Qt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ya(t){if(t>=Qt._0&&t<=Qt._9)return t-Qt._0;if(t>=Qt.A&&t<=Qt.F)return t-(Qt.A-10);if(t>=Qt.a&&t<=Qt.f)return t-(Qt.a-10)}function Ni(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(s);for(let r=0,n=0;r<s;r++,n+=2){const o=ya(t.charCodeAt(n)),a=ya(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[r]=o*16+a}return i}function Ds(t){return No(Ii(t))}function cr(t){return mr(t),No(Ii(Uint8Array.from(t).reverse()))}function Ai(t,e){return Ni(t.toString(16).padStart(e*2,"0"))}function Zr(t,e){return Ai(t,e).reverse()}function Yp(t){return Ni(ui(t))}function gt(t,e,s){let i;if(typeof e=="string")try{i=Ni(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(Bs(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const r=i.length;if(typeof s=="number"&&r!==s)throw new Error(t+" of length "+s+" expected, got "+r);return i}function lr(...t){let e=0;for(let i=0;i<t.length;i++){const r=t[i];mr(r),e+=r.length}const s=new Uint8Array(e);for(let i=0,r=0;i<t.length;i++){const n=t[i];s.set(n,r),r+=n.length}return s}function Xp(t,e){if(t.length!==e.length)return!1;let s=0;for(let i=0;i<t.length;i++)s|=t[i]^e[i];return s===0}function Zp(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const gn=t=>typeof t=="bigint"&&Yr<=t;function Qr(t,e,s){return gn(t)&&gn(e)&&gn(s)&&e<=t&&t<s}function rs(t,e,s,i){if(!Qr(e,s,i))throw new Error("expected valid "+t+": "+s+" <= n < "+i+", got "+e)}function gl(t){let e;for(e=0;t>Yr;t>>=Xr,e+=1);return e}function Qp(t,e){return t>>BigInt(e)&Xr}function eg(t,e,s){return t|(s?Xr:Yr)<<BigInt(e)}const Ao=t=>(Gp<<BigInt(t-1))-Xr,fn=t=>new Uint8Array(t),ba=t=>Uint8Array.from(t);function fl(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");let i=fn(t),r=fn(t),n=0;const o=()=>{i.fill(1),r.fill(0),n=0},a=(...d)=>s(r,i,...d),c=(d=fn())=>{r=a(ba([0]),d),i=a(),d.length!==0&&(r=a(ba([1]),d),i=a())},l=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const u=[];for(;d<e;){i=a();const h=i.slice();u.push(h),d+=i.length}return lr(...u)};return(d,u)=>{o(),c(d);let h;for(;!(h=u(l()));)c();return o(),h}}const tg={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Bs(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function xi(t,e,s={}){const i=(r,n,o)=>{const a=tg[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[r];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))i(r,n,!1);for(const[r,n]of Object.entries(s))i(r,n,!0);return t}const sg=()=>{throw new Error("not implemented")};function Gn(t){const e=new WeakMap;return(s,...i)=>{const r=e.get(s);if(r!==void 0)return r;const n=t(s,...i);return e.set(s,n),n}}var ig=Object.freeze({__proto__:null,isBytes:Bs,abytes:mr,abool:Ci,bytesToHex:Ii,numberToHexUnpadded:ui,hexToNumber:No,hexToBytes:Ni,bytesToNumberBE:Ds,bytesToNumberLE:cr,numberToBytesBE:Ai,numberToBytesLE:Zr,numberToVarBytesBE:Yp,ensureBytes:gt,concatBytes:lr,equalBytes:Xp,utf8ToBytes:Zp,inRange:Qr,aInRange:rs,bitLen:gl,bitGet:Qp,bitSet:eg,bitMask:Ao,createHmacDrbg:fl,validateObject:xi,notImplemented:sg,memoized:Gn});const We=BigInt(0),Pe=BigInt(1),ks=BigInt(2),rg=BigInt(3),Jn=BigInt(4),va=BigInt(5),Ea=BigInt(8);function ct(t,e){const s=t%e;return s>=We?s:e+s}function ml(t,e,s){if(e<We)throw new Error("invalid exponent, negatives unsupported");if(s<=We)throw new Error("invalid modulus");if(s===Pe)return We;let i=Pe;for(;e>We;)e&Pe&&(i=i*t%s),t=t*t%s,e>>=Pe;return i}function xt(t,e,s){let i=t;for(;e-- >We;)i*=i,i%=s;return i}function Yn(t,e){if(t===We)throw new Error("invert: expected non-zero number");if(e<=We)throw new Error("invert: expected positive modulus, got "+e);let s=ct(t,e),i=e,r=We,n=Pe;for(;s!==We;){const o=i/s,a=i%s,c=r-n*o;i=s,s=a,r=n,n=c}if(i!==Pe)throw new Error("invert: does not exist");return ct(r,e)}function ng(t){const e=(t-Pe)/ks;let s,i,r;for(s=t-Pe,i=0;s%ks===We;s/=ks,i++);for(r=ks;r<t&&ml(r,e,t)!==t-Pe;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+Pe)/Jn;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const n=(s+Pe)/ks;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,l=o.pow(o.mul(o.ONE,r),s),d=o.pow(a,n),u=o.pow(a,s);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let h=1;for(let w=o.sqr(u);h<c&&!o.eql(w,o.ONE);h++)w=o.sqr(w);const g=o.pow(l,Pe<<BigInt(c-h-1));l=o.sqr(g),d=o.mul(d,g),u=o.mul(u,l),c=h}return d}}function og(t){if(t%Jn===rg){const e=(t+Pe)/Jn;return function(s,i){const r=s.pow(i,e);if(!s.eql(s.sqr(r),i))throw new Error("Cannot find square root");return r}}if(t%Ea===va){const e=(t-va)/Ea;return function(s,i){const r=s.mul(i,ks),n=s.pow(r,e),o=s.mul(i,n),a=s.mul(s.mul(o,ks),n),c=s.mul(o,s.sub(a,s.ONE));if(!s.eql(s.sqr(c),i))throw new Error("Cannot find square root");return c}}return ng(t)}const ag=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function cg(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},s=ag.reduce((i,r)=>(i[r]="function",i),e);return xi(t,s)}function lg(t,e,s){if(s<We)throw new Error("invalid exponent, negatives unsupported");if(s===We)return t.ONE;if(s===Pe)return e;let i=t.ONE,r=e;for(;s>We;)s&Pe&&(i=t.mul(i,r)),r=t.sqr(r),s>>=Pe;return i}function dg(t,e){const s=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(s[a]=n,t.mul(n,o)),t.ONE),r=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(s[a]=t.mul(n,s[a]),t.mul(n,o)),r),s}function wl(t,e){const s=e!==void 0?e:t.toString(2).length,i=Math.ceil(s/8);return{nBitLength:s,nByteLength:i}}function yl(t,e,s=!1,i={}){if(t<=We)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:r,nByteLength:n}=wl(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:s,BITS:r,BYTES:n,MASK:Ao(r),ZERO:We,ONE:Pe,create:c=>ct(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return We<=c&&c<t},is0:c=>c===We,isOdd:c=>(c&Pe)===Pe,neg:c=>ct(-c,t),eql:(c,l)=>c===l,sqr:c=>ct(c*c,t),add:(c,l)=>ct(c+l,t),sub:(c,l)=>ct(c-l,t),mul:(c,l)=>ct(c*l,t),pow:(c,l)=>lg(a,c,l),div:(c,l)=>ct(c*Yn(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Yn(c,t),sqrt:i.sqrt||(c=>(o||(o=og(t)),o(a,c))),invertBatch:c=>dg(a,c),cmov:(c,l,d)=>d?l:c,toBytes:c=>s?Zr(c,n):Ai(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return s?cr(c):Ds(c)}});return Object.freeze(a)}function bl(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 vl(t){const e=bl(t);return e+Math.ceil(e/2)}function ug(t,e,s=!1){const i=t.length,r=bl(e),n=vl(e);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=s?cr(t):Ds(t),a=ct(o,e-Pe)+Pe;return s?Zr(a,r):Ai(a,r)}const Ca=BigInt(0),_r=BigInt(1);function mn(t,e){const s=e.negate();return t?s:e}function El(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function wn(t,e){El(t,e);const s=Math.ceil(e/t)+1,i=2**(t-1);return{windows:s,windowSize:i}}function hg(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,i)=>{if(!(s instanceof e))throw new Error("invalid point at index "+i)})}function pg(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,i)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+i)})}const yn=new WeakMap,Cl=new WeakMap;function bn(t){return Cl.get(t)||1}function gg(t,e){return{constTimeNegate:mn,hasPrecomputes(s){return bn(s)!==1},unsafeLadder(s,i,r=t.ZERO){let n=s;for(;i>Ca;)i&_r&&(r=r.add(n)),n=n.double(),i>>=_r;return r}
7,precomputeWindow(s,i){const{windows:r,windowSize:n}=wn(i,e),o=[];let a=s,c=a;for(let l=0;l<r;l++){c=a,o.push(c);for(let d=1;d<n;d++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(s,i,r){const{windows:n,windowSize:o}=wn(s,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**s-1),d=2**s,u=BigInt(s);for(let h=0;h<n;h++){const g=h*o;let w=Number(r&l);r>>=u,w>o&&(w-=d,r+=_r);const m=g,f=g+Math.abs(w)-1,y=h%2!==0,b=w<0;w===0?c=c.add(mn(y,i[m])):a=a.add(mn(b,i[f]))}return{p:a,f:c}},wNAFUnsafe(s,i,r,n=t.ZERO){const{windows:o,windowSize:a}=wn(s,e),c=BigInt(2**s-1),l=2**s,d=BigInt(s);for(let u=0;u<o;u++){const h=u*a;if(r===Ca)break;let g=Number(r&c);if(r>>=d,g>a&&(g-=l,r+=_r),g===0)continue;let w=i[h+Math.abs(g)-1];g<0&&(w=w.negate()),n=n.add(w)}return n},getPrecomputes(s,i,r){let n=yn.get(i);return n||(n=this.precomputeWindow(i,s),s!==1&&yn.set(i,r(n))),n},wNAFCached(s,i,r){const n=bn(s);return this.wNAF(n,this.getPrecomputes(n,s,r),i)},wNAFCachedUnsafe(s,i,r,n){const o=bn(s);return o===1?this.unsafeLadder(s,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,s,r),i,n)},setWindowSize(s,i){El(i,e),Cl.set(s,i),yn.delete(s)}}}function fg(t,e,s,i){if(hg(s,t),pg(i,e),s.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const r=t.ZERO,n=gl(BigInt(s.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r),l=Math.floor((e.BITS-1)/o)*o;let d=r;for(let u=l;u>=0;u-=o){c.fill(r);for(let g=0;g<i.length;g++){const w=i[g],m=Number(w>>BigInt(u)&BigInt(a));c[m]=c[m].add(s[g])}let h=r;for(let g=c.length-1,w=r;g>0;g--)w=w.add(c[g]),h=h.add(w);if(d=d.add(h),u!==0)for(let g=0;g<o;g++)d=d.double()}return d}function Il(t){return cg(t.Fp),xi(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...wl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Vs=BigInt(0),vn=BigInt(1);function mg(t){return xi(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function wg(t){const e=mg(t),{P:s}=e,i=b=>ct(b,s),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),c=e.powPminus2||(b=>ml(b,s-BigInt(2),s));function l(b,E,_){const x=i(b*(E-_));return E=i(E-x),_=i(_+x),[E,_]}const d=(e.a-BigInt(2))/BigInt(4);function u(b,E){rs("u",b,Vs,s),rs("scalar",E,Vs,s);const _=E,x=b;let P=vn,S=Vs,D=b,v=vn,R=Vs,C;for(let H=BigInt(r-1);H>=Vs;H--){const I=_>>H&vn;R^=I,C=l(R,P,D),P=C[0],D=C[1],C=l(R,S,v),S=C[0],v=C[1],R=I;const T=P+S,A=i(T*T),F=P-S,j=i(F*F),k=A-j,G=D+v,Q=D-v,se=i(Q*T),Ee=i(G*F),he=se+Ee,Oe=se-Ee;D=i(he*he),v=i(x*i(Oe*Oe)),P=i(A*j),S=i(k*(A+i(d*k)))}C=l(R,P,D),P=C[0],D=C[1],C=l(R,S,v),S=C[0],v=C[1];const L=c(S);return i(P*L)}function h(b){return Zr(i(b),n)}function g(b){const E=gt("u coordinate",b,n);return o===32&&(E[31]&=127),cr(E)}function w(b){const E=gt("scalar",b),_=E.length;if(_!==n&&_!==o){let x=""+n+" or "+o;throw new Error("invalid scalar, expected "+x+" bytes, got "+_)}return cr(a(E))}function m(b,E){const _=g(E),x=w(b),P=u(_,x);if(P===Vs)throw new Error("invalid private or public key received");return h(P)}const f=h(e.Gu);function y(b){return m(b,f)}return{scalarMult:m,scalarMultBase:y,getSharedSecret:(b,E)=>m(b,E),getPublicKey:b=>y(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:f}}const Xn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const yg=BigInt(1),Ia=BigInt(2),bg=BigInt(3),vg=BigInt(5);BigInt(8);function Eg(t){const e=BigInt(10),s=BigInt(20),i=BigInt(40),r=BigInt(80),n=Xn,o=t*t%n*t%n,a=xt(o,Ia,n)*o%n,c=xt(a,yg,n)*t%n,l=xt(c,vg,n)*c%n,d=xt(l,e,n)*l%n,u=xt(d,s,n)*d%n,h=xt(u,i,n)*u%n,g=xt(h,r,n)*h%n,w=xt(g,r,n)*h%n,m=xt(w,e,n)*l%n;return{pow_p_5_8:xt(m,Ia,n)*t%n,b2:o}}function Cg(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Zn=wg({P:Xn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=Xn,{pow_p_5_8:s,b2:i}=Eg(t);return ct(xt(s,bg,e)*i,e)},adjustScalarBytes:Cg,randomBytes:ki});function Na(t){t.lowS!==void 0&&Ci("lowS",t.lowS),t.prehash!==void 0&&Ci("prehash",t.prehash)}function Ig(t){const e=Il(t);xi(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});
vendor: 10,968 bytes, line 7
7const{endo:s,Fp:i,a:r}=e;if(s){if(!i.eql(r,i.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof s!="object"||typeof s.beta!="bigint"||typeof s.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:Ng,hexToBytes:Ag}=ig;class _g extends Error{constructor(e=""){super(e)}}const ss={Err:_g,_tlv:{encode:(t,e)=>{const{Err:s}=ss;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const i=e.length/2,r=ui(i);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const n=i>127?ui(r.length/2|128):"";return ui(t)+n+r+e},decode(t,e){const{Err:s}=ss;let i=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new s("tlv.decode: wrong tlv");const r=e[i++],n=!!(r&128);let o=0;if(!n)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(i,i+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(i+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=ss;if(t<is)throw new e("integer: negative integers are not allowed");let s=ui(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}=ss;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 Ng(t)}},toSig(t){const{Err:e,_int:s,_tlv:i}=ss,r=typeof t=="string"?Ag(t):t;mr(r);const{v:n,l:o}=i.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:l,l:d}=i.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}=ss,i=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),n=i+r;return e.encode(48,n)}},is=BigInt(0),Be=BigInt(1);BigInt(2);const Aa=BigInt(3);BigInt(4);function Sg(t){const e=Ig(t),{Fp:s}=e,i=yl(e.n,e.nBitLength),r=e.toBytes||((m,f,y)=>{const b=f.toAffine();return lr(Uint8Array.from([4]),s.toBytes(b.x),s.toBytes(b.y))}),n=e.fromBytes||(m=>{const f=m.subarray(1),y=s.fromBytes(f.subarray(0,s.BYTES)),b=s.fromBytes(f.subarray(s.BYTES,2*s.BYTES));return{x:y,y:b}});function o(m){const{a:f,b:y}=e,b=s.sqr(m),E=s.mul(b,m);return s.add(s.add(E,s.mul(m,f)),y)}if(!s.eql(s.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Qr(m,Be,e.n)}function c(m){const{allowedPrivateKeyLengths:f,nByteLength:y,wrapPrivateKey:b,n:E}=e;if(f&&typeof m!="bigint"){if(Bs(m)&&(m=Ii(m)),typeof m!="string"||!f.includes(m.length))throw new Error("invalid private key");m=m.padStart(y*2,"0")}let _;try{_=typeof m=="bigint"?m:Ds(gt("private key",m,y))}catch{throw new Error("invalid private key, expected hex or "+y+" bytes, got "+typeof m)}return b&&(_=ct(_,E)),rs("private key",_,Be,E),_}function l(m){if(!(m instanceof h))throw new Error("ProjectivePoint expected")}const d=Gn((m,f)=>{const{px:y,py:b,pz:E}=m;if(s.eql(E,s.ONE))return{x:y,y:b};const _=m.is0();f==null&&(f=_?s.ONE:s.inv(E));const x=s.mul(y,f),P=s.mul(b,f),S=s.mul(E,f);if(_)return{x:s.ZERO,y:s.ZERO};if(!s.eql(S,s.ONE))throw new Error("invZ was invalid");return{x,y:P}}),u=Gn(m=>{if(m.is0()){if(e.allowInfinityPoint&&!s.is0(m.py))return;throw new Error("bad point: ZERO")}const{x:f,y}=m.toAffine();if(!s.isValid(f)||!s.isValid(y))throw new Error("bad point: x or y not FE");const b=s.sqr(y),E=o(f);if(!s.eql(b,E))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(f,y,b){if(this.px=f,this.py=y,this.pz=b,f==null||!s.isValid(f))throw new Error("x required");if(y==null||!s.isValid(y))throw new Error("y required");if(b==null||!s.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(f){const{x:y,y:b}=f||{};if(!f||!s.isValid(y)||!s.isValid(b))throw new Error("invalid affine point");if(f instanceof h)throw new Error("projective point not allowed");const E=_=>s.eql(_,s.ZERO);return E(y)&&E(b)?h.ZERO:new h(y,b,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const y=s.invertBatch(f.map(b=>b.pz));return f.map((b,E)=>b.toAffine(y[E])).map(h.fromAffine)}static fromHex(f){const y=h.fromAffine(n(gt("pointHex",f)));return y.assertValidity(),y}static fromPrivateKey(f){return h.BASE.multiply(c(f))}static msm(f,y){return fg(h,i,f,y)}_setWindowSize(f){w.setWindowSize(this,f)}assertValidity(){u(this)}hasEvenY(){const{y:f}=this.toAffine();if(s.isOdd)return!s.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){l(f);const{px:y,py:b,pz:E}=this,{px:_,py:x,pz:P}=f,S=s.eql(s.mul(y,P),s.mul(_,E)),D=s.eql(s.mul(b,P),s.mul(x,E));return S&&D}negate(){return new h(this.px,s.neg(this.py),this.pz)}double(){const{a:f,b:y}=e,b=s.mul(y,Aa),{px:E,py:_,pz:x}=this;let P=s.ZERO,S=s.ZERO,D=s.ZERO,v=s.mul(E,E),R=s.mul(_,_),C=s.mul(x,x),L=s.mul(E,_);return L=s.add(L,L),D=s.mul(E,x),D=s.add(D,D),P=s.mul(f,D),S=s.mul(b,C),S=s.add(P,S),P=s.sub(R,S),S=s.add(R,S),S=s.mul(P,S),P=s.mul(L,P),D=s.mul(b,D),C=s.mul(f,C),L=s.sub(v,C),L=s.mul(f,L),L=s.add(L,D),D=s.add(v,v),v=s.add(D,v),v=s.add(v,C),v=s.mul(v,L),S=s.add(S,v),C=s.mul(_,x),C=s.add(C,C),v=s.mul(C,L),P=s.sub(P,v),D=s.mul(C,R),D=s.add(D,D),D=s.add(D,D),new h(P,S,D)}add(f){l(f);const{px:y,py:b,pz:E}=this,{px:_,py:x,pz:P}=f;let S=s.ZERO,D=s.ZERO,v=s.ZERO;const R=e.a,C=s.mul(e.b,Aa);let L=s.mul(y,_),H=s.mul(b,x),I=s.mul(E,P),T=s.add(y,b),A=s.add(_,x);T=s.mul(T,A),A=s.add(L,H),T=s.sub(T,A),A=s.add(y,E);let F=s.add(_,P);return A=s.mul(A,F),F=s.add(L,I),A=s.sub(A,F),F=s.add(b,E),S=s.add(x,P),F=s.mul(F,S),S=s.add(H,I),F=s.sub(F,S),v=s.mul(R,A),S=s.mul(C,I),v=s.add(S,v),S=s.sub(H,v),v=s.add(H,v),D=s.mul(S,v),H=s.add(L,L),H=s.add(H,L),I=s.mul(R,I),A=s.mul(C,A),H=s.add(H,I),I=s.sub(L,I),I=s.mul(R,I),A=s.add(A,I),L=s.mul(H,A),D=s.add(D,L),L=s.mul(F,A),S=s.mul(T,S),S=s.sub(S,L),L=s.mul(T,H),v=s.mul(F,v),v=s.add(v,L),new h(S,D,v)}subtract(f){return this.add(f.negate())}is0(){return this.equals(h.ZERO)}wNAF(f){return w.wNAFCached(this,f,h.normalizeZ)}multiplyUnsafe(f){const{endo:y,n:b}=e;rs("scalar",f,is,b);const E=h.ZERO;if(f===is)return E;if(this.is0()||f===Be)return this;if(!y||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,f,h.normalizeZ);let{k1neg:_,k1:x,k2neg:P,k2:S}=y.splitScalar(f),D=E,v=E,R=this;for(;x>is||S>is;)x&Be&&(D=D.add(R)),S&Be&&(v=v.add(R)),R=R.double(),x>>=Be,S>>=Be;return _&&(D=D.negate()),P&&(v=v.negate()),v=new h(s.mul(v.px,y.beta),v.py,v.pz),D.add(v)}multiply(f){const{endo:y,n:b}=e;rs("scalar",f,Be,b);let E,_;if(y){const{k1neg:x,k1:P,k2neg:S,k2:D}=y.splitScalar(f);let{p:v,f:R}=this.wNAF(P),{p:C,f:L}=this.wNAF(D);v=w.constTimeNegate(x,v),C=w.constTimeNegate(S,C),C=new h(s.mul(C.px,y.beta),C.py,C.pz),E=v.add(C),_=R.add(L)}else{const{p:x,f:P}=this.wNAF(f);E=x,_=P}return h.normalizeZ([E,_])[0]}multiplyAndAddUnsafe(f,y,b){const E=h.BASE,_=(P,S)=>S===is||S===Be||!P.equals(E)?P.multiplyUnsafe(S):P.multiply(S),x=_(this,y).add(_(f,b));return x.is0()?void 0:x}toAffine(f){return d(this,f)}isTorsionFree(){const{h:f,isTorsionFree:y}=e;if(f===Be)return!0;if(y)return y(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:y}=e;return f===Be?this:y?y(h,this):this.multiplyUnsafe(e.h)}toRawBytes(f=!0){return Ci("isCompressed",f),this.assertValidity(),r(h,this,f)}toHex(f=!0){return Ci("isCompressed",f),Ii(this.toRawBytes(f))}}h.BASE=new h(e.Gx,e.Gy,s.ONE),h.ZERO=new h(s.ZERO,s.ONE,s.ZERO);const g=e.nBitLength,w=gg(h,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Pg(t){const e=Il(t);return xi(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Og(t){const e=Pg(t),{Fp:s,n:i}=e,r=s.BYTES+1,n=2*s.BYTES+1;function o(I){return ct(I,i)}function a(I){return Yn(I,i)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:d,isWithinCurveOrder:u}=Sg({...e,toBytes(I,T,A){const F=T.toAffine(),j=s.toBytes(F.x),k=lr;return Ci("isCompressed",A),A?k(Uint8Array.from([T.hasEvenY()?2:3]),j):k(Uint8Array.from([4]),j,s.toBytes(F.y))},fromBytes(I){const T=I.length,A=I[0],F=I.subarray(1);if(T===r&&(A===2||A===3)){const j=Ds(F);if(!Qr(j,Be,s.ORDER))throw new Error("Point is not on curve");const k=d(j);let G;try{G=s.sqrt(k)}catch(se){const Ee=se instanceof Error?": "+se.message:"";throw new Error("Point is not on curve"+Ee)}const Q=(G&Be)===Be;return(A&1)===1!==Q&&(G=s.neg(G)),{x:j,y:G}}else if(T===n&&A===4){const j=s.fromBytes(F.subarray(0,s.BYTES)),k=s.fromBytes(F.subarray(s.BYTES,2*s.BYTES));return{x:j,y:k}}else{const j=r,k=n;throw new Error("invalid Point, expected length of "+j+", or uncompressed "+k+", got "+T)}}}),h=I=>Ii(Ai(I,e.nByteLength));function g(I){const T=i>>Be;return I>T}function w(I){return g(I)?o(-I):I}const m=(I,T,A)=>Ds(I.slice(T,A));class f{constructor(T,A,F){this.r=T,this.s=A,this.recovery=F,this.assertValidity()}static fromCompact(T){const A=e.nByteLength;return T=gt("compactSignature",T,A*2),new f(m(T,0,A),m(T,A,2*A))}static fromDER(T){const{r:A,s:F}=ss.toSig(gt("DER",T));return new f(A,F)}assertValidity(){rs("r",this.r,Be,i),rs("s",this.s,Be,i)}addRecoveryBit(T){return new f(this.r,this.s,T)}recoverPublicKey(T){const{r:A,s:F,recovery:j}=this,k=P(gt("msgHash",T));if(j==null||![0,1,2,3].includes(j))throw new Error("recovery id invalid");const G=j===2||j===3?A+e.n:A;if(G>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const Q=j&1?"03":"02",se=c.fromHex(Q+h(G)),Ee=a(G),he=o(-k*Ee),Oe=o(F*Ee),Le=c.BASE.multiplyAndAddUnsafe(se,he,Oe);if(!Le)throw new Error("point at infinify");return Le.assertValidity(),Le}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Ni(this.toDERHex())}toDERHex(){return ss.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ni(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}const y={isValidPrivateKey(I){try{return l(I),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const I=vl(e.n);return ug(e.randomBytes(I),e.n)},precompute(I=8,T=c.BASE){return T._setWindowSize(I),T.multiply(BigInt(3)),T}};function b(I,T=!0){return c.fromPrivateKey(I).toRawBytes(T)}
7function E(I){const T=Bs(I),A=typeof I=="string",F=(T||A)&&I.length;return T?F===r||F===n:A?F===2*r||F===2*n:I instanceof c}function _(I,T,A=!0){if(E(I))throw new Error("first arg must be private key");if(!E(T))throw new Error("second arg must be public key");return c.fromHex(T).multiply(l(I)).toRawBytes(A)}const x=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const T=Ds(I),A=I.length*8-e.nBitLength;return A>0?T>>BigInt(A):T},P=e.bits2int_modN||function(I){return o(x(I))},S=Ao(e.nBitLength);function D(I){return rs("num < 2^"+e.nBitLength,I,is,S),Ai(I,e.nByteLength)}function v(I,T,A=R){if(["recovered","canonical"].some(xe=>xe in A))throw new Error("sign() legacy options not supported");const{hash:F,randomBytes:j}=e;let{lowS:k,prehash:G,extraEntropy:Q}=A;k==null&&(k=!0),I=gt("msgHash",I),Na(A),G&&(I=gt("prehashed msgHash",F(I)));const se=P(I),Ee=l(T),he=[D(Ee),D(se)];if(Q!=null&&Q!==!1){const xe=Q===!0?j(s.BYTES):Q;he.push(gt("extraEntropy",xe))}const Oe=lr(...he),Le=se;function Je(xe){const Re=x(xe);if(!u(Re))return;const Ns=a(Re),Vt=c.BASE.multiply(Re).toAffine(),Lt=o(Vt.x);if(Lt===is)return;const Gt=o(Ns*o(Le+Lt*Ee));if(Gt===is)return;let Jt=(Vt.x===Lt?0:2)|Number(Vt.y&Be),Er=Gt;return k&&g(Gt)&&(Er=w(Gt),Jt^=1),new f(Lt,Er,Jt)}return{seed:Oe,k2sig:Je}}const R={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function L(I,T,A=R){const{seed:F,k2sig:j}=v(I,T,A),k=e;return fl(k.hash.outputLen,k.nByteLength,k.hmac)(F,j)}c.BASE._setWindowSize(8);function H(I,T,A,F=C){var Gt;const j=I;T=gt("msgHash",T),A=gt("publicKey",A);const{lowS:k,prehash:G,format:Q}=F;if(Na(F),"strict"in F)throw new Error("options.strict was renamed to lowS");if(Q!==void 0&&Q!=="compact"&&Q!=="der")throw new Error("format must be compact or der");const se=typeof j=="string"||Bs(j),Ee=!se&&!Q&&typeof j=="object"&&j!==null&&typeof j.r=="bigint"&&typeof j.s=="bigint";if(!se&&!Ee)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let he,Oe;try{if(Ee&&(he=new f(j.r,j.s)),se){try{Q!=="compact"&&(he=f.fromDER(j))}catch(Jt){if(!(Jt instanceof ss.Err))throw Jt}!he&&Q!=="der"&&(he=f.fromCompact(j))}Oe=c.fromHex(A)}catch{return!1}if(!he||k&&he.hasHighS())return!1;G&&(T=e.hash(T));const{r:Le,s:Je}=he,xe=P(T),Re=a(Je),Ns=o(xe*Re),Vt=o(Le*Re),Lt=(Gt=c.BASE.multiplyAndAddUnsafe(Oe,Ns,Vt))==null?void 0:Gt.toAffine();return Lt?o(Lt.x)===Le:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:_,sign:L,verify:H,ProjectivePoint:c,Signature:f,utils:y}}function Tg(t){return{hash:t,hmac:(e,...s)=>Jr(t,e,$h(...s)),randomBytes:ki}}function kg(t,e){const s=i=>Og({...t,...Tg(i)});return{...s(e),create:s}}const Nl=yl(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),xg=Nl.create(BigInt("-3")),Rg=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),$g=kg({a:xg,b:Rg,Fp:Nl,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},fr),Al="base10",et="base16",Ut="base64pad",gs="base64url",wr="utf8",_l=0,ns=1,yr=2,Ug=0,_a=1,er=12,_o=32;function Dg(){const t=Zn.utils.randomPrivateKey(),e=Zn.getPublicKey(t);return{privateKey:lt(t,et),publicKey:lt(e,et)}}function Qn(){const t=ki(_o);return lt(t,et)}function Lg(t,e){const s=Zn.getSharedSecret(At(t,et),At(e,et)),i=qp(fr,s,void 0,void 0,_o);return lt(i,et)}function Dr(t){const e=fr(At(t,et));return lt(e,et)}function zt(t){const e=fr(At(t,wr));return lt(e,et)}function Sl(t){return At(`${t}`,Al)}function qs(t){return Number(lt(t,Al))}function Pl(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ol(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function Mg(t){const e=Sl(typeof t.type<"u"?t.type:_l);if(qs(e)===ns&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?At(t.senderPublicKey,et):void 0,i=typeof t.iv<"u"?At(t.iv,et):ki(er),r=At(t.symKey,et),n=hl(r,i).encrypt
7(At(t.message,wr)),o=Tl({type:e,sealed:n,iv:i,senderPublicKey:s});return t.encoding===gs?Pl(o):o}function Fg(t){const e=At(t.symKey,et),{sealed:s,iv:i}=dr({encoded:t.encoded,encoding:t.encoding}),r=hl(e,i).decrypt(s);if(r===null)throw new Error("Failed to decrypt");return lt(r,wr)}function Bg(t,e){const s=Sl(yr),i=ki(er),r=At(t,wr),n=Tl({type:s,sealed:r,iv:i});return e===gs?Pl(n):n}function qg(t,e){const{sealed:s}=dr({encoded:t,encoding:e});return lt(s,wr)}function Tl(t){if(qs(t.type)===yr)return lt(Ji([t.type,t.sealed]),Ut);if(qs(t.type)===ns){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return lt(Ji([t.type,t.senderPublicKey,t.iv,t.sealed]),Ut)}return lt(Ji([t.type,t.iv,t.sealed]),Ut)}function dr(t){const e=(t.encoding||Ut)===gs?Ol(t.encoded):t.encoded,s=At(e,Ut),i=s.slice(Ug,_a),r=_a;if(qs(i)===ns){const c=r+_o,l=c+er,d=s.slice(r,c),u=s.slice(c,l),h=s.slice(l);return{type:i,sealed:h,iv:u,senderPublicKey:d}}if(qs(i)===yr){const c=s.slice(r),l=ki(er);return{type:i,sealed:c,iv:l}}const n=r+er,o=s.slice(r,n),a=s.slice(n);return{type:i,sealed:a,iv:o}}function jg(t,e){const s=dr({encoded:t,encoding:e==null?void 0:e.encoding});return kl({type:qs(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?lt(s.senderPublicKey,et):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function kl(t){const e=(t==null?void 0:t.type)||_l;if(e===ns){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 Sa(t){return t.type===ns&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Pa(t){return t.type===yr}function Wg(t){const e=Buffer.from(t.x,"base64"),s=Buffer.from(t.y,"base64");return Ji([new Uint8Array([4]),e,s])}function zg(t,e){const[s,i,r]=t.split("."),n=Buffer.from(Ol(r),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${s}.${i}`,l=fr(c),d=Wg(e);if(!$g.verify(Ji([o,a]),l,d))throw new Error("Invalid signature");return Un(t).payload}const Hg="irn";function Wr(t){return(t==null?void 0:t.relay)||{protocol:Hg}}function Ki(t){const e=md[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function Kg(t,e="-"){const s={},i="relay"+e;return Object.keys(t).forEach(r=>{if(r.startsWith(i)){const n=r.replace(i,""),o=t[r];s[n]=o}}),s}function Oa(t){if(!t.includes("wc:")){const l=Qc(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,i=t.substring(0,e),r=t.substring(e+1,s).split("@"),n=typeof s<"u"?t.substring(s):"",o=new URLSearchParams(n),a={};o.forEach((l,d)=>{a[d]=l});
7const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:Vg(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:Kg(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Vg(t){return t.startsWith("//")?t.substring(2):t}function Gg(t,e="-"){const s="relay",i={};return Object.keys(t).forEach(r=>{const n=r,o=s+e+n;t[n]&&(i[o]=t[n])}),i}function Ta(t){const e=new URLSearchParams,s=Gg(t.relay);Object.keys(s).sort().forEach(r=>{e.set(r,s[r])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const i=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${i}`}function Sr(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var Jg=Object.defineProperty,Yg=Object.defineProperties,Xg=Object.getOwnPropertyDescriptors,ka=Object.getOwnPropertySymbols,Zg=Object.prototype.hasOwnProperty,Qg=Object.prototype.propertyIsEnumerable,xa=(t,e,s)=>e in t?Jg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ef=(t,e)=>{for(var s in e||(e={}))Zg.call(e,s)&&xa(t,s,e[s]);if(ka)for(var s of ka(e))Qg.call(e,s)&&xa(t,s,e[s]);return t},tf=(t,e)=>Yg(t,Xg(e));function Ri(t){const e=[];return t.forEach(s=>{const[i,r]=s.split(":");e.push(`${i}:${r}`)}),e}function sf(t){const e=[];return Object.values(t).forEach(s=>{e.push(...Ri(s.accounts))}),e}function rf(t,e){const s=[];return Object.values(t).forEach(i=>{Ri(i.accounts).includes(e)&&s.push(...i.methods)}),s}function nf(t,e){const s=[];return Object.values(t).forEach(i=>{Ri(i.accounts).includes(e)&&s.push(...i.events)}),s}function en(t){return t.includes(":")}function hi(t){return en(t)?t.split(":")[0]:t}function Ra(t){var e,s,i;const r={};if(!vs(t))return r;for(const[n,o]of Object.entries(t)){const a=en(n)?[n]:o.chains,c=o.methods||[],l=o.events||[],d=hi(n);r[d]=tf(ef({},r[d]),{chains:Ht(a,(e=r[d])==null?void 0:e.chains),methods:Ht(c,(s=r[d])==null?void 0:s.methods),events:Ht(l,(i=r[d])==null?void 0:i.events)})}return r}function of(t){const e={};return t==null||t.forEach(s=>{var i;const[r,n]=s.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(s),(i=e[r].chains)==null||i.push(`${r}:${n}`)}),e}function $a(t,e){e=e.map(i=>i.replace("did:pkh:",""));const s=of(e);for(const[i,r]of Object.entries(s))r.methods?r.methods=Ht(r.methods,t):r.methods=t,r.events=["chainChanged","accountsChanged"];return s}function af(t,e){var s,i,r,n,o,a;const c=Ra(t),l=Ra(e),d={},u=Object.keys(c).concat(Object.keys(l));for(const h of u)d[h]={chains:Ht((s=c[h])==null?void 0:s.chains,(i=l[h])==null?void 0:i.chains),methods:Ht((r=c[h])==null?void 0:r.methods,(n=l[h])==null?void 0:n.methods),events:Ht((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return d}const cf={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}},lf={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 $(t,e){const{message:s,code:i}=lf[t];return{message:e?`${s} ${e}
7`:s,code:i}}function me(t,e){const{message:s,code:i}=cf[t];return{message:e?`${s} ${e}`:s,code:i}}function bs(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function vs(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Ve(t){return typeof t>"u"}function ke(t,e){return e&&Ve(t)?!0:typeof t=="string"&&!!t.trim().length}function So(t,e){return e&&Ve(t)?!0:typeof t=="number"&&!isNaN(t)}function df(t,e){const{requiredNamespaces:s}=e,i=Object.keys(t.namespaces),r=Object.keys(s);let n=!0;return Us(r,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],d=Ri(a),u=s[o];(!Us(Gc(o,u),d)||!Us(u.methods,c)||!Us(u.events,l))&&(n=!1)}),n):!1}function zr(t){return ke(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function uf(t){if(ke(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&zr(s)}}return!1}function hf(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(ke(t,!1)){if(e(t))return!0;const s=Qc(t);return e(s)}}catch{}return!1}function pf(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function gf(t){return t==null?void 0:t.topic}function ff(t,e){let s=null;return ke(t==null?void 0:t.publicKey,!1)||(s=$("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function Ua(t){let e=!0;return bs(t)?t.length&&(e=t.every(s=>ke(s,!1))):e=!1,e}function mf(t,e,s){let i=null;return bs(e)&&e.length?e.forEach(r=>{i||zr(r)||(i=me("UNSUPPORTED_CHAINS",`${s}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):zr(t)||(i=me("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"] }`)),i}function wf(t,e,s){let i=null;return Object.entries(t).forEach(([r,n])=>{if(i)return;const o=mf(r,Gc(r,n),`${e} ${s}`);o&&(i=o)}),i}function yf(t,e){let s=null;return bs(t)?t.forEach(i=>{s||uf(i)||(s=me("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):s=me("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function bf(t,e){let s=null;return Object.values(t).forEach(i=>{if(s)return;const r=yf(i==null?void 0:i.accounts,`${e} namespace`);r&&(s=r)}),s}function vf(t,e){let s=null;return Ua(t==null?void 0:t.methods)?Ua(t==null?void 0:t.events)||(s=me("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=me("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function xl(t,e){let s=null;return Object.values(t).forEach(i=>{if(s)return;const r=vf(i,`${e}, namespace`);r&&(s=r)}),s}function Ef(t,e,s){let i=null;if(t&&vs(t)){const r=xl(t,e);r&&(i=r);const n=wf(t,e,s);n&&(i=n)}else i=$("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return i}function En(t,e){let s=null;if(t&&vs(t)){const i=xl(t,e);i&&(s=i);const r=bf(t,e);r&&(s=r)}else s=$("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function Rl(t){return ke(t.protocol,!0)}function Cf(t,e){let s=!1;return e&&!t?s=!0:t&&bs(t)&&t.length&&t.forEach(i=>{s=Rl(i)}),s}function If(t){return typeof t=="number"}function at(t){return typeof t<"u"&&typeof t!==null}function Nf(t){return!(!t||typeof t!="object"||!t.code||!So(t.code,!1)||!t.message||!ke(t.message,!1))}function Af(t){return!(Ve(t)||!ke(t.method,!1))}function _f(t){return!(Ve(t)||Ve(t.result)&&Ve(t.error)||!So(t.id,!1)||!ke(t.jsonrpc,!1))}function Sf(t){return!(Ve(t)||!ke(t.name,!1))}function Da(t,e){return!(!zr(e)||!sf(t).includes(e))}function Pf(t,e,s){return ke(s,!1)?rf(t,e).includes(s):!1}function Of(t,e,s){return ke(s,!1)?nf(t,e).includes(s):!1}function La(t,e,s){let i=null;const r=Tf(t),n=kf(e),o=Object.keys(r),a=Object.keys(n),c=Ma(Object.keys(t)),l=Ma(Object.keys(e)),d=c.filter(u=>!l.includes(u));return d.length&&(i=$("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
8      Required: ${d.toString()}
9      Received: ${Object.keys(e).toString()}`)),Us(o,a)||(i=$("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.
10      Required: ${o.toString()}
11      Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||i)return;const h=Ri(e[u].accounts);h.includes(u)||(i=$("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${u}
12        Required: ${u}
13        Approved: ${h.toString()}`))}),o.forEach(u=>{i||(Us(r[u].methods,n[u].methods)?Us(r[u].events,n[u].events)||(i=$("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${u}`)):i=$("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${u}`))}),i}function Tf(t){const e={};return Object.keys(t).forEach(s=>{var i;
13s.includes(":")?e[s]=t[s]:(i=t[s].chains)==null||i.forEach(r=>{e[r]={methods:t[s].methods,events:t[s].events}})}),e}function Ma(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function kf(t){const e={};return Object.keys(t).forEach(s=>{if(s.includes(":"))e[s]=t[s];else{const i=Ri(t[s].accounts);i==null||i.forEach(r=>{e[r]={accounts:t[s].accounts.filter(n=>n.includes(`${r}:`)),methods:t[s].methods,events:t[s].events}})}}),e}function xf(t,e){return So(t,!1)&&t<=e.max&&t>=e.min}function Fa(){const t=pr();return new Promise(e=>{switch(t){case mt.browser:e(Rf());break;case mt.reactNative:e($f());break;case mt.node:e(Uf());break;default:e(!0)}})}function Rf(){return Ti()&&(navigator==null?void 0:navigator.onLine)}async function $f(){if(Is()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function Uf(){return!0}function Df(t){switch(pr()){case mt.browser:Lf(t);break;case mt.reactNative:Mf(t);break}}function Lf(t){!Is()&&Ti()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function Mf(t){Is()&&typeof global<"u"&&global!=null&&global.NetInfo&&(global==null||global.NetInfo.addEventListener(e=>t(e==null?void 0:e.isConnected)))}function Ff(){var t;return Ti()&&wi()?((t=wi())==null?void 0:t.visibilityState)==="visible":!0}const Cn={};class Mi{static get(e){return Cn[e]}static set(e,s){Cn[e]=s}static delete(e){delete Cn[e]}}const $l="wc",Ul=2,Hr="core",Kt=`${$l}@2:${Hr}:`,Bf={name:Hr,logger:"error"},qf={database:":memory:"},jf="crypto",Ba="client_ed25519_seed",Wf=U.ONE_DAY,zf="keychain",Hf="0.3",Kf="messages",Vf="0.3",qa=U.SIX_HOURS,Gf="publisher",Dl="irn",Jf="error",Ll="wss://relay.walletconnect.org",Yf="relayer",qe={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"},Xf="_subscription",Ct={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Zf=.1,eo="2.21.0",Ne={link_mode:"link_mode",relay:"relay"},Lr={inbound:"inbound",outbound:"outbound"},Qf="0.3",em="WALLETCONNECT_CLIENT_ID",ja="WALLETCONNECT_LINK_MODE_APPS",ht={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},tm="subscription",sm="0.3",im="pairing",rm="0.3",Fi={wc_pairingDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:U.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:U.ONE_DAY,prompt:!1,tag:0},res:{ttl:U.ONE_DAY,prompt:!1,tag:0}}},xs={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},nm="history",om="0.3",am="expirer",Nt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},cm="0.3",lm="verify-api",dm="https://verify.walletconnect.com",Ml="https://verify.walletconnect.org",tr=Ml,um=`${tr}/v3`,hm=[dm,Ml],pm="echo",gm="https://echo.walletconnect.com",qt={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"},ts={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"},Tt={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"},_s={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"},Ss={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"},Bi={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"},fm=.1,mm="event-client",wm=86400,ym="https://pulse.walletconnect.org/batch";function bm(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),i=0;i<s.length;i++)s[i]=255;for(var r=0;r<t.length;r++){var n=t.charAt(r),o=n.charCodeAt(0);if(s[o]!==255)throw new TypeError(n+" 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(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.b
vendor: 6,100 bytes, line 13
13yteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var m=0,f=0,y=0,b=w.length;y!==b&&w[y]===0;)y++,m++;for(var E=(b-y)*d+1>>>0,_=new Uint8Array(E);y!==b;){for(var x=w[y],P=0,S=E-1;(x!==0||P<f)&&S!==-1;S--,P++)x+=256*_[S]>>>0,_[S]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");f=P,y++}for(var D=E-f;D!==E&&_[D]===0;)D++;for(var v=c.repeat(m);D<E;++D)v+=t.charAt(_[D]);return v}function h(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var m=0;if(w[m]!==" "){for(var f=0,y=0;w[m]===c;)f++,m++;for(var b=(w.length-m)*l+1>>>0,E=new Uint8Array(b);w[m];){var _=s[w.charCodeAt(m)];if(_===255)return;for(var x=0,P=b-1;(_!==0||x<y)&&P!==-1;P--,x++)_+=a*E[P]>>>0,E[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");y=x,m++}if(w[m]!==" "){for(var S=b-y;S!==b&&E[S]===0;)S++;for(var D=new Uint8Array(f+(b-S)),v=f;S!==b;)D[v++]=E[S++];return D}}}function g(w){var m=h(w);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:g}}var vm=bm,Em=vm;const Fl=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")},Cm=t=>new TextEncoder().encode(t),Im=t=>new TextDecoder().decode(t);class Nm{constructor(e,s,i){this.name=e,this.prefix=s,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Am{constructor(e,s,i){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=i}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 Bl(this,e)}}class _m{constructor(e){this.decoders=e}or(e){return Bl(this,e)}decode(e){const s=e[0],i=this.decoders[s];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Bl=(t,e)=>new _m({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Sm{constructor(e,s,i,r){this.name=e,this.prefix=s,this.baseEncode=i,this.baseDecode=r,this.encoder=new Nm(e,s,i),this.decoder=new Am(e,s,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const tn=({name:t,prefix:e,encode:s,decode:i})=>new Sm(t,e,s,i),br=({prefix:t,name:e,alphabet:s})=>{const{encode:i,decode:r}=Em(s,e);return tn({prefix:t,name:e,encode:i,decode:n=>Fl(r(n))})},Pm=(t,e,s,i)=>{const r={};for(let d=0;d<e.length;++d)r[e[d]]=d;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*s/8|0);let a=0,c=0,l=0;for(let d=0;d<n;++d){const u=r[t[d]];if(u===void 0)throw new SyntaxError(`Non-${i} 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},Om=(t,e,s)=>{const i=e[e.length-1]==="=",r=(1<<s)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,n+=e[r&a>>o];if(o&&(n+=e[r&a<<s-o]),i)for(;n.length*s&7;)n+="=";return n},Ge=({name:t,prefix:e,bitsPerChar:s,alphabet:i})=>tn({prefix:e,name:t,encode(r){return Om(r,i,s)},decode(r){return Pm(r,i,s,t)}}),Tm=tn({prefix:"\0",name:"identity",encode:t=>Im(t),decode:t=>Cm(t)});var km=Object.freeze({__proto__:null,identity:Tm});const xm=Ge({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Rm=Object.freeze({__proto__:null,base2:xm});const $m=Ge({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Um=Object.freeze({__proto__:null,base8:$m});const Dm=br({prefix:"9",name:"base10",alphabet:"0123456789"});var Lm=Object.freeze({__proto__:null,base10:Dm});const Mm=Ge({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Fm=Ge({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Bm=Object.freeze({__proto__:null,base16:Mm,base16upper:Fm});const qm=Ge({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jm=Ge({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wm=Ge({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),zm=Ge({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Hm=Ge({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Km=Ge({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Vm=Ge({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Gm=Ge({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jm=Ge({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ym=Object.freeze({__proto__:null,base32:qm,base32upper:jm,base32pad:Wm,base32padupper:zm,base32hex:Hm,base32hexupper:Km,base32hexpad:Vm,base32hexpadupper:Gm,base32z:Jm});const Xm=br({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zm=br({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Qm=Object.freeze({__proto__:null,base36:Xm,base36upper:Zm});const ew=br({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tw=br({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var sw=Object.freeze({__proto__:null,base58btc:ew,base58flickr:tw});const iw=Ge({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
13+/",bitsPerChar:6}),rw=Ge({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nw=Ge({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ow=Ge({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var aw=Object.freeze({__proto__:null,base64:iw,base64pad:rw,base64url:nw,base64urlpad:ow});const ql=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),cw=ql.reduce((t,e,s)=>(t[s]=e,t),[]),lw=ql.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function dw(t){return t.reduce((e,s)=>(e+=cw[s],e),"")}function uw(t){const e=[];for(const s of t){const i=lw[s.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(i)}return new Uint8Array(e)}const hw=tn({prefix:"🚀",name:"base256emoji",encode:dw,decode:uw});var pw=Object.freeze({__proto__:null,base256emoji:hw}),gw=jl,Wa=128,fw=127,mw=~fw,ww=Math.pow(2,31);function jl(t,e,s){e=e||[],s=s||0;for(var i=s;t>=ww;)e[s++]=t&255|Wa,t/=128;for(;t&mw;)e[s++]=t&255|Wa,t>>>=7;return e[s]=t|0,jl.bytes=s-i+1,e}var yw=to,bw=128,za=127;function to(t,i){var s=0,i=i||0,r=0,n=i,o,a=t.length;do{if(n>=a)throw to.bytes=0,new RangeError("Could not decode varint");o=t[n++],s+=r<28?(o&za)<<r:(o&za)*Math.pow(2,r),r+=7}while(o>=bw);return to.bytes=n-i,s}var vw=Math.pow(2,7),Ew=Math.pow(2,14),Cw=Math.pow(2,21),Iw=Math.pow(2,28),Nw=Math.pow(2,35),Aw=Math.pow(2,42),_w=Math.pow(2,49),Sw=Math.pow(2,56),Pw=Math.pow(2,63),Ow=function(t){return t<vw?1:t<Ew?2:t<Cw?3:t<Iw?4:t<Nw?5:t<Aw?6:t<_w?7:t<Sw?8:t<Pw?9:10},Tw={encode:gw,decode:yw,encodingLength:Ow},Wl=Tw;const Ha=(t,e,s=0)=>(Wl.encode(t,e,s),e),Ka=t=>Wl.encodingLength(t),so=(t,e)=>{const s=e.byteLength,i=Ka(t),r=i+Ka(s),n=new Uint8Array(r+s);return Ha(t,n,0),Ha(s,n,i),n.set(e,r),new kw(t,s,e,n)};class kw{constructor(e,s,i,r){this.code=e,this.size=s,this.digest=i,this.bytes=r}}const zl=({name:t,code:e,encode:s})=>new xw(t,e,s);class xw{constructor(e,s,i){this.name=e,this.code=s,this.encode=i}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?so(this.code,s):s.then(i=>so(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Hl=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Rw=zl({name:"sha2-256",code:18,encode:Hl("SHA-256")}),$w=zl({name:"sha2-512",code:19,encode:Hl("SHA-512")});var Uw=Object.freeze({__proto__:null,sha256:Rw,sha512:$w});const Kl=0,Dw="identity",Vl=Fl,Lw=t=>so(Kl,Vl(t)),Mw={code:Kl,name:Dw,encode:Vl,digest:Lw};var Fw=Object.freeze({__proto__:null,identity:Mw});new TextEncoder,new TextDecoder;const Va={...km,...Rm,...Um,...Lm,...Bm,...Ym,...Qm,...sw,...aw,...pw};({...Uw,...Fw});function Bw(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Gl(t,e,s,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:i}}}const Ga=Gl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),In=Gl("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=Bw(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),qw={utf8:Ga,"utf-8":Ga,hex:Va.base16,latin1:In,ascii:In,binary:In,...Va};function jw(t,e="utf8"){const s=qw[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):s.decoder.decode(`${s.prefix}${t}`)}var Ww=Object.defineProperty,zw=(t,e,s)=>e in t?Ww(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ft=(t,e,s)=>zw(t,typeof e!="symbol"?e+"":e,s);class Hw{constructor(e,s){this.core=e,this.logger=s,Ft(this,"keychain",new Map),Ft(this,"name",zf),Ft(this,"version",Hf),Ft(this,"initialized",!1),Ft(this,"storagePrefix",Kt),Ft(this,"init",async()=>
vendor: 4,384 bytes, line 13
13{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Ft(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Ft(this,"set",async(i,r)=>{this.isInitialized(),this.keychain.set(i,r),await this.persist()}),Ft(this,"get",i=>{this.isInitialized();const r=this.keychain.get(i);if(typeof r>"u"){const{message:n}=$("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return r}),Ft(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=tt(s,this.name)}get context(){return yt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,jn(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Wn(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Kw=Object.defineProperty,Vw=(t,e,s)=>e in t?Kw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,He=(t,e,s)=>Vw(t,typeof e!="symbol"?e+"":e,s);class Gw{constructor(e,s,i){this.core=e,this.logger=s,He(this,"name",jf),He(this,"keychain"),He(this,"randomSessionIdentifier",Qn()),He(this,"initialized",!1),He(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),He(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),He(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=Ro(r);return vd(n.publicKey)}),He(this,"generateKeyPair",()=>{this.isInitialized();const r=Dg();return this.setPrivateKey(r.publicKey,r.privateKey)}),He(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=Ro(n),a=this.randomSessionIdentifier;return await Ed(a,r,Wf,o)}),He(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Lg(a,n);return this.setSymKey(c,o)}),He(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||Dr(r);return await this.keychain.set(o,r),o}),He(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),He(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),He(this,"encode",async(r,n,o)=>{this.isInitialized();const a=kl(o),c=Cd(n);if(Pa(a))return Bg(c,o==null?void 0:o.encoding);if(Sa(a)){const h=a.senderPublicKey,g=a.receiverPublicKey;r=await this.generateSharedKey(h,g)}const l=this.getSymKey(r),{type:d,senderPublicKey:u}=a;return Mg({type:d,symKey:l,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),He(this,"decode",async(r,n,o)=>{this.isInitialized();const a=jg(n,o);if(Pa(a)){const c=qg(n,o==null?void 0:o.encoding);return $o(c)}if(Sa(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=Fg({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return $o(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),He(this,"getPayloadType",(r,n=Ut)=>{const o=dr({encoded:r,encoding:n});return qs(o.type)}),He(this,"getPayloadSenderPublicKey",(r,n=Ut)=>{const o=dr({encoded:r,encoding:n});return o.senderPublicKey?lt(o.senderPublicKey,et):void 0}),this.core=e,this.logger=tt(s,this.name),this.keychain=i||new Hw(this.core,this.logger)}get context(){return yt(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(Ba)}catch{e=Qn(),await this.keychain.set(Ba,e)}return jw(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Jw=Object.defineProperty,Yw=Object.defineProperties,Xw=Object.getOwnPropertyDescriptors,Ja=Object.getOwnPropertySymbols,Zw=Object.prototype.hasOwnProperty,Qw=Object.prototype.propertyIsEnumerable,io=(t,e,s)=>e in t?Jw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ey=(t,e)=>{for(var s in e||(e={}))Zw.call(e,s)&&io(t,s,e[s]);if(Ja)for(var s of Ja(e))Qw.call(e,s)&&io(t,s,e[s]);return t},ty=(t,e)=>Yw(t,Xw(e)),ut=(t,e,s)=>io(t,typeof e!="symbol"?e+"":e,s);
13class sy extends Eu{constructor(e,s){super(e,s),this.logger=e,this.core=s,ut(this,"messages",new Map),ut(this,"messagesWithoutClientAck",new Map),ut(this,"name",Kf),ut(this,"version",Vf),ut(this,"initialized",!1),ut(this,"storagePrefix",Kt),ut(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);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(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ut(this,"set",async(i,r,n)=>{this.isInitialized();const o=zt(r);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(i,a),n===Lr.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,ty(ey({},c),{[o]:r}))}return await this.persist(),o}),ut(this,"get",i=>{this.isInitialized();let r=this.messages.get(i);return typeof r>"u"&&(r={}),r}),ut(this,"getWithoutAck",i=>{this.isInitialized();const r={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};r[n]=Object.values(o)}return r}),ut(this,"has",(i,r)=>{this.isInitialized();const n=this.get(i),o=zt(r);return typeof n[o]<"u"}),ut(this,"ack",async(i,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=zt(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),ut(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=tt(e,this.name),this.core=s}get context(){return yt(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,jn(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,jn(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Wn(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Wn(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var iy=Object.defineProperty,ry=Object.defineProperties,ny=Object.getOwnPropertyDescriptors,Ya=Object.getOwnPropertySymbols,oy=Object.prototype.hasOwnProperty,ay=Object.prototype.propertyIsEnumerable,ro=(t,e,s)=>e in t?iy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Pr=(t,e)=>{for(var s in e||(e={}))oy.call(e,s)&&ro(t,s,e[s]);if(Ya)for(var s of Ya(e))ay.call(e,s)&&ro(t,s,e[s]);return t},Nn=(t,e)=>ry(t,ny(e)),kt=(t,e,s)=>ro(t,typeof e!="symbol"?e+"":e,s);class cy extends Cu{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,kt(this,"events",new js.EventEmitter),kt(this,"name",Gf),kt(this,"queue",new Map),kt(this,"publishTimeout",U.toMiliseconds(U.ONE_MINUTE)),kt(this,"initialPublishTimeout",U.toMiliseconds(U.ONE_SECOND*15)),kt(this,"needsTransportRestart",!1),kt(this,"publish",async(i,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:r,opts:n}});const a=(n==null?void 0:n.ttl)||qa,c=Wr(n),l=(n==null?void 0:n.prompt)||!1,d=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||di().toString(),h={topic:i,message:r,opts:{ttl:a,relay:c,prompt:l,tag:d,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},g=`Failed to publish payload, please try again. id:${u} tag:${d}`;try{const w=new Promise(async m=>{const f=({id:b})=>{h.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(qe.publish,f),m(h))};this.relayer.events.on(qe.publish,f);const y=ms(new Promise((b,E)=>{this.rpcPublish({topic:i,message:r,ttl:a,prompt:l,tag:d,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(b).catch(_=>{this.logger.warn(_,_==null?void 0:_.message),E(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${d}`);try{await y,this.events.removeListener(qe.publish,f)}catch(b){this.queue.set(u,Nn(Pr({},h),{attempt:1})),this.logger.warn(b,b==null?void 0:b.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:i,message:r,opts:n}}),await ms(w,this.publishTimeout,g)}catch(w){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(w),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw w}finally{this.queue.delete(u)}}),kt(this,"on",(i,r)=>{this.events.on(i,r)}),kt(this,"once",(i,r)=>{this.events.once(i,r)}),kt(this,"off",(i,r)=>{this.events.off(i,r)}),kt(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.relayer=e,this.logger=tt(s,this.name),this.registerEventListeners()}get context(){return yt(this.logger)}async rpcPublish(e){var s,i,r,n;const{topic:o,message:a,ttl:c=qa,prompt:l,tag:d,id:u,attestation:h,tvf:g}=e,w={method:Ki(Wr().protocol).publish,params:Pr({topic:o,message:a,ttl:c,prompt:l,tag:d,attestation:h},g),id:u};Ve((s=w.params)==null?void 0:s.prompt)&&((i=w.params)==null||delete i.prompt),Ve((r=w.params)==null?void 0:r.tag)&&((n=w.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w});const m=await this.relayer.request(w);return this.relayer.events.emit(qe.publish,e),this.logger.debug("Successfully Published Payload"),m}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{const i=e.attempt+1;this.queue.set(s,Nn(Pr({},e),{attempt:i}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Nn(Pr({},e),{topic:r,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Si.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(qe.connection_stalled);return}this.checkQueue()}),this.relayer.on(qe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var ly=Object.defineProperty,dy=(t,e,s)=>e in t?ly(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Gs=(t,e,s)=>dy(t,typeof e!="symbol"?e+"":e,s);class uy{constructor(){Gs(this,"map",new Map),Gs(this,"set",(e,s)=>{const i=this.get(e);this.exists(e,s)||this.map.set(e,[...i,s])}),Gs(this,"get",e=>this.map.get(e)||[]),Gs(this,"exists",(e,s)=>this.get(e).includes(s)),Gs(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,s))return;const r=i.filter(n=>n!==s);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),Gs(this,"clear",()=>{this.map.clear()})}
vendor: 9,609 bytes, line 13
13get topics(){return Array.from(this.map.keys())}}var hy=Object.defineProperty,py=Object.defineProperties,gy=Object.getOwnPropertyDescriptors,Xa=Object.getOwnPropertySymbols,fy=Object.prototype.hasOwnProperty,my=Object.prototype.propertyIsEnumerable,no=(t,e,s)=>e in t?hy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qi=(t,e)=>{for(var s in e||(e={}))fy.call(e,s)&&no(t,s,e[s]);if(Xa)for(var s of Xa(e))my.call(e,s)&&no(t,s,e[s]);return t},An=(t,e)=>py(t,gy(e)),ye=(t,e,s)=>no(t,typeof e!="symbol"?e+"":e,s);class wy extends Au{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,ye(this,"subscriptions",new Map),ye(this,"topicMap",new uy),ye(this,"events",new js.EventEmitter),ye(this,"name",tm),ye(this,"version",sm),ye(this,"pending",new Map),ye(this,"cached",[]),ye(this,"initialized",!1),ye(this,"storagePrefix",Kt),ye(this,"subscribeTimeout",U.toMiliseconds(U.ONE_MINUTE)),ye(this,"initialSubscribeTimeout",U.toMiliseconds(U.ONE_SECOND*15)),ye(this,"clientId"),ye(this,"batchSubscribeTopicsLimit",500),ye(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ye(this,"subscribe",async(i,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}});try{const n=Wr(r),o={topic:i,relay:n,transportType:r==null?void 0:r.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,r);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),ye(this,"unsubscribe",async(i,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(i,r.id,r):await this.unsubscribeByTopic(i,r)}),ye(this,"isSubscribed",i=>new Promise(r=>{r(this.topicMap.topics.includes(i))})),ye(this,"isKnownTopic",i=>new Promise(r=>{r(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),ye(this,"on",(i,r)=>{this.events.on(i,r)}),ye(this,"once",(i,r)=>{this.events.once(i,r)}),ye(this,"off",(i,r)=>{this.events.off(i,r)}),ye(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),ye(this,"start",async()=>{await this.onConnect()}),ye(this,"stop",async()=>{await this.onDisconnect()}),ye(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ye(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(r=>{i.push(r)}),await this.batchSubscribe(i)}),ye(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Si.pulse,async()=>{await this.checkPending()}),this.events.on(ht.created,async i=>{const r=ht.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()}),this.events.on(ht.deleted,async i=>{const r=ht.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()})}),this.relayer=e,this.logger=tt(s,this.name),this.clientId=""}get context(){return yt(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 i=!1;try{i=this.getSubscription(e).topic===s}catch{}return i}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 i=this.topicMap.get(e);await Promise.all(i.map(async r=>await this.unsubscribeById(e,r,s)))}async unsubscribeById(e,s,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:i}});try{const r=Wr(i);await this.restartToComplete({topic:e,id:s,relay:r}),await this.rpcUnsubscribe(e,s,r);const n=me("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:i}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,s,i){var r;(!i||(i==null?void 0:i.transportType)===Ne.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const n={method:Ki(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===Ne.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(d=>this.logger.warn(d))},U.toMiliseconds(U.ONE_SECOND)),a;const c=new Promise(async d=>{const u=h=>{h.topic===e&&(this.events.removeListener(ht.created,u),d(h.id))};this.events.on(ht.created,u);try{const h=await ms(new Promise((g,w)=>{this.relayer.request(n).catch(m=>{this.logger.warn(m,m==null?void 0:m.message),w(m)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(ht.created,u),d(h)}catch{}}),l=await ms(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(qe.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,i={method:Ki(s.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await ms(new Promise(r=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(qe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,i={method:Ki(s.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let r;try{r=await await ms(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(qe.connection_stalled)}return r}rpcUnsubscribe(e,s,i){const r={method:Ki(i.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,An(qi({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,qi({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,i){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,i),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,qi({},s)),this.topicMap.set(s.topic,e),this.events.emit(ht.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:i}=$("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(ht.deleted,An(qi({},i),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ht.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<s;i++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(ht.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:s}=$("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=>An(qi({}
13,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 Ih(U.toMiliseconds(U.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}=$("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 zt(e+await this.getClientId())}}var yy=Object.defineProperty,Za=Object.getOwnPropertySymbols,by=Object.prototype.hasOwnProperty,vy=Object.prototype.propertyIsEnumerable,oo=(t,e,s)=>e in t?yy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qa=(t,e)=>{for(var s in e||(e={}))by.call(e,s)&&oo(t,s,e[s]);if(Za)for(var s of Za(e))vy.call(e,s)&&oo(t,s,e[s]);return t},le=(t,e,s)=>oo(t,typeof e!="symbol"?e+"":e,s);class Ey extends Iu{constructor(e){super(e),le(this,"protocol","wc"),le(this,"version",2),le(this,"core"),le(this,"logger"),le(this,"events",new js.EventEmitter),le(this,"provider"),le(this,"messages"),le(this,"subscriber"),le(this,"publisher"),le(this,"name",Yf),le(this,"transportExplicitlyClosed",!1),le(this,"initialized",!1),le(this,"connectionAttemptInProgress",!1),le(this,"relayUrl"),le(this,"projectId"),le(this,"packageName"),le(this,"bundleId"),le(this,"hasExperiencedNetworkDisruption",!1),le(this,"pingTimeout"),le(this,"heartBeatTimeout",U.toMiliseconds(U.THIRTY_SECONDS+U.FIVE_SECONDS)),le(this,"reconnectTimeout"),le(this,"connectPromise"),le(this,"reconnectInProgress",!1),le(this,"requestsInFlight",[]),le(this,"connectTimeout",U.toMiliseconds(U.ONE_SECOND*15)),le(this,"request",async s=>{var i,r;this.logger.debug("Publishing Request Payload");const n=s.id||di().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:s.method,topic:(i=s.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((r=s.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(s);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),le(this,"resetPingTimeout",()=>{qr()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var s,i,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(i=(s=this.provider)==null?void 0:s.connection)==null?void 0:i.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),le(this,"onPayloadHandler",s=>{this.onProviderPayload(s),this.resetPingTimeout()}),le(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(qe.connect)}),le(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),le(this,"onProviderErrorHandler",s=>{this.logger.fatal(`Fatal socket error: ${s.message}`),this.events.emit(qe.error,s),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),le(this,"registerProviderListeners",()=>{this.provider.on(Ct.payload,this.onPayloadHandler),this.provider.on(Ct.connect,this.onConnectHandler),this.provider.on(Ct.disconnect,this.onDisconnectHandler),this.provider.on(Ct.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?tt(e.logger,this.name):bo(ur({level:e.logger||Jf})),this.messages=new sy(this.logger,e.core),this.subscriber=new wy(this,this.logger),this.publisher=new cy(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Ll,this.projectId=e.projectId,ah()?this.packageName=Xo():ch()&&(this.bundleId=Xo()),this.provider={}}
13async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return yt(this.logger)}get connected(){var e,s,i;return((i=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,s,i;return((i=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,i){this.isInitialized(),await this.publisher.publish(e,s,i),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:Ne.relay},Lr.outbound)}async subscribe(e,s){var i,r,n;this.isInitialized(),(!(s!=null&&s.transportType)||(s==null?void 0:s.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=s==null?void 0:s.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(r=s==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=d=>{d.topic===e&&(this.subscriber.off(ht.created,l),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(ht.created,l)}),new Promise(async(d,u)=>{a=await this.subscriber.subscribe(e,Qa({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 ms(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.warn("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,i)=>{await this.connect(e).then(s).catch(i).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 Fa())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((i,r)=>i.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const i of s)try{await this.onMessageEvent(i)}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:i}=e;if(!s.sessionExists){const r=Ue(U.FIVE_MINUTES),n={topic:i,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(qe.message,e),await this.recordMessageEvent(e,Lr.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(i,r)=>{const n=()=>
vendor: 20,847 bytes, line 13
13{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ct.disconnect,n),await ms(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(Ct.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ct.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Ct.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const r=i;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(i=>setTimeout(i,U.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,i,r,n;if(qr())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((n=(r=(i=this.provider)==null?void 0:i.connection)==null?void 0:r.socket)==null||n.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 _t(new bd(ph({sdkVersion:eo,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:i,message:r}=e;await this.messages.set(i,r,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const r=this.messages.has(s,i);return r&&this.logger.warn(`Ignoring duplicate message: ${i}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),mo(e)){if(!e.method.endsWith(Xf))return;const s=e.params,{topic:i,message:r,publishedAt:n,attestation:o}=s.data,a={topic:i,message:r,publishedAt:n,transportType:Ne.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Qa({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else wo(e)&&this.events.emit(qe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Lr.inbound),this.events.emit(qe.message,e))}async acknowledgePayload(e){const s=Gr(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Ct.payload,this.onPayloadHandler),this.provider.off(Ct.connect,this.onConnectHandler),this.provider.off(Ct.disconnect,this.onDisconnectHandler),this.provider.off(Ct.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Fa();Df(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Si.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Ff())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(qe.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},U.toMiliseconds(Zf)))))}isInitialized(){if(!this.initialized){const{message:e}=$("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 Cy(){}function ec(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 tc(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function sc(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const Iy="[object RegExp]",Ny="[object String]",Ay="[object Number]",_y="[object Boolean]",ic="[object Arguments]",Sy="[object Symbol]",Py="[object Date]",Oy="[object Map]",Ty="[object Set]",ky="[object Array]",xy="[object Function]",Ry="[object ArrayBuffer]",_n="[object Object]",$y="[object Error]",Uy="[object DataView]",Dy="[object Uint8Array]",Ly="[object Uint8ClampedArray]",My="[object Uint16Array]",Fy="[object Uint32Array]",By="[object BigUint64Array]",qy="[object Int8Array]",jy="[object Int16Array]",Wy="[object Int32Array]",zy="[object BigInt64Array]",Hy="[object Float32Array]",Ky="[object Float64Array]";function Vy(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Gy(t,e,s){return Vi(t,e,void 0,void 0,void 0,void 0,s)}function Vi(t,e,s,i,r,n,o){const a=o(t,e,s,i,r,n);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 sr(t,e,n,o)}return sr(t,e,n,o)}function sr(t,e,s,i){if(Object.is(t,e))return!0;let r=sc(t),n=sc(e);if(r===ic&&(r=_n),n===ic&&(n=_n),r!==n)return!1;switch(r){case Ny:return t.toString()===e.toString();case Ay:{const c=t.valueOf(),l=e.valueOf();return Vy(c,l)}case _y:case Py:case Sy:return Object.is(t.valueOf(),e.valueOf());case Iy:return t.source===e.source&&t.flags===e.flags;case xy: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 Oy:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Vi(l,e.get(c),c,t,e,s,i))return!1;return!0}case Ty:{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(g=>Vi(u,g,void 0,t,e,s,i));if(h===-1)return!1;l.splice(h,1)}return!0}case ky:case Dy:case Ly:case My:case Fy:case By:case qy:case jy:case Wy:case zy:case Hy:case Ky:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Vi(t[c],e[c],c,t,e,s,i))return!1;return!0}case Ry:return t.byteLength!==e.byteLength?!1:sr(new Uint8Array(t),new Uint8Array(e),s,i);case Uy:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:sr(new Uint8Array(t),new Uint8Array(e),s,i);case $y:return t.name===e.name&&t.message===e.message;case _n:{if(!(sr(t.constructor,e.constructor,s,i)||ec(t)&&ec(e)))return!1;const c=[...Object.keys(t),...tc(t)],l=[...Object.keys(e),...tc(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 g=e[u];if(!Vi(h,g,u,t,e,s,i))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function Jy(t,e){return Gy(t,e,Cy)}var Yy=Object.defineProperty,rc=Object.getOwnPropertySymbols,Xy=Object.prototype.hasOwnProperty,Zy=Object.prototype.propertyIsEnumerable,ao=(t,e,s)=>e in t?Yy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,nc=(t,e)=>{for(var s in e||(e={}))Xy.call(e,s)&&ao(t,s,e[s]);if(rc)for(var s of rc(e))Zy.call(e,s)&&ao(t,s,e[s]);return t},nt=(t,e,s)=>ao(t,typeof e!="symbol"?e+"":e,s);class Ws extends Nu{constructor(e,s,i,r=Kt,n=void 0){super(e,s,i,r),this.core=e,this.logger=s,this.name=i,nt(this,"map",new Map),nt(this,"version",Qf),nt(this,"cached",[]),nt(this,"initialized",!1),nt(this,"getKey"),nt(this,"storagePrefix",Kt),nt(this,"recentlyDeleted",[]),nt(this,"recentlyDeletedLimit",200),nt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ve(o)?this.map.set(this.getKey(o),o):pf(o)?this.map.set(o.id,o):gf(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),nt(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())}),nt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),nt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Jy(a[c],o[c]))):this.values)),nt(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=nc(nc({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),nt(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=tt(s,this.name),this.storagePrefix=r,this.getKey=n}get context(){return yt(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}=$("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:i}=$("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}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}=$("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}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Qy=Object.defineProperty,eb=(t,e,s)=>e in t?Qy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,re=(t,e,s)=>eb(t,typeof e!="symbol"?e+"":e,s);class tb{constructor(e,s){this.core=e,this.logger=s,re(this,"name",im),re(this,"version",rm),re(this,"events",new yo),re(this,"pairings"),re(this,"initialized",!1),re(this,"storagePrefix",Kt),re(this,"ignoredPayloadTypes",[ns]),re(this,"registeredMethods",[]),re(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),re(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),re(this,"create",async i=>{this.isInitialized();const r=Qn(),n=await this.core.crypto.setSymKey(r),o=Ue(U.FIVE_MINUTES),a={protocol:Dl},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=Ta({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(xs.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:l}}),re(this,"pair",async i=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[qt.pairing_started]}});this.isValidPair(i,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Oa(i.uri);r.props.properties.topic=n,r.addTrace(qt.pairing_uri_validation_success),r.addTrace(qt.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(n)){if(d=this.pairings.get(n),r.addTrace(qt.existing_pairing),d.active)throw r.setError(ts.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(qt.pairing_not_expired)}const u=c||Ue(U.FIVE_MINUTES),h={topic:n,relay:a,expiry:u,active:!1,methods:l};this.core.expirer.set(n,u),await this.pairings.set(n,h),r.addTrace(qt.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(xs.create,h),r.addTrace(qt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(qt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(ts.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(g){throw r.setError(ts.subscribe_pairing_topic_failure),g}return r.addTrace(qt.subscribe_pairing_topic_success),h}),re(this,"activate",async({topic:i})=>{this.isInitialized();const r=Ue(U.FIVE_MINUTES);this.core.expirer.set(i,r),await this.pairings.update(i,{active:!0,expiry:r})}),re(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=i;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Os();this.events.once(pe("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),re(this,"updateExpiry",async({topic:i,expiry:r})=>{this.isInitialized(),await this.pairings.update(i,{expiry:r})}),re(this,"updateMetadata",async({topic:i,metadata:r})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:r})}),re(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),re(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:r}=i;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",me("USER_DISCONNECTED")),await this.deletePairing(r))}),re(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(r);return Ta({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),re(this,"sendRequest",async(i,r,n)=>{const o=$s(r,n),a=await this.core.crypto.encode(i,o),c=Fi[r].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),re(this,"sendResult",async(i,r,n)=>{const o=Gr(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=Fi[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),re(this,"sendError",async(i,r,n)=>{const o=Rc(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=Fi[c]?Fi[c].res:Fi.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),re(this,"deletePairing",async(i,r)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,me("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),r?Promise.resolve():this.core.expirer.del(i)])}),re(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(r=>ps(r.expiry));await Promise.all(i.map(r=>this.deletePairing(r.topic)))}),re(this,"onRelayEventRequest",async i=>{const{topic:r,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,n);default:return await this.onUnknownRpcMethodRequest(r,n)}}),re(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n}=i,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),re(this,"onPairingPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(xs.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),re(this,"onPairingPingResponse",(i,r)=>{const{id:n}=r;setTimeout(()=>{es(r)?this.events.emit(pe("pairing_ping",n),{}):jt(r)&&this.events.emit(pe("pairing_ping",n),{error:r.error})},500)}),re(this,"onPairingDeleteRequest",async(i,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(xs.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),re(this,"onUnknownRpcMethodRequest",async(i,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=me("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),re(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(me("WC_METHOD_UNSUPPORTED",i))}),re(this,"isValidPair",(i,r)=>{var n;if(!at(i)){const{message:a}=$("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(ts.malformed_pairing_uri),new Error(a)}if(!hf(i.uri)){const{message:a}=$("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(ts.malformed_pairing_uri),new Error(a)}const o=Oa(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=$("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(ts.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=$("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(ts.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&U.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(ts.pairing_expired);const{message:a}=$("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),re(this,"isValidPing",async i=>{if(!at(i)){const{message:n}=$("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),re(this,"isValidDisconnect",async i=>{if(!at(i)){const{message:n}=$("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),re(this,"isValidPairingTopic",async i=>{if(!ke(i,!1)){const{message:r}=$("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(r)}if(!this.pairings.keys.includes(i)){const{message:r}=$("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(r)}if(ps(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:r}=$("EXPIRED",`pairing topic: ${i}`);throw new Error(r)}}),this.core=e,this.logger=tt(s,this.name),this.pairings=new Ws(this.core,this.logger,this.name,this.storagePrefix)}get context(){return yt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(qe.message,async e=>{const{topic:s,message:i,transportType:r}=e;if(this.pairings.keys.includes(s)&&r!==Ne.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(s,i);mo(n)?(this.core.history.set(s,n),await this.onRelayEventRequest({topic:s,payload:n})):wo(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:s,payload:n}),this.core.history.delete(s,n.id)),await this.core.relayer.messages.ack(s,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(Nt.expired,async e=>{const{topic:s}=Zc(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(xs.expire,{topic:s}))})}}var sb=Object.defineProperty,ib=(t,e,s)=>e in t?sb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ke=(t,e,s)=>ib(t,typeof e!="symbol"?e+"":e,s);class rb extends vu{constructor(e,s){super(e,s),this.core=e,this.logger=s,Ke(this,"records",new Map),Ke(this,"events",new js.EventEmitter),Ke(this,"name",nm),Ke(this,"version",om),Ke(this,"cac
13hed",[]),Ke(this,"initialized",!1),Ke(this,"storagePrefix",Kt),Ke(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ke(this,"set",(i,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:i,request:{method:r.method,params:r.params||null},chainId:n,expiry:Ue(U.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ot.created,o)}),Ke(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const r=await this.getRecord(i.id);typeof r.response>"u"&&(r.response=jt(i)?{error:i.error}:{result:i.result},this.records.set(r.id,r),this.persist(),this.events.emit(Ot.updated,r))}),Ke(this,"get",async(i,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:r}),await this.getRecord(r))),Ke(this,"delete",(i,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===i){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(Ot.deleted,n)}}),this.persist()}),Ke(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),Ke(this,"on",(i,r)=>{this.events.on(i,r)}),Ke(this,"once",(i,r)=>{this.events.once(i,r)}),Ke(this,"off",(i,r)=>{this.events.off(i,r)}),Ke(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=tt(s,this.name)}get context(){return yt(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 i={topic:s.topic,request:$s(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(i)}),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:i}=$("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=$("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(Ot.created,e=>{const s=Ot.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Ot.updated,e=>{const s=Ot.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Ot.deleted,e=>{const s=Ot.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(Si.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{U.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(Ot.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var nb=Object.defineProperty,ob=(t,e,s)=>e in t?nb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ye=(t,e,s)=>ob(t,typeof e!="symbol"?e+"":e,s);class ab extends _u{constructor(e,s){super(e,s),this.core=e,this.logger=s,Ye(this,"expirations",new Map),Ye(this,"events",new js.EventEmitter),Ye(this,"name",am),Ye(this,"version",cm),Ye(this,"cac
13hed",[]),Ye(this,"initialized",!1),Ye(this,"storagePrefix",Kt),Ye(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ye(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ye(this,"set",(i,r)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Nt.created,{target:n,expiration:o})}),Ye(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),Ye(this,"del",i=>{if(this.isInitialized(),this.has(i)){const r=this.formatTarget(i),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Nt.deleted,{target:r,expiration:n})}}),Ye(this,"on",(i,r)=>{this.events.on(i,r)}),Ye(this,"once",(i,r)=>{this.events.once(i,r)}),Ye(this,"off",(i,r)=>{this.events.off(i,r)}),Ye(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=tt(s,this.name)}get context(){return yt(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 gh(e);if(typeof e=="number")return fh(e);const{message:s}=$("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(Nt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=$("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:i}=$("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return s}checkExpiry(e,s){const{expiry:i}=s;U.toMiliseconds(i)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(Nt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(Si.pulse,()=>this.checkExpirations()),this.events.on(Nt.created,e=>{const s=Nt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Nt.expired,e=>{const s=Nt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Nt.deleted,e=>{const s=Nt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}}var cb=Object.defineProperty,lb=(t,e,s)=>e in t?cb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Te=(t,e,s)=>lb(t,typeof e!="symbol"?e+"":e,s);class db extends Su{constructor(e,s,i){super(e,s,i),this.core=e,this.logger=s,this.store=i,Te(this,"name",lm),Te(this,"abortController"),Te(this,"isDevEnv"),Te(this,"verifyUrlV3",um),Te(this,"storagePrefix",Kt),Te(this,"version",Ul),Te(this,"publicKey"),Te(this,"fetchPromise"),Te(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&U.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Te(this,"register",async r=>{if(!Ti()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=wi(),d=this.startAbortTimer(U.ONE_SECOND*5),u=await new Promise((h,g)=>{const w=()=>{window.removeEventListener("message",f),l.body.removeChild(m),g("attestation aborted")};this.abortController.signal.addEventListener("abort",w);const m=l.createElement("iframe");m.src=c,m.style.display="none",m.addEventListener("error",w,{signal:this.abortController.signal});const f=y=>
vendor: 11,583 bytes, line 13
13{if(y.data&&typeof y.data=="string")try{const b=JSON.parse(y.data);if(b.type==="verify_attestation"){if(Un(b.attestation).payload.id!==o)return;clearInterval(d),l.body.removeChild(m),this.abortController.signal.removeEventListener("abort",w),window.removeEventListener("message",f),h(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};l.body.appendChild(m),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(l){this.logger.warn(l)}return""}),Te(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(Un(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);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)}),Te(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(U.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),Te(this,"getVerifyUrl",r=>{let n=r||tr;return hm.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${tr}`),n=tr),n}),Te(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(U.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),Te(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),Te(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Te(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}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")}}),Te(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Te(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),Te(this,"validateAttestation",(r,n)=>{const o=zg(r,n.publicKey),a={hasExpired:U.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=tt(s,this.name),this.abortController=new AbortController,this.isDevEnv=vo(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return yt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),U.toMiliseconds(e))}}var ub=Object.defineProperty,hb=(t,e,s)=>e in t?ub(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oc=(t,e,s)=>hb(t,typeof e!="symbol"?e+"":e,s);class pb extends Pu{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,oc(this,"context",pm),oc(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${gm}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=tt(s,this.context)}}var gb=Object.defineProperty,ac=Object.getOwnPropertySymbols,fb=Object.prototype.hasOwnProperty,mb=Object.prototype.propertyIsEnumerable,co=(t,e,s)=>e in t?gb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ji=(t,e)=>{for(var s in e||(e={}))fb.call(e,s)&&co(t,s,e[s]);if(ac)for(var s of ac(e))mb.call(e,s)&&co(t,s,e[s]);return t},Me=(t,e,s)=>co(t,typeof e!="symbol"?e+"":e,s);class wb extends Ou{constructor(e,s,i=!0){super(e,s,i),this.core=e,this.logger=s,Me(this,"context",mm),Me(this,"storagePrefix",Kt),Me(this,"storageVersion",fm),Me(this,"events",new Map),Me(this,"shouldPersist",!1),Me(this,"init",async()=>{if(!vo())try{const r={eventId:Qo(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Yc(this.core.relayer.protocol,this.core.relayer.version,eo)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),Me(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=Qo(),d=this.core.projectId||"",u=Date.now(),h=ji({eventId:l,timestamp:u,props:{event:n,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}),Me(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return ji(ji({},a),this.setMethods(a.eventId))}),Me(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),Me(this,"setEventListeners",()=>{this.core.heartbeat.on(Si.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{U.fromMiliseconds(Date.now())-U.fromMiliseconds(r.timestamp)>wm&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),Me(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),Me(this,"addTrace",(r,n)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(n),this.events.set(r,o),this.shouldPersist=!0)}),Me(this,"setError",(r,n)=>{const o=this.events.get(r);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),Me(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Me(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(n=>{this.events.set(n.eventId,ji(ji({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),Me(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[n,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const n of r)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),Me(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${ym}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${eo}${n}`,{method:"POST",body:JSON.stringify(r)})}),Me(this,"getAppDomain",()=>Jc().url),this.logger=tt(s,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var yb=Object.defineProperty,cc=Object.getOwnPropertySymbols,bb=Object.prototype.hasOwnProperty,vb=Object.prototype.propertyIsEnumerable,lo=(t,e,s)=>e in t?yb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,lc=(t,e)=>{for(var s in e||(e={}))bb.call(e,s)&&lo(t,s,e[s]);if(cc)for(var s of cc(e))vb.call(e,s)&&lo(t,s,e[s]);return t},Ie=(t,e,s)=>lo(t,typeof e!="symbol"?e+"":e,s);let Eb=class Jl extends mu{constructor(e){var s;super(e),Ie(this,"protocol",$l),Ie(this,"version",Ul),Ie(this,"name",Hr),Ie(this,"relayUrl"),Ie(this,"projectId"),Ie(this,"customStoragePrefix"),Ie(this,"events",new js.EventEmitter),Ie(this,"logger"),Ie(this,"heartbeat"),Ie(this,"relayer"),Ie(this,"crypto"),Ie(this,"storage"),Ie(this,"history"),Ie(this,"expirer"),Ie(this,"pairing"),Ie(this,"verify"),Ie(this,"echoClient"),Ie(this,"linkModeSupportedApps"),Ie(this,"eventClient"),Ie(this,"initialized",!1),Ie(this,"logChunkController"),Ie(this,"on",(a,c)=>this.events.on(a,c)),Ie(this,"once",(a,c)=>this.events.once(a,c)),Ie(this,"off",(a,c)=>this.events.off(a,c)),Ie(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Ie(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const d={topic:a,message:c,publishedAt:Date.now(),transportType:Ne.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:l})});const i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}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)||Ll,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=ur({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:Bf.logger,name:Hr}),{logger:n,chunkLoggerController:o}=$c({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=tt(n,this.name),this.heartbeat=new wd,this.crypto=new Gw(this,this.logger,e==null?void 0:e.keychain),this.history=new rb(this,this.logger),this.expirer=new ab(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new yd(lc(lc({},qf),e==null?void 0:e.storageOptions)),this.relayer=new Ey({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new tb(this,this.logger),this.verify=new db(this,this.logger,this.storage),this.echoClient=new pb(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new wb(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new Jl(e);await s.initialize();const i=await s.crypto.getClientId();return await s.storage.setItem(em,i),s}get context(){return yt(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(ja,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(
13),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(ja)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${e}`,i=`${s}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} 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 i=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const Cb=Eb,Yl="wc",Xl=2,Zl="client",Po=`${Yl}@${Xl}:${Zl}:`,Sn={name:Zl,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},dc="WALLETCONNECT_DEEPLINK_CHOICE",Ib="proposal",uc="Proposal expired",Nb="session",Js=U.SEVEN_DAYS,Ab="engine",Fe={wc_sessionPropose:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1104},res:{ttl:U.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1106},res:{ttl:U.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1112},res:{ttl:U.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1114},res:{ttl:U.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:U.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:U.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1119}}},Pn={min:U.FIVE_MINUTES,max:U.SEVEN_DAYS},Bt={idle:"IDLE",active:"ACTIVE"},hc={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},_b="request",Sb=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Pb="wc",Ob="auth",Tb="authKeys",kb="pairingTopics",xb="requests",sn=`${Pb}@${1.5}:${Ob}:`,Mr=`${sn}:PUB_KEY`;var Rb=Object.defineProperty,$b=Object.defineProperties,Ub=Object.getOwnPropertyDescriptors,pc=Object.getOwnPropertySymbols,Db=Object.prototype.hasOwnProperty,Lb=Object.prototype.propertyIsEnumerable,uo=(t,e,s)=>e in t?Rb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,be=(t,e)=>{for(var s in e||(e={}))Db.call(e,s)&&uo(t,s,e[s]);if(pc)for(var s of pc(e))Lb.call(e,s)&&uo(t,s,e[s]);return t},Qe=(t,e)=>$b(t,Ub(e)),N=(t,e,s)=>uo(t,typeof e!="symbol"?e+"":e,s);class Mb extends Ru{constructor(e){super(e),N(this,"name",Ab),N(this,"events",new yo),N(this,"initialized",!1),N(this,"requestQueue",{state:Bt.idle,queue:[]}),N(this,"sessionRequestQueue",{state:Bt.idle,queue:[]}),N(this,"requestQueueDelay",U.ONE_SECOND),N(this,"expectedPairingMethodMap",new Map),N(this,"recentlyDeletedMap",new Map),N(this,"recentlyDeletedLimit",200),N(this,"relayMessageCache",[]),N(this,"pendingSessions",new Map),N(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(Fe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay)))}),N(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Qe(be({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=af(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=i;let d=r,u,h=!1;try{if(d){const P=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=P.active}}catch(P){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),P}if(!d||!h){const{topic:P,uri:S}=await this.client.core.pairing.create();d=P,u=S}if(!d){const{message:P}=$("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(P)}const g=await this.client.core.crypto.generateKeyPair(),w=Fe.wc_sessionPropose.req.ttl||U.FIVE_MINUTES,m=Ue(w),f=Qe(be(be({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:Dl}],proposer:{publicKey:g,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:d},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:os()}),y=pe("session_connect",f.id),{reject:b,resolve:E,done:_}=Os(w,uc),x=({id:P})=>{P===f.id&&(this.client.events.off("proposal_expire",x),this.pendingSessions.delete(f.id),this.events.emit(y,{error:{message:uc,code:0}}))};return this.client.events.on("proposal_expire",x),this.events.once(y,({error:P,session:S})=>{this.client.events.off("proposal_expire",x),P?b(P):S&&E(S)}),await this.sendRequest({topic:d,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:u,approval:_}}),N(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(i){throw this.client.logger.error("pair() failed"),i}}),N(this,"approve",async s=>{var i,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=s==null?void 0:s.id)==null?void 0:i.toString(),trace:[Tt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(v){throw o.setError(_s.no_internet_connection),v}try{await this.isValidProposalId(s==null?void 0:s.id)}catch(v){throw this.client.logger.error(`approve() -> proposal.get(${s==null?void 0:s.id}) failed`),o.setError(_s.proposal_not_found),v}try{await this.isValidApprove(s)}catch(v){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(_s.session_approve_namespace_validation_failure),v}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=s,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:w,proposer:m,requiredNamespaces:f,optionalNamespaces:y}=g;let b=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:w});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Tt.session_approve_started,properties:{topic:w,trace:[Tt.session_approve_started,Tt.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),_=m.publicKey,x=await this.client.core.crypto.generateSharedKey(E,_),P=be(be(be({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:E,metadata:this.client.metadata},expiry:Ue(Js)},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),S=Ne.relay;b.addTrace(Tt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(x,{transportType:S})}catch(v){throw b.setError(_s.subscribe_session_topic_failure),v}b.addTrace(Tt.subscribe_session_topic_success);const D=Qe(be({},P),{topic:x,requiredNamespaces:f,optionalNamespaces:y,pairingTopic:w,acknowledged:!1,self:P.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:E,transportType:Ne.relay});await this.client.session.set(x,D),b.addTrace(Tt.store_session);try{b.addTrace(Tt.publishing_session_settle),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:P,throwOnFailedPublish:!0}).catch(v=>{throw b==null||b.setError(_s.session_settle_publish_failure),v}),b.addTrace(Tt.session_settle_publish_success),b.addTrace(Tt.publishing_session_approve),await this.sendResult({id:a,topic:w,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(v=>{throw b==null||b.setError(_s.session_approve_publish_failure),v}),b.addTrace(Tt.session_approve_publish_success)}catch(v){throw this.client.logger.error(v),this.client.session.delete(x,me("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),v}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:m.metadata}),await this.client.proposal.delete(a,me("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(x,Ue(Js)),{topic:x,acknowledged:()=>Promise.resolve(this.client.session.get(x))}}),N(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:i,reason:r}=s;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}
13n&&(await this.sendError({id:i,topic:n,error:r,rpcOpts:Fe.wc_sessionPropose.reject}),await this.client.proposal.delete(i,me("USER_DISCONNECTED")))}),N(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:i,namespaces:r}=s,{done:n,resolve:o,reject:a}=Os(),c=os(),l=di().toString(),d=this.client.session.get(i).namespaces;return this.events.once(pe("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(i,{namespaces:r}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(u=>{this.client.logger.error(u),this.client.session.update(i,{namespaces:d}),a(u)}),{acknowledged:n}}),N(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:i}=s,r=os(),{done:n,resolve:o,reject:a}=Os();return this.events.once(pe("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,Ue(Js)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),N(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:i,request:r,topic:n,expiry:o=Fe.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Ne.relay&&await this.confirmOnlineStateOrThrow();const c=os(),l=di().toString(),{done:d,resolve:u,reject:h}=Os(o,"Request expired. Please try again.");this.events.once(pe("session_request",c),({error:y,result:b})=>{y?h(y):u(b)});const g="wc_sessionRequest",w=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(w)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:g,params:{request:Qe(be({},r),{expiryTimestamp:Ue(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:w}).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),await d();const m={request:Qe(be({},r),{expiryTimestamp:Ue(o)}),chainId:i},f=this.shouldSetTVF(g,m);return await Promise.all([new Promise(async y=>{await this.sendRequest(be({clientRpcId:c,relayRpcId:l,topic:n,method:g,params:m,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,m)})).catch(b=>h(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),y()}),new Promise(async y=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const E=await bh(this.client.core.storage,dc);await mh({id:c,topic:n,wcDeepLink:E})}y()}),d()]).then(y=>y[2])}),N(this,"respond",async s=>{this.isInitialized(),await this.isValidRespond(s);const{topic:i,response:r}=s,{id:n}=r,o=this.client.session.get(i);o.transportType===Ne.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);es(r)?await this.sendResult({id:n,topic:i,result:r.result,throwOnFailedPublish:!0,appLink:a}):jt(r)&&await this.sendError({id:n,topic:i,error:r.error,appLink:a}),this.cleanupAfterResponse(s)}),N(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:i}=s;if(this.client.session.keys.includes(i)){const r=os(),n=di().toString(),{done:o,resolve:a,reject:c}=Os();this.events.once(pe("session_ping",r),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(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:i}))}),N(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:i,event:r,chainId:n}=s,o=di().toString(),a=os();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),N(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:i}=s;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:me("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:r}=$("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(r)}}),N(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(i=>df(i,s)))),N(this,"getPendingSessionRequests",()=>
vendor: 9,804 bytes, line 13
13this.client.pendingRequest.getAll()),N(this,"authenticate",async(s,i)=>{var r;this.isInitialized(),this.isValidAuthenticate(s);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?Ne.link_mode:Ne.relay;o===Ne.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:d,nonce:u,type:h,exp:g,nbf:w,methods:m=[],expiry:f}=s,y=[...s.resources||[]],{topic:b,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:E}});const _=await this.client.core.crypto.generateKeyPair(),x=Dr(_);if(await Promise.all([this.client.auth.authKeys.set(Mr,{responseTopic:x,publicKey:_}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:b})]),await this.client.core.relayer.subscribe(x,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),m.length>0){const{namespace:k}=fi(a[0]);let G=up(k,"request",m);Ur(y)&&(G=pp(G,y.pop())),y.push(G)}const P=f&&f>Fe.wc_sessionAuthenticate.req.ttl?f:Fe.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:d,version:"1",nonce:u,iat:new Date().toISOString(),exp:g,nbf:w,resources:y},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Ue(P)},D={eip155:{chains:a,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},v={requiredNamespaces:{},optionalNamespaces:D,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Ue(Fe.wc_sessionPropose.req.ttl),id:os()},{done:R,resolve:C,reject:L}=Os(P,"Request expired"),H=os(),I=pe("session_connect",v.id),T=pe("session_request",H),A=async({error:k,session:G})=>{this.events.off(T,F),k?L(k):G&&C({session:G})},F=async k=>{var G,Q,se;if(await this.deletePendingAuthRequest(H,{message:"fulfilled",code:0}),k.error){const Re=me("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return k.error.code===Re.code?void 0:(this.events.off(I,A),L(k.error.message))}await this.deleteProposal(v.id),this.events.off(I,A);const{cacaos:Ee,responder:he}=k.result,Oe=[],Le=[];for(const Re of Ee){await aa({cacao:Re,projectId:this.client.core.projectId})||(this.client.logger.error(Re,"Signature verification failed"),L(me("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ns}=Re,Vt=Ur(Ns.resources),Lt=[zn(Ns.iss)],Gt=jr(Ns.iss);if(Vt){const Jt=ca(Vt),Er=la(Vt);Oe.push(...Jt),Lt.push(...Er)}for(const Jt of Lt)Le.push(`${Jt}:${Gt}`)}const Je=await this.client.core.crypto.generateSharedKey(_,he.publicKey);let xe;Oe.length>0&&(xe={topic:Je,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:he,controller:he.publicKey,expiry:Ue(Js),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:$a([...new Set(Oe)],[...new Set(Le)]),transportType:o},await this.client.core.relayer.subscribe(Je,{transportType:o}),await this.client.session.set(Je,xe),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:he.metadata}),xe=this.client.session.get(Je)),(G=this.client.metadata.redirect)!=null&&G.linkMode&&(Q=he.metadata.redirect)!=null&&Q.linkMode&&(se=he.metadata.redirect)!=null&&se.universal&&i&&(this.client.core.addLinkModeSupportedApp(he.metadata.redirect.universal),this.client.session.update(Je,{transportType:Ne.link_mode})),C({auths:Ee,session:xe})};this.events.once(I,A),this.events.once(T,F);let j;try{if(n){const k=$s("wc_sessionAuthenticate",S,H);this.client.core.history.set(b,k);const G=await this.client.core.crypto.encode("",k,{type:yr,encoding:gs});j=Sr(i,b,G)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:S,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:H}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:v,expiry:Fe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:v.id})])}catch(k){throw this.events.off(I,A),this.events.off(T,F),k}return await this.setProposal(v.id,v),await this.setAuthRequest(H,{request:Qe(be({},S),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:j??E,response:R}}),N(this,"approveSessionAuthenticate",async s=>{const{id:i,auths:r}=s,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Ss.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(Bi.no_internet_connection),f}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(Bi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Ne.relay;a===Ne.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=Dr(c),u={type:ns,receiverPublicKey:c,senderPublicKey:l},h=[],g=[];for(const f of r){if(!await aa({cacao:f,projectId:this.client.core.projectId})){n.setError(Bi.invalid_cacao);const x=me("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:d,error:x,encodeOpts:u}),new Error(x.message)}n.addTrace(Ss.cacaos_verified);const{p:y}=f,b=Ur(y.resources),E=[zn(y.iss)],_=jr(y.iss);if(b){const x=ca(b),P=la(b);h.push(...x),E.push(...P)}for(const x of E)g.push(`${x}:${_}`)}const w=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Ss.create_authenticated_session_topic);let m;if((h==null?void 0:h.length)>0){m={topic:w,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Ue(Js),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:$a([...new Set(h)],[...new Set(g)]),transportType:a},n.addTrace(Ss.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:a})}catch(f){throw n.setError(Bi.subscribe_authenticated_session_topic_failure),f}n.addTrace(Ss.subscribe_authenticated_session_topic_success),await this.client.session.set(w,m),n.addTrace(Ss.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Ss.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:i,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(f){throw n.setError(Bi.authenticated_session_approve_publish_failure),f}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:m}}),N(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:i,reason:r}=s,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===Ne.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Dr(o),l={type:ns,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:r,encodeOpts:l,rpcOpts:Fe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,me("USER_DISCONNECTED"))}),N(this,"formatAuthMessage",s=>{this.isInitialized();const{request:i,iss:r}=s;return al(i,r)}),N(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)}),N(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const i=this.client.core.pairing.pairings.get(s.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),N(this,"deleteSession",async s=>{var i;const{topic:r,expirerHasDeleted:n=!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,me("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),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(dc).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,me("USER_DISCONNECTED"))}),r===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Bt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),N(this,"deleteProposal",async(s,i)=>{if(i)try{const r=this.client.proposal.get(s),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(_s.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,me("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),N(this,"deletePendingSessionRequest",async(s,i,r=!1)=>
13{await Promise.all([this.client.pendingRequest.delete(s,i),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==s),r&&(this.sessionRequestQueue.state=Bt.idle,this.client.events.emit("session_request_expire",{id:s}))}),N(this,"deletePendingAuthRequest",async(s,i,r=!1)=>{await Promise.all([this.client.auth.requests.delete(s,i),r?Promise.resolve():this.client.core.expirer.del(s)])}),N(this,"setExpiry",async(s,i)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,i),await this.client.session.update(s,{expiry:i}))}),N(this,"setProposal",async(s,i)=>{this.client.core.expirer.set(s,Ue(Fe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,i)}),N(this,"setAuthRequest",async(s,i)=>{const{request:r,pairingTopic:n,transportType:o=Ne.relay}=i;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:n,verifyContext:r.verifyContext,transportType:o})}),N(this,"setPendingSessionRequest",async s=>{const{id:i,topic:r,params:n,verifyContext:o}=s,a=n.request.expiryTimestamp||Ue(Fe.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:r,params:n,verifyContext:o})}),N(this,"sendRequest",async s=>{const{topic:i,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:d,tvf:u}=s,h=$s(r,n,c);let g;const w=!!d;try{const y=w?gs:Ut;g=await this.client.core.crypto.encode(i,h,{encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),y}let m;if(Sb.includes(r)){const y=zt(JSON.stringify(h)),b=zt(g);m=await this.client.core.verify.register({id:b,decryptedId:y})}const f=Fe[r].req;if(f.attestation=m,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(i,h),w){const y=Sr(d,i,g);await global.Linking.openURL(y,this.client.name)}else{const y=Fe[r].req;o&&(y.ttl=o),a&&(y.id=a),y.tvf=Qe(be({},u),{correlationId:h.id}),l?(y.internal=Qe(be({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,g,y)):this.client.core.relayer.publish(i,g,y).catch(b=>this.client.logger.error(b))}return h.id}),N(this,"sendResult",async s=>{const{id:i,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=Gr(i,n);let d;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const w=u?gs:Ut;d=await this.client.core.crypto.encode(r,l,Qe(be({},a||{}),{encoding:w}))}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),w}let h,g;try{h=await this.client.core.history.get(r,i);const w=h.request;try{this.shouldSetTVF(w.method,w.params)&&(g=this.getTVFParams(i,w.params,n))}catch(m){this.client.logger.warn("sendResult() -> getTVFParams() failed",m)}}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${i}) failed`),w}if(u){const w=Sr(c,r,d);await global.Linking.openURL(w,this.client.name)}else{const w=h.request.method,m=Fe[w].res;m.tvf=Qe(be({},g),{correlationId:i}),o?(m.internal=Qe(be({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,d,m)):this.client.core.relayer.publish(r,d,m).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(l)}),N(this,"sendError",async s=>{const{id:i,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=Rc(i,n);let d;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const g=u?gs:Ut;d=await this.client.core.crypto.encode(r,l,Qe(be({},o||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),g}let h;try{h=await this.client.core.history.get(r,i)}catch(g){throw this.client.logger.error(`sendError() -> history.get(${r}, ${i}) failed`),g}if(u){const g=Sr(c,r,d);await global.Linking.openURL(g,this.client.name)}else{const g=h.request.method,w=a||Fe[g].res;this.client.core.relayer.publish(r,d,w)}await this.client.core.history.resolve(l)}),N(this,"cleanup",async()=>{const s=[],i=[];
vendor: 14,060 bytes, line 13
13this.client.session.getAll().forEach(r=>{let n=!1;ps(r.expiry)&&(n=!0),this.client.core.crypto.keychain.has(r.topic)||(n=!0),n&&s.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{ps(r.expiryTimestamp)&&i.push(r.id)}),await Promise.all([...s.map(r=>this.deleteSession({topic:r})),...i.map(r=>this.deleteProposal(r))])}),N(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),N(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),N(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Bt.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=Bt.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Bt.idle}),N(this,"processRequest",async s=>{const{topic:i,payload:r,attestation:n,transportType:o,encryptedId:a}=s,c=r.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,r);case"wc_sessionPing":return await this.onSessionPingRequest(i,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),N(this,"onRelayEventResponse",async s=>{const{topic:i,payload:r,transportType:n}=s,o=(await this.client.core.history.get(i,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,r);case"wc_sessionExtend":return this.onSessionExtendResponse(i,r);case"wc_sessionPing":return this.onSessionPingResponse(i,r);case"wc_sessionRequest":return this.onSessionRequestResponse(i,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),N(this,"onRelayEventUnknownPayload",s=>{const{topic:i}=s,{message:r}=$("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),N(this,"shouldIgnorePairingRequest",s=>{const{topic:i,requestMethod:r}=s,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),N(this,"onSessionProposeRequest",async s=>{const{topic:i,payload:r,attestation:n,encryptedId:o}=s,{params:a,id:c}=r;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(ts.proposal_listener_not_found)),this.isValidConnect(be({},r.params));const d=a.expiryTimestamp||Ue(Fe.wc_sessionPropose.req.ttl),u=be({id:c,pairingTopic:i,expiryTimestamp:d},a);await this.setProposal(c,u);const h=await this.getVerifyContext({attestationId:n,hash:zt(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});l==null||l.addTrace(qt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:h})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:Fe.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),N(this,"onSessionProposeResponse",async(s,i,r)=>{const{id:n}=i;if(es(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);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(n,{sessionTopic:d,pairingTopic:s,proposalId:n,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(jt(i)){await this.client.proposal.delete(n,me("USER_DISCONNECTED"));const o=pe("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),N(this,"onSessionSettleRequest",async(s,i)=>{const{id:r,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=i.params,g=[...this.pendingSessions.values()].find(f=>f.sessionTopic===s);if(!g)return this.client.logger.error(`Pending session not found for topic ${s}`);const w=this.client.proposal.get(g.proposalId),m=Qe(be(be(be({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),{transportType:Ne.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(pe("session_connect",g.proposalId),{session:m}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:i.id,topic:s,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),N(this,"onSessionSettleResponse",async(s,i)=>{const{id:r}=i;es(i)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(pe("session_approve",r),{})):jt(i)&&(await this.client.session.delete(s,me("USER_DISCONNECTED")),this.events.emit(pe("session_approve",r),{error:i.error}))}),N(this,"onSessionUpdateRequest",async(s,i)=>{const{params:r,id:n}=i;try{const o=`${s}_session_update`,a=Mi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:s,error:me("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(be({topic:s},r));try{Mi.set(o,n),await this.client.session.update(s,{namespaces:r.namespaces}),await this.sendResult({id:n,topic:s,result:!0,throwOnFailedPublish:!0})}catch(c){throw Mi.delete(o),c}this.client.events.emit("session_update",{id:n,topic:s,params:r})}catch(o){await this.sendError({id:n,topic:s,error:o}),this.client.logger.error(o)}}),N(this,"isRequestOutOfSync",(s,i)=>i.toString().slice(0,-3)<s.toString().slice(0,-3)),N(this,"onSessionUpdateResponse",(s,i)=>{const{id:r}=i,n=pe("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);es(i)?this.events.emit(pe("session_update",r),{}):jt(i)&&this.events.emit(pe("session_update",r),{error:i.error})}),N(this,"onSessionExtendRequest",async(s,i)=>{const{id:r}=i;try{this.isValidExtend({topic:s}),await this.setExpiry(s,Ue(Js)),await this.sendResult({id:r,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:r,topic:s})}catch(n){await this.sendError({id:r,topic:s,error:n}),this.client.logger.error(n)}}),N(this,"onSessionExtendResponse",(s,i)=>{const{id:r}=i,n=pe("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);es(i)?this.events.emit(pe("session_extend",r),{}):jt(i)&&this.events.emit(pe("session_extend",r),{error:i.error})}),N(this,"onSessionPingRequest",async(s,i)=>{const{id:r}=i;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(n){await this.sendError({id:r,topic:s,error:n}),this.client.logger.error(n)}}),N(this,"onSessionPingResponse",(s,i)=>{const{id:r}=i,n=pe("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);es(i)?this.events.emit(pe("session_ping",r),{}):jt(i)&&this.events.emit(pe("session_ping",r),{error:i.error})},500)}),N(this,"onSessionDeleteRequest",async(s,i)=>{const{id:r}=i;try{this.isValidDisconnect({topic:s,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(qe.publish,async()=>{n(await this.deleteSession({topic:s,id:r}))})}),this.sendResult({id:r,topic:s,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:me("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),N(this,"onSessionRequest",async s=>{var i,r,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:d}=s,{id:u,params:h}=a;try{await this.isValidRequest(be({topic:o},h));const g=this.client.session.get(o),w=await this.getVerifyContext({attestationId:c,hash:zt(JSON.stringify($s("wc_sessionRequest",h,u))),encryptedId:l,metadata:g.peer.metadata,transportType:d}),m={id:u,topic:o,params:h,verifyContext:w};await this.setPendingSessionRequest(m),d===Ne.link_mode&&(i=g.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((r=g.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(g){await this.sendError({id:u,topic:o,error:g}),this.client.logger.error(g)}}),N(this,"onSessionRequestResponse",(s,i)=>{const{id:r}=i,n=pe("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);es(i)?this.events.emit(pe("session_request",r),{result:i.result}):jt(i)&&this.events.emit(pe("session_request",r),{error:i.error})}),N(this,"onSessionEventRequest",async(s,i)=>{const{id:r,params:n}=i;try{const o=`${s}_session_event_${n.event.name}`,a=Mi.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(be({topic:s},n)),this.client.events.emit("session_event",{id:r,topic:s,params:n}),Mi.set(o,r)}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),N(this,"onSessionAuthenticateResponse",(s,i)=>{const{id:r}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:i}),es(i)?this.events.emit(pe("session_request",r),{result:i.result}):jt(i)&&this.events.emit(pe("session_request",r),{error:i.error})}),N(this,"onSessionAuthenticateRequest",async s=>{var i;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:d,expiryTimestamp:u}=n.params,h=await this.getVerifyContext({attestationId:o,hash:zt(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),g={requester:l,pairingTopic:r,id:n.id,authPayload:d,verifyContext:h,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:g,pairingTopic:r,transportType:c}),c===Ne.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:h})}catch(l){this.client.logger.error(l);const d=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(n.params.requester.metadata,c),g={type:ns,receiverPublicKey:d,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:l,encodeOpts:g,rpcOpts:Fe.wc_sessionAuthenticate.autoReject,appLink:h})}}),N(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),N(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Bt.idle,this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay))}),N(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:i})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===s&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=pe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(pe("session_request",n.request.id),{error:i})})}),N(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Bt.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.sessionRequestQueue.state=Bt.active,this.emitSessionRequest(s)}catch(i){this.client.logger.error(i)}}),N(this,"emitSessionRequest",s=>{this.client.events.emit("session_request",s)}),N(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const i=this.client.proposal.getAll().find(r=>r.pairingTopic===s.topic);
13i&&this.onSessionProposeRequest({topic:s.topic,payload:$s("wc_sessionPropose",Qe(be({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),N(this,"isValidConnect",async s=>{if(!at(s)){const{message:l}=$("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=s;if(Ve(i)||await this.isValidPairingTopic(i),!Cf(c,!0)){const{message:l}=$("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!Ve(r)&&vs(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(!Ve(n)&&vs(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Ve(o)||this.validateSessionProps(o,"sessionProperties"),!Ve(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(d=>l.includes(d)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),N(this,"validateNamespaces",(s,i)=>{const r=Ef(s,"connect()",i);if(r)throw new Error(r.message)}),N(this,"isValidApprove",async s=>{if(!at(s))throw new Error($("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:i,namespaces:r,relayProtocol:n,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),l=En(r,"approve()");if(l)throw new Error(l.message);const d=La(c.requiredNamespaces,r,"approve()");if(d)throw new Error(d.message);if(!ke(n,!0)){const{message:u}=$("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(Ve(o)||this.validateSessionProps(o,"sessionProperties"),!Ve(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(h=>u.has(h)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),N(this,"isValidReject",async s=>{if(!at(s)){const{message:n}=$("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(n)}const{id:i,reason:r}=s;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!Nf(r)){const{message:n}=$("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),N(this,"isValidSessionSettleRequest",s=>{if(!at(s)){const{message:l}=$("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}
vendor: 4,565 bytes, line 13
13const{relay:i,controller:r,namespaces:n,expiry:o}=s;if(!Rl(i)){const{message:l}=$("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=ff(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=En(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ps(o)){const{message:l}=$("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),N(this,"isValidUpdate",async s=>{if(!at(s)){const{message:c}=$("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:i,namespaces:r}=s;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=En(r,"update()");if(o)throw new Error(o.message);const a=La(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),N(this,"isValidExtend",async s=>{if(!at(s)){const{message:r}=$("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(r)}const{topic:i}=s;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),N(this,"isValidRequest",async s=>{if(!at(s)){const{message:c}=$("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:i,request:r,chainId:n,expiry:o}=s;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!Da(a,n)){const{message:c}=$("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Af(r)){const{message:c}=$("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!Pf(a,n,r.method)){const{message:c}=$("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!xf(o,Pn)){const{message:c}=$("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Pn.min} and ${Pn.max}`);throw new Error(c)}}),N(this,"isValidRespond",async s=>{var i;if(!at(s)){const{message:o}=$("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(o)}const{topic:r,response:n}=s;try{await this.isValidSessionTopic(r)}catch(o){throw(i=s==null?void 0:s.response)!=null&&i.id&&this.cleanupAfterResponse(s),o}if(!_f(n)){const{message:o}=$("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),N(this,"isValidPing",async s=>{if(!at(s)){const{message:r}=$("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(r)}const{topic:i}=s;await this.isValidSessionOrPairingTopic(i)}),N(this,"isValidEmit",async s=>{if(!at(s)){const{message:a}=$("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}const{topic:i,event:r,chainId:n}=s;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!Da(o,n)){const{message:a}=$("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Sf(r)){const{message:a}=$("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Of(o,n,r.name)){const{message:a}=$("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),N(this,"isValidDisconnect",async s=>{if(!at(s)){const{message:r}=$("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(r)}const{topic:i}=s;await this.isValidSessionOrPairingTopic(i)}),N(this,"isValidAuthenticate",s=>{const{chains:i,uri:r,domain:n,nonce:o}=s;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!ke(r,!1))throw new Error("uri is required parameter");if(!ke(n,!1))throw new Error("domain is required parameter");if(!ke(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>fi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=fi(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),N(this,"getVerifyContext",async s=>{const{attestationId:i,hash:r,encryptedId:n,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||tr,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Ne.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:i,hash:r,encryptedId:n,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}),N(this,"validateSessionProps",(s,i)=>
13{Object.values(s).forEach((r,n)=>{if(r==null){const{message:o}=$("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${r} for key ${Object.keys(s)[n]}`);throw new Error(o)}})}),N(this,"getPendingAuthRequest",s=>{const i=this.client.auth.requests.get(s);return typeof i=="object"?i:void 0}),N(this,"addToRecentlyDeleted",(s,i)=>{if(this.recentlyDeletedMap.set(s,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=n)break;this.recentlyDeletedMap.delete(o)}}}),N(this,"checkRecentlyDeleted",s=>{const i=this.recentlyDeletedMap.get(s);if(i){const{message:r}=$("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${s}`);throw new Error(r)}}),N(this,"isLinkModeEnabled",(s,i)=>{var r,n,o,a,c,l,d,u,h;return!s||i!==Ne.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.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(global==null?void 0:global.Linking)<"u"}),N(this,"getAppLinkIfEnabled",(s,i)=>{var r;return this.isLinkModeEnabled(s,i)?(r=s==null?void 0:s.redirect)==null?void 0:r.universal:void 0}),N(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const i=Zo(s,"topic")||"",r=decodeURIComponent(Zo(s,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:Ne.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:r,sessionExists:n})}),N(this,"registerLinkModeListeners",async()=>{var s;if(vo()||Is()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await i.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),N(this,"shouldSetTVF",(s,i)=>{if(!i||s!=="wc_sessionRequest")return!1;const{request:r}=i;return Object.keys(hc).includes(r.method)}),N(this,"getTVFParams",(s,i,r)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,r);return Qe(be({correlationId:s,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),N(this,"isValidContractData",s=>{var i;if(!s)return!1;try{const r=(s==null?void 0:s.data)||((i=s==null?void 0:s[0])==null?void 0:i.data);if(!r.startsWith("0x"))return!1;const n=r.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),N(this,"extractTxHashesFromResult",(s,i)=>{try{const r=hc[s];if(typeof i=="string")return[i];const n=i[r.key];if(bs(n))return s==="solana_signAllTransactions"?n.map(o=>Xh(o)):n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,s=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,r]of Object.entries(s))for(const n of r)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=$("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(qe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:i,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Mr)?this.client.auth.authKeys.get(Mr):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,i,{receiverPublicKey:o,encoding:n===Ne.link_mode?gs:Ut});mo(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:r,transportType:n,encryptedId:zt(i)})):wo(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:n}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(s,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Nt.expired,async e=>{const{topic:s,id:i}=Zc(e.target);
vendor: 3,543 bytes, line 13
13if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,$("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,$("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(xs.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(xs.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ke(e,!1)){const{message:s}=$("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}=$("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(ps(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=$("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!ke(e,!1)){const{message:s}=$("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}=$("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(ps(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=$("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=$("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(ke(e,!1)){const{message:s}=$("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=$("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!If(e)){const{message:s}=$("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=$("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(ps(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=$("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class Fb extends Ws{constructor(e,s){super(e,s,Ib,Po),this.core=e,this.logger=s}}let Bb=class extends Ws{constructor(e,s){super(e,s,Nb,Po),this.core=e,this.logger=s}};class qb extends Ws{constructor(e,s){super(e,s,_b,Po,i=>i.id),this.core=e,this.logger=s}}class jb extends Ws{constructor(e,s){super(e,s,Tb,sn,()=>Mr),this.core=e,this.logger=s}}class Wb extends Ws{constructor(e,s){super(e,s,kb,sn),this.core=e,this.logger=s}}class zb extends Ws{constructor(e,s){super(e,s,xb,sn,i=>i.id),this.core=e,this.logger=s}}var Hb=Object.defineProperty,Kb=(t,e,s)=>e in t?Hb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,On=(t,e,s)=>Kb(t,typeof e!="symbol"?e+"":e,s);class Vb{constructor(e,s){this.core=e,this.logger=s,On(this,"authKeys"),On(this,"pairingTopics"),On(this,"requests"),this.authKeys=new jb(this.core,this.logger),this.pairingTopics=new Wb(this.core,this.logger),this.requests=new zb(this.core,this.logger)}
13async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Gb=Object.defineProperty,Jb=(t,e,s)=>e in t?Gb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ne=(t,e,s)=>Jb(t,typeof e!="symbol"?e+"":e,s);let Yb=class Ql extends xu{constructor(e){super(e),ne(this,"protocol",Yl),ne(this,"version",Xl),ne(this,"name",Sn.name),ne(this,"metadata"),ne(this,"core"),ne(this,"logger"),ne(this,"events",new js.EventEmitter),ne(this,"engine"),ne(this,"session"),ne(this,"proposal"),ne(this,"pendingRequest"),ne(this,"auth"),ne(this,"signConfig"),ne(this,"on",(i,r)=>this.events.on(i,r)),ne(this,"once",(i,r)=>this.events.once(i,r)),ne(this,"off",(i,r)=>this.events.off(i,r)),ne(this,"removeListener",(i,r)=>this.events.removeListener(i,r)),ne(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ne(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"update",async i=>{try{return await this.engine.update(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"request",async i=>{try{return await this.engine.request(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"find",i=>{try{return this.engine.find(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ne(this,"authenticate",async(i,r)=>{try{return await this.engine.authenticate(i,r)}catch(n){throw this.logger.error(n.message),n}}),ne(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),ne(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||Sn.name,this.metadata=dh(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const s=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:bo(ur({level:(e==null?void 0:e.logger)||Sn.logger}));this.core=(e==null?void 0:e.core)||new Cb(e),this.logger=tt(s,this.name),this.session=new Bb(this.core,this.logger),this.proposal=new Fb(this.core,this.logger),this.pendingRequest=new qb(this.core,this.logger),this.engine=new Mb(this),this.auth=new Vb(this.core,this.logger)}static async init(e){const s=new Ql(e);return await s.initialize(),s}get context(){return yt(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"),setTimeout(()=>{this.engine.processRelayMessageCache()},U.toMiliseconds(U.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const gc="error",Xb="wss://relay.walletconnect.org",Zb="wc",Qb="universal_provider",Or=`${Zb}@2:${Qb}:`,ed="https://rpc.walletconnect.org/v1/",ci="generic",e0=`${ed}bundler`,St={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function t0(){}function Oo(t){return t==null||typeof t!="object"&&typeof t!="function"}function To(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function s0(t){if(Oo(t))return t;if(Array.isArray(t)||To(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 i=new s(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const i=new s(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function fc(t){return typeof t=="object"&&t!==null}function td(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}
13function sd(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const i0="[object RegExp]",id="[object String]",rd="[object Number]",nd="[object Boolean]",od="[object Arguments]",r0="[object Symbol]",n0="[object Date]",o0="[object Map]",a0="[object Set]",c0="[object Array]",l0="[object ArrayBuffer]",d0="[object Object]",u0="[object DataView]",h0="[object Uint8Array]",p0="[object Uint8ClampedArray]",g0="[object Uint16Array]",f0="[object Uint32Array]",m0="[object Int8Array]",w0="[object Int16Array]",y0="[object Int32Array]",b0="[object Float32Array]",v0="[object Float64Array]";function E0(t,e){return pi(t,void 0,t,new Map,e)}function pi(t,e,s,i=new Map,r=void 0){const n=r==null?void 0:r(t,e,s,i);if(n!=null)return n;if(Oo(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=pi(t[a],a,s,i,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;i.set(t,o);for(const[a,c]of t)o.set(a,pi(c,a,s,i,r));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(pi(a,void 0,s,i,r));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(To(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=pi(t[a],a,s,i,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 i.set(t,o),Rs(o,t,s,i,r),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Rs(o,t,s,i,r),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Rs(o,t,s,i,r),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Rs(o,t,s,i,r),o}if(typeof t=="object"&&C0(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Rs(o,t,s,i,r),o}return t}function Rs(t,e,s=t,i,r){const n=[...Object.keys(e),...td(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=pi(e[a],a,s,i,r))}}function C0(t){switch(sd(t)){case od:case c0:case l0:case u0:case nd:case n0:case b0:case v0:case m0:case w0:case y0:case o0:case rd:case d0:case i0:case a0:case id:case r0:case h0:case p0:case g0:case f0:return!0;default:return!1}}function I0(t,e){return E0(t,(s,i,r,n)=>{const o=e==null?void 0:e(s,i,r,n);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case rd:case id:case nd:{const a=new t.constructor(t==null?void 0:t.valueOf());return Rs(a,t),a}case od:{const a={};return Rs(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function mc(t){return I0(t)}function wc(t){return t!==null&&typeof t=="object"&&sd(t)==="[object Arguments]"}function N0(t){return To(t)}function A0(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 i=t[Symbol.toStringTag];return i==null||!((s=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&s.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function _0(t,...e){const s=e.slice(0,-1),i=e[e.length-1];let r=t;for(let n=0;n<s.length;n++){const o=s[n];r=ho(r,o,i,new Map)}return r}function ho(t,e,s,i){if(Oo(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return s0(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const r=[...Object.keys(e),...td(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=t[o];if(wc(a)&&(a={...a}),wc(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=mc(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 g=u[h];d[g]=c[g]}c=d}else c=[];const l=s(c,a,o,t,e,i);l!=null?t[o]=l:Array.isArray(a)||fc(c)&&fc(a)?t[o]=ho(c,a,s,i):c==null&&A0(a)?t[o]=ho({},a,s,i):c==null&&N0(a)?t[o]=mc(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function S0(t,...e){return _0(t,...e,t0)}var P0=Object.defineProperty,O0=Object.defineProperties,T0=Object.getOwnPropertyDescriptors,yc=Object.getOwnPropertySymbols,k0=Object.prototype.hasOwnProperty,x0=Object.prototype.propertyIsEnumerable,bc=(t,e,s)=>e in t?P0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Tr=(t,e)=>{for(var s in e||(e={}))k0.call(e,s)&&bc(t,s,e[s]);if(yc)for(var s of yc(e))x0.call(e,s)&&bc(t,s,e[s]);return t},R0=(t,e)=>O0(t,T0(e));function wt(t,e,s){var i;const r=fi(t);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${ed}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function zs(t){return t.includes(":")?t.split(":")[1]:t}function ad(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function $0(t,e){const s=Object.keys(e.namespaces).filter(r=>r.includes(t));if(!s.length)return[];const i=[];
13return s.forEach(r=>{const n=e.namespaces[r].accounts;i.push(...n)}),i}function kr(t={},e={}){const s=vc(t),i=vc(e);return S0(s,i)}function vc(t){var e,s,i,r,n;const o={};if(!vs(t))return o;for(const[a,c]of Object.entries(t)){const l=en(a)?[a]:c.chains,d=c.methods||[],u=c.events||[],h=c.rpcMap||{},g=hi(a);o[g]=R0(Tr(Tr({},o[g]),c),{chains:Ht(l,(e=o[g])==null?void 0:e.chains),methods:Ht(d,(s=o[g])==null?void 0:s.methods),events:Ht(u,(i=o[g])==null?void 0:i.events)}),(vs(h)||vs(((r=o[g])==null?void 0:r.rpcMap)||{}))&&(o[g].rpcMap=Tr(Tr({},h),(n=o[g])==null?void 0:n.rpcMap))}return o}function Ec(t){return t.includes(":")?t.split(":")[2]:t}function Cc(t){const e={};for(const[s,i]of Object.entries(t)){const r=i.methods||[],n=i.events||[],o=i.accounts||[],a=en(s)?[s]:i.chains?i.chains:ad(i.accounts);e[s]={chains:a,methods:r,events:n,accounts:o}}return e}function Tn(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))}const cd={},de=t=>cd[t],kn=(t,e)=>{cd[t]=e};var U0=Object.defineProperty,D0=(t,e,s)=>e in t?U0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ys=(t,e,s)=>D0(t,typeof e!="symbol"?e+"":e,s);class L0{constructor(e){Ys(this,"name","polkadot"),Ys(this,"client"),Ys(this,"httpProviders"),Ys(this,"events"),Ys(this,"namespace"),Ys(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var i;const r=zs(s);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||wt(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new _t(new Dt(i,de("disableProviderPing")))}}var M0=Object.defineProperty,F0=Object.defineProperties,B0=Object.getOwnPropertyDescriptors,Ic=Object.getOwnPropertySymbols,q0=Object.prototype.hasOwnProperty,j0=Object.prototype.propertyIsEnumerable,po=(t,e,s)=>e in t?M0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Nc=(t,e)=>{for(var s in e||(e={}))q0.call(e,s)&&po(t,s,e[s]);if(Ic)for(var s of Ic(e))j0.call(e,s)&&po(t,s,e[s]);return t},Ac=(t,e)=>F0(t,B0(e)),Xs=(t,e,s)=>po(t,typeof e!="symbol"?e+"":e,s);class W0{constructor(e){Xs(this,"name","eip155"),Xs(this,"client"),Xs(this,"chainId"),Xs(this,"namespace"),Xs(this,"httpProviders"),Xs(this,"events"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}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)}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),this.chainId=parseInt(e),this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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 i=s||wt(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new _t(new Dt(i,de("disableProviderPing")))}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var i;const r=parseInt(zs(s));e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[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(){const e=this.chainId,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}async handleSwitchChain(e){var s,i;let r=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,i,r,n,o;const a=(i=(s=e.request)==null?void 0:s.params)==null?void 0:i[0],c=((n=(r=e.request)==null?void 0:r.params)==null?void 0:n[1])||[],l=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const d=this.client.session.get(e.topic),u=((o=d==null?void 0:d.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[l])return u==null?void 0:u[l];const h=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Ac(Nc({},d.sessionProperties||{}),{capabilities:Ac(Nc({},u||{}),{[l]:h})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return h}async getCallStatus(e){var s,i;const r=this.client.session.get(e.topic),n=(s=r.sessionProperties)==null?void 0:s.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=r.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}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 i;
13const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($s("eth_getUserOperationReceipt",[(i=s.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,s){return`${e0}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}}var z0=Object.defineProperty,H0=(t,e,s)=>e in t?z0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Zs=(t,e,s)=>H0(t,typeof e!="symbol"?e+"":e,s);class K0{constructor(e){Zs(this,"name","solana"),Zs(this,"client"),Zs(this,"httpProviders"),Zs(this,"events"),Zs(this,"namespace"),Zs(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}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(){const e={};return this.namespace.chains.forEach(s=>{var i;const r=zs(s);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||wt(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new _t(new Dt(i,de("disableProviderPing")))}}var V0=Object.defineProperty,G0=(t,e,s)=>e in t?V0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qs=(t,e,s)=>G0(t,typeof e!="symbol"?e+"":e,s);class J0{constructor(e){Qs(this,"name","cosmos"),Qs(this,"client"),Qs(this,"httpProviders"),Qs(this,"events"),Qs(this,"namespace"),Qs(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}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(){const e={};return this.namespace.chains.forEach(s=>{var i;const r=zs(s);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||wt(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new _t(new Dt(i,de("disableProviderPing")))}}var Y0=Object.defineProperty,X0=(t,e,s)=>e in t?Y0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ei=(t,e,s)=>X0(t,typeof e!="symbol"?e+"":e,s);class Z0{constructor(e){ei(this,"name","algorand"),ei(this,"client"),ei(this,"httpProviders"),ei(this,"events"),ei(this,"namespace"),ei(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(!this.httpProviders[e]){const i=s||wt(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}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]}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(){const e={};return this.namespace.chains.forEach(s=>{var i;e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||wt(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new _t(new Dt(i,de("disableProviderPing")))}}var Q0=Object.defineProperty,ev=(t,e,s)=>e in t?Q0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ti=(t,e,s)=>ev(t,typeof e!="symbol"?e+"":e,s);class tv{constructor(e){ti(this,"name","cip34"),ti(this,"client"),ti(this,"httpProviders"),ti(this,"events"),ti(this,"namespace"),ti(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}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(){const e={};return this.namespace.chains.forEach(s=>{const i=this.getCardanoRPCUrl(s),r=zs(s);e[r]=this.createHttpProvider(r,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}getCardanoRPCUrl(e){const s=this.namespace.rpcMap;if(s)return s[e]}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new _t(new Dt(i,de("disableProviderPing")))}}var sv=Object.defineProperty,iv=(t,e,s)=>e in t?sv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,si=(t,e,s)=>iv(t,typeof e!="symbol"?e+"":e,s);class rv{constructor(e){si(this,"name","elrond"),si(this,"client"),si(this,"httpProviders"),si(this,"events"),si(this,"namespace"),si(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}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(){const e={};return this.namespace.chains.forEach(s=>{var i;const r=zs(s);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||wt(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new _t(new Dt(i,de("disableProviderPing")))}}var nv=Object.defineProperty,ov=(t,e,s)=>e in t?nv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ii=(t,e,s)=>ov(t,typeof e!="symbol"?e+"":e,s);class av{constructor(e){ii(this,"name","multiversx"),ii(this,"client"),ii(this,"httpProviders"),ii(this,"events"),ii(this,"namespace"),ii(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}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(){const e={};return this.namespace.chains.forEach(s=>{var i;const r=zs(s);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||wt(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new _t(new Dt(i,de("disableProviderPing")))}}var cv=Object.defineProperty,lv=(t,e,s)=>e in t?cv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ri=(t,e,s)=>lv(t,typeof e!="symbol"?e+"":e,s);class dv{constructor(e){ri(this,"name","near"),ri(this,"client"),ri(this,"httpProviders"),ri(this,"events"),ri(this,"namespace"),ri(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const i=s||wt(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var i;e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||wt(e,this.namespace);return typeof i>"u"?void 0:new _t(new Dt(i,de("disableProviderPing")))}}var uv=Object.defineProperty,hv=(t,e,s)=>e in t?uv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ni=(t,e,s)=>hv(t,typeof e!="symbol"?e+"":e,s);class pv{constructor(e){ni(this,"name","tezos"),ni(this,"client"),ni(this,"httpProviders"),ni(this,"events"),ni(this,"namespace"),ni(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const i=s||wt(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{e[s]=this.createHttpProvider(s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||wt(e,this.namespace);return typeof i>"u"?void 0:new _t(new Dt(i))}}var gv=Object.defineProperty,fv=(t,e,s)=>e in t?gv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oi=(t,e,s)=>fv(t,typeof e!="symbol"?e+"":e,s);class mv{constructor(e){oi(this,"name",ci),oi(this,"client"),oi(this,"httpProviders"),oi(this,"events"),oi(this,"namespace"),oi(this,"chainId"),this.namespace=e.namespace,this.events=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),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.
13chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(St.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}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 i={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(r=>{const n=fi(r);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),i}getHttpProvider(e){const s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const i=this.createHttpProvider(e,s);i&&(this.httpProviders[e]=i)}createHttpProvider(e,s){const i=s||wt(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new _t(new Dt(i,de("disableProviderPing")))}}var wv=Object.defineProperty,yv=Object.defineProperties,bv=Object.getOwnPropertyDescriptors,_c=Object.getOwnPropertySymbols,vv=Object.prototype.hasOwnProperty,Ev=Object.prototype.propertyIsEnumerable,go=(t,e,s)=>e in t?wv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xr=(t,e)=>{for(var s in e||(e={}))vv.call(e,s)&&go(t,s,e[s]);if(_c)for(var s of _c(e))Ev.call(e,s)&&go(t,s,e[s]);return t},xn=(t,e)=>yv(t,bv(e)),It=(t,e,s)=>go(t,typeof e!="symbol"?e+"":e,s);class ko{constructor(e){It(this,"client"),It(this,"namespaces"),It(this,"optionalNamespaces"),It(this,"sessionProperties"),It(this,"scopedProperties"),It(this,"events",new yo),It(this,"rpcProviders",{}),It(this,"session"),It(this,"providerOpts"),It(this,"logger"),It(this,"uri"),It(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:bo(ur({level:(e==null?void 0:e.logger)||gc})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const s=new ko(e);return await s.initialize(),s}async request(e,s,i){const[r,n]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:xr({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,s,i,r){const n=new Date().getTime();this.request(e,i,r).then(o=>s(null,Gr(n,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:me("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await 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:i,response:r}=await this.client.authenticate(e,s);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await r();if(this.session=n.session,this.session){const o=Cc(this.session.namespaces);this.namespaces=kr(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}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:i}=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 i();this.session=r;const n=Cc(r.namespaces);return this.namespaces=kr(this.namespaces,n),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[i,r]=this.validateChain(e),n=this.getProvider(i);n.name===ci?n.setDefaultChain(`${i}:${r}`,s):n.setDefaultChain(r,s)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(bs(s)){for(const i of s)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}}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 Yb.init({core:this.providerOpts.core,logger:this.providerOpts.logger||gc,relayUrl:this.providerOpts.relayUrl||Xb,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(i){throw this.logger.error("Failed to get session",i),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 i=this.client.session.getAll();this.session=i[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=>hi(s)))];kn("client",this.client),kn("events",this.events),kn("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const i=$0(s,this.session),r=ad(i),n=kr(this.namespaces,this.optionalNamespaces),o=xn(xr({},n[s]),{accounts:i,chains:r});switch(s){case"eip155":this.rpcProviders[s]=new W0({namespace:o});break;case"algorand":this.rpcProviders[s]=new Z0({namespace:o});break;case"solana":this.rpcProviders[s]=new K0({namespace:o});break;case"cosmos":this.rpcProviders[s]=new J0({namespace:o});break;case"polkadot":this.rpcProviders[s]=new L0({namespace:o});break;case"cip34":this.rpcProviders[s]=new tv({namespace:o});break;case"elrond":this.rpcProviders[s]=new rv({namespace:o});break;case"multiversx":this.rpcProviders[s]=new av({namespace:o});break;case"near":this.rpcProviders[s]=new dv({namespace:o});break;case"tezos":this.rpcProviders[s]=new pv({namespace:o});break;
13default:this.rpcProviders[ci]?this.rpcProviders[ci].updateNamespace(o):this.rpcProviders[ci]=new mv({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:i}=e;i===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:i,topic:r}=e;if(r!==((s=this.session)==null?void 0:s.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&bs(o)&&this.events.emit("accountsChanged",o.map(Ec))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=hi(o),l=Tn(o)!==Tn(a)?`${c}:${Tn(a)}`:o;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var i,r;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=s,o=(r=this.client)==null?void 0:r.session.get(e);this.session=xn(xr({},o),{namespaces:n}),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",xn(xr({},me("USER_DISCONNECTED")),{data:e.topic})))}),this.on(St.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[ci]}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:i={},sessionProperties:r,scopedProperties:n}=e;this.optionalNamespaces=kr(s,i),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[s,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,i];if(s&&!Object.keys(this.namespaces||{}).map(o=>hi(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&i)return[s,i];const r=hi(Object.keys(this.namespaces)[0]),n=this.rpcProviders[r].getDefaultChain();return[r,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,s=!1){if(!this.namespaces)return;const[i,r]=this.validateChain(e);if(!r)return;this.updateNamespaceChain(i,r),this.events.emit("chainChanged",r);const n=this.getProvider(i).getDefaultChain();s||this.getProvider(i).setDefaultChain(r),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:s,newChainId:i}){var r,n;try{if(s===i)return;const o=(n=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(Ec);if(!bs(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,s){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${s}`,r={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=s):this.namespaces[i]=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,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,s){var i;const r=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${Or}/${e}${r}`,s)}async getFromStore(e){var s;const i=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${Or}/${e}${i}`)}async deleteFromStore(e){var s;const i=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${Or}/${e}${i}`)}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 i of s)i.startsWith(Or)&&await this.client.core.storage.removeItem(i)}catch(s){this.logger.warn("Failed to cleanup storage",s)}}}function Rr(t,e){return q.getConnectorId(t)===e}function Cv(t){const e=Array.from(p.state.chains.keys());let s=[];return t?(s.push([t,p.state.chains.get(t)]),Rr(t,B.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(i=>
13{i!==t&&Rr(i,B.CONNECTOR_ID.WALLET_CONNECT)&&s.push([i,p.state.chains.get(i)])}):Rr(t,B.CONNECTOR_ID.AUTH)&&e.forEach(i=>{i!==t&&Rr(i,B.CONNECTOR_ID.AUTH)&&s.push([i,p.state.chains.get(i)])})):s=Array.from(p.state.chains.entries()),s}const De={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",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"ID_AUTH"},Kr={ConnectorExplorerIds:{[B.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[B.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[B.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[B.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[B.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[De.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[De.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[De.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[De.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[De.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[De.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[De.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[De.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[De.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[De.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[De.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13"},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"},ConnectorImageIds:{[B.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[B.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[B.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[B.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[B.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[B.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-454
130-9e6a2b9cae00"},ConnectorNamesMap:{[B.CONNECTOR_ID.INJECTED]:"Browser Wallet",[B.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[B.CONNECTOR_ID.COINBASE]:"Coinbase",[B.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[B.CONNECTOR_ID.LEDGER]:"Ledger",[B.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[B.CONNECTOR_ID.INJECTED]:"INJECTED",[B.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[B.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[B.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]},xo={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,i])=>{e[`${De.EIP155}:${s}`]=i}),e},isLowerCaseMatch(t,e){return(t==null?void 0:t.toLowerCase())===(e==null?void 0:e.toLowerCase())}},Iv=new AbortController,ai={EmbeddedWalletAbortController:Iv,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"INVALID_APP_CONFIGURATION"},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:{shortMessage:"Network Not Found",longMessage:"Network not found - please make sure it is included in 'networks' array in createAppKit function"},INVALID_APP_CONFIGURATION:{shortMessage:"Invalid App Configuration",longMessage:()=>`Origin ${Nv()?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},IFRAME_LOAD_FAILED:{shortMessage:"Network Error - Could not load embedded wallet",longMessage:()=>"There was an issue loading the embedded wallet. Please try again later."},IFRAME_REQUEST_TIMEOUT:{shortMessage:"Embedded Wallet Request Timed Out",longMessage:()=>"There was an issue doing the request to the embedded wallet. Please try again later."},UNVERIFIED_DOMAIN:{shortMessage:"Invalid App Configuration",longMessage:()=>"There was an issue loading the embedded wallet. Please verify that your domain is allowed at cloud.reown.com"},JWT_TOKEN_NOT_VALID:{shortMessage:"Session Expired",longMessage:"Invalid session found on UniversalProvider - please check your time settings and connect again"},INVALID_PROJECT_ID:{shortMessage:"Invalid App Configuration",longMessage:"Invalid Project ID - update configuration"},PROJECT_ID_NOT_CONFIGURED:{shortMessage:"Project ID Not Configured",longMessage:"Project ID Not Configured - update configuration on cloud.reown.com"}}};function Nv(){return typeof window<"u"}const Av={createLogger(t,e="error"){const s=ur({level:e}),{logger:i}=$c({opts:s});return i.error=(...r)=>{for(const n of r)if(n instanceof Error){t(n,...r);return}t(void 0,...r)},i}},_v="rpc.walletconnect.org";function Sc(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 Rn=["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","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],li={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===_v}catch{s=!1}if(s){const i=new URL(t);return i.searchParams.has("projectId")||i.searchParams.set("projectId",e),i.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:B.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${B.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){var r,n,o;const i=(o=(n=(r=t.rpcUrls)==null?void 0:r.default)==null?void 0:n.http)==null?void 0:o[0];return Rn.includes(e)?Sc(e,s):i||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:i}){var h,g,w,m,f;const r=this.getChainNamespace(t),n=this.getCaipNetworkId(t),o=(h=t.rpcUrls.default.http)==null?void 0:h[0],a=this.getDefaultRpcUrl(t,n,s),c=((m=(w=(g=t==null?void 0:t.rpcUrls)==null?void 0:g.chainDefault)==null?void 0:w.http)==null?void 0:m[0])||o,l=((f=i==null?void 0:i[n])==null?void 0:f.map(y=>y.url))||[],d=[...l,a],u=[...l];return c&&!u.includes(c)&&u.push(c),{...t,chainNamespace:r,caipNetworkId:n,assets:{imageId:Kr.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:i}){return t.map(r=>li.extendCaipNetwork(r,{customNetworkImageUrls:e,customRpcUrls:i,projectId:s}))}
13,getViemTransport(t,e,s){var r,n,o;const i=[];return s==null||s.forEach(a=>{i.push(Cr(a.url,a.config))}),Rn.includes(t.caipNetworkId)&&i.push(Cr(Sc(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),(o=(n=(r=t==null?void 0:t.rpcUrls)==null?void 0:r.default)==null?void 0:n.http)==null||o.forEach(a=>{i.push(Cr(a))}),Uo(i)},extendWagmiTransports(t,e,s){if(Rn.includes(t.caipNetworkId)){const i=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return Uo([s,Cr(i)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:B.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){var c;const e=W.getActiveCaipNetworkId(),s=p.getAllRequestedCaipNetworks(),i=Array.from(((c=p.state.chains)==null?void 0:c.keys())||[]),r=e==null?void 0:e.split(":")[0],n=r?i.includes(r):!1,o=s==null?void 0:s.find(l=>l.caipNetworkId===e);return n&&!o&&e?this.getUnsupportedNetwork(e):o||t||(s==null?void 0:s[0])}},Vr={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},ot=Ae({providers:{...Vr},providerIds:{...Vr}}),_e={state:ot,subscribeKey(t,e){return Ze(ot,t,e)},subscribe(t){return Xe(ot,()=>{t(ot)})},subscribeProviders(t){return Xe(ot.providers,()=>t(ot.providers))},setProvider(t,e){e&&(ot.providers[t]=Ls(e))},getProvider(t){return ot.providers[t]},setProviderId(t,e){e&&(ot.providerIds[t]=e)},getProviderId(t){if(t)return ot.providerIds[t]},reset(){ot.providers={...Vr},ot.providerIds={...Vr}},resetChain(t){ot.providers[t]=void 0,ot.providerIds[t]=void 0}},Sv={ACCOUNT_TABS:[{label:"Tokens"},{label:"NFTs"},{label:"Activity"}],SECURE_SITE_ORIGIN:(typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},fo={filterOutDuplicatesByRDNS(t){const e=O.state.enableEIP6963?q.state.connectors:[],s=W.getRecentWallets(),i=e.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}).filter(Boolean),r=s.map(a=>
13a.rdns).filter(Boolean),n=i.concat(r);if(n.includes("io.metamask.mobile")&&X.isMobile()){const a=n.indexOf("io.metamask.mobile");n[a]="io.metamask"}return t.filter(a=>!n.includes(String(a==null?void 0:a.rdns)))},filterOutDuplicatesByIds(t){const e=q.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=W.getRecentWallets(),i=e.map(a=>a.explorerId),r=s.map(a=>a.id),n=i.concat(r);return t.filter(a=>!n.includes(a==null?void 0:a.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=q.state,{featuredWalletIds:s}=O.state,i=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&&!!i[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=O.state.features)==null?void 0:c.connectMethodsOrder),i=e||q.state.connectors;if(s)return s;const{injected:r,announced:n}=Fr.getConnectorsByType(i,K.state.recommended,K.state.featured),o=r.filter(Fr.showConnector),a=n.filter(Fr.showConnector);return o.length||a.length?["wallet","email","social"]:Sv.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&K.state.excludedWallets.some(i=>i.rdns===t.rdns),s=!!t.name&&K.state.excludedWallets.some(i=>xo.isLowerCaseMatch(i.name,t.name));return e||s}},Fr={getConnectorsByType(t,e,s){const{customWallets:i}=O.state,r=W.getRecentWallets(),n=fo.filterOutDuplicateWallets(e),o=fo.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:i,recent:r,external:d,multiChain:a,announced:c,injected:l,recommended:n,featured:o}},showConnector(t){var r;const e=(r=t.info)==null?void 0:r.rdns,s=!!e&&K.state.excludedWallets.some(n=>!!n.rdns&&n.rdns===e),i=!!t.name&&K.state.excludedWallets.some(n=>xo.isLowerCaseMatch(n.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!X.isMobile()||X.isMobile()&&!e&&!Y.checkInstalled())||s||i)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||i))},getIsConnectedWithWC(){return Array.from(p.state.chains.values()).some(s=>q.getConnectorId(s.namespace)===B.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:i,announced:r,injected:n,multiChain:o,external:a,overriddenConnectors:c=(l=>(l=O.state.features)==null?void 0:l.connectorTypeOrder)()??[]}){const d=Fr.getIsConnectedWithWC(),g=[{type:"walletConnect",isEnabled:O.state.enableWalletConnect&&!d},{type:"recent",isEnabled:i.length>0},{type:"injected",isEnabled:[...n,...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(y=>y.isEnabled),w=new Set(g.map(y=>y.type)),m=c.filter(y=>w.has(y)).map(y=>({type:y,isEnabled:!0})),f=g.filter(({type:y})=>!m.some(({type:E})=>E===y));return Array.from(new Set([...m,...f].map(({type:y})=>y)))}};let ir,Es,Cs;function s1(t,e){ir=document.createElement("style"),Es=document.createElement("style"),Cs=document.createElement("style"),ir.textContent=mi(t).core.cssText,Es.textContent=mi(t).dark.cssText,Cs.textContent=mi(t).light.cssText,document.head.appendChild(ir),document.head.appendChild(Es),document.head.appendChild(Cs),ld(e)}function ld(t){Es&&Cs&&(t==="light"?(Es.removeAttribute("media"),Cs.media="enabled"):(Cs.removeAttribute("media"),Es.media="enabled"))}function Pv(t){ir&&Es&&Cs&&(ir.textContent=mi(t).core.cssText,Es.textContent=mi(t).dark.cssText,Cs.textContent=mi(t).light.cssText)}function mi(t){return{core:gi`
14      @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
15      @keyframes w3m-shake {
16        0% {
17          transform: scale(1) rotate(0deg);
18        }
19        20% {
20          transform: scale(1) rotate(-1deg);
21        }
22        40% {
23          transform: scale(1) rotate(1.5deg);
24        }
25        60% {
26          transform: scale(1) rotate(-1.5deg);
27        }
28        80% {
29          transform: scale(1) rotate(1deg);
30        }
31        100% {
32          transform: scale(1) rotate(0deg);
33        }
34      }
35      @keyframes w3m-iframe-fade-out {
36        0% {
37          opacity: 1;
38        }
39        100% {
40          opacity: 0;
41        }
42      }
43      @keyframes w3m-iframe-zoom-in {
44        0% {
45          transform: translateY(50px);
46          opacity: 0;
47        }
48        100% {
49          transform: translateY(0px);
50          opacity: 1;
51        }
52      }
53      @keyframes w3m-iframe-zoom-in-mobile {
54        0% {
55          transform: scale(0.95);
56          opacity: 0;
57        }
58        100% {
59          transform: scale(1);
60          opacity: 1;
61        }
62      }
63      :root {
64        --w3m-modal-width: 360px;
65        --w3m-color-mix-strength: ${Pt(t!=null&&t["--w3m-color-mix-strength"]?`${t["--w3m-color-mix-strength"]}%`:"0%")};
66        --w3m-font-family: ${Pt((t==null?void 0:t["--w3m-font-family"])||"Inter, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;")};
67        --w3m-font-size-master: ${Pt((t==null?void 0:t["--w3m-font-size-master"])||"10px")};
68        --w3m-border-radius-master: ${Pt((t==null?void 0:t["--w3m-border-radius-master"])||"4px")};
69        --w3m-z-index: ${Pt((t==null?void 0:t["--w3m-z-index"])||
vendor: 15,824 bytes, lines 69-495
69999)};
70
71        --wui-font-family: var(--w3m-font-family);
72
73        --wui-font-size-mini: calc(var(--w3m-font-size-master) * 0.8);
74        --wui-font-size-micro: var(--w3m-font-size-master);
75        --wui-font-size-tiny: calc(var(--w3m-font-size-master) * 1.2);
76        --wui-font-size-small: calc(var(--w3m-font-size-master) * 1.4);
77        --wui-font-size-paragraph: calc(var(--w3m-font-size-master) * 1.6);
78        --wui-font-size-medium: calc(var(--w3m-font-size-master) * 1.8);
79        --wui-font-size-large: calc(var(--w3m-font-size-master) * 2);
80        --wui-font-size-title-6: calc(var(--w3m-font-size-master) * 2.2);
81        --wui-font-size-medium-title: calc(var(--w3m-font-size-master) * 2.4);
82        --wui-font-size-2xl: calc(var(--w3m-font-size-master) * 4);
83
84        --wui-border-radius-5xs: var(--w3m-border-radius-master);
85        --wui-border-radius-4xs: calc(var(--w3m-border-radius-master) * 1.5);
86        --wui-border-radius-3xs: calc(var(--w3m-border-radius-master) * 2);
87        --wui-border-radius-xxs: calc(var(--w3m-border-radius-master) * 3);
88        --wui-border-radius-xs: calc(var(--w3m-border-radius-master) * 4);
89        --wui-border-radius-s: calc(var(--w3m-border-radius-master) * 5);
90        --wui-border-radius-m: calc(var(--w3m-border-radius-master) * 7);
91        --wui-border-radius-l: calc(var(--w3m-border-radius-master) * 9);
92        --wui-border-radius-3xl: calc(var(--w3m-border-radius-master) * 20);
93
94        --wui-font-weight-light: 400;
95        --wui-font-weight-regular: 500;
96        --wui-font-weight-medium: 600;
97        --wui-font-weight-bold: 700;
98
99        --wui-letter-spacing-2xl: -1.6px;
100        --wui-letter-spacing-medium-title: -0.96px;
101        --wui-letter-spacing-title-6: -0.88px;
102        --wui-letter-spacing-large: -0.8px;
103        --wui-letter-spacing-medium: -0.72px;
104        --wui-letter-spacing-paragraph: -0.64px;
105        --wui-letter-spacing-small: -0.56px;
106        --wui-letter-spacing-tiny: -0.48px;
107        --wui-letter-spacing-micro: -0.2px;
108        --wui-letter-spacing-mini: -0.16px;
109
110        --wui-spacing-0: 0px;
111        --wui-spacing-4xs: 2px;
112        --wui-spacing-3xs: 4px;
113        --wui-spacing-xxs: 6px;
114        --wui-spacing-2xs: 7px;
115        --wui-spacing-xs: 8px;
116        --wui-spacing-1xs: 10px;
117        --wui-spacing-s: 12px;
118        --wui-spacing-m: 14px;
119        --wui-spacing-l: 16px;
120        --wui-spacing-2l: 18px;
121        --wui-spacing-xl: 20px;
122        --wui-spacing-xxl: 24px;
123        --wui-spacing-2xl: 32px;
124        --wui-spacing-3xl: 40px;
125        --wui-spacing-4xl: 90px;
126        --wui-spacing-5xl: 95px;
127
128        --wui-icon-box-size-xxs: 14px;
129        --wui-icon-box-size-xs: 20px;
130        --wui-icon-box-size-sm: 24px;
131        --wui-icon-box-size-md: 32px;
132        --wui-icon-box-size-mdl: 36px;
133        --wui-icon-box-size-lg: 40px;
134        --wui-icon-box-size-2lg: 48px;
135        --wui-icon-box-size-xl: 64px;
136
137        --wui-icon-size-inherit: inherit;
138        --wui-icon-size-xxs: 10px;
139        --wui-icon-size-xs: 12px;
140        --wui-icon-size-sm: 14px;
141        --wui-icon-size-md: 16px;
142        --wui-icon-size-mdl: 18px;
143        --wui-icon-size-lg: 20px;
144        --wui-icon-size-xl: 24px;
145        --wui-icon-size-xxl: 28px;
146
147        --wui-wallet-image-size-inherit: inherit;
148        --wui-wallet-image-size-sm: 40px;
149        --wui-wallet-image-size-md: 56px;
150        --wui-wallet-image-size-lg: 80px;
151
152        --wui-visual-size-size-inherit: inherit;
153        --wui-visual-size-sm: 40px;
154        --wui-visual-size-md: 55px;
155        --wui-visual-size-lg: 80px;
156
157        --wui-box-size-md: 100px;
158        --wui-box-size-lg: 120px;
159
160        --wui-ease-out-power-2: cubic-bezier(0, 0, 0.22, 1);
161        --wui-ease-out-power-1: cubic-bezier(0, 0, 0.55, 1);
162
163        --wui-ease-in-power-3: cubic-bezier(0.66, 0, 1, 1);
164        --wui-ease-in-power-2: cubic-bezier(0.45, 0, 1, 1);
165        --wui-ease-in-power-1: cubic-bezier(0.3, 0, 1, 1);
166
167        --wui-ease-inout-power-1: cubic-bezier(0.45, 0, 0.55, 1);
168
169        --wui-duration-lg: 200ms;
170        --wui-duration-md: 125ms;
171        --wui-duration-sm: 75ms;
172
173        --wui-path-network-sm: path(
174          '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'
175        );
176
177        --wui-path-network-md: path(
178          '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'
179        );
180
181        --wui-path-network-lg: path(
182          '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'
183        );
184
185        --wui-width-network-sm: 36px;
186        --wui-width-network-md: 48px;
187        --wui-width-network-lg: 86px;
188
189        --wui-height-network-sm: 40px;
190        --wui-height-network-md: 54px;
191        --wui-height-network-lg: 96px;
192
193        --wui-icon-size-network-xs: 12px;
194        --wui-icon-size-network-sm: 16px;
195        --wui-icon-size-network-md: 24px;
196        --wui-icon-size-network-lg: 42px;
197
198        --wui-color-inherit: inherit;
199
200        --wui-color-inverse-100: #fff;
201        --wui-color-inverse-000: #000;
202
203        --wui-cover: rgba(20, 20, 20, 0.8);
204
205        --wui-color-modal-bg: var(--wui-color-modal-bg-base);
206
207        --wui-color-accent-100: var(--wui-color-accent-base-100);
208        --wui-color-accent-090: var(--wui-color-accent-base-090);
209        --wui-color-accent-080: var(--wui-color-accent-base-080);
210
211        --wui-color-success-100: var(--wui-color-success-base-100);
212        --wui-color-success-125: var(--wui-color-success-base-125);
213
214        --wui-color-warning-100: var(--wui-color-warning-base-100);
215
216        --wui-color-error-100: var(--wui-color-error-base-100);
217        --wui-color-error-125: var(--wui-color-error-base-125);
218
219        --wui-color-blue-100: var(--wui-color-blue-base-100);
220        --wui-color-blue-90: var(--wui-color-blue-base-90);
221
222        --wui-icon-box-bg-error-100: var(--wui-icon-box-bg-error-base-100);
223        --wui-icon-box-bg-blue-100: var(--wui-icon-box-bg-blue-base-100);
224        --wui-icon-box-bg-success-100: var(--wui-icon-box-bg-success-base-100);
225        --wui-icon-box-bg-inverse-100: var(--wui-icon-box-bg-inverse-base-100);
226
227        --wui-all-wallets-bg-100: var(--wui-all-wallets-bg-100);
228
229        --wui-avatar-border: var(--wui-avatar-border-base);
230
231        --wui-thumbnail-border: var(--wui-thumbnail-border-base);
232
233        --wui-wallet-button-bg: var(--wui-wallet-button-bg-base);
234
235        --wui-box-shadow-blue: var(--wui-color-accent-glass-020);
236      }
237
238      @supports (background: color-mix(in srgb, white 50%, black)) {
239        :root {
240          --wui-color-modal-bg: color-mix(
241            in srgb,
242            var(--w3m-color-mix) var(--w3m-color-mix-strength),
243            var(--wui-color-modal-bg-base)
244          );
245
246          --wui-box-shadow-blue: color-mix(in srgb, var(--wui-color-accent-100) 20%, transparent);
247
248          --wui-color-accent-100: color-mix(
249            in srgb,
250            var(--wui-color-accent-base-100) 100%,
251            transparent
252          );
253          --wui-color-accent-090: color-mix(
254            in srgb,
255            var(--wui-color-accent-base-100) 90%,
256            transparent
257          );
258          --wui-color-accent-080: color-mix(
259            in srgb,
260            var(--wui-color-accent-base-100) 80%,
261            transparent
262          );
263          --wui-color-accent-glass-090: color-mix(
264            in srgb,
265            var(--wui-color-accent-base-100) 90%,
266            transparent
267          );
268          --wui-color-accent-glass-080: color-mix(
269            in srgb,
270            var(--wui-color-accent-base-100) 80%,
271            transparent
272          );
273          --wui-color-accent-glass-020: color-mix(
274            in srgb,
275            var(--wui-color-accent-base-100) 20%,
276            transparent
277          );
278          --wui-color-accent-glass-015: color-mix(
279            in srgb,
280            var(--wui-color-accent-base-100) 15%,
281            transparent
282          );
283          --wui-color-accent-glass-010: color-mix(
284            in srgb,
285            var(--wui-color-accent-base-100) 10%,
286            transparent
287          );
288          --wui-color-accent-glass-005: color-mix(
289            in srgb,
290            var(--wui-color-accent-base-100) 5%,
291            transparent
292          );
293          --wui-color-accent-002: color-mix(
294            in srgb,
295            var(--wui-color-accent-base-100) 2%,
296            transparent
297          );
298
299          --wui-color-fg-100: color-mix(
300            in srgb,
301            var(--w3m-color-mix) var(--w3m-color-mix-strength),
302            var(--wui-color-fg-100)
303          );
304          --wui-color-fg-125: color-mix(
305            in srgb,
306            var(--w3m-color-mix) var(--w3m-color-mix-strength),
307            var(--wui-color-fg-125)
308          );
309          --wui-color-fg-150: color-mix(
310            in srgb,
311            var(--w3m-color-mix) var(--w3m-color-mix-strength),
312            var(--wui-color-fg-150)
313          );
314          --wui-color-fg-175: color-mix(
315            in srgb,
316            var(--w3m-color-mix) var(--w3m-color-mix-strength),
317            var(--wui-color-fg-175)
318          );
319          --wui-color-fg-200: color-mix(
320            in srgb,
321            var(--w3m-color-mix) var(--w3m-color-mix-strength),
322            var(--wui-color-fg-200)
323          );
324          --wui-color-fg-225: color-mix(
325            in srgb,
326            var(--w3m-color-mix) var(--w3m-color-mix-strength),
327            var(--wui-color-fg-225)
328          );
329          --wui-color-fg-250: color-mix(
330            in srgb,
331            var(--w3m-color-mix) var(--w3m-color-mix-strength),
332            var(--wui-color-fg-250)
333          );
334          --wui-color-fg-275: color-mix(
335            in srgb,
336            var(--w3m-color-mix) var(--w3m-color-mix-strength),
337            var(--wui-color-fg-275)
338          );
339          --wui-color-fg-300: color-mix(
340            in srgb,
341            var(--w3m-color-mix) var(--w3m-color-mix-strength),
342            var(--wui-color-fg-300)
343          );
344          --wui-color-fg-325: color-mix(
345            in srgb,
346            var(--w3m-color-mix) var(--w3m-color-mix-strength),
347            var(--wui-color-fg-325)
348          );
349          --wui-color-fg-350: color-mix(
350            in srgb,
351            var(--w3m-color-mix) var(--w3m-color-mix-strength),
352            var(--wui-color-fg-350)
353          );
354
355          --wui-color-bg-100: color-mix(
356            in srgb,
357            var(--w3m-color-mix) var(--w3m-color-mix-strength),
358            var(--wui-color-bg-100)
359          );
360          --wui-color-bg-125: color-mix(
361            in srgb,
362            var(--w3m-color-mix) var(--w3m-color-mix-strength),
363            var(--wui-color-bg-125)
364          );
365          --wui-color-bg-150: color-mix(
366            in srgb,
367            var(--w3m-color-mix) var(--w3m-color-mix-strength),
368            var(--wui-color-bg-150)
369          );
370          --wui-color-bg-175: color-mix(
371            in srgb,
372            var(--w3m-color-mix) var(--w3m-color-mix-strength),
373            var(--wui-color-bg-175)
374          );
375          --wui-color-bg-200: color-mix(
376            in srgb,
377            var(--w3m-color-mix) var(--w3m-color-mix-strength),
378            var(--wui-color-bg-200)
379          );
380          --wui-color-bg-225: color-mix(
381            in srgb,
382            var(--w3m-color-mix) var(--w3m-color-mix-strength),
383            var(--wui-color-bg-225)
384          );
385          --wui-color-bg-250: color-mix(
386            in srgb,
387            var(--w3m-color-mix) var(--w3m-color-mix-strength),
388            var(--wui-color-bg-250)
389          );
390          --wui-color-bg-275: color-mix(
391            in srgb,
392            var(--w3m-color-mix) var(--w3m-color-mix-strength),
393            var(--wui-color-bg-275)
394          );
395          --wui-color-bg-300: color-mix(
396            in srgb,
397            var(--w3m-color-mix) var(--w3m-color-mix-strength),
398            var(--wui-color-bg-300)
399          );
400          --wui-color-bg-325: color-mix(
401            in srgb,
402            var(--w3m-color-mix) var(--w3m-color-mix-strength),
403            var(--wui-color-bg-325)
404          );
405          --wui-color-bg-350: color-mix(
406            in srgb,
407            var(--w3m-color-mix) var(--w3m-color-mix-strength),
408            var(--wui-color-bg-350)
409          );
410
411          --wui-color-success-100: color-mix(
412            in srgb,
413            var(--w3m-color-mix) var(--w3m-color-mix-strength),
414            var(--wui-color-success-base-100)
415          );
416          --wui-color-success-125: color-mix(
417            in srgb,
418            var(--w3m-color-mix) var(--w3m-color-mix-strength),
419            var(--wui-color-success-base-125)
420          );
421
422          --wui-color-warning-100: color-mix(
423            in srgb,
424            var(--w3m-color-mix) var(--w3m-color-mix-strength),
425            var(--wui-color-warning-base-100)
426          );
427
428          --wui-color-error-100: color-mix(
429            in srgb,
430            var(--w3m-color-mix) var(--w3m-color-mix-strength),
431            var(--wui-color-error-base-100)
432          );
433          --wui-color-blue-100: color-mix(
434            in srgb,
435            var(--w3m-color-mix) var(--w3m-color-mix-strength),
436            var(--wui-color-blue-base-100)
437          );
438          --wui-color-blue-90: color-mix(
439            in srgb,
440            var(--w3m-color-mix) var(--w3m-color-mix-strength),
441            var(--wui-color-blue-base-90)
442          );
443          --wui-color-error-125: color-mix(
444            in srgb,
445            var(--w3m-color-mix) var(--w3m-color-mix-strength),
446            var(--wui-color-error-base-125)
447          );
448
449          --wui-icon-box-bg-error-100: color-mix(
450            in srgb,
451            var(--w3m-color-mix) var(--w3m-color-mix-strength),
452            var(--wui-icon-box-bg-error-base-100)
453          );
454          --wui-icon-box-bg-accent-100: color-mix(
455            in srgb,
456            var(--w3m-color-mix) var(--w3m-color-mix-strength),
457            var(--wui-icon-box-bg-blue-base-100)
458          );
459          --wui-icon-box-bg-success-100: color-mix(
460            in srgb,
461            var(--w3m-color-mix) var(--w3m-color-mix-strength),
462            var(--wui-icon-box-bg-success-base-100)
463          );
464          --wui-icon-box-bg-inverse-100: color-mix(
465            in srgb,
466            var(--w3m-color-mix) var(--w3m-color-mix-strength),
467            var(--wui-icon-box-bg-inverse-base-100)
468          );
469
470          --wui-all-wallets-bg-100: color-mix(
471            in srgb,
472            var(--w3m-color-mix) var(--w3m-color-mix-strength),
473            var(--wui-all-wallets-bg-100)
474          );
475
476          --wui-avatar-border: color-mix(
477            in srgb,
478            var(--w3m-color-mix) var(--w3m-color-mix-strength),
479            var(--wui-avatar-border-base)
480          );
481
482          --wui-thumbnail-border: color-mix(
483            in srgb,
484            var(--w3m-color-mix) var(--w3m-color-mix-strength),
485            var(--wui-thumbnail-border-base)
486          );
487
488          --wui-wallet-button-bg: color-mix(
489            in srgb,
490            var(--w3m-color-mix) var(--w3m-color-mix-strength),
491            var(--wui-wallet-button-bg-base)
492          );
493        }
494      }
495    `,
495light:gi`
496      :root {
497        --w3m-color-mix: ${Pt((t==null?void 0:t["--w3m-color-mix"])||"#fff")};
498        --w3m-accent: ${Pt(fs(t,"dark")["--w3m-accent"])};
499        --w3m-default: #fff;
500
501        --wui-color-modal-bg-base: ${Pt(fs(t,"dark")["--w3m-background"])};
502        --wui-color-accent-base-100: var(--w3m-accent);
503
504        --wui-color-blueberry-100: hsla(230, 100%, 67%, 1);
505        --wui-color-blueberry-090: hsla(231, 76%, 61%, 1);
506        --wui-color-blueberry-080: hsla(230, 59%, 55%, 1);
507        --wui-color-blueberry-050: hsla(231, 100%, 70%, 0.1);
508
509        --wui-color-fg-100: #e4e7e7;
510        --wui-color-fg-125: #d0d5d5;
511        --wui-color-fg-150: #a8b1b1;
512        --wui-color-fg-175: #a8b0b0;
513        --wui-color-fg-200: #949e9e;
514        --wui-color-fg-225: #868f8f;
515        --wui-color-fg-250: #788080;
516        --wui-color-fg-275: #788181;
517        --wui-color-fg-300: #6e7777;
518        --wui-color-fg-325: #9a9a9a;
519        --wui-color-fg-350: #363636;
520
521        --wui-color-bg-100: #141414;
522        --wui-color-bg-125: #191a1a;
523        --wui-color-bg-150: #1e1f1f;
524        --wui-color-bg-175: #222525;
525        --wui-color-bg-200: #272a2a;
526        --wui-color-bg-225: #2c3030;
527        --wui-color-bg-250: #313535;
528        --wui-color-bg-275: #363b3b;
529        --wui-color-bg-300: #3b4040;
530        --wui-color-bg-325: #252525;
531        --wui-color-bg-350: #ffffff;
532
533        --wui-color-success-base-100: #26d962;
534        --wui-color-success-base-125: #30a46b;
535
536        --wui-color-warning-base-100: #f3a13f;
537
538        --wui-color-error-base-100: #f25a67;
539        --wui-color-error-base-125: #df4a34;
540
541        --wui-color-blue-base-100: rgba(102, 125, 255, 1);
542        --wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
543
544        --wui-color-success-glass-001: rgba(38, 217, 98, 0.01);
545        --wui-color-success-glass-002: rgba(38, 217, 98, 0.02);
546        --wui-color-success-glass-005: rgba(38, 217, 98, 0.05);
547        --wui-color-success-glass-010: rgba(38, 217, 98, 0.1);
548        --wui-color-success-glass-015: rgba(38, 217, 98, 0.15);
549        --wui-color-success-glass-020: rgba(38, 217, 98, 0.2);
550        --wui-color-success-glass-025: rgba(38, 217, 98, 0.25);
551        --wui-color-success-glass-030: rgba(38, 217, 98, 0.3);
552        --wui-color-success-glass-060: rgba(38, 217, 98, 0.6);
553        --wui-color-success-glass-080: rgba(38, 217, 98, 0.8);
554
555        --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
556
557        --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
558
559        --wui-color-error-glass-001: rgba(242, 90, 103, 0.01);
560        --wui-color-error-glass-002: rgba(242, 90, 103, 0.02);
561        --wui-color-error-glass-005: rgba(242, 90, 103, 0.05);
562        --wui-color-error-glass-010: rgba(242, 90, 103, 0.1);
563        --wui-color-error-glass-015: rgba(242, 90, 103, 0.15);
564        --wui-color-error-glass-020: rgba(242, 90, 103, 0.2);
565        --wui-color-error-glass-025: rgba(242, 90, 103, 0.25);
566        --wui-color-error-glass-030: rgba(242, 90, 103, 0.3);
567        --wui-color-error-glass-060: rgba(242, 90, 103, 0.6);
568        --wui-color-error-glass-080: rgba(242, 90, 103, 0.8);
569
570        --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
571
572        --wui-color-gray-glass-001: rgba(255, 255, 255, 0.01);
573        --wui-color-gray-glass-002: rgba(255, 255, 255, 0.02);
574        --wui-color-gray-glass-005: rgba(255, 255, 255, 0.05);
575        --wui-color-gray-glass-010: rgba(255, 255, 255, 0.1);
576        --wui-color-gray-glass-015: rgba(255, 255, 255, 0.15);
577        --wui-color-gray-glass-020: rgba(255, 255, 255, 0.2);
578        --wui-color-gray-glass-025: rgba(255, 255, 255, 0.25);
579        --wui-color-gray-glass-030: rgba(255, 255, 255, 0.3);
580        --wui-color-gray-glass-060: rgba(255, 255, 255, 0.6);
581        --wui-color-gray-glass-080: rgba(255, 255, 255, 0.8);
582        --wui-color-gray-glass-090: rgba(255, 255, 255, 0.9);
583
584        --wui-color-dark-glass-100: rgba(42, 42, 42, 1);
585
586        --wui-icon-box-bg-error-base-100: #3c2426;
587        --wui-icon-box-bg-blue-base-100: #20303f;
588        --wui-icon-box-bg-success-base-100: #1f3a28;
589        --wui-icon-box-bg-inverse-base-100: #243240;
590
591        --wui-all-wallets-bg-100: #222b35;
592
593        --wui-avatar-border-base: #252525;
594
595        --wui-thumbnail-border-base: #252525;
596
597        --wui-wallet-button-bg-base: var(--wui-color-bg-125);
598
599        --w3m-card-embedded-shadow-color: rgb(17 17 18 / 25%);
600      }
601    `,dark:gi`
602      :root {
603        --w3m-color-mix: ${Pt((t==null?void 0:t["--w3m-color-mix"])||"#000")};
604        --w3m-accent: ${Pt(fs(t,"light")["--w3m-accent"])};
605        --w3m-default: #000;
606
607        --wui-color-modal-bg-base: ${Pt(fs(t,"light")["--w3m-background"])};
608        --wui-color-accent-base-100: var(--w3m-accent);
609
610        --wui-color-blueberry-100: hsla(231, 100%, 70%, 1);
611        --wui-color-blueberry-090: hsla(231, 97%, 72%, 1);
612        --wui-color-blueberry-080: hsla(231, 92%, 74%, 1);
613
614        --wui-color-fg-100: #141414;
615        --wui-color-fg-125: #2d3131;
616        --wui-color-fg-150: #474d4d;
617        --wui-color-fg-175: #636d6d;
618        --wui-color-fg-200: #798686;
619        --wui-color-fg-225: #828f8f;
620        --wui-color-fg-250: #8b9797;
621        --wui-color-fg-275: #95a0a0;
622        --wui-color-fg-300: #9ea9a9;
623        --wui-color-fg-325: #9a9a9a;
624        --wui-color-fg-350: #d0d0d0;
625
626        --wui-color-bg-100: #ffffff;
627        --wui-color-bg-125: #f5fafa;
628        --wui-color-bg-150: #f3f8f8;
629        --wui-color-bg-175: #eef4f4;
630        --wui-color-bg-200: #eaf1f1;
631        --wui-color-bg-225: #e5eded;
632        --wui-color-bg-250: #e1e9e9;
633        --wui-color-bg-275: #dce7e7;
634        --wui-color-bg-300: #d8e3e3;
635        --wui-color-bg-325: #f3f3f3;
636        --wui-color-bg-350: #202020;
637
638        --wui-color-success-base-100: #26b562;
639        --wui-color-success-base-125: #30a46b;
640
641        --wui-color-warning-base-100: #f3a13f;
642
643        --wui-color-error-base-100: #f05142;
644        --wui-color-error-base-125: #df4a34;
645
646        --wui-color-blue-base-100: rgba(102, 125, 255, 1);
647        --wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
648
649        --wui-color-success-glass-001: rgba(38, 181, 98, 0.01);
650        --wui-color-success-glass-002: rgba(38, 181, 98, 0.02);
651        --wui-color-success-glass-005: rgba(38, 181, 98, 0.05);
652        --wui-color-success-glass-010: rgba(38, 181, 98, 0.1);
653        --wui-color-success-glass-015: rgba(38, 181, 98, 0.15);
654        --wui-color-success-glass-020: rgba(38, 181, 98, 0.2);
655        --wui-color-success-glass-025: rgba(38, 181, 98, 0.25);
656        --wui-color-success-glass-030: rgba(38, 181, 98, 0.3);
657        --wui-color-success-glass-060: rgba(38, 181, 98, 0.6);
658        --wui-color-success-glass-080: rgba(38, 181, 98, 0.8);
659
660        --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
661
662        --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
663
664        --wui-color-error-glass-001: rgba(240, 81, 66, 0.01);
665        --wui-color-error-glass-002: rgba(240, 81, 66, 0.02);
666        --wui-color-error-glass-005: rgba(240, 81, 66, 0.05);
667        --wui-color-error-glass-010: rgba(240, 81, 66, 0.1);
668        --wui-color-error-glass-015: rgba(240, 81, 66, 0.15);
669        --wui-color-error-glass-020: rgba(240, 81, 66, 0.2);
670        --wui-color-error-glass-025: rgba(240, 81, 66, 0.25);
671        --wui-color-error-glass-030: rgba(240, 81, 66, 0.3);
672        --wui-color-error-glass-060: rgba(240, 81, 66, 0.6);
673        --wui-color-error-glass-080: rgba(240, 81, 66, 0.8);
674
675        --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
676
677        --wui-icon-box-bg-error-base-100: #f4dfdd;
678        --wui-icon-box-bg-blue-base-100: #d9ecfb;
679        --wui-icon-box-bg-success-base-100: #daf0e4;
680        --wui-icon-box-bg-inverse-base-100: #dcecfc;
681
682        --wui-all-wallets-bg-100: #e8f1fa;
683
684        --wui-avatar-border-base: #f3f4f4;
685
686        --wui-thumbnail-border-base: #eaefef;
687
688        --wui-wallet-button-bg-base: var(--wui-color-bg-125);
689
690        --wui-color-gray-glass-001: rgba(0, 0, 0, 0.01);
691        --wui-color-gray-glass-002: rgba(0, 0, 0, 0.02);
692        --wui-color-gray-glass-005: rgba(0, 0, 0, 0.05);
693        --wui-color-gray-glass-010: rgba(0, 0, 0, 0.1);
694        --wui-color-gray-glass-015: rgba(0, 0, 0, 0.15);
695        --wui-color-gray-glass-020: rgba(0, 0, 0, 0.2);
696        --wui-color-gray-glass-025: rgba(0, 0, 0, 0.25);
697        --wui-color-gray-glass-030: rgba(0, 0, 0, 0.3);
698        --wui-color-gray-glass-060: rgba(0, 0, 0, 0.6);
699        --wui-color-gray-glass-080: rgba(0, 0, 0, 0.8);
700        --wui-color-gray-glass-090: rgba(0, 0, 0, 0.9);
701
702        --wui-color-dark-glass-100: rgba(233, 233, 233, 1);
703
704        --w3m-card-embedded-shadow-color: rgb(224 225 233 / 25%);
705      }
706    `}}const i1=gi`
707  *,
708  *::after,
709  *::before,
710  :host {
711    margin: 0;
712    padding: 0;
713    box-sizing: border-box;
714    font-style: normal;
715    text-rendering: optimizeSpeed;
716    -webkit-font-smoothing: antialiased;
717    -moz-osx-font-smoothing: grayscale;
718    -webkit-tap-highlight-color: transparent;
719    font-family: var(--wui-font-family);
720    backface-visibility: hidden;
721  }
722`,r1=gi`
723  button,
724  a {
725    cursor: pointer;
726    display: flex;
727    justify-content: center;
728    align-items: center;
729    position: relative;
730    transition:
731      color var(--wui-duration-lg) var(--wui-ease-out-power-1),
732      background-color var(--wui-duration-lg) var(--wui-ease-out-power-1),
733      border var(--wui-duration-lg) var(--wui-ease-out-power-1),
734      border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1),
735      box-shadow var(--wui-duration-lg) var(--wui-ease-out-power-1);
736    will-change: background-color, color, border, box-shadow, border-radius;
737    outline: none;
738    border: none;
739    column-gap: var(--wui-spacing-3xs);
740    background-color: transparent;
741    text-decoration: none;
742  }
743
744  wui-flex {
745    transition: border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1);
746    will-change: border-radius;
747  }
748
749  button:disabled > wui-wallet-image,
750  button:disabled > wui-all-wallets-image,
751  button:disabled > wui-network-image,
752  button:disabled > wui-image,
753  button:disabled > wui-transaction-visual,
754  button:disabled > wui-logo {
755    filter: grayscale(1);
756  }
757
758  @media (hover: hover) and (pointer: fine) {
759    button:hover:enabled {
760      background-color: var(--wui-color-gray-glass-005);
761    }
762
763    button:active:enabled {
764      background-color: var(--wui-color-gray-glass-010);
765    }
766  }
767
768  button:disabled > wui-icon-box {
769    opacity: 0.5;
770  }
771
772  input {
773    border: none;
774    outline: none;
775    appearance: none;
776  }
777`,n1=gi`
778  .wui-color-inherit {
779    color: var(--wui-color-inherit);
780  }
781
782  .wui-color-accent-100 {
783    color: var(--wui-color-accent-100);
784  }
785
786  .wui-color-error-100 {
787    color: var(--wui-color-error-100);
788  }
789
790  .wui-color-blue-100 {
791    color: var(--wui-color-blue-100);
792  }
793
794  .wui-color-blue-90 {
795    color: var(--wui-color-blue-90);
796  }
797
798  .wui-color-error-125 {
799    color: var(--wui-color-error-125);
800  }
801
802  .wui-color-success-100 {
803    color: var(--wui-color-success-100);
804  }
805
806  .wui-color-success-125 {
807    color: var(--wui-color-success-125);
808  }
809
810  .wui-color-inverse-100 {
811    color: var(--wui-color-inverse-100);
812  }
813
814  .wui-color-inverse-000 {
815    color: var(--wui-color-inverse-000);
816  }
817
818  .wui-color-fg-100 {
819    color: var(--wui-color-fg-100);
820  }
821
822  .wui-color-fg-200 {
823    color: var(--wui-color-fg-200);
824  }
825
826  .wui-color-fg-300 {
827    color: var(--wui-color-fg-300);
828  }
829
830  .wui-color-fg-325 {
831    color: var(--wui-color-fg-325);
832  }
833
834  .wui-color-fg-350 {
835    color: var(--wui-color-fg-350);
836  }
837
838  .wui-bg-color-inherit {
839    background-color: var(--wui-color-inherit);
840  }
841
842  .wui-bg-color-blue-100 {
843    background-color: var(--wui-color-accent-100);
844  }
845
846  .wui-bg-color-error-100 {
847    background-color: var(--wui-color-error-100);
848  }
849
850  .wui-bg-color-error-125 {
851    background-color: var(--wui-color-error-125);
852  }
853
854  .wui-bg-color-success-100 {
855    background-color: var(--wui-color-success-100);
856  }
857
858  .wui-bg-color-success-125 {
859    background-color: var(--wui-color-success-100);
860  }
861
862  .wui-bg-color-inverse-100 {
863    background-color: var(--wui-color-inverse-100);
864  }
865
866  .wui-bg-color-inverse-000 {
867    background-color: var(--wui-color-inverse-000);
868  }
869
870  .wui-bg-color-fg-100 {
871    background-color: var(--wui-color-fg-100);
872  }
873
874  .wui-bg-color-fg-200 {
875    background-color: var(--wui-color-fg-200);
876  }
877
878  .wui-bg-color-fg-300 {
879    background-color: var(--wui-color-fg-300);
880  }
881
882  .wui-color-fg-325 {
883    background-color: var(--wui-color-fg-325);
884  }
885
886  .wui-color-fg-350 {
887    background-color: var(--wui-color-fg-350);
888  }
889`,Gi={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]};function vr(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const Pc=vr({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"}
889),Oc=vr({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"});vr({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"});vr({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});vr({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const Ov={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"]},Br={getMethodsByChainNamespace(t){return Ov[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const s={...t},i=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>i.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>i.add(r)),e.events&&Object.keys(e.events).forEach(r=>i.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[n]=r.split(":");n&&i.add(n)}
889),i.forEach(r=>{s[r]||(s[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,n])=>{s[r]&&(s[r].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([r,n])=>{s[r]&&(s[r].chains=n)}),e.events&&Object.entries(e.events).forEach(([r,n])=>{s[r]&&(s[r].events=n)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,c]=n.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((i,r)=>{const{id:n,chainNamespace:o,rpcUrls:a}=r,c=a.default.http[0];i[o]||(i[o]=this.createDefaultNamespace(o));const l=`${o}:${n}`,d=i[o];switch(d.chains.push(l),l){case Pc.caipNetworkId:d.chains.push(Pc.deprecatedCaipNetworkId);break;case Oc.caipNetworkId:d.chains.push(Oc.deprecatedCaipNetworkId);break}return d!=null&&d.rpcMap&&c&&(d.rpcMap[n]=c),i},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{var i;const e=await Zi.resolveName(t);return((i=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:i.address)||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],i=e.accounts.map(r=>{const[n,o]=r.split(":");return`${n}:${o}`});return Array.from(new Set([...s,...i]))})},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},isOriginAllowed(t,e,s){for(const i of[...e,...s])if(i.includes("*")){const n=`^${i.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(n,"u").test(t))return!0}else try{if(new URL(i).origin===t)return!0}catch{if(i===t)return!0}return!1}};class dd{constructor({provider:e,namespace:s}){this.id=B.CONNECTOR_ID.WALLET_CONNECT,this.name=Kr.ConnectorNamesMap[B.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Kr.ConnectorImageIds[B.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=p.getCaipNetworks.bind(p),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(),i=O.state.universalProviderConfigOverride,r=Br.createNamespaces(s,i);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 Qi.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:Tv})}}const Tv=["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"];class kv{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=s=>p.getCaipNetworks(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 networks(){return this.getCaipNetworks(this.namespace)}setAuthProvider(e){this.addConnector({id:B.CONNECTOR_ID.AUTH,type:"AUTH",name:B.CONNECTOR_NAMES.AUTH,provider:e,imageId:Kr.ConnectorImageIds[B.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const s=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(i=>s.has(i.id)?!1:(s.add(i.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,s){z.setStatus(e,s)}on(e,s){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(s)}off(e,s){const i=this.eventListeners.get(e);i&&i.delete(s)}
889removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const i=this.eventListeners.get(e);i&&i.forEach(r=>r(s))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){var n;const{caipNetwork:s,providerType:i}=e;if(!e.provider)return;const r="provider"in e.provider?e.provider.provider:e.provider;if(i==="WALLET_CONNECT"){r.setDefaultChain(s.caipNetworkId);return}if(r&&i==="AUTH"){const o=r,a=(n=z.state.preferredAccountTypes)==null?void 0:n[s.chainNamespace];await o.switchNetwork(s.caipNetworkId);const c=await o.getUser({chainId:s.caipNetworkId,preferredAccountType:a});this.emit("switchNetwork",c)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s instanceof dd);if(!e)throw new Error("WalletConnectConnector not found");return e}}class xv extends kv{setUniversalProvider(e){this.addConnector(new dd({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace}))}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()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){var r,n,o,a;const s=this.provider,i=((a=(o=(n=(r=s==null?void 0:s.session)==null?void 0:r.namespaces)==null?void 0:n[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:i.map(c=>X.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var n,o,a,c,l;if(!(e.caipNetwork&&ve.BALANCE_SUPPORTED_CHAINS.includes((n=e.caipNetwork)==null?void 0:n.chainNamespace))||(o=e.caipNetwork)!=null&&o.testnet)return{balance:"0.00",symbol:((a=e.caipNetwork)==null?void 0:a.nativeCurrency.symbol)||""};if(z.state.balanceLoading&&e.chainId===((c=p.state.activeCaipNetwork)==null?void 0:c.id))return{balance:z.state.balance||"0.00",symbol:z.state.balanceSymbol||""};const r=(await z.fetchTokenBalance()).find(d=>{var u,h;return d.chainId===`${(u=e.caipNetwork)==null?void 0:u.chainNamespace}:${e.chainId}`&&d.symbol===((h=e.caipNetwork)==null?void 0:h.nativeCurrency.symbol)});return{balance:(r==null?void 0:r.quantity.numeric)||"0.00",symbol:(r==null?void 0:r.symbol)||((l=e.caipNetwork)==null?void 0:l.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:s,message:i,address:r}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return((o=p.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===B.CHAIN.SOLANA?n=(await s.request({method:"solana_signMessage",params:{message:xc.encode(new TextEncoder().encode(i)),pubkey:r}},(a=p.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:n=await s.request({method:"personal_sign",params:[i,r]},(c=p.state.activeCaipNetwork)==null?void 0:c.caipNetworkId),{signature:n}}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:""})}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,n,o,a,c,l;const{caipNetwork:s}=e,i=this.getWalletConnectConnector();if(s.chainNamespace===B.CHAIN.EVM)try{await((r=i.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:Do(s.id)}]}))}catch(d){if(d.code===Gi.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||d.code===Gi.ERROR_INVALID_CHAIN_ID||d.code===Gi.ERROR_CODE_DEFAULT||((o=(n=d==null?void 0:d.data)==null?void 0:n.originalError)==null?void 0:o.code)===Gi.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=i.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:Do(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")}}i.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(i=>i.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}const Rv=["email","socials","swaps","onramp","activity","reownBranding"],$r={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?ve.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?ve.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?ve.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?ve.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?ve.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?ve.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?ve.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?ve.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?ve.DEFAULT_REMOTE_FEATURES.reownBranding:!!t}},$v={localSettingsOverridden:new Set,getApiConfig(t,e){return e==null?void 0:e.find(s=>
889s.id===t)},addWarning(t,e){if(t!==void 0){const s=$r[e],i=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(i)}},processFeature(t,e,s,i,r){const n=$r[t],o=e[n.localFeatureName];if(r&&!n.isAvailableOnBasic)return!1;if(i){const a=this.getApiConfig(n.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 $r[t].processApi(e)},processFallbackFeature(t,e){return $r[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let i=null,r=!1;try{i=await K.fetchProjectConfig(),r=i!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const n=r&&!e?ve.DEFAULT_REMOTE_FEATURES:ve.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of Rv){const a=this.processFeature(o,s,i,r,e);Object.assign(n,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),ve.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.`;Ts.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${o}`},"warning")}return n}};class Uv{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,i)=>{var r,n,o,a;if(s){const c=(n=(r=p.getNetworkData(s))==null?void 0:r.requestedCaipNetworks)==null?void 0:n.find(u=>u.id===i);if(c)return c;const l=(o=p.getNetworkData(s))==null?void 0:o.caipNetwork;return l||((a=p.getRequestedCaipNetworks(s).filter(u=>u.chainNamespace===s))==null?void 0:a[0])}return p.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>p.getCaipNetworks(s),this.getActiveChainNamespace=()=>p.state.activeChain,this.setRequestedCaipNetworks=(s,i)=>{p.setRequestedCaipNetworks(s,i)},this.getApprovedCaipNetworkIds=()=>p.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>p.state.activeChain===s||!s?p.state.activeCaipAddress:p.getAccountProp("caipAddress",s),this.setClientId=s=>{J.setClientId(s)},this.getProvider=s=>_e.getProvider(s),this.getProviderType=s=>_e.getProviderId(s),this.getPreferredAccountType=s=>{var i;return(i=z.state.preferredAccountTypes)==null?void 0:i[s]},this.setCaipAddress=(s,i)=>{z.setCaipAddress(s,i),s&&O.state.enableEmbedded&&this.close()},this.setBalance=(s,i,r)=>{z.setBalance(s,i,r)},this.setProfileName=(s,i)=>{z.setProfileName(s,i)},this.setProfileImage=(s,i)=>{z.setProfileImage(s,i)},this.setUser=(s,i)=>{z.setUser(s,i)},this.resetAccount=s=>{z.resetAccount(s)},this.setCaipNetwork=s=>{p.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,i)=>{p.setChainNetworkData(i,{caipNetwork:s})},this.setAllAccounts=(s,i)=>{z.setAllAccounts(s,i),O.setHasMultipleAddresses((s==null?void 0:s.length)>1)},this.setStatus=(s,i)=>{z.setStatus(s,i),q.isConnected()?W.setConnectionStatus("connected"):W.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>p.getAccountProp("address",s),this.setConnectors=s=>{const i=[...q.state.allConnectors,...s];q.setConnectors(i)},this.setConnections=(s,i)=>{Y.setConnections(s,i)},this.fetchIdentity=s=>J.fetchIdentity(s),this.getReownName=s=>Zi.getNamesForAddress(s),this.getConnectors=()=>q.getConnectors(),this.getConnectorImage=s=>Lc.getConnectorImage(s),this.setConnectedWalletInfo=(s,i)=>{const r=_e.getProviderId(i),n=s?{...s,type:r}:void 0;z.setConnectedWalletInfo(n,i)},this.getIsConnectedState=()=>!!p.state.activeCaipAddress,this.addAddressLabel=(s,i,r)=>{z.addAddressLabel(s,i,r)},this.removeAddressLabel=(s,i)=>{z.removeAddressLabel(s,i)},this.getAddress=s=>p.state.activeChain===s||!s?z.state.address:p.getAccountProp("address",s),this.setApprovedCaipNetworksData=s=>
889p.setApprovedCaipNetworksData(s),this.resetNetwork=s=>{p.resetNetwork(s)},this.addConnector=s=>{q.addConnector(s)},this.resetWcConnection=()=>{Y.resetWcConnection()},this.setAddressExplorerUrl=(s,i)=>{z.setAddressExplorerUrl(s,i)},this.setSmartAccountDeployed=(s,i)=>{z.setSmartAccountDeployed(s,i)},this.setSmartAccountEnabledNetworks=(s,i)=>{p.setSmartAccountEnabledNetworks(s,i)},this.setPreferredAccountType=(s,i)=>{z.setPreferredAccountType(s,i)},this.setEIP6963Enabled=s=>{O.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 i=e==null?void 0:e.map(n=>n.namespace).filter(n=>!!n);if(i!=null&&i.length)return[...new Set(i)];const r=s==null?void 0:s.map(n=>n.chainNamespace);return[...new Set(r)]}async initialize(e){var s,i,r;this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),await this.syncExistingConnection(),this.remoteFeatures=await $v.fetchRemoteFeatures(e),O.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&Fn.setOnrampProviders(this.remoteFeatures.onramp),((s=O.state.remoteFeatures)!=null&&s.email||Array.isArray((i=O.state.remoteFeatures)==null?void 0:i.socials)&&((r=O.state.remoteFeatures)==null?void 0:r.socials.length)>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await K.fetchAllowedOrigins();if(e&&X.isClient()){const s=window.location.origin;Br.isOriginAllowed(s,e,Gi.DEFAULT_ALLOWED_ANCESTORS)||Ts.open(ai.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else Ts.open(ai.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){var i;const{...s}=e;delete s.adapters,delete s.universalProvider,Se.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(r=>r.id),siweConfig:{options:((i=e.siweConfig)==null?void 0:i.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&pt.setThemeMode(e.themeMode),e.themeVariables&&pt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");p.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const s=this.getDefaultNetwork();s&&p.setActiveCaipNetwork(s)}initializeConnectionController(e){Y.setWcBasic(e.basic??!1)}initializeConnectorController(){q.initialize(this.chainNamespaces)}initializeProjectSettings(e){O.setProjectId(e.projectId),O.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var o;O.setDebug(e.debug!==!1),O.setEnableWalletConnect(e.enableWalletConnect!==!1),O.setEnableWalletGuide(e.enableWalletGuide!==!1),O.setEnableWallets(e.enableWallets!==!1),O.setEIP6963Enabled(e.enableEIP6963!==!1),O.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),O.setEnableAuthLogger(e.enableAuthLogger!==!1),O.setCustomRpcUrls(e.customRpcUrls),O.setEnableEmbedded(e.enableEmbedded),O.setAllWallets(e.allWallets),O.setIncludeWalletIds(e.includeWalletIds),O.setExcludeWalletIds(e.excludeWalletIds),O.setFeaturedWalletIds(e.featuredWalletIds),O.setTokens(e.tokens),O.setTermsConditionsUrl(e.termsConditionsUrl),O.setPrivacyPolicyUrl(e.privacyPolicyUrl),O.setCustomWallets(e.customWallets),O.setFeatures(e.features),O.setAllowUnsupportedChain(e.allowUnsupportedChain),O.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),O.setPreferUniversalLinks(e.experimental_preferUniversalLinks),O.setDefaultAccountTypes(e.defaultAccountTypes);const s=W.getPreferredAccountTypes()||{},i={...O.state.defaultAccountTypes,...s};z.setPreferredAccountTypes(i);const r=this.getDefaultMetaData();if(!e.metadata&&r&&(e.metadata=r),O.setMetadata(e.metadata),O.setDisableAppend(e.disableAppend),O.setEnableEmbedded(e.enableEmbedded),O.setSIWX(e.siwx),!e.projectId){Ts.open(ai.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((o=e.adapters)==null?void 0:o.find(a=>a.namespace===B.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");O.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,s,i,r;return X.isClient()?{name:((s=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:s.textContent)||"",description:((i=document.querySelector('meta[property="og:description"]'))==null?void 0:i.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 i=li.getUnsupportedNetwork(`${s}:${e}`);p.setActiveCaipNetwork(i)}}getDefaultNetwork(){return li.getCaipNetworkFromStorage(this.defaultCaipNetwork)}
889extendCaipNetwork(e,s){return li.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return li.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(r=>{var n;return r.id===((n=e.defaultNetwork)==null?void 0:n.id)});return s?li.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e){try{const s=this.getAdapter(e),i=_e.getProvider(e),r=_e.getProviderId(e),{caipAddress:n}=p.getAccountData(e)||{};this.setLoading(!0,e),n&&(s!=null&&s.disconnect)&&await s.disconnect({provider:i,providerType:r}),W.removeConnectedNamespace(e),_e.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),q.removeConnectorId(e),p.resetAccount(e),p.resetNetwork(e),this.setLoading(!1,e)}catch(s){throw this.setLoading(!1,e),new Error(`Failed to disconnect chain ${e}: ${s.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var n;const e=p.state.activeChain,s=this.getAdapter(e),i=(n=this.getCaipNetwork(e))==null?void 0:n.id;if(!s)throw new Error("Adapter not found");const r=await s.connectWalletConnect(i);this.close(),this.setClientId((r==null?void 0:r.clientId)||null),W.setConnectedNamespaces([...p.state.chains.keys()]),this.chainNamespaces.forEach(o=>{q.setConnectorId(De.CONNECTOR_TYPE_WALLET_CONNECT,o)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:s,type:i,provider:r,chain:n,caipNetwork:o,socialUri:a})=>{var m,f,y,b,E,_;const c=p.state.activeChain,l=n||c,d=this.getAdapter(l);if(n&&n!==c&&!o){const x=this.getCaipNetworks().find(P=>P.chainNamespace===n);x&&this.setCaipNetwork(x)}if(!d)throw new Error("Adapter not found");const u=this.getCaipNetwork(l),h=await d.connect({id:e,info:s,type:i,provider:r,socialUri:a,chainId:(o==null?void 0:o.id)||(u==null?void 0:u.id),rpcUrl:((y=(f=(m=o==null?void 0:o.rpcUrls)==null?void 0:m.default)==null?void 0:f.http)==null?void 0:y[0])||((_=(E=(b=u==null?void 0:u.rpcUrls)==null?void 0:b.default)==null?void 0:E.http)==null?void 0:_[0])});if(!h)return;W.addConnectedNamespace(l),this.syncProvider({...h,chainNamespace:l});const g=z.state.allAccounts,{accounts:w}=(g==null?void 0:g.length)>0?{accounts:[...g]}:await d.getAccounts({namespace:l,id:e});this.setAllAccounts(w,l),this.setStatus("connected",l),this.syncConnectedWalletInfo(l)},reconnectExternal:async({id:e,info:s,type:i,provider:r})=>{var a;const n=p.state.activeChain,o=this.getAdapter(n);o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:s,type:i,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),W.addConnectedNamespace(n),this.syncConnectedWalletInfo(n))},disconnect:async e=>{const s=Cv(e);try{const i=await Promise.allSettled(s.map(async([n])=>this.disconnectNamespace(n)));ue.resetSend(),Y.resetWcConnection(),await Qi.clearSessions(),q.setFilterByNamespace(void 0);const r=i.filter(n=>n.status==="rejected");if(r.length>0)throw new Error(r.map(n=>n.reason.message).join(", "));W.deleteConnectedSocialProvider(),Se.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:e||"all"}})}catch(i){throw new Error(`Failed to disconnect chains: ${i.message}`)}},checkInstalled:e=>e?e.some(s=>{var i;return!!((i=window.ethereum)!=null&&i[String(s)])}):!!window.ethereum,signMessage:async e=>{const s=this.getAdapter(p.state.activeChain),i=await(s==null?void 0:s.signMessage({message:e,address:z.state.address,provider:_e.getProvider(p.state.activeChain)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{const s=e.chainNamespace;if(ve.SEND_SUPPORTED_NAMESPACES.includes(s)){const i=this.getAdapter(p.state.activeChain),r=_e.getProvider(s),n=await(i==null?void 0:i.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:r}));return(n==null?void 0:n.hash)||""}return""},estimateGas:async e=>{if(e.chainNamespace===B.CHAIN.EVM){const s=this.getAdapter(p.state.activeChain),i=_e.getProvider(p.state.activeChain),r=this.getCaipNetwork();if(!r)throw new Error("CaipNetwork is undefined");const n=await(s==null?void 0:s.estimateGas({...e,provider:i,caipNetwork:r}));return(n==null?void 0:n.gas)||0n}return 0n},getEnsAvatar:async()=>{var e;return await this.syncIdentity({address:z.state.address,chainId:Number((e=this.getCaipNetwork())==null?void 0:e.id),chainNamespace:p.state.activeChain}),z.state.profileImage||!1},getEnsAddress:async e=>await Br.resolveReownName(e),writeContract:async e=>{const s=this.getAdapter(p.state.activeChain),i=this.getCaipNetwork(),r=this.getCaipAddress(),n=_e.getProvider(p.state.activeChain);if(!i||!r)throw new Error("CaipNetwork or CaipAddress is undefined");const o=await(s==null?void 0:s.writeContract({...e,caipNetwork:i,provider:n,caipAddress:r}));return o==null?void 0:o.hash},parseUnits:(e,s)=>{const i=this.getAdapter(p.state.activeChain);return(i==null?void 0:i.parseUnits({value:e,decimals:s}))??0n},formatUnits:(e,s)=>{const i=this.getAdapter(p.state.activeChain);return(i==null?void 0:i.formatUnits({value:e,decimals:s}))??"0"},getCapabilities:async e=>{const s=this.getAdapter(p.state.activeChain);return await(s==null?void 0:s.getCapabilities(e))},grantPermissions:async e=>{const s=this.getAdapter(p.state.activeChain);return await(s==null?void 0:s.grantPermissions(e))},revokePermissions:async e=>{const s=this.getAdapter(p.state.activeChain);return s!=null&&s.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(p.state.activeChain);return await(s==null?void 0:s.walletGetAssets(e))??{}},updateBalance:e=>{const s=this.getCaipNetwork(e);!s||!z.state.address||this.updateNativeBalance(z.state.address,s==null?void 0:s.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Y.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var s,i,r,n,o;if(_e.getProviderId(p.state.activeChain)===De.CONNECTOR_TYPE_WALLET_CONNECT){const a=(i=(s=this.universalProvider)==null?void 0:s.session)==null?void 0:i.namespaces;return{supportsAllNetworks:((o=(n=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:n.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=_e.getProvider(s),n=_e.getProviderId(s);if(e.chainNamespace===p.state.activeChain){const o=this.getAdapter(s);
889await(o==null?void 0:o.switchNetwork({caipNetwork:e,provider:r,providerType:n}))}else if(this.setCaipNetwork(e),n===De.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(s);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:s})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(s=>{const i=s.chains||[],r=s.accounts.map(n=>{const{chainId:o,chainNamespace:a}=as.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...i,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,i)=>{var n;const r=e==null?void 0:e.find(o=>o.namespace===i);return r?(r.construct({namespace:i,projectId:(n=this.options)==null?void 0:n.projectId,networks:this.getCaipNetworks()}),s[i]=r):s[i]=new xv({namespace:i,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){var s;this.onConnectors(e),this.listenAdapter(e),await((s=this.chainAdapters)==null?void 0:s[e].syncConnectors(this.options,this)),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}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 i=W.getConnectionStatus();i==="connected"?this.setStatus("connecting",e):i==="disconnected"?(W.clearAddressCache(),this.setStatus(i,e)):this.setStatus(i,e),s.on("switchNetwork",({address:r,chainId:n})=>{const o=this.getCaipNetworks().find(l=>l.id===n||l.caipNetworkId===n),a=p.state.activeChain===e,c=p.getAccountProp("address",e);if(o){const l=a&&r?r:c;l&&this.syncAccount({address:l,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),s.on("disconnect",this.disconnect.bind(this,e)),s.on("connections",r=>{this.setConnections(r,e)}),s.on("pendingTransactions",()=>{const r=z.state.address,n=p.state.activeCaipNetwork;!r||!(n!=null&&n.id)||this.updateNativeBalance(r,n.id,n.chainNamespace)}),s.on("accountChanged",({address:r,chainId:n})=>{var a,c;const o=p.state.activeChain===e;o&&n?this.syncAccount({address:r,chainId:n,chainNamespace:e}):o&&((a=p.state.activeCaipNetwork)!=null&&a.id)?this.syncAccount({address:r,chainId:(c=p.state.activeCaipNetwork)==null?void 0:c.id,chainNamespace:e}):this.syncAccountInfo(r,n,e),this.syncAllAccounts(e)})}async createUniversalProviderForAdapter(e){var s,i,r;await this.getUniversalProvider(),this.universalProvider&&((r=(i=(s=this.chainAdapters)==null?void 0:s[e])==null?void 0:i.setUniversalProvider)==null||r.call(i,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{e===B.CHAIN.EVM&&X.isSafeApp()&&q.setConnectorId(B.CONNECTOR_ID.SAFE,e);const s=q.getConnectorId(e);switch(this.setStatus("connecting",e),s){case B.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case B.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){var a,c,l;const s=this.getAdapter(e),i=q.getConnectorId(e),r=this.getCaipNetwork(e),o=q.getConnectors(e).find(d=>d.id===i);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(r!=null&&r.id))throw new Error("CaipNetwork not found");const d=await(s==null?void 0:s.syncConnection({namespace:e,id:o.id,chainId:r.id,rpcUrl:(l=(c=(a=r==null?void 0:r.rpcUrls)==null?void 0:a.default)==null?void 0:c.http)==null?void 0:l[0]}));if(d){const u=await(s==null?void 0:s.getAccounts({namespace:e,id:o.id}));u&&u.accounts.length>0?this.setAllAccounts(u.accounts,e):this.setAllAccounts([X.createAccount(e,d.address,"eoa")],e),this.syncProvider({...d,chainNamespace:e}),await this.syncAccount({...d,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async s=>{var a,c,l,d,u;const i=this.getAdapter(s),r=((d=(l=(c=(a=this.universalProvider)==null?void 0:a.session)==null?void 0:c.namespaces)==null?void 0:l[s])==null?void 0:d.accounts)||[],n=(u=p.state.activeCaipNetwork)==null?void 0:u.id,o=r.find(h=>{const{chainId:g}=as.parseCaipAddress(h);return g===(n==null?void 0:n.toString())})||r[0];
889if(o){const h=as.validateCaipAddress(o),{chainId:g,address:w}=as.parseCaipAddress(h);if(_e.setProviderId(s,De.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&p.state.activeCaipNetwork&&(i==null?void 0:i.namespace)!==B.CHAIN.EVM){const m=i==null?void 0:i.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:p.state.activeCaipNetwork});_e.setProvider(s,m)}else _e.setProvider(s,this.universalProvider);q.setConnectorId(B.CONNECTOR_ID.WALLET_CONNECT,s),W.addConnectedNamespace(s),this.syncWalletConnectAccounts(s),await this.syncAccount({address:w,chainId:g,chainNamespace:s})}else this.setStatus("disconnected",s);this.syncConnectedWalletInfo(s),await p.setApprovedCaipNetworksData(s)});await Promise.all(e)}syncWalletConnectAccounts(e){var i,r,n,o,a;const s=(a=(o=(n=(r=(i=this.universalProvider)==null?void 0:i.session)==null?void 0:r.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const{address:l}=as.parseCaipAddress(c);return l}).filter((c,l,d)=>d.indexOf(c)===l);s&&this.setAllAccounts(s.map(c=>X.createAccount(e,c,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:s,id:i,chainNamespace:r}){_e.setProviderId(r,e),_e.setProvider(r,s),q.setConnectorId(i,r)}async syncAllAccounts(e){const s=q.getConnectorId(e);if(!s)return;const i=this.getAdapter(e),r=await(i==null?void 0:i.getAccounts({namespace:e,id:s}));r&&r.accounts.length>0&&this.setAllAccounts(r.accounts,e)}async syncAccount(e){var u,h;const s=e.chainNamespace===p.state.activeChain,i=p.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:n,chainNamespace:o}=e,{chainId:a}=W.getActiveNetworkProps(),c=n||a,l=((u=p.state.activeCaipNetwork)==null?void 0:u.name)===B.UNSUPPORTED_NETWORK_NAME,d=p.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!d)&&c){let g=this.getCaipNetworks().find(f=>f.id.toString()===c.toString()),w=this.getCaipNetworks().find(f=>f.chainNamespace===o);if(!d&&!g&&!w){const f=this.getApprovedCaipNetworkIds()||[],y=f.find(E=>{var _;return((_=as.parseCaipNetworkId(E))==null?void 0:_.chainId)===c.toString()}),b=f.find(E=>{var _;return((_=as.parseCaipNetworkId(E))==null?void 0:_.chainNamespace)===o});g=this.getCaipNetworks().find(E=>E.caipNetworkId===y),w=this.getCaipNetworks().find(E=>E.caipNetworkId===b||"deprecatedCaipNetworkId"in E&&E.deprecatedCaipNetworkId===b)}const m=g||w;(m==null?void 0:m.chainNamespace)===p.state.activeChain?O.state.enableNetworkSwitch&&!O.state.allowUnsupportedChain&&((h=p.state.activeCaipNetwork)==null?void 0:h.name)===B.UNSUPPORTED_NETWORK_NAME?p.showUnsupportedChainUI():this.setCaipNetwork(m):s||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),xo.isLowerCaseMatch(r,z.state.address)||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:i==null?void 0:i.id,chainNamespace:o})}}async syncAccountInfo(e,s,i){const r=this.getCaipAddress(i),n=s||(r==null?void 0:r.split(":")[1]);if(!n)return;const o=`${i}:${n}:${e}`;this.setCaipAddress(o,i),await this.syncIdentity({address:e,chainId:n,chainNamespace:i})}async syncReownName(e,s){try{const i=await this.getReownName(e);if(i[0]){const r=i[0];this.setProfileName(r.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){var r;const s=q.getConnectorId(e),i=_e.getProviderId(e);if(i===De.CONNECTOR_TYPE_ANNOUNCED||i===De.CONNECTOR_TYPE_INJECTED){if(s){const n=this.getConnectors().find(o=>o.id===s);if(n){const{info:o,name:a,imageUrl:c}=n,l=c||this.getConnectorImage(n);this.setConnectedWalletInfo({name:a,icon:l,...o},e)}}}else if(i===De.CONNECTOR_TYPE_WALLET_CONNECT){const n=_e.getProvider(e);n!=null&&n.session&&this.setConnectedWalletInfo({...n.session.peer.metadata,name:n.session.peer.metadata.name,icon:(r=n.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(s&&s===B.CONNECTOR_ID.COINBASE){const n=this.getConnectors().find(o=>o.id===B.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(n)},e)}}async syncBalance(e){!Uc.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(i=>{var r;return i.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,i){const r=this.getAdapter(i),n=p.getCaipNetworkByNamespace(i,s);if(r){const o=await r.getBalance({address:e,chainId:s,caipNetwork:n,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,i),o}}async initializeUniversalAdapter(){var i,r,n,o,a,c,l,d,u,h;const e=Av.createLogger((g,...w)=>{g&&this.handleAlertError(g),console.error(...w)}),s={projectId:(i=this.options)==null?void 0:i.projectId,metadata:{name:(r=this.options)!=null&&r.metadata?(n=this.options)==null?void 0:n.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};O.setManualWCControl(!!((h=this.options)!=null&&h.manualWCControl)),this.universalProvider=this.options.universalProvider??await ko.init(s),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Y.setUri(e)}),this.universalProvider.on("connect",Y.finalizeWcConnection),this.universalProvider.on("disconnect",()=>
889{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Y.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const s=this.getCaipNetworks().find(r=>r.id==e),i=this.getCaipNetwork();if(!s){this.setUnsupportedNetwork(e);return}(i==null?void 0:i.id)!==(s==null?void 0:s.id)&&this.setCaipNetwork(s)}),this.universalProvider.on("session_event",e=>{if(Br.isSessionEventData(e)){const{name:s,data:i}=e.params.event;s==="accountsChanged"&&Array.isArray(i)&&X.isCaipAddress(i[0])&&this.syncAccount(as.parseCaipAddress(i[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&X.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Se.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}handleAlertError(e){const s=Object.entries(ai.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[i,r]=s??[],{message:n,alertErrorKey:o}=r??{};if(i&&n&&!this.reportedAlertErrors[i]){const a=ai.ALERT_ERRORS[o];a&&(Ts.open(a,"error"),this.reportedAlertErrors[i]=!0)}}getAdapter(e){var s;if(e)return(s=this.chainAdapters)==null?void 0:s[e]}createAdapter(e){var r;if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const i=e;i.namespace=s,i.construct({namespace:s,projectId:(r=this.options)==null?void 0:r.projectId,networks:this.getCaipNetworks()}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=i)}async open(e){if(await this.injectModalUi(),e!=null&&e.uri&&Y.setUri(e.uri),e!=null&&e.arguments)switch(e==null?void 0:e.view){case"Swap":return je.open({...e,data:{swap:e.arguments}})}return je.open(e)}async close(){await this.injectModalUi(),je.close()}setLoading(e,s){je.setLoading(e,s)}async disconnect(e){await Y.disconnect(e)}getSIWX(){return O.state.siwx}getError(){return""}getChainId(){var e;return(e=p.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e){const s=this.getCaipNetworks().find(i=>i.id===e.id);if(!s){Ts.open(ai.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await p.switchActiveNetwork(s)}getWalletProvider(){return p.state.activeChain?_e.state.providers[p.state.activeChain]:null}getWalletProviderType(){return _e.getProviderId(p.state.activeChain)}subscribeProviders(e){return _e.subscribeProviders(e)}getThemeMode(){return pt.state.themeMode}getThemeVariables(){return pt.state.themeVariables}setThemeMode(e){pt.setThemeMode(e),ld(pt.state.themeMode)}setTermsConditionsUrl(e){O.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){O.setPrivacyPolicyUrl(e)}setThemeVariables(e){pt.setThemeVariables(e),Pv(pt.state.themeVariables)}subscribeTheme(e){return pt.subscribe(e)}getWalletInfo(){return z.state.connectedWalletInfo}getAccount(e){var o;const s=q.getAuthConnector(e),i=p.getAccountData(e),r=p.state.activeChain,n=W.getConnectedConnectorId(e||r);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:X.getPlainAddress(i.caipAddress),isConnected:!!i.caipAddress,status:i.status,embeddedWalletInfo:s&&n===B.CONNECTOR_ID.AUTH?{user:i.user?{...i.user,username:W.getConnectedSocialUsername()}:void 0,authProvider:i.socialProvider||"email",accountType:(o=i.preferredAccountTypes)==null?void 0:o[e||r],isSmartAccountDeployed:!!i.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const i=()=>{const r=this.getAccount(s);r&&e(r)};s?p.subscribeChainProp("accountState",i,s):p.subscribe(i),q.subscribe(i)}subscribeNetwork(e){return p.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s==null?void 0:s.id,caipNetworkId:s==null?void 0:s.caipNetworkId})})}subscribeWalletInfo(e){return z.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){z.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){p.subscribeKey("activeCaipNetwork",e)}getState(){return ws.state}subscribeState(e){return ws.subscribe(e)}showErrorMessage(e){$t.showError(e)}showSuccessMessage(e){$t.showSuccess(e)}getEvent(){return{...Se.state}}subscribeEvents(e){return Se.subscribe(e)}replace(e){ie.replace(e)}redirect(e){ie.push(e)}popTransactionStack(e){ie.popTransactionStack(e)}isOpen(){return je.state.open}isTransactionStackEmpty(){return ie.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){O.setFeatures(e)}updateRemoteFeatures(e){O.setRemoteFeatures(e)}updateOptions(e){const i={...O.state||{},...e};O.setOptions(i)}setConnectMethodsOrder(e){O.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){O.setWalletFeaturesOrder(e)}setCollapseWallets(e){O.setCollapseWallets(e)}setSocialsOrder(e){O.setSocialsOrder(e)}getConnectMethodsOrder(){return fo.getConnectOrderMethod(O.state.features,q.getConnectors())}
889addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const i=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(r=>r.id===i.id)||p.addNetwork(i)}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)&&p.removeNetwork(e,s)}}let Tc=!1;class ud extends Uv{async open(e){q.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Y.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!Tc&&X.isClient()){if(await $n(()=>import("./basic-1487c761.js"),["assets/basic-1487c761.js","assets/index-c2fc66f8.js","assets/index-401e0e46.css","assets/class-map-57c26684.js","assets/index-02b3fc98.js","assets/async-directive-73fd2c02.js","assets/if-defined-2b5452c9.js","assets/browser-e933942f.js","assets/ref-e1e6c463.js","assets/index.es-7ecd5e33.js"]),await $n(()=>import("./w3m-modal-7ab77b07.js"),["assets/w3m-modal-7ab77b07.js","assets/index-c2fc66f8.js","assets/index-401e0e46.css","assets/class-map-57c26684.js","assets/if-defined-2b5452c9.js","assets/index-02b3fc98.js","assets/async-directive-73fd2c02.js","assets/index.es-7ecd5e33.js"]),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!O.state.disableAppend&&!O.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}Tc=!0}}}const Dv="1.7.8";function Lv(t){return new ud({...t,basic:!0,sdkVersion:`html-core-${Dv}`})}const o1=Object.freeze(Object.defineProperty({__proto__:null,AppKit:ud,createAppKit:Lv},Symbol.toStringTag,{value:"Module"}));export{Ts as A,p as C,Se as E,je as M,O,ie as R,Qi as S,pt as T,fo as W,Ze as a,Lc as b,n1 as c,Rt as d,r1 as e,Sv as f,q as g,z as h,$t as i,K as j,s1 as k,X as l,B as m,Fr as n,Y as o,Ae as p,W as q,i1 as r,Xe as s,ve as t,o1 as u,bt as w};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.