1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-bCnuLLg1.js","assets/index-BEJHjMzZ.js","assets/index-CT57dS2p.css","assets/parseUnits-ragi_lId.js","assets/parseSignature-G70V5xpw.js","assets/ccip-CtfxJpza.js","assets/parseEther-DBc1DAmg.js","assets/secp256k1-Dyn9Y2cF.js","assets/features-DTjur7ym.js","assets/basic-C22azmFS.js","assets/index-DRHBhFVT.js","assets/browser-DY1yB4tL.js","assets/w3m-modal-BGdqyti6.js"])))=>i.map(i=>d[i]); 2import{q as rp,b9 as ip,bg as op,aC as ap,h9 as cp,d4 as Bd,gM as Ur,t as oi,ha as lp,f8 as dp,hb as zo,hc as sr,hd as up,he as hp,hf as Dt,hg as yt,hh as W,hi as Ss,hj as pp,hk as fp,hl as Tr,hm as Go,hn as nr,ho as gp,hp as mp,hq as wp,hr as yp,hs as In,ht as bp,hu as Cp,hv as ts,hw as rr,hx as Ma,hy as Ep,hz as Ba,hA as ja,hB as Dr,hC as Fa,hD as pc,hE as vp,hF as Ap,hG as fc,hH as un,hI as jd,hJ as fs,hK as es,hL as Os,hM as Fd,s as ai,cm as gc}from"./index-BEJHjMzZ.js";function mc(t,e={}){const{key:s="fallback",name:n="Fallback",rank:r=!1,shouldThrow:i=Ip,retryCount:o,retryDelay:a}=e;return(({chain:c,pollingInterval:l=4e3,timeout:d,...u})=>{let h=t,f=()=>{};const g=rp({key:s,name:n,async request({method:m,params:w}){let A;const C=async(S=0)=>{const L=h[S]({...u,chain:c,retryCount:0,timeout:d});try{const B=await L.request({method:m,params:w});return f({method:m,params:w,response:B,transport:L,status:"success"}),B}catch(B){if(f({error:B,method:m,params:w,transport:L,status:"error"}),i(B)||S===h.length-1||(A??=h.slice(S+1).some(b=>{const{include:R,exclude:$}=b({chain:c}).config.methods||{};return R?R.includes(m):$?!$.includes(m):!0}),!A))throw B;return C(S+1)}};return C()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:m=>f=m,transports:h.map(m=>m({chain:c,retryCount:0}))});if(r){const m=typeof r=="object"?r:{};Np({chain:c,interval:m.interval??l,onTransports:w=>h=w,ping:m.ping,sampleCount:m.sampleCount,timeout:m.timeout,transports:h,weights:m.weights})}return g})}function Ip(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===ip.code||t.code===op.code||ap.nodeMessage.test(t.message)||t.code===5e3))}function Np({chain:t,interval:e=4e3,onTransports:s,ping:n,sampleCount:r=10,timeout:i=1e3,transports:o,weights:a={}}){const{stability:c=.7,latency:l=.3}=a,d=[],u=async()=>{const h=await Promise.all(o.map(async m=>{const w=m({chain:t,retryCount:0,timeout:i}),A=Date.now();let C,S;try{await(n?n({transport:w}):w.request({method:"net_listening"})),S=1}catch{S=0}finally{C=Date.now()}return{latency:C-A,success:S}}));d.push(h),d.length>r&&d.shift();const f=Math.max(...d.map(m=>Math.max(...m.map(({latency:w})=>w)))),g=o.map((m,w)=>{const A=d.map(b=>b[w].latency),S=1-A.reduce((b,R)=>b+R,0)/A.length/f,L=d.map(b=>b[w].success),B=L.reduce((b,R)=>b+R,0)/L.length;return B===0?[0,w]:[l*S+c*B,w]}).sort((m,w)=>w[0]-m[0]);s(g.map(([,m])=>o[m])),await cp(e),u()};u()}var wc={};const T={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"}
2,CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof wc<"u"?wc.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}}},IS_DEVELOPMENT:typeof process<"u"&&!1},qd={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?.filter(s=>s.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const s=t.find(r=>r.caipNetworkId===e);if(s)return s.name;const[n]=e.split(":");return T.CHAIN_NAME_MAP?.[n]||void 0}},Wd=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var _p=20,Sp=1,yn=1e6,yc=1e6,Tp=-7,kp=21,Op=!1,zr="[big.js] ",Nn=zr+"Invalid ",Ji=Nn+"decimal places",Pp=Nn+"rounding mode",Hd=zr+"Division by zero",Ne={},as=void 0,Rp=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Vd(){function t(e){var s=this;if(!(s instanceof t))return e===as?Vd():new t(e);if(e instanceof t)s.s=e.s,s.e=e.e,s.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(Nn+"value");e=e===0&&1/e<0?"-0":String(e)}xp(s,e)}s.constructor=t}return t.prototype=Ne,t.DP=_p,t.RM=Sp,t.NE=Tp,t.PE=kp,t.strict=Op,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function xp(t,e){var s,n,r;if(!Rp.test(e))throw Error(Nn+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(s=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(s<0&&(s=n),s+=+e.slice(n+1),e=e.substring(0,n)):s<0&&(s=e.length),r=e.length,n=0;n<r&&e.charAt(n)=="0";)++n;if(n==r)t.c=[t.e=0];else{for(;r>0&&e.charAt(--r)=="0";);for(t.e=s-n-1,t.c=[],s=0;n<=r;)t.c[s++]=+e.charAt(n++)}return t}function _n(t,e,s,n){var r=t.c;if(s===as&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(Pp);if(e<1)n=s===3&&(n||!!r[0])||e===0&&(s===1&&r[0]>=5||s===2&&(r[0]>5||r[0]===5&&(n||r[1]!==as))),r.length=1,n?(t.e=t.e-e+1,r[0]=1):r[0]=t.e=0;else if(e<r.length){if(n=s===1&&r[e]>=5||s===2&&(r[e]>5||r[e]===5&&(n||r[e+1]!==as||r[e-1]&1))||s===3&&(n||!!r[0]),r.length=e,n){for(;++r[--e]>9;)if(r[e]=0,e===0){++t.e,r.unshift(1);break}}for(e=r.length;!r[--e];)r.pop()}return t}function Sn(t,e,s){var n=t.e,r=t.c.join(""),i=r.length;if(e)r=r.charAt(0)+(i>1?"."+r.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)r="0"+r;r="0."+r}else if(n>0)if(++n>i)for(n-=i;n--;)r+="0";else n<i&&(r=r.slice(0,n)+"."+r.slice(n));else i>1&&(r=r.charAt(0)+"."+r.slice(1));return t.s<0&&s?"-"+r:r}Ne.abs=function(){var t=new this.constructor(this);return t.s=1,t};Ne.cmp=function(t){var e,s=this,n=s.c,r=(t=new s.constructor(t)).c,i=s.s,o=t.s,a=s.e,c=t.e;if(!n[0]||!r[0])return n[0]?i:r[0]?-o:0;if(i!=o)return i;if(e=i<0,a!=c)return a>c^e?1:-1;for(o=(a=n.length)<(c=r.length)?a:c,i=-1;++i<o;)if(n[i]!=r[i])return n[i]>r[i]^e?1:-1;return a==c?0:a>c^e?1:-1};Ne.div=function(t){var e=this,s=e.constructor,n=e.c,r=(t=new s(t)).c,i=e.s==t.s?1:-1,o=s.DP;if(o!==~~o||o<0||o>yn)throw Error(Ji);if(!r[0])throw Error(Hd);if(!n[0])return t.s=i,t.c=[t.e=0],t;
2var a,c,l,d,u,h=r.slice(),f=a=r.length,g=n.length,m=n.slice(0,a),w=m.length,A=t,C=A.c=[],S=0,L=o+(A.e=e.e-t.e)+1;for(A.s=i,i=L<0?0:L,h.unshift(0);w++<a;)m.push(0);do{for(l=0;l<10;l++){if(a!=(w=m.length))d=a>w?1:-1;else for(u=-1,d=0;++u<a;)if(r[u]!=m[u]){d=r[u]>m[u]?1:-1;break}if(d<0){for(c=w==a?r:h;w;){if(m[--w]<c[w]){for(u=w;u&&!m[--u];)m[u]=9;--m[u],m[w]+=10}m[w]-=c[w]}for(;!m[0];)m.shift()}else break}C[S++]=d?l:++l,m[0]&&d?m[w]=n[f]||0:m=[n[f]]}while((f++<g||m[0]!==as)&&i--);return!C[0]&&S!=1&&(C.shift(),A.e--,L--),S>L&&_n(A,L,s.RM,m[0]!==as),A};Ne.eq=function(t){return this.cmp(t)===0};Ne.gt=function(t){return this.cmp(t)>0};Ne.gte=function(t){return this.cmp(t)>-1};Ne.lt=function(t){return this.cmp(t)<0};Ne.lte=function(t){return this.cmp(t)<1};Ne.minus=Ne.sub=function(t){var e,s,n,r,i=this,o=i.constructor,a=i.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,i.plus(t);var l=i.c.slice(),d=i.e,u=t.c,h=t.e;if(!l[0]||!u[0])return u[0]?t.s=-c:l[0]?t=new o(i):t.s=1,t;if(a=d-h){for((r=a<0)?(a=-a,n=l):(h=d,n=u),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(s=((r=l.length<u.length)?l:u).length,a=c=0;c<s;c++)if(l[c]!=u[c]){r=l[c]<u[c];break}if(r&&(n=l,l=u,u=n,t.s=-t.s),(c=(s=u.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;s>a;){if(l[--s]<u[s]){for(e=s;e&&!l[--e];)l[e]=9;--l[e],l[s]+=10}l[s]-=u[s]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(t.s=1,l=[h=0]),t.c=l,t.e=h,t};Ne.mod=function(t){var e,s=this,n=s.constructor,r=s.s,i=(t=new n(t)).s;if(!t.c[0])throw Error(Hd);return s.s=t.s=1,e=t.cmp(s)==1,s.s=r,t.s=i,e?new n(s):(r=n.DP,i=n.RM,n.DP=n.RM=0,s=s.div(t),n.DP=r,n.RM=i,this.minus(s.times(t)))};Ne.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};Ne.plus=Ne.add=function(t){var e,s,n,r=this,i=r.constructor;if(t=new i(t),r.s!=t.s)return t.s=-t.s,r.minus(t);var o=r.e,a=r.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new i(r):t.s=r.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,n=l):(e=-e,n=a),n.reverse();e--;)n.push(0);n.reverse()}for(a.length-l.length<0&&(n=l,l=a,a=n),e=l.length,s=0;e;a[e]%=10)s=(a[--e]=a[e]+l[e]+s)/10|0;for(s&&(a.unshift(s),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t};Ne.pow=function(t){var e=this,s=new e.constructor("1"),n=s,r=t<0;if(t!==~~t||t<-yc||t>yc)throw Error(Nn+"exponent");for(r&&(t=-t);t&1&&(n=n.times(e)),t>>=1,!!t;)e=e.times(e);return r?s.div(n):n};Ne.prec=function(t,e){if(t!==~~t||t<1||t>yn)throw Error(Nn+"precision");return _n(new this.constructor(this),t,e)};Ne.round=function(t,e){if(t===as)t=0;else if(t!==~~t||t<-yn||t>yn)throw Error(Ji);return _n(new this.constructor(this),t+this.e+1,e)};Ne.sqrt=function(){var t,e,s,n=this,r=n.constructor,i=n.s,o=n.e,a=new r("0.5");if(!n.c[0])return new r(n);if(i<0)throw Error(zr+"No square root");i=Math.sqrt(+Sn(n,!0,!0)),i===0||i===1/0?(e=n.c.join(""),e.length+o&1||(e+="0"),i=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new r((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+o)):t=new r(i+""),o=t.e+(r.DP+=4);do s=t,t=a.times(s.plus(n.div(s)));while(s.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return _n(t,(r.DP-=4)+t.e+1,r.RM)};Ne.times=Ne.mul=function(t){var e,s=this,n=s.constructor,r=s.c,i=(t=new n(t)).c,o=r.length,a=i.length,c=s.e,l=t.e;if(t.s=s.s==t.s?1:-1,!r[0]||!i[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=r,r=i,i=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+i[c]*r[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t};Ne.toExponential=function(t,e){var s=this,n=s.c[0];if(t!==as){if(t!==~~t||t<0||t>yn)throw Error(Ji);for(s=_n(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return Sn(s,!0,!!n)};Ne.toFixed=function(t,e){var s=this,n=s.c[0];if(t!==as){if(t!==~~t||t<0||t>yn)throw Error(Ji);for(s=_n(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return Sn(s,!1,!!n)};Ne[Symbol.for("nodejs.util.inspect.custom")]=Ne.toJSON=Ne.toString=function(){var t=this,e=t.constructor;return Sn(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};Ne.toNumber=function(){var t=+Sn(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(zr+"Imprecise conversion");return t};Ne.toPrecision=function(t,e){var s=this,n=s.constructor,r=s.c[0];if(t!==as){if(t!==~~t||t<1||t>yn)throw Error(Nn+"precision");for(s=_n(new n(s),t,e);s.c.length<t;)s.c.push(0)}return Sn(s,t<=s.e||s.e<=n.NE||s.e>=n.PE,!!r)};Ne.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(zr+"valueOf disallowed");return Sn(t,t.e<=e.NE||t.e>=e.PE,!0)};var Ps=Vd();const $p={bigNumber(t){return t?new Ps(t):new Ps(0)},multiply(t,e){if(t===void 0||e===void 0)return new Ps(0);const s=new Ps(t),n=new Ps(e);return s.times(n)}
2,toFixed(t,e=2){return t===void 0||t===""?new Ps(0).toFixed(e):new Ps(t).toFixed(e)},formatNumberToLocalString(t,e=2){return t===void 0||t===""?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"})},parseLocalStringToNumber(t){if(t===void 0||t==="")return 0;const e=t.replace(/,/gu,"");return new Ps(e).toNumber()}},Up=[{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"}]}],Dp=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Lp=[{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"}]}],Mp={getERC20Abi:t=>T.USDT_CONTRACT_ADDRESSES.includes(t)?Lp:Up,getSwapAbi:()=>Dp},it={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,n,r]=e;if(!s||!n||!r)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:n,address:r}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,n]=e;if(!s||!n)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:n}}},zs={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError"},isRpcProviderError(t){try{if(typeof t=="object"&&t!==null){const e=t,s=typeof e.message=="string",n=typeof e.code=="number";return s&&n}return!1}catch{return!1}},isUserRejectedMessage(t){return t.toLowerCase().includes("user rejected")||t.toLowerCase().includes("user cancelled")||t.toLowerCase().includes("user canceled")},isUserRejectedRequestError(t){return zs.isRpcProviderError(t)?t.code===zs.RPC_ERROR_CODE.USER_REJECTED_REQUEST||zs.isUserRejectedMessage(t.message):t instanceof Error?zs.isUserRejectedMessage(t.message):!1}};class Bp extends Error{constructor(e,s){super(s.message,{cause:e}),this.name=zs.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=s.code}}class Kd extends Bp{constructor(e){super(e,{code:zs.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=zs.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const Q={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version"};function uo(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const X={setItem(t,e){vr()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(vr())return localStorage.getItem(t)||void 0},removeItem(t){vr()&&localStorage.removeItem(t)},clear(){vr()&&localStorage.clear()}};function vr(){return typeof window<"u"&&typeof localStorage<"u"}function Ri(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const jp=Symbol(),bc=Object.getPrototypeOf,Yo=new WeakMap,Fp=t=>t&&(Yo.has(t)?Yo.get(t):bc(t)===Object.prototype||bc(t)===Array.prototype),qp=t=>Fp(t)&&t[jp]||null,Cc=(t,e=!0)=>{Yo.set(t,e)},xi={},qa=t=>typeof t=="object"&&t!==null,Wp=t=>qa(t)&&!Gr.has(t)&&(Array.isArray(t)||!(Symbol.iterator in t))&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!(t instanceof Error)&&!(t instanceof Number)&&!(t instanceof Date)&&!(t instanceof String)&&!(t instanceof RegExp)&&!(t instanceof ArrayBuffer)&&!(t instanceof Promise),zd=(t,e)=>{const s=Jo.get(t);if(s?.[0]===e)return s[1];const n=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return Cc(n,!0),Jo.set(t,[e,n]),Reflect.ownKeys(t).forEach(r=>{if(Object.getOwnPropertyDescriptor(n,r))return;const i=Reflect.get(t,r),{enumerable:o}=Reflect.getOwnPropertyDescriptor(t,r),a={value:i,enumerable:o,configurable:!0};if(Gr.has(i))Cc(i,!1);else if(Ys.has(i)){const[c,l]=Ys.get(i);a.value=zd(c,l())}Object.defineProperty(n,r,a)}),Object.preventExtensions(n)},Hp=(t,e,s,n)=>({deleteProperty(r,i){const o=Reflect.get(r,i);s(i);const a=Reflect.deleteProperty(r,i);return a&&n(["delete",[i],o]),a},set(r,i,o,a){const c=!t()&&Reflect.has(r,i),l=Reflect.get(r,i,a);if(c&&(Ec(l,o)||Lr.has(o)&&Ec(l,Lr.get(o))))return!0;s(i),qa(o)&&(o=qp(o)||o);const d=!Ys.has(o)&&Kp(o)?Oe(o):o;return e(i,d),Reflect.set(r,i,d,a),n(["set",[i],o,l]),!0}}),Ys=new WeakMap,Gr=new WeakSet,Jo=new WeakMap,vi=[1],Lr=new WeakMap;let Ec=Object.is,Vp=(t,e)=>new Proxy(t,e),Kp=Wp,zp=zd,Gp=Hp;function Oe(t={}){if(!qa(t))throw new Error("object required");const e=Lr.get(t);if(e)return e;let s=vi[0];const n=new Set,r=(w,A=++vi[0])=>
2{s!==A&&(i=s=A,n.forEach(C=>C(w,A)))};let i=s;const o=(w=vi[0])=>(i!==w&&(i=w,c.forEach(([A])=>{const C=A[1](w);C>s&&(s=C)})),s),a=w=>(A,C)=>{const S=[...A];S[1]=[w,...S[1]],r(S,C)},c=new Map,l=(w,A)=>{const C=!Gr.has(A)&&Ys.get(A);if(C){if((xi?"production":void 0)!=="production"&&c.has(w))throw new Error("prop listener already exists");if(n.size){const S=C[2](a(w));c.set(w,[C,S])}else c.set(w,[C])}},d=w=>{var A;const C=c.get(w);C&&(c.delete(w),(A=C[1])==null||A.call(C))},u=w=>(n.add(w),n.size===1&&c.forEach(([C,S],L)=>{if((xi?"production":void 0)!=="production"&&S)throw new Error("remove already exists");const B=C[2](a(L));c.set(L,[C,B])}),()=>{n.delete(w),n.size===0&&c.forEach(([C,S],L)=>{S&&(S(),c.set(L,[C]))})});let h=!0;const f=Gp(()=>h,l,d,r),g=Vp(t,f);Lr.set(t,g);const m=[t,o,u];return Ys.set(g,m),Reflect.ownKeys(t).forEach(w=>{const A=Object.getOwnPropertyDescriptor(t,w);"value"in A&&A.writable&&(g[w]=t[w])}),h=!1,g}function Je(t,e,s){const n=Ys.get(t);(xi?"production":void 0)!=="production"&&!n&&console.warn("Please use proxy object");let r;const i=[],o=n[2];let a=!1;const l=o(d=>{i.push(d),r||(r=Promise.resolve().then(()=>{r=void 0,a&&e(i.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Mr(t){const e=Ys.get(t);(xi?"production":void 0)!=="production"&&!e&&console.warn("Please use proxy object");const[s,n]=e;return zp(s,n())}function Xn(t){return Gr.add(t),t}function Yp(){return{proxyStateMap:Ys,refSet:Gr,snapCache:Jo,versionHolder:vi,proxyCache:Lr}}function Xe(t,e,s,n){let r=t[e];return Je(t,()=>{const i=t[e];Object.is(r,i)||s(r=i)})}const{proxyStateMap:Jp,snapCache:Xp}=Yp(),ci=t=>Jp.has(t);function Zp(t){const e=[];let s=0;const n=new Map,r=new WeakMap,i=()=>{const l=Xp.get(a),d=l?.[1];if(d&&!r.has(d)){const u=new Map(n);r.set(d,u)}},o=l=>r.get(l)||n,a={data:e,index:s,epoch:0,get size(){return ci(this)||i(),o(this).size},get(l){const u=o(this).get(l);if(u===void 0){this.epoch;return}return this.data[u]},has(l){const d=o(this);return this.epoch,d.has(l)},set(l,d){if(!ci(this))throw new Error("Cannot perform mutations on a snapshot");const u=n.get(l);return u===void 0?(n.set(l,this.index),this.data[this.index++]=d):this.data[u]=d,this.epoch++,this},delete(l){if(!ci(this))throw new Error("Cannot perform mutations on a snapshot");const d=n.get(l);return d===void 0?!1:(delete this.data[d],n.delete(l),this.epoch++,!0)},clear(){if(!ci(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,n.clear()},forEach(l){this.epoch,o(this).forEach((u,h)=>{l(this.data[u],h,this)})},*entries(){this.epoch;const l=o(this);for(const[d,u]of l)yield[d,this.data[u]]},*keys(){this.epoch;const l=o(this);for(const d of l.keys())yield d},*values(){this.epoch;const l=o(this);for(const d of l.values())yield this.data[d]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=Oe(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}var vc={};const ho=(typeof process<"u"&&typeof vc<"u"?vc.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Gd=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Qp="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",me={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:ho,SECURE_SITE_DASHBOARD:`${ho}/dashboard`,SECURE_SITE_FAVICON:`${ho}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:[T.CHAIN.EVM,T.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[T.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:
256","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[T.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[T.CHAIN.EVM,T.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[T.CHAIN.EVM,T.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[T.CHAIN.EVM],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[T.CHAIN.EVM,T.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0}},U={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=U.getActiveNamespace(),e=U.getActiveCaipNetworkId(),s=e?e.split(":")[1]:void 0,n=s?isNaN(Number(s))?s:Number(s):void 0;return{namespace:t,caipNetworkId:e,chainId:n}},setWalletConnectDeepLink({name:t,href:e}){try{X.setItem(Q.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=X.getItem(Q.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{X.removeItem(Q.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{X.setItem(Q.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{X.setItem(Q.ACTIVE_CAIP_NETWORK_ID,t),U.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return X.getItem(Q.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{X.removeItem(Q.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=uo(t);X.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=U.getRecentWallets();e.find(n=>n.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),X.setItem(Q.RECENT_WALLETS,JSON.stringify(e)),X.setItem(Q.RECENT_WALLET,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=X.getItem(Q.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const t=X.getItem(Q.RECENT_WALLET);return t?JSON.parse(t):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{X.removeItem(Q.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(t,e){try{const s=uo(t);X.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return X.getItem(Q.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=uo(t);return X.getItem(e)}catch{console.info("Unable to get connected connector id in namespace",t)}},setConnectedSocialProvider(t){try{X.setItem(Q.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return X.getItem(Q.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{X.removeItem(Q.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return X.getItem(Q.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return X.getItem(Q.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{X.setItem(Q.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return X.getItem(Q.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=X.getItem(Q.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));X.setItem(Q.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=U.getConnectedNamespaces();e.includes(t)||(e.push(t),U.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=U.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),U.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return X.getItem(Q.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{X.setItem(Q.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{X.removeItem(Q.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=X.getItem(Q.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=U.getBalanceCache();X.setItem(Q.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=U.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;U.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=U.getBalanceCache();e[t.caipAddress]=t,X.setItem(Q.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=X.getItem(Q.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=U.getBalanceCache();X.setItem(Q.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=U.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),U.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=U.getNativeBalanceCache();e[t.caipAddress]=t,X.setItem(Q.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=X.getItem(Q.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t}
vendor: 13,392 bytes, line 2
2,getEnsFromCacheForAddress(t){try{const s=U.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;U.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=U.getEnsCache();e[t.address]=t,X.setItem(Q.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=U.getEnsCache();X.setItem(Q.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=X.getItem(Q.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=U.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;U.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=U.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},X.setItem(Q.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=U.getIdentityCache();X.setItem(Q.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{X.removeItem(Q.PORTFOLIO_CACHE),X.removeItem(Q.NATIVE_BALANCE_CACHE),X.removeItem(Q.ENS_CACHE),X.removeItem(Q.IDENTITY_CACHE),X.removeItem(Q.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{X.setItem(Q.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=X.getItem(Q.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s=U.getConnections(),n=s[e]??[],r=new Map;for(const o of n)r.set(o.connectorId,{...o});for(const o of t){const a=r.get(o.connectorId),c=o.connectorId===T.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(u=>u.address.toLowerCase())),d=o.accounts.filter(u=>!l.has(u.address.toLowerCase()));a.accounts.push(...d)}else r.set(o.connectorId,{...o})}const i={...s,[e]:Array.from(r.values())};X.setItem(Q.CONNECTIONS,JSON.stringify(i))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=X.getItem(Q.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}},deleteAddressFromConnection({connectorId:t,address:e,namespace:s}){try{const n=U.getConnections(),r=n[s]??[],i=new Map(r.map(a=>[a.connectorId,a])),o=i.get(t);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase()).length===0?i.delete(t):i.set(t,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase())})),X.setItem(Q.CONNECTIONS,JSON.stringify({...n,[s]:Array.from(i.values())}))}catch{console.error(`Unable to remove address "${e}" from connector "${t}" in namespace "${s}"`)}},getDisconnectedConnectorIds(){try{const t=X.getItem(Q.DISCONNECTED_CONNECTOR_IDS);return t?JSON.parse(t):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(t,e){try{const s=U.getDisconnectedConnectorIds(),n=s[e]??[];n.push(t),X.setItem(Q.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[e]:Array.from(new Set(n))}))}catch{console.error(`Unable to set disconnected connector id "${t}" for namespace "${e}"`)}},removeDisconnectedConnectorId(t,e){try{const s=U.getDisconnectedConnectorIds();let n=s[e]??[];n=n.filter(r=>r.toLowerCase()!==t.toLowerCase()),X.setItem(Q.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[e]:Array.from(new Set(n))}))}catch{console.error(`Unable to remove disconnected connector id "${t}" for namespace "${e}"`)}},isConnectorDisconnected(t,e){try{return(U.getDisconnectedConnectorIds()[e]??[]).some(r=>r.toLowerCase()===t.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${t}" for namespace "${e}"`)}return!1},getTransactionsCache(){try{const t=X.getItem(Q.HISTORY_TRANSACTIONS_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:t,chainId:e=""}){try{const n=U.getTransactionsCache()[t]?.[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.transactionsHistory))return n.transactions;U.removeTransactionsCache({address:t,chainId:e})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:t,chainId:e="",timestamp:s,transactions:n}){try{const r=U.getTransactionsCache();r[t]={...r[t],[e]:{timestamp:s,transactions:n}},X.setItem(Q.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(r))}catch{console.info("Unable to update transactions cache",{address:t,chainId:e,timestamp:s,transactions:n})}},removeTransactionsCache({address:t,chainId:e}){try{const s=U.getTransactionsCache(),n=s?.[t]||{},{[e]:r,...i}=n;X.setItem(Q.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...s,[t]:i}))}catch{console.info("Unable to remove transactions cache",{address:t,chainId:e})}},getTokenPriceCache(){try{const t=X.getItem(Q.TOKEN_PRICE_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(t){try{const s=U.getTokenPriceCache()[t.join(",")];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.tokenPrice))return s.tokenPrice;U.removeTokenPriceCache(t)}catch{console.info("Unable to get token price cache for addresses",t)}},updateTokenPriceCache(t){try{const e=U.getTokenPriceCache();e[t.addresses.join(",")]={timestamp:t.timestamp,tokenPrice:t.tokenPrice},X.setItem(Q.TOKEN_PRICE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update token price cache",t)}},removeTokenPriceCache(t){try{const e=U.getTokenPriceCache();X.setItem(Q.TOKEN_PRICE_CACHE,JSON.stringify({...e,[t.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",t)}},getLatestAppKitVersion(){try{const t=this.getLatestAppKitVersionCache(),e=t?.version;return e&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.latestAppKitVersion)?e:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const t=X.getItem(Q.LATEST_APPKIT_VERSION);return t?JSON.parse(t):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(t){try{const e=U.getLatestAppKitVersionCache();e.timestamp=t.timestamp,e.version=t.version,X.setItem(Q.LATEST_APPKIT_VERSION,JSON.stringify(e))}catch{console.info("Unable to update latest AppKit version on local storage",t)}}},J={isMobile(){return this.isClient()?!!(window?.matchMedia&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return J.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=me.TEN_SEC_MS:!0},isAllowedRetry(t,e=me.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(J.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const s=new URL(t),n=new URL(e);return s.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+me.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let s;return(...n)=>{function r(){t(...n)}s&&clearTimeout(s),s=setTimeout(r,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(J.isHttpUrl(t))return this.formatUniversalUrl(t,e);let n=t,r=s;n&&(n.includes("://")||(n=t.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`)),r&&!r?.endsWith("/")&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${n}wc?uri=${i}`,redirectUniversalLink:r?`${r}wc?uri=${i}`:void 0,href:n}},formatUniversalUrl(t,e){if(!J.isHttpUrl(t))return this.formatNativeUrl(t,e);let s=t;s.endsWith("/")||(s=`${s}/`);const n=encodeURIComponent(e);return{redirect:`${s}wc?uri=${n}`,href:s}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?U.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window?.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(display-mode: standalone)")?.matches:!1,e=window?.navigator?.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,n)=>{const r=new Image;r.onload=s,r.onerror=n,r.crossOrigin="anonymous",r.src=t});return Promise.race([e,J.wait(2e3)])},parseBalance(t,e){let s="0.000";if(typeof t=="string"){const c=Number(t);if(!isNaN(c)){const l=(Math.floor(c*1e3)/1e3).toFixed(3);l&&(s=l)}}const[n,r]=s.split("."),i=n||"0",o=r||"000";return{formattedText:`${i}.${o}${e?` ${e}`:""}`,value:i,decimals:o,symbol:e}},getApiUrl(){return T.W3M_API_URL},getBlockchainApiUrl(){return T.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return T.PULSE_API_URL},getUUID(){return 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){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const s={};return e&&t&&(t.forEach((n,r)=>{s[n]=r}),e.sort((n,r)=>{const i=s[n.id],o=s[r.id];return i!==void 0&&o!==void 0?i-o:i!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const s of t)e+=s.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[s,n]=e.split(".");return{dollars:s,pennies:n}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const s=new Set;return t.filter(n=>{const r=n[e];return s.has(r)?!1:(s.add(r),!0)})},generateSdkVersion(t,e,s){const r=t.length===0?me.ADAPTER_TYPES.UNIVERSAL:t.map(i=>i.adapterType).join(",");return`${e}-${r}-${s}`},createAccount(t,e,s,n,r){return{namespace:t,address:e,type:s,publicKey:n,path:r}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),s=e[0];return e.filter(Boolean).length===3&&s in T.CHAIN_NAME_MAP},getAccount(t){return t?typeof t=="string"?{address:t,chainId:void 0}:{address:t.address,chainId:t.chainId}:{address:void 0,chainId:void 0}},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const r="provider_authorization_url=",i=t.substring(t.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(i),s,e);return t.replace(i,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const n=t.indexOf(e);if(n===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const r=t.indexOf("&",n),i=e.length,o=r!==-1?r:t.length,a=t.substring(0,n+i),c=t.substring(n+i,o),l=t.substring(r),d=c+s;return a+d+l}};async function dr(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class Yr{constructor({baseUrl:e,clientId:s}){this.baseUrl=e,this.clientId=s}async get({headers:e,signal:s,cache:n,...r}){const i=this.createUrl(r);return(await dr(i,{method:"GET",headers:e,signal:s,cache:n})).json()}async getBlob({headers:e,signal:s,...n}){const r=this.createUrl(n);return(await dr(r,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await dr(i,{method:"POST",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}async put({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await dr(i,{method:"PUT",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}async delete({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await dr(i,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}createUrl({path:e,params:s}){const n=new URL(e,this.baseUrl);
2return s&&Object.entries(s).forEach(([r,i])=>{i&&n.searchParams.append(r,i)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}sendBeacon({body:e,...s}){const n=this.createUrl(s);return navigator.sendBeacon(n.toString(),e?JSON.stringify(e):void 0)}}const Xo={getFeatureValue(t,e){const s=e?.[t];return s===void 0?me.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(J.isTelegram()){if(J.isIos())return t.filter(e=>e!=="google");if(J.isMac())return t.filter(e=>e!=="x");if(J.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t},isSocialsEnabled(){return Array.isArray(_.state.features?.socials)&&_.state.features?.socials.length>0||Array.isArray(_.state.remoteFeatures?.socials)&&_.state.remoteFeatures?.socials.length>0},isEmailEnabled(){return!!(_.state.features?.email||_.state.remoteFeatures?.email)}},Z=Oe({features:me.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:me.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1}),_={state:Z,subscribeKey(t,e){return Xe(Z,t,e)},setOptions(t){Object.assign(Z,t)},setRemoteFeatures(t){if(!t)return;const e={...Z.remoteFeatures,...t};Z.remoteFeatures=e,Z.remoteFeatures?.socials&&(Z.remoteFeatures.socials=Xo.filterSocialsByPlatform(Z.remoteFeatures.socials)),Z.features?.pay&&(Z.remoteFeatures.email=!1,Z.remoteFeatures.socials=!1)},setFeatures(t){if(!t)return;Z.features||(Z.features=me.DEFAULT_FEATURES);const e={...Z.features,...t};Z.features=e,Z.features?.pay&&Z.remoteFeatures&&(Z.remoteFeatures.email=!1,Z.remoteFeatures.socials=!1)},setProjectId(t){Z.projectId=t},setCustomRpcUrls(t){Z.customRpcUrls=t},setAllWallets(t){Z.allWallets=t},setIncludeWalletIds(t){Z.includeWalletIds=t},setExcludeWalletIds(t){Z.excludeWalletIds=t},setFeaturedWalletIds(t){Z.featuredWalletIds=t},setTokens(t){Z.tokens=t},setTermsConditionsUrl(t){Z.termsConditionsUrl=t},setPrivacyPolicyUrl(t){Z.privacyPolicyUrl=t},setCustomWallets(t){Z.customWallets=t},setIsSiweEnabled(t){Z.isSiweEnabled=t},setIsUniversalProvider(t){Z.isUniversalProvider=t},setSdkVersion(t){Z.sdkVersion=t},setMetadata(t){Z.metadata=t},setDisableAppend(t){Z.disableAppend=t},setEIP6963Enabled(t){Z.enableEIP6963=t},setDebug(t){Z.debug=t},setEnableWalletGuide(t){Z.enableWalletGuide=t},setEnableAuthLogger(t){Z.enableAuthLogger=t},setEnableWallets(t){Z.enableWallets=t},setPreferUniversalLinks(t){Z.experimental_preferUniversalLinks=t},setSIWX(t){if(t)for(const[e,s]of Object.entries(me.SIWX_DEFAULTS))t[e]??=s;Z.siwx=t},setConnectMethodsOrder(t){Z.features={...Z.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){Z.features={...Z.features,walletFeaturesOrder:t}},setSocialsOrder(t){Z.remoteFeatures={...Z.remoteFeatures,socials:t}},setCollapseWallets(t){Z.features={...Z.features,collapseWallets:t}},setEnableEmbedded(t){Z.enableEmbedded=t},setAllowUnsupportedChain(t){Z.allowUnsupportedChain=t},setManualWCControl(t){Z.manualWCControl=t},setEnableNetworkSwitch(t){Z.enableNetworkSwitch=t},setEnableMobileFullScreen(t){Z.enableMobileFullScreen=J.isMobile()&&t},setEnableReconnect(t){Z.enableReconnect=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(Z.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){Z.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return Z.universalProviderConfigOverride},getSnapshot(){return Mr(Z)}},on=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),je=Oe({...on}),ef={state:je,subscribeKey(t,e){return Xe(je,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=J.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){je.message=on.message,je.variant=on.variant,je.svg=on.svg,je.open=on.open,je.autoClose=on.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:n=on.autoClose}){je.open?(je.open=!1,setTimeout(()=>{je.message=t,je.variant=s,je.svg=e,je.open=!0,je.autoClose=n},150)):(je.message=t,je.variant=s,je.svg=e,je.open=!0,je.autoClose=n)}}
vendor: 23,991 bytes, lines 2-4
2,rs=ef,tf={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"}]}]},Yd=J.getBlockchainApiUrl(),lt=Oe({clientId:null,api:new Yr({baseUrl:Yd,clientId:null}),supportedChains:{http:[],ws:[]}}),se={state:lt,async get(t){const{st:e,sv:s}=se.getSdkProperties(),n=_.state.projectId,r={...t.params||{},st:e,sv:s,projectId:n};return lt.api.get({...t,params:r})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=_.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{lt.supportedChains.http.length||await se.getSupportedNetworks()}catch{return!1}return lt.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await se.get({path:"v1/supported-chains"});return lt.supportedChains=t,t}catch{return lt.supportedChains}},async fetchIdentity({address:t}){const e=U.getIdentityFromCacheForAddress(t);if(e)return e;const s=await se.get({path:`/v1/identity/${t}`,params:{sender:p.state.activeCaipAddress?J.getPlainAddress(p.state.activeCaipAddress):void 0}});return U.updateIdentityCache({address:t,identity:s,timestamp:Date.now()}),s},async fetchTransactions({account:t,cursor:e,signal:s,cache:n,chainId:r}){if(!await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};const o=U.getTransactionsCacheForAddress({address:t,chainId:r});if(o)return o;const a=await se.get({path:`/v1/account/${t}/history`,params:{cursor:e,chainId:r},signal:s,cache:n});return U.updateTransactionsCache({address:t,chainId:r,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:n,gasPrice:r}){return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?se.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:s,to:n,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?se.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){if(!await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId))return{fungibles:[]};const s=U.getTokenPriceCacheForAddresses(t);if(s)return s;const n=await lt.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:_.state.projectId},headers:{"Content-Type":"application/json"}});return U.updateTokenPriceCache({addresses:t,timestamp:Date.now(),tokenPrice:n}),n},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?se.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){const{st:e,sv:s}=se.getSdkProperties();if(!await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return se.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:s}})},async generateSwapCalldata({amount:t,from:e,to:s,userAddress:n,disableEstimate:r}){if(!await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return lt.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:me.CONVERT_SLIPPAGE_TOLERANCE},projectId:_.state.projectId,from:e,to:s,userAddress:n,disableEstimate:r}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){const{st:n,sv:r}=se.getSdkProperties();if(!await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return se.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:t,to:e,st:n,sv:r}})},async getBalance(t,e,s){const{st:n,sv:r}=se.getSdkProperties();if(!await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId))return rs.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=U.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await se.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:n,sv:r}});return U.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?se.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){if(!await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId))return[];const s=p.getAccountData()?.address;return se.get({path:`/v1/profile/reverse/${t}`,params:{sender:s,apiVersion:"2"}})},async getEnsNameSuggestions(t){return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?se.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:n}){return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?lt.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:s,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:s,purchaseAmount:n,paymentAmount:r}){return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?(await lt.api.post({path:"/v1/generators/onrampurl",params:{projectId:_.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:r}})).url:""},async getOnrampOptions(){if(!await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await se.get({path:"/v1/onramp/options"})}catch{return tf}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}){try{return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?await lt.api.post({path:"/v1/onramp/quote",params:{projectId:_.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}}):null}catch{return{networkFee:{amount:s,currency:e.id},paymentSubtotal:{amount:s,currency:e.id},paymentTotal:{amount:s,currency:e.id},purchaseAmount:{amount:s,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?se.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){return await se.isNetworkSupported(p.state.activeCaipNetwork?.caipNetworkId)?lt.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:_.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){lt.clientId=t,lt.api=new Yr({baseUrl:Yd,clientId:t})}},Es={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"}},Rt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"},BINANCE:{id:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25",appId:"yFK5FCqYprrXDiVFbhyRx7",deeplink:"bnc://app.binance.com/mp/app",url:"https://app.binance.com/en/download"}},sf={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,n=encodeURIComponent(s);if(t===Rt.PHANTOM.id&&!("phantom"in window)){const r=s.startsWith("https")?"https":"http",i=s.split("/")[2],o=encodeURIComponent(`${r}://${i}`);window.location.href=`${Rt.PHANTOM.url}/ul/browse/${n}?ref=${o}`}if(t===Rt.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Rt.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),e===T.CHAIN.SOLANA&&t===Rt.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Rt.COINBASE.url}/dapp?cb_url=${n}`),e===T.CHAIN.BITCOIN&&t===Rt.BINANCE.id&&!("binancew3w"in window)){const r=p.state.activeCaipNetwork,i=window.btoa("/pages/browser/index"),o=window.btoa(`url=${n}&defaultChainId=${r?.id??1}`),a=new URL(Rt.BINANCE.deeplink);a.searchParams.set("appId",Rt.BINANCE.appId),a.searchParams.set("startPagePath",i),a.searchParams.set("startPageQuery",o);const c=new URL(Rt.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}},nf=Object.freeze({enabled:!0,events:[]}),rf=new Yr({baseUrl:J.getAnalyticsUrl(),clientId:null}),of=5,af=60*1e3,Rs=Oe({...nf}),cf={state:Rs,subscribeKey(t,e){return Xe(Rs,t,e)},async sendError(t,e){if(!Rs.enabled)return;const s=Date.now();if(Rs.events.filter(i=>{const o=new Date(i.properties.timestamp||"").getTime();return s-o<af}).length>=of)return;const r={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Rs.events.push(r);try{if(typeof window>"u")return;const{projectId:i,sdkType:o,sdkVersion:a}=_.state;await rf.post({path:"/e",params:{projectId:i,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:J.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(){Rs.enabled=!0},disable(){Rs.enabled=!1},clearEvents(){Rs.events=[]}};class bn extends Error{constructor(e,s,n){super(e),this.originalName="AppKitError",this.name="AppKitError",this.category=s,this.originalError=n,n&&n instanceof Error&&(this.originalName=n.name),Object.setPrototypeOf(this,bn.prototype);let r=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){const i=n.stack,o=i.indexOf(` 3`);if(o>-1){const a=i.substring(o+1);this.stack=`${this.name}: ${this.message} 4${a}`,r=!0}}r||(Error.captureStackTrace?Error.captureStackTrace(this,bn):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Ac(t,e){let s="";try{t instanceof Error?s=t.message:typeof t=="string"?s=t:typeof t=="object"&&t!==null?Object.keys(t).length===0?s="Unknown error":s=t?.message||JSON.stringify(t):s=String(t)}catch(r){s="Unknown error",console.error("Error parsing error message",r)}const n=t instanceof bn?t:new bn(s,e,t);throw cf.sendError(n,n.category),n}function Bt(t,e="INTERNAL_SDK_ERROR"){const s={};return Object.keys(t).forEach(n=>{const r=t[n];if(typeof r=="function"){let i=r;r.constructor.name==="AsyncFunction"?i=async(...o)=>{try{return await r(...o)}catch(a){return Ac(a,e)}}:i=(...o)=>{try{return r(...o)}catch(a){return Ac(a,e)}},s[n]=i}else s[n]=r}),s}const Ct=Oe({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),lf={state:Ct,subscribeNetworkImages(t){return Je(Ct.networkImages,()=>t(Ct.networkImages))},subscribeKey(t,e){return Xe(Ct,t,e)},subscribe(t){return Je(Ct,()=>t(Ct))},setWalletImage(t,e){Ct.walletImages[t]=e},setNetworkImage(t,e){Ct.networkImages[t]=e},setChainImage(t,e){Ct.chainImages[t]=e},setConnectorImage(t,e){Ct.connectorImages={...Ct.connectorImages,[t]:e}},setTokenImage(t,e){Ct.tokenImages[t]=e},setCurrencyImage(t,e){Ct.currencyImages[t]=e}},Ut=Bt(lf),df={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:""},po=Oe({networkImagePromises:{}}),Jd={async fetchWalletImage(t){if(t)return await ee._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(po.networkImagePromises[t]||(po.networkImagePromises[t]=ee._fetchNetworkImage(t)),await po.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return Ut.state.walletImages[t]},getWalletImage(t){if(t?.image_url)return t?.image_url;if(t?.image_id)return Ut.state.walletImages[t.image_id]},getNetworkImage(t){if(t?.assets?.imageUrl)return t?.assets?.imageUrl;if(t?.assets?.imageId)return Ut.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return Ut.state.networkImages[t]},getConnectorImage(t){if(t?.imageUrl)return t.imageUrl;if(t?.info?.icon)return t.info.icon;if(t?.imageId)return Ut.state.connectorImages[t.imageId]},getChainImage(t){return Ut.state.networkImages[df[t]]},getTokenImage(t){if(t)return Ut.state.tokenImages[t]}},uf=J.getAnalyticsUrl(),hf=new Yr({baseUrl:uf,clientId:null}),pf=["MODAL_CREATED"],ff=45,Ic=1e3*10,$e=Oe({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),le={state:$e,subscribe(t){return Je($e,()=>t($e))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=_.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},shouldFlushEvents(){const t=JSON.stringify($e.pendingEvents).length/1024>ff,e=$e.lastFlush+Ic<Date.now();return t||e},_setPendingEvent(t){try{let e=p.getAccountData()?.address;if("address"in t.data&&t.data.address&&(e=t.data.address),pf.includes(t.data.event)||typeof window>"u")return;const s=p.getActiveCaipNetwork()?.caipNetworkId;this.state.pendingEvents.push({eventId:J.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e,properties:{..."properties"in t.data?t.data.properties:{},caipNetworkId:s}}}),$e.reportedErrors.FORBIDDEN=!1,le.shouldFlushEvents()&&le._submitPendingEvents()}catch(e){console.warn("_setPendingEvent",e)}},sendEvent(t){$e.timestamp=Date.now(),$e.data=t;const e=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];(_.state.features?.analytics||e.includes(t.event))&&le._setPendingEvent($e),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(t){$e.walletImpressions.push(t)},_transformPendingEventsForBatch(t){try{return t.filter(e=>e.props.event!=="WALLET_IMPRESSION")}catch{return t}},_submitPendingEvents(){if($e.lastFlush=Date.now(),!($e.pendingEvents.length===0&&$e.walletImpressions.length===0))try{const t=le._transformPendingEventsForBatch($e.pendingEvents);$e.walletImpressions.length&&t.push({eventId:J.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION",items:[...$e.walletImpressions]}}),hf.sendBeacon({path:"/batch",params:le.getSdkProperties(),body:t}),$e.reportedErrors.FORBIDDEN=!1,$e.pendingEvents=[],$e.walletImpressions=[]}catch{$e.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){$e.subscribedToVisibilityChange||typeof document>"u"||($e.subscribedToVisibilityChange=!0,document?.addEventListener?.("visibilitychange",()=>{document.visibilityState==="hidden"&&le._submitPendingEvents()}),document?.addEventListener?.("freeze",()=>{le._submitPendingEvents()}),window?.addEventListener?.("pagehide",()=>{le._submitPendingEvents()}),setInterval(()=>{le._submitPendingEvents()},Ic))}},gf=J.getApiUrl(),dt=new Yr({baseUrl:gf,clientId:null}),mf=40,Nc=4,wf=20,re=Oe({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1,explorerWallets:[],explorerFilteredWallets:[]}),ee={state:re,subscribeKey(t,e){return Xe(re,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=_.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return _.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${dt.baseUrl}/getWalletImage/${t}`,s=await dt.getBlob({path:e,params:ee._getSdkProperties()});Ut.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${dt.baseUrl}/public/getAssetImage/${t}`,s=await dt.getBlob({path:e,params:ee._getSdkProperties()});Ut.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${dt.baseUrl}/public/getAssetImage/${t}`,s=await dt.getBlob({path:e,params:ee._getSdkProperties()});Ut.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${dt.baseUrl}/public/getCurrencyImage/${t}`,s=await dt.getBlob({path:e,params:ee._getSdkProperties()});Ut.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${dt.baseUrl}/public/getTokenImage/${t}`,s=await dt.getBlob({path:e,params:ee._getSdkProperties()});Ut.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){const e=t.length,s=J.isMobile()?t?.filter(r=>r.mobile_link||r.webapp_link?!0:Object.values(Rt).map(o=>o.id).includes(r.id)):t,n=e-s.length;return{filteredWallets:s,mobileFilteredOutWalletsLength:n}},async fetchProjectConfig(){return(await dt.get({path:"/appkit/v1/config",params:ee._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await dt.get({path:"/projects/v1/origins",params:ee._getSdkProperties()});return t}catch(t){if(t instanceof Error&&t.cause instanceof Response){const e=t.cause.status;if(e===T.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:t});if(e>=T.HTTP_STATUS_CODES.SERVER_ERROR&&e<600)throw new Error("SERVER_ERROR",{cause:t});return[]}return[]}},async fetchNetworkImages(){const e=p.getAllRequestedCaipNetworks()?.map(({assets:s})=>s?.imageId).filter(Boolean).filter(s=>!Jd.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>ee._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=M.state,e=t.map(({imageId:s})=>s).filter(Boolean);await Promise.allSettled(e.map(s=>ee._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>ee._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>ee._fetchTokenImage(e)))},async fetchWallets(t){const e=t.exclude??[];ee._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Rt).map(o=>o.id));const n=await dt.get({path:"/getWallets",params:{...ee._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:t.include?.join(","),exclude:e.join(",")}}),{filteredWallets:r,mobileFilteredOutWalletsLength:i}=ee._filterWalletsByPlatform(n?.data);return{data:r||[],count:n?.count,mobileFilteredOutWalletsLength:i}},async prefetchWalletRanks(){const t=M.state.connectors;if(!t?.length)return;const e={page:1,entries:20,badge:"certified"};if(e.names=t.map(r=>r.name).join(","),p.state.activeChain===T.CHAIN.EVM){const r=[...t.flatMap(i=>i.connectors?.map(o=>o.info?.rdns)||[]),...t.map(i=>i.info?.rdns)].filter(i=>typeof i=="string"&&i.length>0);r.length&&(e.rdns=r.join(","))}const{data:s}=await ee.fetchWallets(e);re.explorerWallets=s;const n=p.getRequestedCaipNetworkIds().join(",");re.explorerFilteredWallets=s.filter(r=>r.chains?.some(i=>n.includes(i)))},async fetchFeaturedWallets(){const{featuredWalletIds:t}=_.state;if(t?.length){const e={...ee._getSdkProperties(),page:1,entries:t?.length??Nc,include:t},{data:s}=await ee.fetchWallets(e),n=[...s].sort((i,o)=>t.indexOf(i.id)-t.indexOf(o.id)),r=n.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(r.map(i=>ee._fetchWalletImage(i))),re.featured=n,re.allFeatured=n}},async fetchRecommendedWallets(){try{re.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=_.state,n=[...e??[],...s??[]].filter(Boolean),r=p.getRequestedCaipNetworkIds().join(","),i={page:1,entries:Nc,include:t,exclude:n,chains:r},{data:o,count:a}=await ee.fetchWallets(i),c=U.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=>ee._fetchWalletImage(u))),re.recommended=o,re.allRecommended=o,re.count=a??0}catch{}finally{re.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:n}=_.state,r=p.getRequestedCaipNetworkIds().join(","),i=[...re.recommended.map(({id:u})=>u),...s??[],...n??[]].filter(Boolean),o={page:t,entries:mf,include:e,exclude:i,chains:r},{data:a,count:c,mobileFilteredOutWalletsLength:l}=await ee.fetchWallets(o);re.mobileFilteredOutWalletsLength=l+(re.mobileFilteredOutWalletsLength??0);const d=a.slice(0,wf).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(d.map(u=>ee._fetchWalletImage(u))),re.wallets=J.uniqueBy([...re.wallets,...ee._filterOutExtensions(a)],"id").filter(u=>u.chains?.some(h=>r.includes(h))),re.count=c>re.count?c:re.count,re.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await ee.fetchWallets(e);s&&s.forEach(n=>{re.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:n}=_.state,r=p.getRequestedCaipNetworkIds().join(",");re.search=[];const i={page:1,entries:100,search:t?.trim(),badge_type:e,include:s,exclude:n,chains:r},{data:o}=await ee.fetchWallets(i);le.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=>ee._fetchWalletImage(c)),J.wait(300)]),re.search=ee._filterOutExtensions(o)},initPromise(t,e){const s=re.promises[t];return s||(re.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:n=!0,fetchWalletRanks:r=!0}={}){const i=[t&&ee.initPromise("connectorImages",ee.fetchConnectorImages),e&&ee.initPromise("featuredWallets",ee.fetchFeaturedWallets),s&&ee.initPromise("recommendedWallets",ee.fetchRecommendedWallets),n&&ee.initPromise("networkImages",ee.fetchNetworkImages),r&&ee.initPromise("walletRanks",ee.prefetchWalletRanks)].filter(
4Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){_.state.features?.analytics&&ee.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await dt.get({path:"/getAnalyticsConfig",params:ee._getSdkProperties()});_.setFeatures({analytics:t})}catch{_.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!t?.length){re.featured=re.allFeatured,re.recommended=re.allRecommended;return}const e=p.getRequestedCaipNetworkIds().join(",");re.featured=re.allFeatured.filter(s=>s.chains?.some(n=>e.includes(n))),re.recommended=re.allRecommended.filter(s=>s.chains?.some(n=>e.includes(n))),re.filteredWallets=re.wallets.filter(s=>s.chains?.some(n=>e.includes(n)))},clearFilterByNamespaces(){re.filteredWallets=[]},setFilterByNamespace(t){if(!t){re.featured=re.allFeatured,re.recommended=re.allRecommended;return}const e=p.getRequestedCaipNetworkIds().join(",");re.featured=re.allFeatured.filter(s=>s.chains?.some(n=>e.includes(n))),re.recommended=re.allRecommended.filter(s=>s.chains?.some(n=>e.includes(n))),re.filteredWallets=re.wallets.filter(s=>s.chains?.some(n=>e.includes(n)))}},ve=Oe({view:"Connect",history:["Connect"],transactionStack:[]}),yf={state:ve,subscribeKey(t,e){return Xe(ve,t,e)},pushTransactionStack(t){ve.transactionStack.push(t)},popTransactionStack(t){const e=ve.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:n,onCancel:r}=e;switch(t){case"success":s?.();break;case"error":n?.(),te.goBack();break;case"cancel":r?.(),te.goBack();break}},push(t,e){t!==ve.view&&(ve.view=t,ve.history.push(t),ve.data=e)},reset(t,e){ve.view=t,ve.history=[t],ve.data=e},replace(t,e){ve.history.at(-1)===t||(ve.view=t,ve.history[ve.history.length-1]=t,ve.data=e)},goBack(){const t=p.state.activeCaipAddress,e=te.state.view==="ConnectingFarcaster",s=!t&&e;if(ve.history.length>1){ve.history.pop();const[n]=ve.history.slice(-1);n&&(t&&n==="Connect"?ve.view="Account":ve.view=n)}else he.close();ve.data?.wallet&&(ve.data.wallet=void 0),ve.data?.redirectView&&(ve.data.redirectView=void 0),setTimeout(()=>{if(s){p.setAccountProp("farcasterUrl",void 0,p.state.activeChain);const n=M.getAuthConnector();n?.provider?.reload();const r=Mr(_.state);n?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType})}},100)},goBackToIndex(t){if(ve.history.length>1){ve.history=ve.history.slice(0,t+1);const[e]=ve.history.slice(-1);e&&(ve.view=e)}},goBackOrCloseModal(){te.state.history.length>1?te.goBack():he.close()}},te=Bt(yf),us=Oe({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Zo={state:us,subscribe(t){return Je(us,()=>t(us))},setThemeMode(t){us.themeMode=t;try{const e=M.getAuthConnector();if(e){const s=Zo.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:Ri(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){us.themeVariables={...us.themeVariables,...t};try{const e=M.getAuthConnector();if(e){const s=Zo.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:Ri(us.themeVariables,us.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Mr(us)}},It=Bt(Zo),Xd=Object.fromEntries(Wd.map(t=>[t,void 0])),bf=Object.fromEntries(Wd.map(t=>[t,!0])),ye=Oe({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:Xd,filterByNamespaceMap:bf}),Cf={state:ye,subscribe(t){return Je(ye,()=>{t(ye)})},subscribeKey(t,e){return Xe(ye,t,e)},initialize(t){t.forEach(e=>{const s=U.getConnectedConnectorId(e);s&&M.setConnectorId(s,e)})},setActiveConnector(t){t&&(ye.activeConnector=Xn(t))},setConnectors(t){t.filter(r=>!ye.allConnectors.some(i=>i.id===r.id&&M.getConnectorName(i.name)===M.getConnectorName(r.name)&&i.chain===r.chain)).forEach(r=>{r.type!=="MULTI_CHAIN"&&ye.allConnectors.push(Xn(r))});const s=M.getEnabledNamespaces(),n=M.getEnabledConnectors(s);ye.connectors=M.mergeMultiChainConnectors(n)},filterByNamespaces(t){Object.keys(ye.filterByNamespaceMap).forEach(e=>{ye.filterByNamespaceMap[e]=!1}
vendor: 4,141 bytes, line 4
4),t.forEach(e=>{ye.filterByNamespaceMap[e]=!0}),M.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){ye.filterByNamespaceMap[t]=e,M.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=M.getEnabledNamespaces(),e=M.getEnabledConnectors(t),s=M.areAllNamespacesEnabled();ye.connectors=M.mergeMultiChainConnectors(e),s?ee.clearFilterByNamespaces():ee.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(ye.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return ye.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(ye.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=M.generateConnectorMapByName(t),s=[];return e.forEach(n=>{const r=n[0],i=r?.id===T.CONNECTOR_ID.AUTH;n.length>1&&r?s.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...n],type:i?"AUTH":"MULTI_CHAIN",chain:"eip155",id:r?.id||""}):r&&s.push(r)}),s},generateConnectorMapByName(t){const e=new Map;return t.forEach(s=>{const{name:n}=s,r=M.getConnectorName(n);if(!r)return;const i=e.get(r)||[];i.find(a=>a.chain===s.chain)||i.push(s),e.set(r,i)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(s=>{e.find(n=>n.chain===s.chain)||e.push(s)}),e},addConnector(t){if(t.id===T.CONNECTOR_ID.AUTH){const e=t,s=Mr(_.state),n=It.getSnapshot().themeMode,r=It.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,projectId:s.projectId,sdkType:s.sdkType}),e?.provider?.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:Ri(r,n)}),M.setConnectors([t])}else M.setConnectors([t])},getAuthConnector(t){const e=t||p.state.activeChain,s=ye.connectors.find(n=>n.id===T.CONNECTOR_ID.AUTH);if(s)return s?.connectors?.length?s.connectors.find(r=>r.chain===e):s},getAnnouncedConnectorRdns(){return ye.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>t.info?.rdns)},getConnectorById(t){return ye.allConnectors.find(e=>e.id===t)},getConnector({id:t,rdns:e,namespace:s}){const n=s||p.state.activeChain;return ye.allConnectors.filter(i=>i.chain===n).find(i=>i.explorerId===t||i.info?.rdns===e)},syncIfAuthConnector(t){if(t.id!=="ID_AUTH")return;const e=t,s=Mr(_.state),n=It.getSnapshot().themeMode,r=It.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:Ri(r,n)})},getConnectorsByNamespace(t){const e=ye.allConnectors.filter(s=>s.chain===t);return M.mergeMultiChainConnectors(e)},canSwitchToSmartAccount(t){return p.checkIfSmartAccountEnabled()&&Lt(t)===Es.ACCOUNT_TYPES.EOA},selectWalletConnector(t){const e=te.state.data?.redirectView,s=M.getConnector({id:t.id,rdns:t.rdns});sf.handleMobileDeeplinkRedirect(s?.explorerId||t.id,p.state.activeChain),s?te.push("ConnectingExternal",{connector:s,wallet:t,redirectView:e}):te.push("ConnectingWalletConnect",{wallet:t,redirectView:e})},getConnectors(t){return t?M.getConnectorsByNamespace(t):M.mergeMultiChainConnectors(ye.allConnectors)},setFilterByNamespace(t){ye.filterByNamespace=t,ye.connectors=M.getConnectors(t),ee.setFilterByNamespace(t)},setConnectorId(t,e){t&&(ye.activeConnectorIds={...ye.activeConnectorIds,[e]:t},U.setConnectedConnectorId(e,t))},removeConnectorId(t){ye.activeConnectorIds={...ye.activeConnectorIds,[t]:void 0},U.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return ye.activeConnectorIds[t]},isConnected(t){return t?!!ye.activeConnectorIds[t]:Object.values(ye.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){ye.activeConnectorIds={...Xd}}},M=Bt(Cf),Ef=1e3,ur={checkNamespaceConnectorId(t,e){return M.getConnectorId(t)===e},isSocialProvider(t){return me.DEFAULT_REMOTE_FEATURES.socials.includes(t)},connectWalletConnect({walletConnect:t,connector:e,closeModalOnConnect:s=!0,redirectViewOnModalClose:n="Connect",onOpen:r,onConnect:i}){return new Promise((o,a)=>{if(t&&M.setActiveConnector(e),r?.(J.isMobile()&&t),n){const l=he.subscribeKey("open",d=>
4{d||(te.state.view!==n&&te.replace(n),l(),a(new Error("Modal closed")))})}const c=p.subscribeKey("activeCaipAddress",l=>{l&&(i?.(),s&&he.close(),c(),o(it.parseCaipAddress(l)))})})},connectExternal(t){return new Promise((e,s)=>{const n=p.subscribeKey("activeCaipAddress",r=>{r&&(he.close(),n(),e(it.parseCaipAddress(r)))});V.connectExternal(t,t.chain).catch(()=>{n(),s(new Error("Connection rejected"))})})},connectSocial({social:t,namespace:e,closeModalOnConnect:s=!0,onOpenFarcaster:n,onConnect:r}){const i=p.getAccountData(e);let o=i?.socialWindow,a=i?.socialProvider,c=!1,l=null;const d=e||p.state.activeChain,u=p.subscribeKey("activeCaipAddress",h=>{h&&(s&&he.close(),u())});return new Promise((h,f)=>{async function g(w){if(w.data?.resultUri)if(w.origin===T.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",g,!1);try{const A=M.getAuthConnector(d);if(A&&!c){const C=p.getAccountData(d);o&&(o.close(),p.setAccountProp("socialWindow",void 0,d),o=C?.socialWindow),c=!0;const S=w.data.resultUri;if(a&&le.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:a}}),a){U.setConnectedSocialProvider(a),await V.connectExternal({id:A.id,type:A.type,socialUri:S},A.chain);const L=p.state.activeCaipAddress;if(!L){f(new Error("Failed to connect"));return}h(it.parseCaipAddress(L)),le.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:a}})}}}catch(A){a&&le.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:a,message:J.parseError(A)}}),f(new Error("Failed to connect"))}}else a&&le.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:a,message:"Untrusted Origin"}})}async function m(){if(t){const w=p.getAccountData(d);p.setAccountProp("socialProvider",t,d),a=w?.socialProvider,le.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:a}})}if(a==="farcaster"){n?.();const w=he.subscribeKey("open",C=>{!C&&t==="farcaster"&&(f(new Error("Popup closed")),r?.(),w())}),A=M.getAuthConnector();if(A&&!p.getAccountData(d)?.farcasterUrl)try{const{url:S}=await A.provider.getFarcasterUri();p.setAccountProp("farcasterUrl",S,d)}catch{f(new Error("Failed to connect to farcaster"))}}else{const w=M.getAuthConnector();l=J.returnOpenHref(`${T.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(w&&a){const{uri:A}=await w.provider.getSocialRedirectUri({provider:a});if(l&&A){p.setAccountProp("socialWindow",Xn(l),d),o=i?.socialWindow,l.location.href=A;const C=setInterval(()=>{o?.closed&&!c&&(f(new Error("Popup closed")),clearInterval(C))},1e3);window.addEventListener("message",g,!1)}else l?.close(),f(new Error("Failed to initiate social connection"))}}catch{f(new Error("Failed to initiate social connection")),l?.close()}}}m()})},connectEmail({closeModalOnConnect:t=!0,redirectViewOnModalClose:e="Connect",onOpen:s,onConnect:n}){return new Promise((r,i)=>{if(s?.(),e){const a=he.subscribeKey("open",c=>{c||(te.state.view!==e&&te.replace(e),a(),i(new Error("Modal closed")))})}const o=p.subscribeKey("activeCaipAddress",a=>{a&&(n?.(),t&&he.close(),o(),r(it.parseCaipAddress(a)))})})},async updateEmail(){const t=U.getConnectedConnectorId(p.state.activeChain),e=M.getAuthConnector();if(!e)throw new Error("No auth connector found");if(t!==T.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");const s=e.provider.getEmail()??"";return await he.open({view:"UpdateEmailWallet",data:{email:s,redirectView:void 0}}),new Promise((n,r)=>{const i=setInterval(()=>{const a=e.provider.getEmail()??"";a!==s&&(he.close(),clearInterval(i),o(),n({email:a}))},Ef),o=he.subscribeKey("open",a=>{a||(te.state.view!=="Connect"&&te.push("Connect"),clearInterval(i),o(),r(new Error("Modal closed")))})})},canSwitchToSmartAccount(t){return p.checkIfSmartAccountEnabled()&&Lt(t)===Es.ACCOUNT_TYPES.EOA}};function Zd(){const t=p.state.activeCaipNetwork?.chainNamespace||"eip155",e=p.state.activeCaipNetwork?.id||1,s=me.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`}function Lt(t){return p.getAccountData(t)?.preferredAccountType}function li(t){return p.state.activeCaipNetwork}const $i={getConnectionStatus(t,e){const s=M.state.activeConnectorIds[e],n=V.getConnections(e);return!!s&&t.connectorId===s?"connected":n.some(o=>o.connectorId.toLowerCase()===t.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:t,connectorId:e,addresses:s}){return t.map(n=>{if((e?n.connectorId.toLowerCase()===e.toLowerCase():!1)&&s){const i=n.accounts.filter(o=>!s.some(c=>c.toLowerCase()===o.address.toLowerCase()));return{...n,accounts:i}}return n})},excludeExistingConnections(t,e){const s=new Set(t);return e.filter(n=>!s.has(n.connectorId))},getConnectionsByConnectorId(t,e){return t.filter(s=>s.connectorId.toLowerCase()===e.toLowerCase())},getConnectionsData(t){const e=!!_.state.remoteFeatures?.multiWallet,s=M.state.activeConnectorIds[t],n=V.getConnections(t),i=(V.state.recentConnections.get(t)??[]).filter(a=>M.getConnectorById(a.connectorId)),o=$i.excludeExistingConnections([...n.map(a=>a.connectorId),...s?[s]:[]],i);return e?{connections:n,recentConnections:o}:{connections:n.filter(a=>a.connectorId.toLowerCase()===s?.toLowerCase()),recentConnections:[]}}},Pe=Oe({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),vf={state:Pe,subscribe(t){return Je(Pe,()=>t(Pe))},setLastNetworkInView(t){Pe.lastNetworkInView=t},async fetchTransactions(t){if(!t)throw new Error("Transactions can't be fetched without an accountAddress");Pe.loading=!0;try{const e=await se.fetchTransactions({account:t,cursor:Pe.next,chainId:p.state.activeCaipNetwork?.caipNetworkId}),s=Ai.filterSpamTransactions(e.data),n=Ai.filterByConnectedChain(s),r=[...Pe.transactions,...n];Pe.loading=!1,Pe.transactions=r,Pe.transactionsByYear=Ai.groupTransactionsByYearAndMonth(Pe.transactionsByYear,n),Pe.empty=r.length===0,Pe.next=e.next?e.next:void 0}catch{const s=p.state.activeChain;le.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:_.state.projectId,cursor:Pe.next,isSmartAccount:Lt(s)===Es.ACCOUNT_TYPES.SMART_ACCOUNT}}),rs.showError("Failed to fetch transactions"),Pe.loading=!1,Pe.empty=!0,Pe.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const s=t;return e.forEach(n=>{const r=new Date(n.metadata.minedAt).getFullYear(),i=new Date(n.metadata.minedAt).getMonth(),o=s[r]??{},c=(o[i]??[]).filter(l=>
4l.id!==n.id);s[r]={...o,[i]:[...c,n].sort((l,d)=>new Date(d.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),s},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(n=>n.nft_info?.flags.is_spam===!0))},filterByConnectedChain(t){const e=p.state.activeCaipNetwork?.caipNetworkId;return t.filter(n=>n.metadata.chain===e)},clearCursor(){Pe.next=void 0},resetTransactions(){Pe.transactions=[],Pe.transactionsByYear={},Pe.lastNetworkInView=void 0,Pe.loading=!1,Pe.empty=!1,Pe.next=void 0}},Ai=Bt(vf,"API_ERROR"),be=Oe({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,buffering:!1,status:"disconnected"});let en;const Af={state:be,subscribe(t){return Je(be,()=>t(be))},subscribeKey(t,e){return Xe(be,t,e)},_getClient(){return be._client},setClient(t){be._client=Xn(t)},initialize(t){const e=t.filter(s=>!!s.namespace).map(s=>s.namespace);V.syncStorageConnections(e)},syncStorageConnections(t){const e=U.getConnections(),s=t??Array.from(p.state.chains.keys());for(const n of s){const r=e[n]??[],i=new Map(be.recentConnections);i.set(n,r),be.recentConnections=i}},getConnections(t){return t?be.connections.get(t)??[]:[]},hasAnyConnection(t){const e=V.state.connections;return Array.from(e.values()).flatMap(s=>s).some(({connectorId:s})=>s===t)},async connectWalletConnect({cache:t="auto"}={}){const e=J.isTelegram()||J.isSafari()&&J.isIos();if(t==="always"||t==="auto"&&e){if(en){await en,en=void 0;return}if(!J.isPairingExpired(be?.wcPairingExpiry)){const s=be.wcUri;be.wcUri=s;return}en=V._getClient()?.connectWalletConnect?.().catch(()=>{}),V.state.status="connecting",await en,en=void 0,be.wcPairingExpiry=void 0,V.state.status="connected"}else await V._getClient()?.connectWalletConnect?.()},async connectExternal(t,e,s=!0){const n=await V._getClient()?.connectExternal?.(t);return s&&p.setActiveNamespace(e),n},async reconnectExternal(t){await V._getClient()?.reconnectExternal?.(t);const e=t.chain||p.state.activeChain;e&&M.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){if(!e)return;he.setLoading(!0,p.state.activeChain);const s=M.getAuthConnector();s&&(p.setAccountProp("preferredAccountType",t,e),await s.provider.setPreferredAccount(t),U.setPreferredAccountTypes(Object.entries(p.state.chains).reduce((n,[r,i])=>{const o=r,a=Lt(o);return a!==void 0&&(n[o]=a),n},{})),await V.reconnectExternal(s),he.setLoading(!1,p.state.activeChain),le.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:p.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(t){return V._getClient()?.signMessage(t)},parseUnits(t,e){return V._getClient()?.parseUnits(t,e)},formatUnits(t,e){return V._getClient()?.formatUnits(t,e)},updateBalance(t){return V._getClient()?.updateBalance(t)},async sendTransaction(t){return V._getClient()?.sendTransaction(t)},async getCapabilities(t){return V._getClient()?.getCapabilities(t)},async grantPermissions(t){return V._getClient()?.grantPermissions(t)},async walletGetAssets(t){return V._getClient()?.walletGetAssets(t)??{}},async estimateGas(t){return V._getClient()?.estimateGas(t)},async writeContract(t){return V._getClient()?.writeContract(t)},async getEnsAddress(t){return V._getClient()?.getEnsAddress(t)},async getEnsAvatar(t){return V._getClient()?.getEnsAvatar(t)},checkInstalled(t){return V._getClient()?.checkInstalled?.(t)||!1},resetWcConnection(){be.wcUri=void 0,be.wcPairingExpiry=void 0,be.wcLinking=void 0,be.recentWallet=void 0,be.status="disconnected",Ai.resetTransactions(),U.deleteWalletConnectDeepLink(),U.deleteRecentWallet()},resetUri(){be.wcUri=void 0,be.wcPairingExpiry=void 0,en=void 0},finalizeWcConnection(t){const{wcLinking:e,recentWallet:s}=V.state;e&&U.setWalletConnectDeepLink(e),s&&U.setAppKitRecent(s),t&&le.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:t,properties:{method:e?"mobile":"qrcode",name:te.state.data?.wallet?.name||"Unknown",view:te.state.view,walletRank:s?.order}})},setWcBasic(t){be.wcBasic=t},setUri(t){be.wcUri=t,be.wcPairingExpiry=J.getPairingExpiry()},setWcLinking(t){be.wcLinking=t},setWcError(t){be.wcError=t,be.buffering=!1},setRecentWallet(t){be.recentWallet=t},setBuffering(t){be.buffering=t},setStatus(t){be.status=t},setIsSwitchingConnection(t){be.isSwitchingConnection=t},async disconnect({id:t,namespace:e,initialDisconnect:s}={}){try{await V._getClient()?.disconnect({id:t,chainNamespace:e,initialDisconnect:s})}catch(n){throw new bn("Failed to disconnect","INTERNAL_SDK_ERROR",n)}},async disconnectConnector({id:t,namespace:e}){try{await V._getClient()?.disconnectConnector({id:t,namespace:e})}catch(s){throw new bn("Failed to disconnect connector","INTERNAL_SDK_ERROR",s)}},setConnections(t,e){const s=new Map(be.connections);s.set(e,t),be.connections=s},async handleAuthAccountSwitch({address:t,namespace:e}){const n=p.getAccountData(e)?.user?.accounts?.find(i=>i.type==="smartAccount"),r=n&&n.address.toLowerCase()===t.toLowerCase()&&ur.canSwitchToSmartAccount(e)?"smartAccount":"eoa";await V.setPreferredAccountType(r,e)},async handleActiveConnection({connection:t,namespace:e,address:s}
vendor: 16,115 bytes, line 4
4){const n=M.getConnectorById(t.connectorId),r=t.connectorId===T.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${t.connectorId}`);if(r)r&&s&&await V.handleAuthAccountSwitch({address:s,namespace:e});else return(await V.connectExternal({id:n.id,type:n.type,provider:n.provider,address:s,chain:e},e))?.address;return s},async handleDisconnectedConnection({connection:t,namespace:e,address:s,closeModalOnConnect:n}){const r=M.getConnectorById(t.connectorId),i=t.auth?.name?.toLowerCase(),o=t.connectorId===T.CONNECTOR_ID.AUTH,a=t.connectorId===T.CONNECTOR_ID.WALLET_CONNECT;if(!r)throw new Error(`No connector found for connection: ${t.connectorId}`);let c;if(o)if(i&&ur.isSocialProvider(i)){const{address:l}=await ur.connectSocial({social:i,closeModalOnConnect:n,onOpenFarcaster(){he.open({view:"ConnectingFarcaster"})},onConnect(){te.replace("ProfileWallets")}});c=l}else{const{address:l}=await ur.connectEmail({closeModalOnConnect:n,onOpen(){he.open({view:"EmailLogin"})},onConnect(){te.replace("ProfileWallets")}});c=l}else if(a){const{address:l}=await ur.connectWalletConnect({walletConnect:!0,connector:r,closeModalOnConnect:n,onOpen(d){const u=d?"AllWallets":"ConnectingWalletConnect";he.state.open?te.push(u):he.open({view:u})},onConnect(){te.replace("ProfileWallets")}});c=l}else{const l=await V.connectExternal({id:r.id,type:r.type,provider:r.provider,chain:e},e);l&&(c=l.address)}return o&&s&&await V.handleAuthAccountSwitch({address:s,namespace:e}),c},async switchConnection({connection:t,address:e,namespace:s,closeModalOnConnect:n,onChange:r}){let i;const o=p.getAccountData(s)?.caipAddress;if(o){const{address:c}=it.parseCaipAddress(o);i=c}const a=$i.getConnectionStatus(t,s);switch(a){case"connected":case"active":{const c=await V.handleActiveConnection({connection:t,namespace:s,address:e});if(i&&c){const l=c.toLowerCase()!==i.toLowerCase();r?.({address:c,namespace:s,hasSwitchedAccount:l,hasSwitchedWallet:a==="active"})}break}case"disconnected":{const c=await V.handleDisconnectedConnection({connection:t,namespace:s,address:e,closeModalOnConnect:n});c&&r?.({address:c,namespace:s,hasSwitchedAccount:!0,hasSwitchedWallet:!0});break}default:throw new Error(`Invalid connection status: ${a}`)}}},V=Bt(Af),fo={createBalance(t,e){const s={name:t.metadata.name||"",symbol:t.metadata.symbol||"",decimals:t.metadata.decimals||0,value:t.metadata.value||0,price:t.metadata.price||0,iconUrl:t.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:e,address:t.address==="native"?void 0:this.convertAddressToCAIP10Address(t.address,e),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:t.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance({hex:t,decimals:e}){return Bd(BigInt(t),e)},convertAddressToCAIP10Address(t,e){return`${e}:${t}`},createCAIP2ChainId(t,e){return`${e}:${parseInt(t,16)}`},getChainIdHexFromCAIP2ChainId(t){const e=t.split(":");if(e.length<2||!e[1])return"0x0";const s=e[1],n=parseInt(s,10);return isNaN(n)?"0x0":`0x${n.toString(16)}`},isWalletGetAssetsResponse(t){return typeof t!="object"||t===null?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(s=>this.isValidAsset(s)))},isValidAsset(t){return typeof t=="object"&&t!==null&&typeof t.address=="string"&&typeof t.balance=="string"&&(t.type==="ERC20"||t.type==="NATIVE")&&typeof t.metadata=="object"&&t.metadata!==null&&typeof t.metadata.name=="string"&&typeof t.metadata.symbol=="string"&&typeof t.metadata.decimals=="number"&&typeof t.metadata.price=="number"&&typeof t.metadata.iconUrl=="string"}};let go;async function _c(){if(!go){const{createPublicClient:t,http:e,defineChain:s}=await Ur(async()=>{const{createPublicClient:n,http:r,defineChain:i}=await import("./index-bCnuLLg1.js");return{createPublicClient:n,http:r,defineChain:i}},__vite__mapDeps([0,1,2,3,4,5,6]));go={createPublicClient:t,http:e,defineChain:s}}return go}const Qo={getBlockchainApiRpcUrl(t,e){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",t),s.searchParams.set("projectId",e),s.toString()},async getViemChain(t){const{defineChain:e}=await _c(),{chainId:s}=it.parseCaipNetworkId(t.caipNetworkId);return e({...t,id:Number(s)})},async createViemPublicClient(t){const{createPublicClient:e,http:s}=await _c(),n=_.state.projectId,r=await Qo.getViemChain(t);if(!r)throw new Error(`Chain ${t.caipNetworkId} not found in viem/chains`);return e({chain:r,transport:s(Qo.getBlockchainApiRpcUrl(t.caipNetworkId,n))})}},Wa={async getMyTokensWithBalance(t){const e=p.getAccountData()?.address,s=p.state.activeCaipNetwork,n=M.getConnectorId("eip155")===T.CONNECTOR_ID.AUTH;if(!e||!s)return[];const r=`${s.caipNetworkId}:${e}`,i=U.getBalanceCacheForCaipAddress(r);if(i)return i.balances;if(s.chainNamespace===T.CHAIN.EVM&&n){const a=await this.getEIP155Balances(e,s);if(a)return this.filterLowQualityTokens(a)}const o=await se.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(t,e){try{const s=fo.getChainIdHexFromCAIP2ChainId(e.caipNetworkId);if(!(await V.getCapabilities(t))?.[s]?.assetDiscovery?.supported)return null;const r=await V.walletGetAssets({account:t,chainFilter:[s]});if(!fo.isWalletGetAssetsResponse(r))return null;const o=(r[s]||[]).map(a=>fo.createBalance(a,e.caipNetworkId));return U.updateBalanceCache({caipAddress:`${e.caipNetworkId}:${t}`,balance:{balances:o},timestamp:Date.now()}),o}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:t,assetAddress:e,caipNetwork:s}){const n=await Qo.createViemPublicClient(s),{address:r}=it.parseCaipAddress(t),[{result:i},{result:o},{result:a},{result:c}]=await n.multicall({contracts:[{address:e,functionName:"name",args:[],abi:oi},{address:e,functionName:"symbol",args:[],abi:oi},{address:e,functionName:"balanceOf",args:[r],abi:oi},{address:e,functionName:"decimals",args:[],abi:oi}]});return{name:i,symbol:o,decimals:c,balance:a&&c?Bd(a,c):"0"}}},Pn=Oe({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),vs={state:Pn,subscribe(t){return Je(Pn,()=>t(Pn))},subscribeOpen(t){return Xe(Pn,"open",t)},set(t){Object.assign(Pn,{...Pn,...t})}},If={async getTokenList(t){return(await se.fetchSwapTokens({chainId:t}))?.tokens?.map(n=>({...n,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0}))||[]},async fetchGasPrice(){const t=p.state.activeCaipNetwork;if(!t)return null;try{switch(t.chainNamespace){case"solana":const e=(await V?.estimateGas({chainNamespace:"solana"}))?.toString();return{standard:e,fast:e,instant:e};case"eip155":default:return await se.fetchGasPrice({chainId:t.caipNetworkId})}}catch{return null}},async fetchSwapAllowance({tokenAddress:t,userAddress:e,sourceTokenAmount:s,sourceTokenDecimals:n}){const r=await se.fetchSwapAllowance({tokenAddress:t,userAddress:e});if(r?.allowance&&s&&n){const i=V.parseUnits(s,n)||0;return BigInt(r.allowance)>=i}return!1},async getMyTokensWithBalance(t){const e=await Wa.getMyTokensWithBalance(t);return p.setAccountProp("tokenBalance",e,p.state.activeChain),this.mapBalancesToSwapTokens(e)},mapBalancesToSwapTokens(t){return t?.map(e=>({...e,address:e?.address?e.address:Zd(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]},async handleSwapError(t){try{const e=t?.cause;return e?.json&&(await e.json())?.reasons?.[0]?.description?.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}},ge=Oe({tokenBalances:[],loading:!1}),Nf={state:ge,subscribe(t){return Je(ge,()=>t(ge))},subscribeKey(t,e){return Xe(ge,t,e)},setToken(t){t&&(ge.token=Xn(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},getSdkEventProperties(t){return{message:J.parseError(t),isSmartAccount:Lt(p.state.activeChain)===Es.ACCOUNT_TYPES.SMART_ACCOUNT,token:ge.token?.symbol||"",amount:ge.sendTokenAmount??0,network:p.state.activeCaipNetwork?.caipNetworkId||""}},async sendToken(){try{switch(ce.setLoading(!0),p.state.activeCaipNetwork?.chainNamespace){case"eip155":await ce.sendEvmToken();return;case"solana":await ce.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(t){throw zs.isUserRejectedRequestError(t)?new Kd(t):t}finally{ce.setLoading(!1)}},async sendEvmToken(){const t=p.state.activeChain;if(!t)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const e=Lt(t);if(!ce.state.sendTokenAmount||!ce.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!ce.state.token)throw new Error("A token is required");if(ce.state.token?.address){le.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Es.ACCOUNT_TYPES.SMART_ACCOUNT,token:ce.state.token.address,amount:ce.state.sendTokenAmount,network:p.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:s}=await ce.sendERC20Token({receiverAddress:ce.state.receiverAddress,tokenAddress:ce.state.token.address,sendTokenAmount:ce.state.sendTokenAmount,decimals:ce.state.token.quantity.decimals});s&&(ge.hash=s)}else{le.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Es.ACCOUNT_TYPES.SMART_ACCOUNT,token:ce.state.token.symbol||"",amount:ce.state.sendTokenAmount,network:p.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:s}=await ce.sendNativeToken({receiverAddress:ce.state.receiverAddress,sendTokenAmount:ce.state.sendTokenAmount,decimals:ce.state.token.quantity.decimals});s&&(ge.hash=s)}},async fetchTokenBalance(t){ge.loading=!0;const e=p.state.activeChain,s=p.state.activeCaipNetwork?.caipNetworkId,n=p.state.activeCaipNetwork?.chainNamespace,r=p.getAccountData(e)?.caipAddress??p.state.activeCaipAddress,i=r?J.getPlainAddress(r):void 0;if(ge.lastRetry&&!J.isAllowedRetry(ge.lastRetry,30*me.ONE_SEC_MS))return ge.loading=!1,[];try{if(i&&s&&n){const o=await Wa.getMyTokensWithBalance();return ge.tokenBalances=o,ge.lastRetry=void 0,o}}catch(o){ge.lastRetry=Date.now(),t?.(o),rs.showError("Token Balance Unavailable")}finally{ge.loading=!1}return[]},fetchNetworkBalance(){if(ge.tokenBalances.length===0)return;const t=If.mapBalancesToSwapTokens(ge.tokenBalances);if(!t)return;const e=t.find(s=>s.address===Zd());e&&(ge.networkBalanceInUSD=e?$p.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){te.pushTransactionStack({});const e=t.receiverAddress,s=p.getAccountData()?.address,n=V.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),i=await V.sendTransaction({chainNamespace:T.CHAIN.EVM,to:e,address:s,data:"0x",value:n??BigInt(0)});return le.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Lt("eip155")===Es.ACCOUNT_TYPES.SMART_ACCOUNT,token:ce.state.token?.symbol||"",amount:t.sendTokenAmount,network:p.state.activeCaipNetwork?.caipNetworkId||"",hash:i||""}}),V._getClient()?.updateBalance("eip155"),ce.resetSend(),{hash:i}},async sendERC20Token(t){te.pushTransactionStack({onSuccess(){te.replace("Account")}});const e=V.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),s=p.getAccountData()?.address;if(s&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const n=J.getPlainAddress(t.tokenAddress);if(!n)throw new Error("SendController:sendERC20Token - tokenAddress is required");const r=await V.writeContract({fromAddress:s,tokenAddress:n,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:Mp.getERC20Abi(n),chainNamespace:T.CHAIN.EVM});return le.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Lt("eip155")===Es.ACCOUNT_TYPES.SMART_ACCOUNT,token:ce.state.token?.symbol||"",amount:t.sendTokenAmount,network:p.state.activeCaipNetwork?.caipNetworkId||"",hash:r||""}}),ce.resetSend(),{hash:r}}return{hash:void 0}},async sendSolanaToken(){if(!ce.state.sendTokenAmount||!ce.state.receiverAddress)throw new Error("An amount and receiver address are required");te.pushTransactionStack({onSuccess(){te.replace("Account")}});let t;ce.state.token&&ce.state.token.address!==me.SOLANA_NATIVE_TOKEN_ADDRESS&&(J.isCaipAddress(ce.state.token.address)?t=J.getPlainAddress(ce.state.token.address):t=ce.state.token.address);const e=await V.sendTransaction({chainNamespace:"solana",tokenMint:t,to:ce.state.receiverAddress,value:ce.state.sendTokenAmount});e&&(ge.hash=e),V._getClient()?.updateBalance("solana"),ce.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=[]}},ce=Bt(Nf),mo={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},di={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},H=Oe({chains:Zp(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),Qd={state:H,subscribe(t){return Je(H,()=>{t(H)})},subscribeKey(t,e){return Xe(H,t,e)},subscribeAccountStateProp(t,e,s){const n=s||H.activeChain;return n?Xe(H.chains.get(n)?.accountState||{},t,e):()=>{}},subscribeChainProp(t,e,s){let n;return Je(H.chains,()=>{const r=s||H.activeChain;if(r){const i=H.chains.get(r)?.[t];n!==i&&(n=i,e(i))}})},initialize(t,e,s){const{chainId:n,namespace:r}=U.getActiveNetworkProps(),i=e?.find(d=>d.id.toString()===n?.toString()),a=t.find(d=>d?.namespace===r)||t?.[0],c=t.map(d=>d.namespace).filter(d=>d!==void 0),l=_.state.enableEmbedded?new Set([...c]):new Set([...e?.map(d=>d.chainNamespace)??[]]);(t?.length===0||!a)&&(H.noAdapters=!0),H.noAdapters||(H.activeChain=a?.namespace,H.activeCaipNetwork=i,p.setChainNetworkData(a?.namespace,{caipNetwork:i}),H.activeChain&&vs.set({activeChain:a?.namespace})),l.forEach(d=>{const u=e?.filter(g=>g.chainNamespace===d),h=U.getPreferredAccountTypes()||{},f={..._.state.defaultAccountTypes,...h};p.state.chains.set(d,{namespace:d,networkState:Oe({...di,caipNetwork:u?.[0]}),accountState:Oe({...mo,preferredAccountType:f[d]}),caipNetworks:u??[],...s}),p.setRequestedCaipNetworks(u??[],d)})},removeAdapter(t){if(H.activeChain===t){const e=Array.from(H.chains.entries()).find(([s])=>s!==t);if(e){const s=e[1]?.caipNetworks?.[0];s&&p.setActiveCaipNetwork(s)}}H.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:s},n){if(!t.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");H.chains.set(t.namespace,{namespace:t.namespace,networkState:{...di,caipNetwork:n[0]},accountState:{...mo},caipNetworks:n,connectionControllerClient:s,networkControllerClient:e}),p.setRequestedCaipNetworks(n?.filter(r=>r.chainNamespace===t.namespace)??[],t.namespace)},addNetwork(t){const e=H.chains.get(t.chainNamespace);if(e){const s=[...e.caipNetworks||[]];e.caipNetworks?.find(n=>n.id===t.id)||s.push(t),H.chains.set(t.chainNamespace,{...e,caipNetworks:s}),p.setRequestedCaipNetworks(s,t.chainNamespace),M.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){const s=H.chains.get(t);if(s){const n=H.activeCaipNetwork?.id===e,r=[...s.caipNetworks?.filter(i=>i.id!==e)||[]];n&&s?.caipNetworks?.[0]&&p.setActiveCaipNetwork(s.caipNetworks[0]),H.chains.set(t,{...s,caipNetworks:r}),p.setRequestedCaipNetworks(r||[],t),r.length===0&&M.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=H.chains.get(t);s&&(s.networkState={...s.networkState||di,...e},H.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const n=H.chains.get(t);if(n){const r={...n.accountState||mo,...e};H.chains.set(t,{...n,accountState:r}),(H.chains.size===1||H.activeChain===t)&&e.caipAddress&&(H.activeCaipAddress=e.caipAddress)}},setChainNetworkData(t,e){if(!t)return;const s=H.chains.get(t);if(s){const n={...s.networkState||di,...e};H.chains.set(t,{...s,networkState:n})}}
4,setAccountProp(t,e,s,n=!0){p.setChainAccountData(s,{[t]:e},n)},setActiveNamespace(t){H.activeChain=t;const e=t?H.chains.get(t):void 0,s=e?.networkState?.caipNetwork;s?.id&&t&&(H.activeCaipAddress=e?.accountState?.caipAddress,H.activeCaipNetwork=s,p.setChainNetworkData(t,{caipNetwork:s}),U.setActiveCaipNetworkId(s?.caipNetworkId),vs.set({activeChain:t,selectedNetworkId:s?.caipNetworkId}))},setActiveCaipNetwork(t){if(!t)return;const e=H.activeChain===t.chainNamespace;e||p.setIsSwitchingNamespace(!0);const s=H.chains.get(t.chainNamespace);H.activeChain=t.chainNamespace,H.activeCaipNetwork=t,p.setChainNetworkData(t.chainNamespace,{caipNetwork:t});let n=s?.accountState?.address;if(n)H.activeCaipAddress=`${t.chainNamespace}:${t.id}:${n}`;else if(e&&H.activeCaipAddress){const{address:i}=it.parseCaipAddress(H.activeCaipAddress);n=i,H.activeCaipAddress=`${t.caipNetworkId}:${n}`}else H.activeCaipAddress=void 0;p.setChainAccountData(t.chainNamespace,{address:n,caipAddress:H.activeCaipAddress}),ce.resetSend(),vs.set({activeChain:H.activeChain,selectedNetworkId:H.activeCaipNetwork?.caipNetworkId}),U.setActiveCaipNetworkId(t.caipNetworkId),!p.checkIfSupportedNetwork(t.chainNamespace)&&_.state.enableNetworkSwitch&&!_.state.allowUnsupportedChain&&!V.state.wcBasic&&p.showUnsupportedChainUI()},addCaipNetwork(t){if(!t)return;const e=H.chains.get(t.chainNamespace);e&&e?.caipNetworks?.push(t)},async switchActiveNamespace(t){if(!t)return;const e=t!==p.state.activeChain,s=p.getNetworkData(t)?.caipNetwork,n=p.getCaipNetworkByNamespace(t,s?.id);e&&n&&await p.switchActiveNetwork(n)},async switchActiveNetwork(t,{throwOnFailure:e=!1}={}){const s=p.state.activeChain;if(!s)throw new Error("ChainController:switchActiveNetwork - namespace is required");const r=!p.state.chains.get(s)?.caipNetworks?.some(o=>o.id===H.activeCaipNetwork?.id),i=p.getNetworkControllerClient(t.chainNamespace);if(i){try{await i.switchCaipNetwork(t),r&&he.close()}catch(o){if(e)throw o;te.goBack()}le.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})}},getNetworkControllerClient(t){const e=t||H.activeChain;if(!e)throw new Error("ChainController:getNetworkControllerClient - chain is required");const s=H.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||H.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=H.chains.get(e);if(!s?.connectionControllerClient)throw new Error("ConnectionController client not set");return s.connectionControllerClient},getNetworkProp(t,e){const s=H.chains.get(e)?.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=H.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:n=[]}=e?.networkState||{};return J.sortRequestedNetworks(s,n).filter(o=>o?.id)},getAllRequestedCaipNetworks(){const t=[];return H.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const s=p.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){p.setAdapterNetworkState(e,{requestedCaipNetworks:t});const n=p.getAllRequestedCaipNetworks().map(i=>i.chainNamespace),r=Array.from(new Set(n));M.filterByNamespaces(r)},getAllApprovedCaipNetworkIds(){const t=[];return H.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const s=p.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(t){return t?H.chains.get(t)?.networkState?.caipNetwork:H.activeCaipNetwork},getActiveCaipAddress(){return H.activeCaipAddress},getApprovedCaipNetworkIds(t){return H.chains.get(t)?.networkState?.approvedCaipNetworkIds||[]},async setApprovedCaipNetworksData(t){const s=await p.getNetworkControllerClient()?.getApprovedCaipNetworksData();p.setAdapterNetworkState(t,{approvedCaipNetworkIds:s?.approvedCaipNetworkIds,supportsAllNetworks:s?.supportsAllNetworks})},checkIfSupportedNetwork(t,e){const s=e||H.activeCaipNetwork?.caipNetworkId,n=p.getRequestedCaipNetworks(t);return n.length?n?.some(r=>r.caipNetworkId===s):!0},checkIfSupportedChainId(t){return H.activeChain?p.getRequestedCaipNetworks(H.activeChain)?.some(s=>s.id===t):!0},setSmartAccountEnabledNetworks(t,e){p.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){const t=qd.caipNetworkIdToNumber(H.activeCaipNetwork?.caipNetworkId),e=H.activeChain;return!e||!t?!1:!!p.getNetworkProp("smartAccountEnabledNetworks",e)?.includes(Number(t))},showUnsupportedChainUI(){he.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=H.activeCaipNetwork;return!!(t?.chainNamespace&&me.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){p.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(t){const e=t;if(!e)throw new Error("Chain is required to set account prop");const s=p.state.chains.get(e)?.accountState?.preferredAccountType,n=_.state.defaultAccountTypes[e];H.activeCaipAddress=void 0,p.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol
vendor: 4,375 bytes, line 4
4:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:n||s,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),M.removeConnectorId(e)},setIsSwitchingNamespace(t){H.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){const t=[];let e;if(H.chains.forEach(s=>{T.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===s.namespace)&&s.namespace&&t.push(s.namespace)}),t.length>0){const s=t[0];return e=s?H.chains.get(s)?.caipNetworks?.[0]:void 0,e}},getAccountData(t){const e=t||H.activeChain;if(e)return p.state.chains.get(e)?.accountState},getNetworkData(t){const e=t||H.activeChain;if(e)return p.state.chains.get(e)?.networkState},getCaipNetworkByNamespace(t,e){if(!t)return;const s=p.state.chains.get(t),n=s?.caipNetworks?.find(r=>r.id===e);return n||s?.networkState?.caipNetwork||s?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const t=M.state.filterByNamespace;return(t?[H.chains.get(t)]:Array.from(H.chains.values())).flatMap(s=>s?.caipNetworks||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?p.getRequestedCaipNetworks(t):p.getAllRequestedCaipNetworks()},getCaipNetworkById(t,e){return Qd.getCaipNetworks(e).find(s=>s.id.toString()===t.toString()||s.caipNetworkId.toString()===t.toString())},setLastConnectedSIWECaipNetwork(t){H.lastConnectedSIWECaipNetwork=t},getLastConnectedSIWECaipNetwork(){return H.lastConnectedSIWECaipNetwork},async fetchTokenBalance(t){const e=p.getAccountData();if(!e)return[];const s=p.state.activeCaipNetwork?.caipNetworkId,n=p.state.activeCaipNetwork?.chainNamespace,r=p.state.activeCaipAddress,i=r?J.getPlainAddress(r):void 0;if(p.setAccountProp("balanceLoading",!0,n),e.lastRetry&&!J.isAllowedRetry(e.lastRetry,30*me.ONE_SEC_MS))return p.setAccountProp("balanceLoading",!1,n),[];try{if(i&&s&&n){const o=await Wa.getMyTokensWithBalance();return p.setAccountProp("tokenBalance",o,n),p.setAccountProp("lastRetry",void 0,n),p.setAccountProp("balanceLoading",!1,n),o}}catch(o){p.setAccountProp("lastRetry",Date.now(),n),t?.(o),rs.showError("Token Balance Unavailable")}finally{p.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(t){const e=t.chainNamespace,s=!!p.getAccountData(e)?.caipAddress,n=p.getAllApprovedCaipNetworkIds(),r=p.getNetworkProp("supportsAllNetworks",e)!==!1,i=M.getConnectorId(e),o=M.getAuthConnector(),a=i===T.CONNECTOR_ID.AUTH&&o;return!s||r||a?!1:!n?.includes(t.caipNetworkId)}},p=Bt(Qd),_f={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const s=p.state.activeCaipNetwork,n=p.state.activeChain,r=te.state.data;if(t.id===s?.id)return;const o=!!p.getAccountData(n)?.address,a=!!p.getAccountData(t.chainNamespace)?.address,c=t.chainNamespace!==n,d=M.getConnectorId(n)===T.CONNECTOR_ID.AUTH,u=T.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(h=>h===t.chainNamespace);e||d&&u?te.push("SwitchNetwork",{...r,network:t}):o&&c&&!a?te.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):te.push("SwitchNetwork",{...r,network:t})}},ut=Oe({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),Sf={state:ut,subscribe(t){return Je(ut,()=>t(ut))},subscribeKey(t,e){return Xe(ut,t,e)},async open(t){const e=t?.namespace,s=p.state.activeChain,n=e&&e!==s,r=p.getAccountData(t?.namespace)?.caipAddress,i=p.state.noAdapters;if(V.state.wcBasic?ee.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await ee.prefetch(),M.setFilterByNamespace(t?.namespace),he.setLoading(!0,e),e&&n){const o=p.getNetworkData(e)?.caipNetwork||p.getRequestedCaipNetworks(e)[0];o&&(i?(await p.switchActiveNetwork(o),te.push("ConnectingWalletConnectBasic")):_f.onSwitchNetwork({network:o,ignoreSwitchConfirmation:!0}))}else _.state.manualWCControl||i&&!r?J.isMobile()?te.reset("AllWallets"):te.reset("ConnectingWalletConnectBasic"):t?.view?te.reset(t.view,t.data):r?te.reset("Account"):te.reset("Connect");ut.open=!0,vs.set({open:!0}),le.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!r}})},close(){const t=_.state.enableEmbedded,e=!!p.state.activeCaipAddress;ut.open&&le.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),ut.open=!1,te.reset("Connect"),he.clearLoading(),t?e?te.replace("Account"):te.push("Connect"):vs.set({open:!1}),V.resetUri()}
4,setLoading(t,e){e&&ut.loadingNamespaceMap.set(e,t),ut.loading=t,vs.set({loading:t})},clearLoading(){ut.loadingNamespaceMap.clear(),ut.loading=!1,vs.set({loading:!1})},shake(){ut.shake||(ut.shake=!0,setTimeout(()=>{ut.shake=!1},500))}},he=Bt(Sf),Ui={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0},ht=Oe({providers:{...Ui},providerIds:{...Ui}}),xe={state:ht,subscribeKey(t,e){return Xe(ht,t,e)},subscribe(t){return Je(ht,()=>{t(ht)})},subscribeProviders(t){return Je(ht.providers,()=>t(ht.providers))},setProvider(t,e){t&&e&&(ht.providers[t]=Xn(e))},getProvider(t){if(t)return ht.providers[t]},setProviderId(t,e){e&&(ht.providerIds[t]=e)},getProviderId(t){if(t)return ht.providerIds[t]},reset(){ht.providers={...Ui},ht.providerIds={...Ui}},resetChain(t){ht.providers[t]=void 0,ht.providerIds[t]=void 0}},kr={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"}]},ea={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},Tf={providers:Gd,selectedProvider:null,error:null,purchaseCurrency:kr,paymentCurrency:ea,purchaseCurrencies:[kr],paymentCurrencies:[],quotesLoading:!1},we=Oe(Tf),kf={state:we,subscribe(t){return Je(we,()=>t(we))},subscribeKey(t,e){return Xe(we,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=p.state.activeChain,s=e===T.CHAIN.SOLANA?"SOL":"USDC",n=e?p.state.chains.get(e)?.accountState?.address??"":"",r=new URL(t.url);r.searchParams.append("publicKey",Qp),r.searchParams.append("destinationCurrencyCode",s),r.searchParams.append("walletAddress",n),r.searchParams.append("externalCustomerId",_.state.projectId),we.selectedProvider={...t,url:r.toString()}}else we.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=Gd.filter(n=>e.includes(n.name));we.providers=s}else we.providers=[]},setPurchaseCurrency(t){we.purchaseCurrency=t},setPaymentCurrency(t){we.paymentCurrency=t},setPurchaseAmount(t){ta.state.purchaseAmount=t},setPaymentAmount(t){ta.state.paymentAmount=t},async getAvailableCurrencies(){const t=await se.getOnrampOptions();we.purchaseCurrencies=t.purchaseCurrencies,we.paymentCurrencies=t.paymentCurrencies,we.paymentCurrency=t.paymentCurrencies[0]||ea,we.purchaseCurrency=t.purchaseCurrencies[0]||kr,await ee.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await ee.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){we.quotesLoading=!0;try{const t=await se.getOnrampQuote({purchaseCurrency:we.purchaseCurrency,paymentCurrency:we.paymentCurrency,amount:we.paymentAmount?.toString()||"0",network:we.purchaseCurrency?.symbol});return we.quotesLoading=!1,we.purchaseAmount=Number(t?.purchaseAmount.amount),t}catch(t){return we.error=t.message,we.quotesLoading=!1,null}finally{we.quotesLoading=!1}},resetState(){we.selectedProvider=null,we.error=null,we.purchaseCurrency=kr,we.paymentCurrency=ea,we.purchaseCurrencies=[kr],we.paymentCurrencies=[],we.paymentAmount=void 0,we.purchaseAmount=void 0,we.quotesLoading=!1}},ta=Bt(kf),Ft=Oe({message:"",variant:"info",open:!1}),Of={state:Ft,subscribeKey(t,e){return Xe(Ft,t,e)},open(t,e){const{debug:s}=_.state,{code:n,displayMessage:r,debugMessage:i}=t;r&&s&&(Ft.message=r,Ft.variant=e,Ft.open=!0),i&&console.error(typeof i=="function"?i():i,n?{code:n}:void 0)},warn(t,e,s){Ft.open=!0,Ft.message=t,Ft.variant="warning",e&&console.warn(e,s)},close(){Ft.open=!1,Ft.message="",Ft.variant="info"}},vt=Bt(Of),Sc=2147483648,Pf={convertEVMChainIdToCoinType(t){if(t>=Sc)throw new Error("Invalid chainId");return(Sc|t)>>>0}},St=Oe({suggestions:[],loading:!1}),Rf={state:St,subscribe(t){return Je(St,()=>t(St))},subscribeKey(t,e){return Xe(St,t,e)},async resolveName(t){try{return await se.lookupEnsName(t)}catch(e){const s=e;throw new Error(s?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(t){try{return await se.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{St.loading=!0,St.suggestions=[];const e=await se.getEnsNameSuggestions(t);return St.suggestions=e.suggestions||[],St.suggestions}catch(e){const s=Or.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{St.loading=!1}},async getNamesForAddress(t){try{if(!p.state.activeCaipNetwork)return[];
4const s=U.getEnsFromCacheForAddress(t);if(s)return s;const n=await se.reverseLookupEnsName({address:t});return U.updateEnsCache({address:t,ens:n,timestamp:Date.now()}),n}catch(e){const s=Or.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){const e=p.state.activeCaipNetwork,s=p.getAccountData(e?.chainNamespace)?.address,n=M.getAuthConnector();if(!e)throw new Error("Network not found");if(!s||!n)throw new Error("Address or auth connector not found");St.loading=!0;try{const r=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});te.pushTransactionStack({onCancel(){te.replace("RegisterAccountName")}});const i=await V.signMessage(r);St.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=Pf.convertEVMChainIdToCoinType(Number(o));await se.registerEnsName({coinType:a,address:s,signature:i,message:r}),p.setAccountProp("profileName",t,e.chainNamespace),U.updateEnsCache({address:s,ens:[{name:t,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),te.replace("RegisterAccountNameSuccess")}catch(r){const i=Or.parseEnsApiError(r,`Error registering name ${t}`);throw te.replace("RegisterAccountName"),new Error(i)}finally{St.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){return t?.reasons?.[0]?.description||e}},Or=Bt(Rf),xf={asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"},$f={asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"};var wo,Tc;function Uf(){if(Tc)return wo;Tc=1;const t=lp();wo=r;const e=B().console||{},s={mapHttpRequest:g,mapHttpResponse:g,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:g,res:g,err:h};function n(b,R){return Array.isArray(b)?b.filter(function(N){return N!=="!stdSerializers.err"}):b===!0?Object.keys(R):!1}function r(b){b=b||{},b.browser=b.browser||{};const R=b.browser.transmit;if(R&&typeof R.send!="function")throw Error("pino: transmit option must have a send function");const $=b.browser.write||e;b.browser.write&&(b.browser.asObject=!0);const N=b.serializers||{},j=n(b.browser.serialize,N);let Y=b.browser.serialize;Array.isArray(b.browser.serialize)&&b.browser.serialize.indexOf("!stdSerializers.err")>-1&&(Y=!1);const P=["error","fatal","warn","info","debug","trace"];typeof $=="function"&&($.error=$.fatal=$.warn=$.info=$.debug=$.trace=$),b.enabled===!1&&(b.level="silent");const E=b.level||"info",y=Object.create($);y.log||(y.log=w),Object.defineProperty(y,"levelVal",{get:O}),Object.defineProperty(y,"level",{get:D,set:F});const v={transmit:R,serialize:j,asObject:b.browser.asObject,levels:P,timestamp:f(b)};y.levels=r.levels,y.level=E,y.setMaxListeners=y.getMaxListeners=y.emit=y.addListener=y.on=y.prependListener=y.once=y.prependOnceListener=y.removeListener=y.removeAllListeners=y.listeners=y.listenerCount=y.eventNames=y.write=y.flush=w,y.serializers=N,y._serialize=j,y._stdErrSerialize=Y,y.child=I,R&&(y._logEvent=u());function O(){return this.level==="silent"?1/0:this.levels.values[this.level]}function D(){return this._level}function F(k){if(k!=="silent"&&!this.levels.values[k])throw Error("unknown level "+k);this._level=k,i(v,y,"error","log"),i(v,y,"fatal","error"),i(v,y,"warn","error"),i(v,y,"info","log"),i(v,y,"debug","log"),i(v,y,"trace","log")}function I(k,K){if(!k)throw new Error("missing bindings for child Pino");K=K||{},j&&k.serializers&&(K.serializers=k.serializers);const z=K.serializers;if(j&&z){var ae=Object.assign({},N,z),oe=b.browser.serialize===!0?Object.keys(ae):j;delete k.serializers,c([k],oe,ae,this._stdErrSerialize)}function ne(ie){this._childLevel=(ie._childLevel|0)+1,this.error=l(ie,k,"error"),this.fatal=l(ie,k,"fatal"),this.warn=l(ie,k,"warn"),this.info=l(ie,k,"info"),this.debug=l(ie,k,"debug"),this.trace=l(ie,k,"trace"),ae&&(this.serializers=ae,this._serialize=oe),R&&(this._logEvent=u([].concat(ie._logEvent.bindings,k)))}return ne.prototype=this,new ne(this)}return y}r.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},r.stdSerializers=s,r.stdTimeFunctions=Object.assign({},{nullTime:A,epochTime:C,unixTime:S,isoTime:L});function i(b,R,$,N){const j=Object.getPrototypeOf(R);R[$]=R.levelVal>
4R.levels.values[$]?w:j[$]?j[$]:e[$]||e[N]||w,o(b,R,$)}function o(b,R,$){!b.transmit&&R[$]===w||(R[$]=(function(N){return function(){const Y=b.timestamp(),P=new Array(arguments.length),E=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var y=0;y<P.length;y++)P[y]=arguments[y];if(b.serialize&&!b.asObject&&c(P,this._serialize,this.serializers,this._stdErrSerialize),b.asObject?N.call(E,a(this,$,P,Y)):N.apply(E,P),b.transmit){const v=b.transmit.level||R.level,O=r.levels.values[v],D=r.levels.values[$];if(D<O)return;d(this,{ts:Y,methodLevel:$,methodValue:D,transmitValue:r.levels.values[b.transmit.level||R.level],send:b.transmit.send,val:R.levelVal},P)}}})(R[$]))}function a(b,R,$,N){b._serialize&&c($,b._serialize,b.serializers,b._stdErrSerialize);const j=$.slice();let Y=j[0];const P={};N&&(P.time=N),P.level=r.levels.values[R];let E=(b._childLevel|0)+1;if(E<1&&(E=1),Y!==null&&typeof Y=="object"){for(;E--&&typeof j[0]=="object";)Object.assign(P,j.shift());Y=j.length?t(j.shift(),j):void 0}else typeof Y=="string"&&(Y=t(j.shift(),j));return Y!==void 0&&(P.msg=Y),P}function c(b,R,$,N){for(const j in b)if(N&&b[j]instanceof Error)b[j]=r.stdSerializers.err(b[j]);else if(typeof b[j]=="object"&&!Array.isArray(b[j]))for(const Y in b[j])R&&R.indexOf(Y)>-1&&Y in $&&(b[j][Y]=$[Y](b[j][Y]))}function l(b,R,$){return function(){const N=new Array(1+arguments.length);N[0]=R;for(var j=1;j<N.length;j++)N[j]=arguments[j-1];return b[$].apply(this,N)}}function d(b,R,$){const N=R.send,j=R.ts,Y=R.methodLevel,P=R.methodValue,E=R.val,y=b._logEvent.bindings;c($,b._serialize||Object.keys(b.serializers),b.serializers,b._stdErrSerialize===void 0?!0:b._stdErrSerialize),b._logEvent.ts=j,b._logEvent.messages=$.filter(function(v){return y.indexOf(v)===-1}),b._logEvent.level.label=Y,b._logEvent.level.value=P,N(Y,b._logEvent,E),b._logEvent=u(y)}function u(b){return{ts:0,messages:[],bindings:b||[],level:{label:"",value:0}}}function h(b){const R={type:b.constructor.name,msg:b.message,stack:b.stack};for(const $ in b)R[$]===void 0&&(R[$]=b[$]);return R}function f(b){return typeof b.timestamp=="function"?b.timestamp:b.timestamp===!1?A:C}function g(){return{}}function m(b){return b}function w(){}function A(){return!1}function C(){return Date.now()}function S(){return Math.round(Date.now()/1e3)}function L(){return new Date(Date.now()).toISOString()}function B(){function b(R){return typeof R<"u"&&R}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return b(self)||b(window)||b(this)||{}}}return wo}var Bn=Uf();const Jr=dp(Bn),Df={level:"info"},Xr="custom_context",Ha=1e3*1024;let Lf=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},kc=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const s=new Lf(e);if(s.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${s.size}`);for(;this.size+s.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=s),this.tail=s):(this.head=s,this.tail=s),this.lengthInNodes++,this.sizeInBytes+=s.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let s=this.head;for(;s!==null;)e.push(s.value),s=s.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const s=e.value;return e=e.next,{done:!1,value:s}}}}},eu=class{constructor(e,s=Ha){this.level=e??"error",this.levelValue=Bn.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=s,this.logs=new kc(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,s){s===Bn.levels.values.error?console.error(e):s===Bn.levels.values.warn?console.warn(e):s===Bn.levels.values.debug?console.debug(e):s===Bn.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(zo({timestamp:new Date().toISOString(),log:e}));const s=typeof e=="string"?JSON.parse(e).level:e.level;s>=this.levelValue&&this.forwardToConsole(e,s)}getLogs(){return this.logs}clearLogs(){this.logs=new kc(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const s=this.getLogArray();return s.push(zo({extraMetadata:e})),new Blob(s,{type:"application/json"})}},Mf=class{constructor(e,s=Ha){this.baseChunkLogger=new eu(e,s)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const s=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=s,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}},Bf=class{constructor(e,s=Ha){this.baseChunkLogger=new eu(e,s)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var jf=Object.defineProperty,Ff=Object.defineProperties,qf=Object.getOwnPropertyDescriptors,Oc=Object.getOwnPropertySymbols,Wf=Object.prototype.hasOwnProperty,Hf=Object.prototype.propertyIsEnumerable,Pc=(t,e,s)=>e in t?jf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Di=(t,e)=>{for(var s in e||(e={}))Wf.call(e,s)&&Pc(t,s,e[s]);if(Oc)for(var s of Oc(e))Hf.call(e,s)&&Pc(t,s,e[s]);return t},Li=(t,e)=>Ff(t,qf(e));function Zr(t){return Li(Di({},t),{level:t?.level||Df.level})}function Vf(t,e=Xr){return t[e]||""}function Kf(t,e,s=Xr){return t[s]=e,t}function bt(t,e=Xr){let s="";return typeof t.bindings>"u"?s=Vf(t,e):s=t.bindings().context||"",s}function zf(t,e,s=Xr){const n=bt(t,s);return n.trim()?`${n}/${e}`:e}function ct(t,e,s=Xr){const n=zf(t,e,s),r=t.child({context:n});return Kf(r,n,s)}function Gf(t){var e,s;const n=new Mf((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Jr(Li(Di({},t.opts),{level:"trace",browser:Li(Di({},(s=t.opts)==null?void 0:s.browser),{write:r=>n.write(r)})}
4)),chunkLoggerController:n}}function Yf(t){var e;const s=new Bf((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Jr(Li(Di({},t.opts),{level:"trace"}),s),chunkLoggerController:s}}function tu(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Gf(t):Yf(t)}var Jf=Object.defineProperty,Xf=(t,e,s)=>e in t?Jf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Rc=(t,e,s)=>Xf(t,typeof e!="symbol"?e+"":e,s);let Zf=class extends sr{constructor(e){super(),this.opts=e,Rc(this,"protocol","wc"),Rc(this,"version",2)}};var Qf=Object.defineProperty,eg=(t,e,s)=>e in t?Qf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,tg=(t,e,s)=>eg(t,e+"",s);let sg=class extends sr{constructor(e,s){super(),this.core=e,this.logger=s,tg(this,"records",new Map)}},ng=class{constructor(e,s){this.logger=e,this.core=s}},rg=class extends sr{constructor(e,s){super(),this.relayer=e,this.logger=s}},ig=class extends sr{constructor(e){super()}},og=class{constructor(e,s,n,r){this.core=e,this.logger=s,this.name=n}},ag=class extends sr{constructor(e,s){super(),this.relayer=e,this.logger=s}},cg=class extends sr{constructor(e,s){super(),this.core=e,this.logger=s}},lg=class{constructor(e,s,n){this.core=e,this.logger=s,this.store=n}},dg=class{constructor(e,s){this.projectId=e,this.logger=s}},ug=class{constructor(e,s,n){this.core=e,this.logger=s,this.telemetryEnabled=n}};var hg=Object.defineProperty,pg=(t,e,s)=>e in t?hg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xc=(t,e,s)=>pg(t,typeof e!="symbol"?e+"":e,s);let fg=class{constructor(e){this.opts=e,xc(this,"protocol","wc"),xc(this,"version",2)}},gg=class{constructor(e){this.client=e}};function Br(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function sa(t){return Br(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const su="2.36.0";let yo={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${su}`};class Cn extends Error{constructor(e,s={}
4){const n=s.cause instanceof Cn?s.cause.details:s.cause?.message?s.cause.message:s.details,r=s.cause instanceof Cn&&s.cause.docsPath||s.docsPath,i=yo.getDocsUrl?.({...s,docsPath:r}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...yo.version?[`Version: ${yo.version}`]:[]].join(` 5`);super(o,s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=r,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=su}walk(e){return nu(this,e)}}function nu(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?nu(t.cause,e):e?null:t}class ru extends Cn{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}}function ir(t,{dir:e,size:s=32}={}){return typeof t=="string"?mg(t,{dir:e,size:s}):wg(t,{dir:e,size:s})}function mg(t,{dir:e,size:s=32}={}){if(s===null)return t;const n=t.replace("0x","");if(n.length>s*2)throw new ru({size:Math.ceil(n.length/2),targetSize:s,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function wg(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new ru({size:t.length,targetSize:s,type:"bytes"});const n=new Uint8Array(s);for(let r=0;r<s;r++){const i=e==="right";n[i?r:s-r-1]=t[i?r:t.length-r-1]}return n}class yg extends Cn{constructor({max:e,min:s,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${r*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${s} to ${e})`:`(above ${s})`}`,{name:"IntegerOutOfRangeError"})}}class bg extends Cn{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function or(t,{size:e}){if(sa(t)>e)throw new bg({givenSize:sa(t),maxSize:e})}function na(t,e={}){const{signed:s}=e;e.size&&or(t,{size:e.size});const n=BigInt(t);if(!s)return n;const r=(t.length-2)/2,i=(1n<<BigInt(r)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function Cg(t,e={}){return Number(na(t,e))}const Eg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ra(t,e={}){return typeof t=="number"||typeof t=="bigint"?ou(t,e):typeof t=="string"?Ig(t,e):typeof t=="boolean"?vg(t,e):iu(t,e)}function vg(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(or(s,{size:e.size}),ir(s,{size:e.size})):s}function iu(t,e={}){let s="";for(let r=0;r<t.length;r++)s+=Eg[t[r]];const n=`0x${s}`;return typeof e.size=="number"?(or(n,{size:e.size}),ir(n,{dir:"right",size:e.size})):n}function ou(t,e={}){const{signed:s,size:n}=e,r=BigInt(t);let i;n?s?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&s?-i-1n:0;if(i&&r>i||r<o){const c=typeof t=="bigint"?"n":"";throw new yg({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:s,size:n,value:`${t}${c}`})}const a=`0x${(s&&r<0?(1n<<BigInt(n*8))+BigInt(r):r).toString(16)}`;return n?ir(a,{size:n}):a}const Ag=new TextEncoder;function Ig(t,e={}){const s=Ag.encode(t);return iu(s,e)}const Ng=new TextEncoder;function _g(t,e={}){return typeof t=="number"||typeof t=="bigint"?Tg(t,e):typeof t=="boolean"?Sg(t,e):Br(t)?au(t,e):cu(t,e)}function Sg(t,e={}){const s=new Uint8Array(1);return s[0]=Number(t),typeof e.size=="number"?(or(s,{size:e.size}),ir(s,{size:e.size})):s}const hs={zero:48,nine:57,A:65,F:70,a:97,f:102};function $c(t){if(t>=hs.zero&&t<=hs.nine)return t-hs.zero;if(t>=hs.A&&t<=hs.F)return t-(hs.A-10);if(t>=hs.a&&t<=hs.f)return t-(hs.a-10)}function au(t,e={}){let s=t;e.size&&(or(s,{size:e.size}),s=ir(s,{dir:"right",size:e.size}));let n=s.slice(2);n.length%2&&(n=`0${n}`);const r=n.length/2,i=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=$c(n.charCodeAt(a++)),l=$c(n.charCodeAt(a++));if(c===void 0||l===void 0)throw new Cn(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+l}return i}function Tg(t,e){const s=ou(t,e);return au(s)}function cu(t,e={}){const s=Ng.encode(t);return typeof e.size=="number"?(or(s,{size:e.size}),ir(s,{dir:"right",size:e.size})):s}function lu(t,e){const s=e||"hex",n=up(Br(t,{strict:!1})?_g(t):t);return s==="bytes"?n:ra(n)}class kg extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const s=super.get(e);return super.has(e)&&s!==void 0&&(this.delete(e),super.set(e,s)),s}set(e,s){if(super.set(e,s),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const bo=new kg(8192);function Og(t,e){if(bo.has(`${t}.${e}`))return bo.get(`${t}.${e}`);const s=t.substring(2).toLowerCase(),n=lu(cu(s),"bytes"),r=s.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(n[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const i=`0x${r.join("")}`;return bo.set(`${t}.${e}`,i),i}function Pg(t){const e=lu(`0x${t.substring(4)}`).substring(26);return Og(`0x${e}`)}async function Rg({hash:t,signature:e}){const s=Br(t)?t:ra(t),{secp256k1:n}=await Ur(async()=>{const{secp256k1:o}=await import("./secp256k1-Dyn9Y2cF.js");return{secp256k1:o}},__vite__mapDeps([7,1,2]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:d,v:u,yParity:h}=e,f=Number(h??u),g=Uc(f);return new n.Signature(na(l),na(d)).addRecoveryBit(g)}const o=Br(e)?e:ra(e);if(sa(o)!==65)throw new Error("invalid signature length");const a=Cg(`0x${o.slice(130)}`),c=Uc(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(s.substring(2)).toHex(!1)}`}function Uc(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 xg({hash:t,signature:e}){return Pg(await Rg({hash:t,signature:e}))}var $g={};const Ug=":";function Is(t){const[e,s]=t.split(Ug);return{namespace:e,reference:s}}function du(t,e){return t.includes(":")?[t]:e.chains||[]}var Dg=Object.defineProperty,Lg=Object.defineProperties,Mg=Object.getOwnPropertyDescriptors,Dc=Object.getOwnPropertySymbols,Bg=Object.prototype.hasOwnProperty,jg=Object.prototype.propertyIsEnumerable,ia=(t,e,s)=>e in t?Dg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Lc=(t,e)=>{for(var s in e||(e={}))Bg.call(e,s)&&ia(t,s,e[s]);if(Dc)for(var s of Dc(e))jg.call(e,s)&&ia(t,s,e[s]);return t},Fg=(t,e)=>Lg(t,Mg(e)),Mc=(t,e,s)=>ia(t,typeof e!="symbol"?e+"":e,s);const qg="ReactNative",_t={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Wg="js";function Mi(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Xs(){return!Ss.getDocument()&&!!Ss.getNavigator()&&navigator.product===qg}function Hg(){return Xs()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function Vg(){return Xs()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function ar(){return!Mi()&&!!Ss.getNavigator()&&!!Ss.getDocument()}
vendor: 17,582 bytes, line 5
5function Qr(){return Xs()?_t.reactNative:Mi()?_t.node:ar()?_t.browser:_t.unknown}function Bc(){var t;try{return Xs()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Kg(t,e){const s=new URLSearchParams(t);return Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!=null&&s.set(n,String(r))}),s.toString()}function zg(t){var e,s;const n=uu();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(r=>r!=="")),Fg(Lc(Lc({},n),t),{url:t?.url||n.url,name:t?.name||n.name,description:t?.description||n.description,icons:(s=t?.icons)!=null&&s.length&&t.icons.length>0?t.icons:n.icons})}catch(r){return console.warn("Error populating app metadata",r),t||n}}function uu(){return hp.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Gg(){if(Qr()===_t.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:s,Version:n}=global.Platform;return[s,n].join("-")}const t=fp();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 Yg(){var t;const e=Qr();return e===_t.browser?[e,((t=Ss.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function hu(t,e,s){const n=Gg(),r=Yg();return[[t,e].join("-"),[Wg,s].join("-"),n,r].join("/")}function Jg({protocol:t,version:e,relayUrl:s,sdkVersion:n,auth:r,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d=hu(t,e,n),u={auth:r,ua:d,projectId:i,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=Kg(l[1]||"",u);return l[0]+"?"+h}function hn(t,e){return t.filter(s=>e.includes(s)).length===t.length}function oa(t){return Object.fromEntries(t.entries())}function aa(t){return new Map(Object.entries(t))}function an(t=W.FIVE_MINUTES,e){const s=W.toMiliseconds(t||W.FIVE_MINUTES);let n,r,i,o;return{resolve:a=>{i&&n&&(clearTimeout(i),n(a),o=Promise.resolve(a))},reject:a=>{i&&r&&(clearTimeout(i),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);i=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),n=a,r=c})}}function is(t,e,s){return new Promise(async(n,r)=>{const i=setTimeout(()=>r(new Error(s)),e);try{const o=await t;n(o)}catch(o){r(o)}clearTimeout(i)})}function pu(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 Xg(t){return pu("topic",t)}function Zg(t){return pu("id",t)}function fu(t){const[e,s]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")n.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))n.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return n}function Me(t,e){return W.fromMiliseconds(Date.now()+W.toMiliseconds(t))}function ss(t){return Date.now()>=W.toMiliseconds(t)}function Ae(t,e){return`${t}${e?`:${e}`:""}`}function cs(t=[],e=[]){return[...new Set([...t,...e])]}async function Qg({id:t,topic:e,wcDeepLink:s}){var n;try{if(!s)return;const r=typeof s=="string"?JSON.parse(s):s,i=r?.href;if(typeof i!="string")return;const o=em(i,t,e),a=Qr();if(a===_t.browser){if(!((n=Ss.getDocument())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}tm(o)}else a===_t.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(r){console.error(r)}}function em(t,e,s){const n=`requestId=${e}&sessionTopic=${s}`;t.endsWith("/")&&(t=t.slice(0,-1));let r=`${t}`;if(t.startsWith("https://t.me")){const i=t.includes("?")?"&startapp=":"?startapp=";r=`${r}${i}${im(n,!0)}`}else r=`${r}/wc?${n}`;return r}function tm(t){let e="_self";rm()?e="_top":(nm()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function sm(t,e){let s="";try{if(ar()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(n){console.error(n)}return s}function jc(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),n=s.indexOf(e);return s[n+2]}function Fc(){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 Va(){return typeof process<"u"&&$g.IS_VITEST==="true"}function nm(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function rm(){try{return window.self!==window.top}catch{return!1}}function im(t,e=!1){const s=Buffer.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function gu(t){return Buffer.from(t,"base64").toString("utf-8")}function om(t){return new Promise(e=>setTimeout(e,t))}let am=class{constructor({limit:e}){Mc(this,"limit"),Mc(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const s=this.set.values().next().value;s&&this.set.delete(s)}this.set.add(e)}}has(e){return this.set.has(e)}};const ui=BigInt(2**32-1),qc=BigInt(32);function mu(t,e=!1){return e?{h:Number(t&ui),l:Number(t>>qc&ui)}:{h:Number(t>>qc&ui)|0,l:Number(t&ui)|0}}function wu(t,e=!1){const s=t.length;let n=new Uint32Array(s),r=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=mu(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const Wc=(t,e,s)=>t>>>s,Hc=(t,e,s)=>t<<32-s|e>>>s,js=(t,e,s)=>t>>>s|e<<32-s,Fs=(t,e,s)=>t<<32-s|e>>>s,Ar=(t,e,s)=>t<<64-s|e>>>s-32,Ir=(t,e,s)=>t>>>s-32|e<<64-s,cm=(t,e)=>e,lm=(t,e)=>t,dm=(t,e,s)=>t<<s|e>>>32-s,um=(t,e,s)=>e<<s|t>>>32-s,hm=(t,e,s)=>e<<s-32|t>>>64-s,pm=(t,e,s)=>t<<s-32|e>>>64-s;function Ht(t,e,s,n){const r=(e>>>0)+(n>>>0);return{h:t+s+(r/2**32|0)|0,l:r|0}}const Ka=(t,e,s)=>(t>>>0)+(e>>>0)+(s>>>0),za=(t,e,s,n)=>e+s+n+(t/2**32|0)|0,fm=(t,e,s,n)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0),gm=(t,e,s,n,r)=>e+s+n+r+(t/2**32|0)|0,mm=(t,e,s,n,r)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0)+(r>>>0),wm=(t,e,s,n,r,i)=>e+s+n+r+i+(t/2**32|0)|0,Rn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Xi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ts(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Yt(t,...e){if(!Xi(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 Zi(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ts(t.outputLen),Ts(t.blockLen)}function Js(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 Ga(t,e){Yt(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function jr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Mt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Co(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Jt(t,e){return t<<32-e|t>>>e}const yu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function bu(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const gs=yu?t=>t:t=>bu(t);function ym(t){for(let e=0;e<t.length;e++)t[e]=bu(t[e]);return t}const qs=yu?t=>t:ym,Cu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",bm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Kn(t){if(Yt(t),Cu)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=bm[t[s]];return e}const ps={_0:48,_9:57,A:65,F:70,a:97,f:102};function Vc(t){if(t>=ps._0&&t<=ps._9)return t-ps._0;if(t>=ps.A&&t<=ps.F)return t-(ps.A-10);if(t>=ps.a&&t<=ps.f)return t-(ps.a-10)}function Bi(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Cu)return Uint8Array.fromHex(t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=Vc(t.charCodeAt(i)),a=Vc(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[r]=o*16+a}return n}function Eu(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function zt(t){return typeof t=="string"&&(t=Eu(t)),Yt(t),t}function Ws(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];Yt(r),e+=r.length}const s=new Uint8Array(e);for(let n=0,r=0;n<t.length;n++){const i=t[n];s.set(i,r),r+=i.length}return s}class Qi{}function ei(t){const e=n=>t().update(zt(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function Cm(t){const e=(n,r)=>t(r).update(zt(n)).digest(),s=t({});return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}function Tn(t=32){if(Rn&&typeof Rn.getRandomValues=="function")return Rn.getRandomValues(new Uint8Array(t));if(Rn&&typeof Rn.randomBytes=="function")return Uint8Array.from(Rn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Em=BigInt(0),hr=BigInt(1),vm=BigInt(2),Am=BigInt(7),Im=BigInt(256),Nm=BigInt(113),vu=[],Au=[],Iu=[];for(let t=0,e=hr,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],vu.push(2*(5*n+s)),Au.push((t+1)*(t+2)/2%64);let r=Em;for(let i=0;i<7;i++)e=(e<<hr^(e>>Am)*Nm)%Im,e&vm&&(r^=hr<<(hr<<BigInt(i))-hr);Iu.push(r)}const Nu=wu(Iu,!0),_m=Nu[0],Sm=Nu[1],Kc=(t,e,s)=>s>32?hm(t,e,s):dm(t,e,s),zc=(t,e,s)=>s>32?pm(t,e,s):um(t,e,s);function Tm(t,e=24){const s=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],d=s[c+1],u=Kc(l,d,1)^s[a],h=zc(l,d,1)^s[a+1];for(let f=0;f<50;f+=10)t[o+f]^=u,t[o+f+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=Au[o],c=Kc(r,i,a),l=zc(r,i,a),d=vu[o];r=t[d],i=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=_m[n],t[1]^=Sm[n]}Mt(s)}let km=class _u extends Qi{constructor(e,s,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=s,this.outputLen=n,this.enableXOF=r,this.rounds=i,Ts(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=jr(this.state)}clone(){return this._cloneInto()}keccak(){qs(this.state32),Tm(this.state32,this.rounds),qs(this.state32),this.posOut=0,this.pos=0}update(e){Js(this),e=zt(e),Yt(e);const{blockLen:s,state:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:n,blockLen:r}=this;e[n]^=s,(s&128)!==0&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Js(this,!1),Yt(e),this.finish();const s=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(s.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ts(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ga(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,Mt(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new _u(s,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Om=(t,e,s)=>ei(()=>new km(e,t,s)),Pm=Om(1,136,256/8);function Rm(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function xm(t,e,s){return t&e^~t&s}function $m(t,e,s){return t&e^t&s^e&s}let Su=class extends Qi{constructor(e,s,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=s,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Co(this.buffer)}update(e){Js(this),e=zt(e),Yt(e);const{view:s,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(r-this.pos,i-o);if(a===r){const c=Co(e);for(;r<=i-o;o+=r)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Js(this),Ga(e,this),this.finished=!0;const{buffer:s,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,Mt(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)s[u]=0;Rm(n,r-8,BigInt(this.length*8),i),this.process(n,0);const a=Co(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=a,r%s&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const xs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Qe=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),et=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Um=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$s=new Uint32Array(64);class Dm extends Su{constructor(e=32){super(64,e,8,!1),this.A=xs[0]|0,this.B=xs[1]|0,this.C=xs[2]|0,this.D=xs[3]|0,this.E=xs[4]|0,this.F=xs[5]|0,this.G=xs[6]|0,this.H=xs[7]|0}get(){const{A:e,B:s,C:n,D:r,E:i,F:o,G:a,H:c}=this;return[e,s,n,r,i,o,a,c]}set(e,s,n,r,i,o,a,c){this.A=e|0,this.B=s|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let u=0;u<16;u++,s+=4)$s[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const h=$s[u-15],f=$s[u-2],g=Jt(h,7)^Jt(h,18)^h>>>3,m=Jt(f,17)^Jt(f,19)^f>>>10;$s[u]=m+$s[u-7]+g+$s[u-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=Jt(a,6)^Jt(a,11)^Jt(a,25),f=d+h+xm(a,c,l)+Um[u]+$s[u]|0,g=(Jt(n,2)^Jt(n,13)^Jt(n,22))+$m(n,r,i)|0;d=l,l=c,c=a,a=o+f|0,o=i,i=r,r=n,n=f+g|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,r,i,o,a,c,l,d)}roundClean(){Mt($s)}destroy(){this.set(0,0,0,0,0,0,0,0),Mt(this.buffer)}}const Tu=wu(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e3585
55771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Lm=Tu[0],Mm=Tu[1],Us=new Uint32Array(80),Ds=new Uint32Array(80);let Ya=class extends Su{constructor(e=64){super(128,e,16,!1),this.Ah=et[0]|0,this.Al=et[1]|0,this.Bh=et[2]|0,this.Bl=et[3]|0,this.Ch=et[4]|0,this.Cl=et[5]|0,this.Dh=et[6]|0,this.Dl=et[7]|0,this.Eh=et[8]|0,this.El=et[9]|0,this.Fh=et[10]|0,this.Fl=et[11]|0,this.Gh=et[12]|0,this.Gl=et[13]|0,this.Hh=et[14]|0,this.Hl=et[15]|0}get(){const{Ah:e,Al:s,Bh:n,Bl:r,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:h,Gh:f,Gl:g,Hh:m,Hl:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,f,g,m,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,f,g,m,w){this.Ah=e|0,this.Al=s|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=h|0,this.Gh=f|0,this.Gl=g|0,this.Hh=m|0,this.Hl=w|0}process(e,s){for(let S=0;S<16;S++,s+=4)Us[S]=e.getUint32(s),Ds[S]=e.getUint32(s+=4);for(let S=16;S<80;S++){const L=Us[S-15]|0,B=Ds[S-15]|0,b=js(L,B,1)^js(L,B,8)^Wc(L,B,7),R=Fs(L,B,1)^Fs(L,B,8)^Hc(L,B,7),$=Us[S-2]|0,N=Ds[S-2]|0,j=js($,N,19)^Ar($,N,61)^Wc($,N,6),Y=Fs($,N,19)^Ir($,N,61)^Hc($,N,6),P=fm(R,Y,Ds[S-7],Ds[S-16]),E=gm(P,b,j,Us[S-7],Us[S-16]);Us[S]=E|0,Ds[S]=P|0}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:h,Fh:f,Fl:g,Gh:m,Gl:w,Hh:A,Hl:C}=this;for(let S=0;S<80;S++){const L=js(u,h,14)^js(u,h,18)^Ar(u,h,41),B=Fs(u,h,14)^Fs(u,h,18)^Ir(u,h,41),b=u&f^~u&m,R=h&g^~h&w,$=mm(C,B,R,Mm[S],Ds[S]),N=wm($,A,L,b,Lm[S],Us[S]),j=$|0,Y=js(n,r,28)^Ar(n,r,34)^Ar(n,r,39),P=Fs(n,r,28)^Ir(n,r,34)^Ir(n,r,39),E=n&i^n&a^i&a,y=r&o^r&c^o&c;A=m|0,C=w|0,m=f|0,w=g|0,f=u|0,g=h|0,{h:u,l:h}=Ht(l|0,d|0,N|0,j|0),l=a|0,d=c|0,a=i|0,c=o|0,i=n|0,o=r|0;const v=Ka(j,P,y);n=za(v,N,Y,E),r=v|0}({h:n,l:r}=Ht(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:o}=Ht(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Ht(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Ht(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:h}=Ht(this.Eh|0,this.El|0,u|0,h|0),{h:f,l:g}=Ht(this.Fh|0,this.Fl|0,f|0,g|0),{h:m,l:w}=Ht(this.Gh|0,this.Gl|0,m|0,w|0),{h:A,l:C}=Ht(this.Hh|0,this.Hl|0,A|0,C|0),this.set(n,r,i,o,a,c,l,d,u,h,f,g,m,w,A,C)}roundClean(){Mt(Us,Ds)}destroy(){Mt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class Bm extends Ya{constructor(){super(48),this.Ah=Qe[0]|0,this.Al=Qe[1]|0,this.Bh=Qe[2]|0,this.Bl=Qe[3]|0,this.Ch=Qe[4]|0,this.Cl=Qe[5]|0,this.Dh=Qe[6]|0,this.Dl=Qe[7]|0,this.Eh=Qe[8]|0,this.El=Qe[9]|0,this.Fh=Qe[10]|0,this.Fl=Qe[11]|0,this.Gh=Qe[12]|0,this.Gl=Qe[13]|0,this.Hh=Qe[14]|0,this.Hl=Qe[15]|0}}const tt=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class jm extends Ya{constructor(){super(32),this.Ah=tt[0]|0,this.Al=tt[1]|0,this.Bh=tt[2]|0,this.Bl=tt[3]|0,this.Ch=tt[4]|0,this.Cl=tt[5]|0,this.Dh=tt[6]|0,this.Dl=tt[7]|0,this.Eh=tt[8]|0,this.El=tt[9]|0,this.Fh=tt[10]|0,this.Fl=tt[11]|0,this.Gh=tt[12]|0,this.Gl=tt[13]|0,this.Hh=tt[14]|0,this.Hl=tt[15]|0}}const eo=ei(()=>new Dm),Fm=ei(()=>new Ya),qm=ei(()=>new Bm),Wm=ei(()=>new jm),Hm=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Fe=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),G=new Uint32Array(32);function Ls(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=G[2*t],l=G[2*t+1],d=G[2*e],u=G[2*e+1],h=G[2*s],f=G[2*s+1],g=G[2*n],m=G[2*n+1],w=Ka(c,d,o);l=za(w,l,u,a),c=w|0,{Dh:m,Dl:g}={Dh:m^l,Dl:g^c},{Dh:m,Dl:g}={Dh:cm(m,g),Dl:lm(m)},{h:f,l:h}=Ht(f,h,m,g),{Bh:u,Bl:d}={Bh:u^f,Bl:d^h},{Bh:u,Bl:d}={Bh:js(u,d,24),Bl:Fs(u,d,24)}
vendor: 66,720 bytes, lines 5-8
5,G[2*t]=c,G[2*t+1]=l,G[2*e]=d,G[2*e+1]=u,G[2*s]=h,G[2*s+1]=f,G[2*n]=g,G[2*n+1]=m}function Ms(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=G[2*t],l=G[2*t+1],d=G[2*e],u=G[2*e+1],h=G[2*s],f=G[2*s+1],g=G[2*n],m=G[2*n+1],w=Ka(c,d,o);l=za(w,l,u,a),c=w|0,{Dh:m,Dl:g}={Dh:m^l,Dl:g^c},{Dh:m,Dl:g}={Dh:js(m,g,16),Dl:Fs(m,g,16)},{h:f,l:h}=Ht(f,h,m,g),{Bh:u,Bl:d}={Bh:u^f,Bl:d^h},{Bh:u,Bl:d}={Bh:Ar(u,d,63),Bl:Ir(u,d,63)},G[2*t]=c,G[2*t+1]=l,G[2*e]=d,G[2*e+1]=u,G[2*s]=h,G[2*s+1]=f,G[2*n]=g,G[2*n+1]=m}function Vm(t,e={},s,n,r){if(Ts(s),t<0||t>s)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.length>s))throw new Error("key length must be undefined or 1.."+s);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==r)throw new Error("personalization must be undefined or "+r)}class Km extends Qi{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Ts(e),Ts(s),this.blockLen=e,this.outputLen=s,this.buffer=new Uint8Array(e),this.buffer32=jr(this.buffer)}update(e){Js(this),e=zt(e),Yt(e);const{blockLen:s,buffer:n,buffer32:r}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===s&&(qs(r),this.compress(r,0,!1),qs(r),this.pos=0);const l=Math.min(s-this.pos,i-c),d=o+c;if(l===s&&!(d%4)&&c+l<i){const u=new Uint32Array(a,d,Math.floor((i-c)/4));qs(u);for(let h=0;c+s<i;h+=r.length,c+=s)this.length+=s,this.compress(u,h,!1);qs(u);continue}n.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){Js(this),Ga(e,this);const{pos:s,buffer32:n}=this;this.finished=!0,Mt(this.buffer.subarray(s)),qs(n),this.compress(n,0,!0),qs(n);const r=jr(e);this.get().forEach((i,o)=>r[o]=gs(i))}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){const{buffer:s,length:n,finished:r,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(s),e.destroyed=i,e.finished=r,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class zm extends Km{constructor(e={}){const s=e.dkLen===void 0?64:e.dkLen;super(128,s),this.v0l=Fe[0]|0,this.v0h=Fe[1]|0,this.v1l=Fe[2]|0,this.v1h=Fe[3]|0,this.v2l=Fe[4]|0,this.v2h=Fe[5]|0,this.v3l=Fe[6]|0,this.v3h=Fe[7]|0,this.v4l=Fe[8]|0,this.v4h=Fe[9]|0,this.v5l=Fe[10]|0,this.v5h=Fe[11]|0,this.v6l=Fe[12]|0,this.v6h=Fe[13]|0,this.v7l=Fe[14]|0,this.v7h=Fe[15]|0,Vm(s,e,64,16,16);let{key:n,personalization:r,salt:i}=e,o=0;if(n!==void 0&&(n=zt(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=zt(i);const a=jr(i);this.v4l^=gs(a[0]),this.v4h^=gs(a[1]),this.v5l^=gs(a[2]),this.v5h^=gs(a[3])}if(r!==void 0){r=zt(r);const a=jr(r);this.v6l^=gs(a[0]),this.v6h^=gs(a[1]),this.v7l^=gs(a[2]),this.v7h^=gs(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:s,v1l:n,v1h:r,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:d,v5l:u,v5h:h,v6l:f,v6h:g,v7l:m,v7h:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,f,g,m,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,f,g,m,w){this.v0l=e|0,this.v0h=s|0,this.v1l=n|0,this.v1h=r|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=d|0,this.v5l=u|0,this.v5h=h|0,this.v6l=f|0,this.v6h=g|0,this.v7l=m|0,this.v7h=w|0}compress(e,s,n){this.get().forEach((c,l)=>G[l]=c),G.set(Fe,16);let{h:r,l:i}=mu(BigInt(this.length));G[24]=Fe[8]^i,G[25]=Fe[9]^r,n&&(G[28]=~G[28],G[29]=~G[29]);let o=0;const a=Hm;for(let c=0;c<12;c++)Ls(0,4,8,12,e,s+2*a[o++]),Ms(0,4,8,12,e,s+2*a[o++]),Ls(1,5,9,13,e,s+2*a[o++]),Ms(1,5,9,13,e,s+2*a[o++]),Ls(2,6,10,14,e,s+2*a[o++]),Ms(2,6,10,14,e,s+2*a[o++]),Ls(3,7,11,15,e,s+2*a[o++]),Ms(3,7,11,15,e,s+2*a[o++]),Ls(0,5,10,15,e,s+2*a[o++]),Ms(0,5,10,15,e,s+2*a[o++]),Ls(1,6,11,12,e,s+2*a[o++]),Ms(1,6,11,12,e,s+2*a[o++]),Ls(2,7,8,13,e,s+2*a[o++]),Ms(2,7,8,13,e,s+2*a[o++]),Ls(3,4,9,14,e,s+2*a[o++]),Ms(3,4,9,14,e,s+2*a[o++]);this.v0l^=G[0]^G[16],this.v0h^=G[1]^G[17],this.v1l^=G[2]^G[18],this.v1h^=G[3]^G[19],this.v2l^=G[4]^G[20],this.v2h^=G[5]^G[21],this.v3l^=G[6]^G[22],this.v3h^=G[7]^G[23],this.v4l^=G[8]^G[24],this.v4h^=G[9]^G[25],this.v5l^=G[10]^G[26],this.v5h^=G[11]^G[27],this.v6l^=G[12]^G[28],this.v6h^=G[13]^G[29],this.v7l^=G[14]^G[30],this.v7h^=G[15]^G[31],Mt(G)}destroy(){this.destroyed=!0,Mt(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Gm=Cm(t=>new zm(t)),Ym="https://rpc.walletconnect.org/v1";function ku(t){const e=`�Ethereum Signed Message: 6${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Pm(s)).toString("hex")}async function Jm(t,e,s,n,r,i){switch(s.t){case"eip191":return await Xm(t,e,s.s);case"eip1271":return await Zm(t,e,s.s,n,r,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}async function Xm(t,e,s){return(await xg({hash:ku(e),signature:s})).toLowerCase()===t.toLowerCase()}async function Zm(t,e,s,n,r,i){const o=Is(n);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l=s.substring(2),d=(l.length/2).toString(16).padStart(64,"0"),u=(e.startsWith("0x")?e:ku(e)).substring(2),h=a+u+c+d+l,f=await fetch(`${i||Ym}/?chainId=${n}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Qm(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:g}=await f.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Qm(){return Date.now()+Math.floor(Math.random()*1e3)}function ew(t){const e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);const n=s[0];if(n===0)throw new Error("No signatures found");const r=1+n*64;if(s.length<r)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const i=Buffer.from(t,"base64").slice(1,65);return nr.encode(i)}function tw(t){const e=new Uint8Array(Buffer.from(t,"base64")),s=Array.from("TransactionData::").map(i=>i.charCodeAt(0)),n=new Uint8Array(s.length+e.length);n.set(s),n.set(e,s.length);const r=Gm(n,{dkLen:32});return nr.encode(r)}function Gc(t){const e=new Uint8Array(eo(sw(t)));return nr.encode(e)}function sw(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function Yc(t){const e=Buffer.from(t,"base64"),s=gp(e).txn;if(!s)throw new Error("Invalid signed transaction: missing 'txn' field");const n=mp(s),r=Buffer.from("TX"),i=Buffer.concat([r,Buffer.from(n)]),o=Wm(i);return wp.encode(o).replace(/=+$/,"")}function Eo(t){const e=[];let s=BigInt(t);for(;s>=BigInt(128);)e.push(Number(s&BigInt(127)|BigInt(128))),s>>=BigInt(7);return e.push(Number(s)),Buffer.from(e)}function nw(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),s=Buffer.from(t.signed.authInfoBytes,"base64"),n=Buffer.from(t.signature.signature,"base64"),r=[];r.push(Buffer.from([10])),r.push(Eo(e.length)),r.push(e),r.push(Buffer.from([18])),r.push(Eo(s.length)),r.push(s),r.push(Buffer.from([26])),r.push(Eo(n.length)),r.push(n);const i=Buffer.concat(r),o=eo(i);return Buffer.from(o).toString("hex").toUpperCase()}function rw(t){var e,s;const n=[];try{if(typeof t=="string")return n.push(t),n;if(typeof t!="object")return n;t!=null&&t.id&&n.push(t.id);const r=(s=(e=t?.capabilities)==null?void 0:e.caip345)==null?void 0:s.transactionHashes;r&&n.push(...r)}catch(r){console.warn("getWalletSendCallsHashes failed: ",r)}return n}var iw=Object.defineProperty,ow=Object.defineProperties,aw=Object.getOwnPropertyDescriptors,Jc=Object.getOwnPropertySymbols,cw=Object.prototype.hasOwnProperty,lw=Object.prototype.propertyIsEnumerable,Xc=(t,e,s)=>e in t?iw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,dw=(t,e)=>{for(var s in e||(e={}))cw.call(e,s)&&Xc(t,s,e[s]);if(Jc)for(var s of Jc(e))lw.call(e,s)&&Xc(t,s,e[s]);return t},uw=(t,e)=>ow(t,aw(e));const hw="did:pkh:",Ja=t=>t?.split(":"),pw=t=>{const e=t&&Ja(t);if(e)return t.includes(hw)?e[3]:e[1]},ca=t=>{const e=t&&Ja(t);if(e)return e[2]+":"+e[3]},ji=t=>{const e=t&&Ja(t);if(e)return e.pop()};async function Zc(t){const{cacao:e,projectId:s}=t,{s:n,p:r}=e,i=Ou(r,r.iss),o=ji(r.iss);return await Jm(o,i,n,ca(r.iss),s)}const Ou=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,n=ji(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=t.statement||void 0;const i=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${pw(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,f=t.resources?`Resources:${t.resources.map(m=>` 7- ${m}`).join("")}`:void 0,g=Ii(t.resources);if(g){const m=Fr(g);r=vw(r,m)}return[s,n,"",r,"",i,o,a,c,l,d,u,h,f].filter(m=>m!=null).join(` 8`)};function fw(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function gw(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function En(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(s=>{const n=t.att[s];if(Array.isArray(n))throw new Error(`Resource must be an object: ${s}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${s}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${s}`);Object.keys(n).forEach(r=>{const i=n[r];if(!Array.isArray(i))throw new Error(`Ability limits ${r} must be an array of objects, found: ${i}`);if(!i.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);i.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function mw(t,e,s,n={}){return s?.sort((r,i)=>r.localeCompare(i)),{att:{[t]:ww(e,s,n)}}}function ww(t,e,s={}){e=e?.sort((r,i)=>r.localeCompare(i));const n=e.map(r=>({[`${t}/${r}`]:[s]}));return Object.assign({},...n)}function Pu(t){return En(t),`urn:recap:${fw(t).replace(/=/g,"")}`}function Fr(t){const e=gw(t.replace("urn:recap:",""));return En(e),e}function yw(t,e,s){const n=mw(t,e,s);return Pu(n)}function bw(t){return t&&t.includes("urn:recap:")}function Cw(t,e){const s=Fr(t),n=Fr(e),r=Ew(s,n);return Pu(r)}function Ew(t,e){En(t),En(e);const s=Object.keys(t.att).concat(Object.keys(e.att)).sort((r,i)=>r.localeCompare(i)),n={att:{}};return s.forEach(r=>{var i,o;Object.keys(((i=t.att)==null?void 0:i[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;n.att[r]=uw(dw({},n.att[r]),{[a]:((c=t.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),n}function vw(t="",e){En(e);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(s))return t;const n=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,h)=>u.action.localeCompare(h.action));const l={};c.forEach(u=>{l[u.ability]||(l[u.ability]=[]),l[u.ability].push(u.action)});const d=Object.keys(l).map(u=>(r++,`(${r}) '${u}': '${l[u].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});const i=n.join(" "),o=`${s}${i}`;return`${t?t+" ":""}${o}`}function Qc(t){var e;const s=Fr(t);En(s);const n=(e=s.att)==null?void 0:e.eip155;return n?Object.keys(n).map(r=>r.split("/")[1]):[]}function el(t){const e=Fr(t);En(e);const s=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(r=>{var i;(i=r?.[0])!=null&&i.chains&&s.push(r[0].chains)})}),[...new Set(s.flat())]}function Ii(t){if(!t)return;const e=t?.[t.length-1];return bw(e)?e:void 0}function Ru(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function la(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function vo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function gt(t,...e){if(!Ru(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 tl(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 Aw(t,e){gt(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Gs(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Zn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Iw(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Nw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function _w(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function da(t){if(typeof t=="string")t=_w(t);else if(Ru(t))t=ua(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Sw(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Tw(t,e){if(t.length!==e.length)return!1;let s=0;for(let n=0;n<t.length;n++)s|=t[n]^e[n];return s===0}const kw=(t,e)=>{function s(n,...r){if(gt(n),!Nw)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?gt(l):gt(l,t.nonceLength)}const i=t.tagLength;i&&r[1]!==void 0&>(r[1]);const o=e(n,...r),a=(l,d)=>{if(d!==void 0){if(l!==2)throw new Error("cipher output not supported");gt(d)}};let c=!1;return{encrypt(l,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,gt(l),a(o.encrypt.length,d),o.encrypt(l,d)},decrypt(l,d){if(gt(l),i&&l.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return a(o.decrypt.length,d),o.decrypt(l,d)}}}return Object.assign(s,t),s};function sl(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&&!Pw(e))throw new Error("invalid output, must be aligned");return e}function nl(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i);t.setUint32(e+4,o,n),t.setUint32(e+0,a,n)}function Ow(t,e,s){la(s);const n=new Uint8Array(16),r=Iw(n);return nl(r,0,BigInt(e),s),nl(r,8,BigInt(t),s),n}function Pw(t){return t.byteOffset%4===0}function ua(t){return Uint8Array.from(t)}const xu=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),Rw=xu("expand 16-byte k"),xw=xu("expand 32-byte k"),$w=Gs(Rw),Uw=Gs(xw);function Ce(t,e){return t<<e|t>>>32-e}function ha(t){return t.byteOffset%4===0}const hi=64,Dw=16,$u=2**32-1,rl=new Uint32Array;function Lw(t,e,s,n,r,i,o,a){const c=r.length,l=new Uint8Array(hi),d=Gs(l),u=ha(r)&&ha(i),h=u?Gs(r):rl,f=u?Gs(i):rl;for(let g=0;g<c;o++){if(t(e,s,n,d,o,a),o>=$u)throw new Error("arx: counter overflow");const m=Math.min(hi,c-g);if(u&&m===hi){const w=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let A=0,C;A<Dw;A++)C=w+A,f[C]=h[C]^d[A];g+=hi;continue}for(let w=0,A;w<m;w++)A=g+w,i[A]=r[A]^l[w];g+=m}}function Mw(t,e){const{allowShortKeys:s,extendNonceFn:n,counterLength:r,counterRight:i,rounds:o}=Sw({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return vo(r),vo(o),la(i),la(s),(a,c,l,d,u=0)=>{gt(a),gt(c),gt(l);const h=l.length;if(d===void 0&&(d=new Uint8Array(h)),gt(d),vo(u),u<0||u>=$u)throw new Error("arx: counter overflow");if(d.length<h)throw new Error(`arx: output (${d.length}) is shorter than data (${h})`);const f=[];let g=a.length,m,w;if(g===32)f.push(m=ua(a)),w=Uw;else if(g===16&&s)m=new Uint8Array(32),m.set(a),m.set(a,16),w=$w,f.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);ha(c)||f.push(c=ua(c));const A=Gs(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(w,A,Gs(c.subarray(0,16)),A),c=c.subarray(16)}const C=16-r;if(C!==c.length)throw new Error(`arx: nonce must be ${C} or 16 bytes`);if(C!==12){const L=new Uint8Array(12);L.set(c,i?0:12-c.length),c=L,f.push(c)}const S=Gs(c);return Lw(t,w,A,S,l,d,u,o),Zn(...f),d}}const Ve=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class Bw{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=da(e),gt(e,32);const s=Ve(e,0),n=Ve(e,2),r=Ve(e,4),i=Ve(e,6),o=Ve(e,8),a=Ve(e,10),c=Ve(e,12),l=Ve(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Ve(e,16+2*d)}process(e,s,n=!1){const r=n?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],d=o[3],u=o[4],h=o[5],f=o[6],g=o[7],m=o[8],w=o[9],A=Ve(e,s+0),C=Ve(e,s+2),S=Ve(e,s+4),L=Ve(e,s+6),B=Ve(e,s+8),b=Ve(e,s+10),R=Ve(e,s+12),$=Ve(e,s+14);let N=i[0]+(A&8191),j=i[1]+((A>>>13|C<<3)&8191),Y=i[2]+((C>>>10|S<<6)&8191),P=i[3]+((S>>>7|L<<9)&8191),E=i[4]+((L>>>4|B<<12)&8191),y=i[5]+(B>>>1&8191),v=i[6]+((B>>>14|b<<2)&8191),O=i[7]+((b>>>11|R<<5)&8191),D=i[8]+((R>>>8|$<<8)&8191),F=i[9]+($>>>5|r),I=0,k=I+N*a+j*(5*w)+Y*(5*m)+P*(5*g)+E*(5*f);I=k>>>13,k&=8191,k+=y*(5*h)+v*(5*u)+O*(5*d)+D*(5*l)+F*(5*c),I+=k>>>13,k&=8191;let K=I+N*c+j*a+Y*(5*w)+P*(5*m)+E*(5*g);I=K>>>13,K&=8191,K+=y*(5*f)+v*(5*h)+O*(5*u)+D*(5*d)+F*(5*l),I+=K>>>13,K&=8191;let z=I+N*l+j*c+Y*a+P*(5*w)+E*(5*m);I=z>>>13,z&=8191,z+=y*(5*g)+v*(5*f)+O*(5*h)+D*(5*u)+F*(5*d),I+=z>>>13,z&=8191;let ae=I+N*d+j*l+Y*c+P*a+E*(5*w);I=ae>>>13,ae&=8191,ae+=y*(5*m)+v*(5*g)+O*(5*f)+D*(5*h)+F*(5*u),I+=ae>>>13,ae&=8191;let oe=I+N*u+j*d+Y*l+P*c+E*a;I=oe>>>13,oe&=8191,oe+=y*(5*w)+v*(5*m)+O*(5*g)+D*(5*f)+F*(5*h),I+=oe>>>13,oe&=8191;let ne=I+N*h+j*u+Y*d+P*l+E*c;I=ne>>>13,ne&=8191,ne+=y*a+v*(5*w)+O*(5*m)+D*(5*g)+F*(5*f),I+=ne>>>13,ne&=8191;let ie=I+N*f+j*h+Y*u+P*d+E*l;I=ie>>>13,ie&=8191,ie+=y*c+v*a+O*(5*w)+D*(5*m)+F*(5*g),I+=ie>>>13,ie&=8191;let de=I+N*g+j*f+Y*h+P*u+E*d;I=de>>>13,de&=8191,de+=y*l+v*c+O*a+D*(5*w)+F*(5*m),I+=de>>>13,de&=8191;let Te=I+N*m+j*g+Y*f+P*h+E*u;I=Te>>>13,Te&=8191,Te+=y*d+v*l+O*c+D*a+F*(5*w),I+=Te>>>13,Te&=8191;let ue=I+N*w+j*m+Y*g+P*f+E*h;I=ue>>>13,ue&=8191,ue+=y*u+v*d+O*l+D*c+F*a,I+=ue>>>13,ue&=8191,I=(I<<2)+I|0,I=I+k|0,k=I&8191,I=I>>>13,K+=I,i[0]=k,i[1]=K,i[2]=z,i[3]=ae,i[4]=oe,i[5]=ne,i[6]=ie,i[7]=de,i[8]=Te,i[9]=ue}finalize(){const{h:e,pad:s}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+r,r=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(r^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+s[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+s[a]|0)+(o>>>16)|0,e[a]=o&65535;Zn(n)}update(e){tl(this),e=da(e),gt(e);const{buffer:s,blockLen:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(n-this.pos,r-i);if(o===n){for(;n<=r-i;i+=n)this.process(e,i);continue}s.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){Zn(this.h,this.r,this.buffer,this.pad)}digestInto(e){tl(this),Aw(e,this),this.finished=!0;const{buffer:s,h:n}=this;let{pos:r}=this;if(r){for(s[r++]=1;r<16;r++)s[r]=0;this.process(s,0,!0)}this.finalize();let i=0;for(let o=0;o<8;o++)e[i++]=n[o]>>>0,e[i++]=n[o]>>>8;return e}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}}function jw(t){const e=(n,r)=>t(r).update(da(n)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}const Fw=jw(t=>new Bw(t));function qw(t,e,s,n,r,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],h=e[2],f=e[3],g=e[4],m=e[5],w=e[6],A=e[7],C=r,S=s[0],L=s[1],B=s[2],b=o,R=a,$=c,N=l,j=d,Y=u,P=h,E=f,y=g,v=m,O=w,D=A,F=C,I=S,k=L,K=B;for(let ae=0;ae<i;ae+=2)b=b+j|0,F=Ce(F^b,16),y=y+F|0,j=Ce(j^y,12),b=b+j|0,F=Ce(F^b,8),y=y+F|0,j=Ce(j^y,7),R=R+Y|0,I=Ce(I^R,16),v=v+I|0,Y=Ce(Y^v,12),R=R+Y|0,I=Ce(I^R,8),v=v+I|0,Y=Ce(Y^v,7),$=$+P|0,k=Ce(k^$,16),O=O+k|0,P=Ce(P^O,12),$=$+P|0,k=Ce(k^$,8),O=O+k|0,P=Ce(P^O,7),N=N+E|0,K=Ce(K^N,16),D=D+K|0,E=Ce(E^D,12),N=N+E|0,K=Ce(K^N,8),D=D+K|0,E=Ce(E^D,7),b=b+Y|0,K=Ce(K^b,16),O=O+K|0,Y=Ce(Y^O,12),b=b+Y|0,K=Ce(K^b,8),O=O+K|0,Y=Ce(Y^O,7),R=R+P|0,F=Ce(F^R,16),D=D+F|0,P=Ce(P^D,12),R=R+P|0,F=Ce(F^R,8),D=D+F|0,P=Ce(P^D,7),$=$+E|0,I=Ce(I^$,16),y=y+I|0,E=Ce(E^y,12),$=$+E|0,I=Ce(I^$,8),y=y+I|0,E=Ce(E^y,7),N=N+j|0,k=Ce(k^N,16),v=v+k|0,j=Ce(j^v,12),N=N+j|0,k=Ce(k^N,8),v=v+k|0,j=Ce(j^v,7);let z=0;n[z++]=o+b|0,n[z++]=a+R|0,n[z++]=c+$|0,n[z++]=l+N|0,n[z++]=d+j|0,n[z++]=u+Y|0,n[z++]=h+P|0,n[z++]=f+E|0,n[z++]=g+y|0,n[z++]=m+v|0,n[z++]=w+O|0,n[z++]=A+D|0,n[z++]=C+F|0,n[z++]=S+I|0,n[z++]=L+k|0,n[z++]=B+K|0}const Ww=Mw(qw,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Hw=new Uint8Array(16),il=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(Hw.subarray(s))},Vw=new Uint8Array(32);function ol(t,e,s,n,r){const i=t(e,s,Vw),o=Fw.create(i);r&&il(o,r),il(o,n);const a=Ow(n.length,r?r.length:0,!0);o.update(a);const c=o.digest();return Zn(i,a),c}const Kw=t=>(e,s,n)=>({encrypt(r,i){const o=r.length;i=sl(o+16,i,!1),i.set(r);const a=i.subarray(0,-16);t(e,s,a,a,1);const c=ol(t,e,s,a,n);return i.set(c,o),Zn(c),i},decrypt(r,i){i=sl(r.length-16,i,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=ol(t,e,s,o,n);if(!Tw(a,c))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),t(e,s,i,i,1),Zn(c),i}}),Uu=kw({blockSize:64,nonceLength:12,tagLength:16},Kw(Ww));let Du=class extends Qi{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,Zi(e);const n=zt(s);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Mt(i)}update(e){return Js(this),this.iHash.update(e),this}digestInto(e){Js(this),Yt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const to=(t,e,s)=>new Du(t,e).update(s).digest();to.create=(t,e)=>new Du(t,e);function zw(t,e,s){return Zi(t),s===void 0&&(s=new Uint8Array(t.outputLen)),to(t,zt(s),zt(e))}const Ao=Uint8Array.from([0]),al=Uint8Array.of();function Gw(t,e,s,n=32){Zi(t),Ts(n);const r=t.outputLen;if(n>255*r)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/r);s===void 0&&(s=al);const o=new Uint8Array(i*r),a=to.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)Ao[0]=d+1,c.update(d===0?al:l).update(s).update(Ao).digestInto(l),o.set(l,r*d),a._cloneInto(c);return a.destroy(),c.destroy(),Mt(l,Ao),o.slice(0,n)}const Yw=(t,e,s,n,r)=>Gw(t,zw(t,e,s),n,r),so=eo,Xa=BigInt(0),pa=BigInt(1);function Fi(t,e=""){if(typeof t!="boolean"){const s=e&&`"${e}"`;throw new Error(s+"expected boolean, got type="+typeof t)}return t}function pn(t,e,s=""){const n=Xi(t),r=t?.length,i=e!==void 0;if(!n||i&&r!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=n?`length=${r}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function pi(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Lu(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Xa:BigInt("0x"+t)}function no(t){return Lu(Kn(t))}function qi(t){return Yt(t),Lu(Kn(Uint8Array.from(t).reverse()))}function Za(t,e){return Bi(t.toString(16).padStart(e*2,"0"))}function Qa(t,e){return Za(t,e).reverse()}function rt(t,e,s){let n;if(typeof e=="string")try{n=Bi(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(Xi(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const r=n.length;if(typeof s=="number"&&r!==s)throw new Error(t+" of length "+s+" expected, got "+r);return n}const Io=t=>typeof t=="bigint"&&Xa<=t;function Jw(t,e,s){return Io(t)&&Io(e)&&Io(s)&&e<=t&&t<s}function fa(t,e,s,n){if(!Jw(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function Mu(t){let e;for(e=0;t>Xa;t>>=pa,e+=1);return e}const ti=t=>(pa<<BigInt(t))-pa;function Xw(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),r=h=>Uint8Array.of(h);let i=n(t),o=n(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...h)=>s(o,i,...h),d=(h=n(0))=>{o=l(r(0),h),i=l(),h.length!==0&&(o=l(r(1),h),i=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<e;){i=l();const g=i.slice();f.push(g),h+=i.length}return Ws(...f)};return(h,f)=>{c(),d(h);let g;for(;!(g=f(u()));)d();return c(),g}}function ro(t,e,s={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(r,i,o){const a=t[r];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${r}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([r,i])=>n(r,i,!1)),Object.entries(s).forEach(([r,i])=>n(r,i,!0))}function cl(t){const e=new WeakMap;return(s,...n)=>{const r=e.get(s);if(r!==void 0)return r;const i=t(s,...n);return e.set(s,i),i}}const wt=BigInt(0),ot=BigInt(1),fn=BigInt(2),Bu=BigInt(3),ju=BigInt(4),Fu=BigInt(5),Zw=BigInt(7),qu=BigInt(8),Qw=BigInt(9),Wu=BigInt(16);function Nt(t,e){const s=t%e;return s>=wt?s:e+s}function Wt(t,e,s){let n=t;for(;e-- >wt;)n*=n,n%=s;return n}function ll(t,e){if(t===wt)throw new Error("invert: expected non-zero number");if(e<=wt)throw new Error("invert: expected positive modulus, got "+e);let s=Nt(t,e),n=e,r=wt,i=ot;for(;s!==wt;){const o=n/s,a=n%s,c=r-i*o;n=s,s=a,r=i,i=c}if(n!==ot)throw new Error("invert: does not exist");return Nt(r,e)}function ec(t,e,s){if(!t.eql(t.sqr(e),s))throw new Error("Cannot find square root")}function Hu(t,e){const s=(t.ORDER+ot)/ju,n=t.pow(e,s);return ec(t,n,e),n}function ey(t,e){const s=(t.ORDER-Fu)/qu,n=t.mul(e,fn),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,fn),r),a=t.mul(i,t.sub(o,t.ONE));return ec(t,a,e),a}function ty(t){const e=Zs(t),s=Vu(t),n=s(e,e.neg(e.ONE)),r=s(e,n),i=s(e,e.neg(n)),o=(t+Zw)/Wu;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,n);const u=a.mul(l,r),h=a.mul(l,i),f=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,f),d=a.cmov(h,u,g);const m=a.eql(a.sqr(d),c),w=a.cmov(l,d,m);return ec(a,w,c),w}}function Vu(t){if(t<Bu)throw new Error("sqrt is not defined for small field");let e=t-ot,s=0;for(;e%fn===wt;)e/=fn,s++;let n=fn;const r=Zs(t);for(;dl(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Hu;let i=r.pow(n,e);const o=(e+ot)/fn;return function(a,c){if(a.is0(c))return c;if(dl(a,c)!==1)throw new Error("Cannot find square root");let l=s,d=a.mul(a.ONE,i),u=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(u,a.ONE);){if(a.is0(u))return a.ZERO;let f=1,g=a.sqr(u);for(;!a.eql(g,a.ONE);)if(f++,g=a.sqr(g),f===l)throw new Error("Cannot find square root");const m=ot<<BigInt(l-f-1),w=a.pow(d,m);l=f,d=a.sqr(w),u=a.mul(u,d),h=a.mul(h,w)}return h}}function sy(t){return t%ju===Bu?Hu:t%qu===Fu?ey:t%Wu===Qw?ty(t):Vu(t)}const ny=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ry(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},s=ny.reduce((n,r)=>(n[r]="function",n),e);return ro(t,s),t}function iy(t,e,s){if(s<wt)throw new Error("invalid exponent, negatives unsupported");if(s===wt)return t.ONE;if(s===ot)return e;let n=t.ONE,r=e;for(;s>wt;)s&ot&&(n=t.mul(n,r)),r=t.sqr(r),s>>=ot;return n}function Ku(t,e,s=!1){const n=new Array(e.length).fill(s?t.ZERO:void 0),r=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(r);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function dl(t,e){const s=(t.ORDER-ot)/fn,n=t.pow(e,s),r=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function zu(t,e){e!==void 0&&Ts(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function Zs(t,e,s=!1,n={}){if(t<=wt)throw new Error("invalid field: expected ORDER > 0, got "+t);let r,i,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||s)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(r=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(s=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(r=e),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=zu(t,r);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:s,BITS:c,BYTES:l,MASK:ti(c),ZERO:wt,ONE:ot,allowedLengths:a,create:h=>Nt(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return wt<=h&&h<t},is0:h=>h===wt,isValidNot0:h=>!u.is0(h)&&u.isValid(h),isOdd:h=>(h&ot)===ot,neg:h=>Nt(-h,t),eql:(h,f)=>h===f,sqr:h=>Nt(h*h,t),add:(h,f)=>Nt(h+f,t),sub:(h,f)=>Nt(h-f,t),mul:(h,f)=>Nt(h*f,t),pow:(h,f)=>iy(u,h,f),div:(h,f)=>Nt(h*ll(f,t),t),sqrN:h=>h*h,addN:(h,f)=>h+f,subN:(h,f)=>h-f,mulN:(h,f)=>h*f,inv:h=>ll(h,t),sqrt:i||(h=>(d||(d=sy(t)),d(u,h))),toBytes:h=>s?Qa(h,l):Za(h,l),fromBytes:(h,f=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const m=new Uint8Array(l);m.set(h,s?0:m.length-h.length),h=m}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let g=s?qi(h):no(h);if(o&&(g=Nt(g,t)),!f&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>Ku(u,h),cmov:(h,f,g)=>g?f:h});return Object.freeze(u)}function Gu(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 Yu(t){const e=Gu(t);return e+Math.ceil(e/2)}function oy(t,e,s=!1){const n=t.length,r=Gu(e),i=Yu(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?qi(t):no(t),a=Nt(o,e-ot)+ot;return s?Qa(a,r):Za(a,r)}const Qn=BigInt(0),gn=BigInt(1);function Wi(t,e){const s=e.negate();return t?s:e}function No(t,e){const s=Ku(t.Fp,e.map(n=>n.Z));return e.map((n,r)=>t.fromAffine(n.toAffine(s[r])))}function Ju(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function _o(t,e){Ju(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=ti(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function ul(t,e,s){const{windowSize:n,mask:r,maxNumber:i,shiftBy:o}=s;let a=Number(t&r),c=t>>o;a>n&&(a-=i,c+=gn);const l=e*n,d=l+Math.abs(a)-1,u=a===0,h=a<0,f=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:f,offsetF:l}}function ay(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,n)=>{if(!(s instanceof e))throw new Error("invalid point at index "+n)})}function cy(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,n)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+n)})}const So=new WeakMap,Xu=new WeakMap;function To(t){return Xu.get(t)||1}function hl(t){if(t!==Qn)throw new Error("invalid wNAF")}class ly{constructor(e,s){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,n=this.ZERO){let r=e;for(;s>Qn;)s&gn&&(n=n.add(r)),r=r.double(),s>>=gn;return n}precomputeWindow(e,s){const{windows:n,windowSize:r}=_o(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<n;c++){a=o,i.push(a);for(let l=1;l<r;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=_o(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:h,offsetF:f}=ul(n,a,o);n=c,d?i=i.add(Wi(h,s[f])):r=r.add(Wi(u,s[l]))}return hl(n),{p:r,f:i}}wNAFUnsafe(e,s,n,r=this.ZERO){const i=_o(e,this.bits);for(let o=0;o<i.windows&&n!==Qn;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=ul(n,o,i);if(n=a,!l){const u=s[c];r=r.add(d?u.negate():u)}}return hl(n),r}getPrecomputes(e,s,n){let r=So.get(s);return r||(r=this.precomputeWindow(s,e),e!==1&&(typeof n=="function"&&(r=n(r)),So.set(s,r))),r}cached(e,s,n){const r=To(e);return this.wNAF(r,this.getPrecomputes(r,e,n),s)}unsafe(e,s,n,r){const i=To(e);return i===1?this._unsafeLadder(e,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),s,r)}createCache(e,s){Ju(s,this.bits),Xu.set(e,s),So.delete(e)}hasCache(e){return To(e)!==1}}function dy(t,e,s,n){let r=e,i=t.ZERO,o=t.ZERO;for(;s>Qn||n>Qn;)s&gn&&(i=i.add(r)),n&gn&&(o=o.add(r)),r=r.double(),s>>=gn,n>>=gn;return{p1:i,p2:o}}function uy(t,e,s,n){ay(s,t),cy(n,e);const r=s.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Mu(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=ti(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let f=u;f>=0;f-=c){d.fill(o);for(let m=0;m<i;m++){const w=n[m],A=Number(w>>BigInt(f)&l);d[A]=d[A].add(s[m])}let g=o;for(let m=d.length-1,w=o;m>0;m--)w=w.add(d[m]),g=g.add(w);if(h=h.add(g),f!==0)for(let m=0;m<c;m++)h=h.double()}return h}function pl(t,e,s){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ry(e),e}else return Zs(t,{isLE:s})}function hy(t,e,s={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>Qn))throw new Error(`CURVE.${a} must be positive bigint`)}const r=pl(e.p,s.Fp,n),i=pl(e.n,s.Fn,n),o=["Gx","Gy","a","b"];for(const a of o)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:i}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Eu("HashToScalar-");const pr=BigInt(0),xn=BigInt(1),fi=BigInt(2);function py(t){return ro(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function fy(t){const e=py(t),{P:s,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:o}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");const c=o||Tn,l=a?255:448,d=a?32:56,u=BigInt(a?9:5),h=BigInt(a?121665:39081),f=a?fi**BigInt(254):fi**BigInt(447),g=a?BigInt(8)*fi**BigInt(251)-xn:BigInt(4)*fi**BigInt(445)-xn,m=f+g+xn,w=P=>Nt(P,s),A=C(u);function C(P){return Qa(w(P),d)}function S(P){const E=rt("u coordinate",P,d);return a&&(E[31]&=127),w(qi(E))}function L(P){return qi(r(rt("scalar",P,d)))}function B(P,E){const y=$(S(E),L(P));if(y===pr)throw new Error("invalid private or public key received");return C(y)}function b(P){return B(P,A)}function R(P,E,y){const v=w(P*(E-y));return E=w(E-v),y=w(y+v),{x_2:E,x_3:y}}function $(P,E){fa("u",P,pr,s),fa("scalar",E,f,m);const y=E,v=P;let O=xn,D=pr,F=P,I=xn,k=pr;for(let z=BigInt(l-1);z>=pr;z--){const ae=y>>z&xn;k^=ae,{x_2:O,x_3:F}=R(k,O,F),{x_2:D,x_3:I}=R(k,D,I),k=ae;const oe=O+D,ne=w(oe*oe),ie=O-D,de=w(ie*ie),Te=ne-de,ue=F+I,Ue=F-I,jt=w(Ue*oe),ks=w(ue*ie),Qs=jt+ks,On=jt-ks;F=w(Qs*Qs),I=w(v*w(On*On)),O=w(ne*de),D=w(Te*(ne+w(h*Te)))}({x_2:O,x_3:F}=R(k,O,F)),{x_2:D,x_3:I}=R(k,D,I);const K=i(D);return w(O*K)}const N={secretKey:d,publicKey:d,seed:d},j=(P=c(d))=>(Yt(P,N.seed),P);function Y(P){const E=j(P);return{secretKey:E,publicKey:b(E)}}return{keygen:Y,getSharedSecret:(P,E)=>B(P,E),getPublicKey:P=>b(P),scalarMult:B,scalarMultBase:b,utils:{randomSecretKey:j,randomPrivateKey:j},GuBytes:A.slice(),lengths:N}}const gy=BigInt(1),fl=BigInt(2),my=BigInt(3),wy=BigInt(5);BigInt(8);const Zu=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),yy={p:Zu,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function by(t){const e=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=Zu,o=t*t%i*t%i,a=Wt(o,fl,i)*o%i,c=Wt(a,gy,i)*t%i,l=Wt(c,wy,i)*c%i,d=Wt(l,e,i)*l%i,u=Wt(d,s,i)*d%i,h=Wt(u,n,i)*u%i,f=Wt(h,r,i)*h%i,g=Wt(f,r,i)*h%i,m=Wt(g,e,i)*l%i;return{pow_p_5_8:Wt(m,fl,i)*t%i,b2:o}}function Cy(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Ey=Zs(yy.p,{isLE:!0}),ga=(()=>{const t=Ey.ORDER;return fy({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:s,b2:n}=by(e);return Nt(Wt(s,my,t)*n,t)},adjustScalarBytes:Cy})})(),gl=(t,e)=>(t+(t>=0?e:-e)/Qu)/e;function vy(t,e,s){const[[n,r],[i,o]]=e,a=gl(o*t,s),c=gl(-r*t,s);let l=t-a*n-c*i,d=-a*r-c*o;const u=l<As,h=d<As;u&&(l=-l),h&&(d=-d);const f=ti(Math.ceil(Mu(s)/2))+zn;if(l<As||l>=f||d<As||d>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}function ma(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function ko(t,e){const s={};for(let n of Object.keys(e))s[n]=t[n]===void 0?e[n]:t[n];return Fi(s.lowS,"lowS"),Fi(s.prehash,"prehash"),s.format!==void 0&&ma(s.format),s}class Ay extends Error{constructor(e=""){super(e)}}const Cs={Err:Ay,_tlv:{encode:(t,e)=>{const{Err:s}=Cs;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const n=e.length/2,r=pi(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?pi(r.length/2|128):"";return pi(t)+i+r+e},decode(t,e){const{Err:s}=Cs;let n=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new s("tlv.decode: wrong tlv");const r=e[n++],i=!!(r&128);let o=0;if(!i)o=r;else{const c=r&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(n+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=Cs;if(t<As)throw new e("integer: negative integers are not allowed");let s=pi(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}=Cs;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 no(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=Cs,r=rt("signature",t),{v:i,l:o}=n.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=Cs,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}},As=BigInt(0),zn=BigInt(1),Qu=BigInt(2),gi=BigInt(3),Iy=BigInt(4);function qn(t,e){const{BYTES:s}=t;let n;if(typeof e=="bigint")n=e;else{let r=rt("private key",e);try{n=t.fromBytes(r)}catch{throw new Error(`invalid private key: expected ui8a of size ${s}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Ny(t,e={}){const s=hy("weierstrass",t,e),{Fp:n,Fn:r}=s;let i=s.CURVE;const{h:o,n:a}=i;ro(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=th(n,r);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(P,E,y){const{x:v,y:O}=E.toAffine(),D=n.toBytes(v);if(Fi(y,"isCompressed"),y){d();const F=!n.isOdd(O);return Ws(eh(F),D)}else return Ws(Uint8Array.of(4),D,n.toBytes(O))}function h(P){pn(P,void 0,"Point");const{publicKey:E,publicKeyUncompressed:y}=l,v=P.length,O=P[0],D=P.subarray(1);if(v===E&&(O===2||O===3)){const F=n.fromBytes(D);if(!n.isValid(F))throw new Error("bad point: is not on curve, wrong x");const I=m(F);let k;try{k=n.sqrt(I)}catch(z){const ae=z instanceof Error?": "+z.message:"";throw new Error("bad point: is not on curve, sqrt error"+ae)}d();const K=n.isOdd(k);return(O&1)===1!==K&&(k=n.neg(k)),{x:F,y:k}}else if(v===y&&O===4){const F=n.BYTES,I=n.fromBytes(D.subarray(0,F)),k=n.fromBytes(D.subarray(F,F*2));if(!w(I,k))throw new Error("bad point: is not on curve");return{x:I,y:k}}else throw new Error(`bad point: got length ${v}, expected compressed=${E} or uncompressed=${y}`)}const f=e.toBytes||u,g=e.fromBytes||h;function m(P){const E=n.sqr(P),y=n.mul(E,P);return n.add(n.add(y,n.mul(P,i.a)),i.b)}function w(P,E){const y=n.sqr(E),v=m(P);return n.eql(y,v)}if(!w(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=n.mul(n.pow(i.a,gi),Iy),C=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(A,C)))throw new Error("bad curve params: a or b");function S(P,E,y=!1){if(!n.isValid(E)||y&&n.is0(E))throw new Error(`bad point coordinate ${P}`);return E}function L(P){if(!(P instanceof N))throw new Error("ProjectivePoint expected")}function B(P){if(!c||!c.basises)throw new Error("no endo");return vy(P,c.basises,r.ORDER)}const b=cl((P,E)=>{const{X:y,Y:v,Z:O}=P;if(n.eql(O,n.ONE))return{x:y,y:v};const D=P.is0();E==null&&(E=D?n.ONE:n.inv(O));const F=n.mul(y,E),I=n.mul(v,E),k=n.mul(O,E);if(D)return{x:n.ZERO,y:n.ZERO};if(!n.eql(k,n.ONE))throw new Error("invZ was invalid");return{x:F,y:I}}),R=cl(P=>{if(P.is0()){if(e.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:E,y}=P.toAffine();if(!n.isValid(E)||!n.isValid(y))throw new Error("bad point: x or y not field elements");if(!w(E,y))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function $(P,E,y,v,O){return y=new N(n.mul(y.X,P),y.Y,y.Z),E=Wi(v,E),y=Wi(O,y),E.add(y)}class N{constructor(E,y,v){this.X=S("x",E),this.Y=S("y",y,!0),this.Z=S("z",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(E){const{x:y,y:v}=E||{};if(!E||!n.isValid(y)||!n.isValid(v))throw new Error("invalid affine point");if(E instanceof N)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(v)?N.ZERO:new N(y,v,n.ONE)}static fromBytes(E){const y=N.fromAffine(g(pn(E,void 0,"point")));return y.assertValidity(),y}static fromHex(E){return N.fromBytes(rt("pointHex",E))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=8,y=!0){return Y.createCache(this,E),y||this.multiply(gi),this}assertValidity(){R(this)}hasEvenY(){const{y:E}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(E)}equals(E){L(E);const{X:y,Y:v,Z:O}=this,{X:D,Y:F,Z:I}=E,k=n.eql(n.mul(y,I),n.mul(D,O)),K=n.eql(n.mul(v,I),n.mul(F,O));return k&&K}negate(){return new N(this.X,n.neg(this.Y),this.Z)}double(){const{a:E,b:y}=i,v=n.mul(y,gi),{X:O,Y:D,Z:F}=this;let I=n.ZERO,k=n.ZERO,K=n.ZERO,z=n.mul(O,O),ae=n.mul(D,D),oe=n.mul(F,F),ne=n.mul(O,D);return ne=n.add(ne,ne),K=n.mul(O,F),K=n.add(K,K),I=n.mul(E,K),k=n.mul(v,oe),k=n.add(I,k),I=n.sub(ae,k),k=n.add(ae,k),k=n.mul(I,k),I=n.mul(ne,I),K=n.mul(v,K),oe=n.mul(E,oe),ne=n.sub(z,oe),ne=n.mul(E,ne),ne=n.add(ne,K),K=n.add(z,z),z=n.add(K,z),z=n.add(z,oe),z=n.mul(z,ne),k=n.add(k,z),oe=n.mul(D,F),oe=n.add(oe,oe),z=n.mul(oe,ne),I=n.sub(I,z),K=n.mul(oe,ae),K=n.add(K,K),K=n.add(K,K),new N(I,k,K)}add(E){L(E);const{X:y,Y:v,Z:O}=this,{X:D,Y:F,Z:I}=E;let k=n.ZERO,K=n.ZERO,z=n.ZERO;const ae=i.a,oe=n.mul(i.b,gi);let ne=n.mul(y,D),ie=n.mul(v,F),de=n.mul(O,I),Te=n.add(y,v),ue=n.add(D,F);Te=n.mul(Te,ue),ue=n.add(ne,ie),Te=n.sub(Te,ue),ue=n.add(y,O);let Ue=n.add(D,I);return ue=n.mul(ue,Ue),Ue=n.add(ne,de),ue=n.sub(ue,Ue),Ue=n.add(v,O),k=n.add(F,I),Ue=n.mul(Ue,k),k=n.add(ie,de),Ue=n.sub(Ue,k),z=n.mul(ae,ue),k=n.mul(oe,de),z=n.add(k,z),k=n.sub(ie,z),z=n.add(ie,z),K=n.mul(k,z),ie=n.add(ne,ne),ie=n.add(ie,ne),de=n.mul(ae,de),ue=n.mul(oe,ue),ie=n.add(ie,de),de=n.sub(ne,de),de=n.mul(ae,de),ue=n.add(ue,de),ne=n.mul(ie,ue),K=n.add(K,ne),ne=n.mul(Ue,ue),k=n.mul(Te,k),k=n.sub(k,ne),ne=n.mul(Te,ie),z=n.mul(Ue,z),z=n.add(z,ne),new N(k,K,z)}subtract(E){return this.add(E.negate())}is0(){return this.equals(N.ZERO)}multiply(E){const{endo:y}=e;if(!r.isValidNot0(E))throw new Error("invalid scalar: out of range");let v,O;const D=F=>Y.cached(this,F,I=>No(N,I));if(y){const{k1neg:F,k1:I,k2neg:k,k2:K}=B(E),{p:z,f:ae}=D(I),{p:oe,f:ne}=D(K);O=ae.add(ne),v=$(y.beta,z,oe,F,k)}else{const{p:F,f:I}=D(E);v=F,O=I}return No(N,[v,O])[0]}multiplyUnsafe(E){const{endo:y}=e,v=this;if(!r.isValid(E))throw new Error("invalid scalar: out of range");if(E===As||v.is0())return N.ZERO;if(E===zn)return v;if(Y.hasCache(this))return this.multiply(E);if(y){const{k1neg:O,k1:D,k2neg:F,k2:I}=B(E),{p1:k,p2:K}=dy(N,v,D,I);return $(y.beta,k,K,O,F)}else return Y.unsafe(v,E)}multiplyAndAddUnsafe(E,y,v){const O=this.multiplyUnsafe(y).add(E.multiplyUnsafe(v));return O.is0()?void 0:O}toAffine(E){return b(this,E)}isTorsionFree(){const{isTorsionFree:E}=e;return o===zn?!0:E?E(N,this):Y.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:E}=e;return o===zn?this:E?E(N,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(E=!0){return Fi(E,"isCompressed"),this.assertValidity(),f(N,this,E)}toHex(E=!0){return Kn(this.toBytes(E))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(E=!0){return this.toBytes(E)}_setWindowSize(E){this.precompute(E)}static normalizeZ(E){return No(N,E)}static msm(E,y){return uy(N,r,E,y)}static fromPrivateKey(E){return N.BASE.multiply(qn(r,E))}}N.BASE=new N(i.Gx,i.Gy,n.ONE),N.ZERO=new N(n.ZERO,n.ONE,n.ZERO),N.Fp=n,N.Fn=r;const j=r.BITS,Y=new ly(N,e.endo?Math.ceil(j/2):j);return N.BASE.precompute(8),N}function eh(t){return Uint8Array.of(t?2:3)}function th(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function _y(t,e={}){const{Fn:s}=t,n=e.randomBytes||Tn,r=Object.assign(th(t.Fp,s),{seed:Yu(s.ORDER)});function i(h){try{return!!qn(s,h)}catch{return!1}}function o(h,f){const{publicKey:g,publicKeyUncompressed:m}=r;try{const w=h.length;return f===!0&&w!==g||f===!1&&w!==m?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(r.seed)){return oy(pn(h,r.seed,"seed"),s.ORDER)}function c(h,f=!0){return t.BASE.multiply(qn(s,h)).toBytes(f)}function l(h){const f=a(h);return{secretKey:f,publicKey:c(f)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:f,publicKey:g,publicKeyUncompressed:m}=r;if(s.allowedLengths||f===g)return;const w=rt("key",h).length;return w===g||w===m}function u(h,f,g=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(f)===!1)throw new Error("second arg must be public key");const m=qn(s,h);return t.fromHex(f).multiply(m).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>qn(s,h),precompute(h=8,f=t.BASE){return f.precompute(h,!1)}},lengths:r})}function Sy(t,e,s={}){Zi(e),ro(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=s.randomBytes||Tn,r=s.hmac||((y,...v)=>to(e,y,Ws(...v))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:f}=_y(t,s),g={prehash:!1,lowS:typeof s.lowS=="boolean"?s.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function w(y){const v=a>>zn;return y>v}function A(y,v){if(!o.isValidNot0(v))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return v}function C(y,v){ma(v);const O=f.signature,D=v==="compact"?O:v==="recovered"?O+1:void 0;return pn(y,D,`${v} signature`)}class S{constructor(v,O,D){this.r=A("r",v),this.s=A("s",O),D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(v,O=m){C(v,O);let D;if(O==="der"){const{r:K,s:z}=Cs.toSig(pn(v));return new S(K,z)}O==="recovered"&&(D=v[0],O="compact",v=v.subarray(1));const F=o.BYTES,I=v.subarray(0,F),k=v.subarray(F,F*2);return new S(o.fromBytes(I),o.fromBytes(k),D)}static fromHex(v,O){return this.fromBytes(Bi(v),O)}addRecoveryBit(v){return new S(this.r,this.s,v)}recoverPublicKey(v){const O=i.ORDER,{r:D,s:F,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*Qu<O&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");const k=I===2||I===3?D+a:D;if(!i.isValid(k))throw new Error("recovery id 2 or 3 invalid");const K=i.toBytes(k),z=t.fromBytes(Ws(eh((I&1)===0),K)),ae=o.inv(k),oe=B(rt("msgHash",v)),ne=o.create(-oe*ae),ie=o.create(F*ae),de=t.BASE.multiplyUnsafe(ne).add(z.multiplyUnsafe(ie));if(de.is0())throw new Error("point at infinify");return de.assertValidity(),de}hasHighS(){return w(this.s)}toBytes(v=m){if(ma(v),v==="der")return Bi(Cs.hexFromSig(this));const O=o.toBytes(this.r),D=o.toBytes(this.s);if(v==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ws(Uint8Array.of(this.recovery),O,D)}return Ws(O,D)}toHex(v){return Kn(this.toBytes(v))}assertValidity(){}static fromCompact(v){return S.fromBytes(rt("sig",v),"compact")}static fromDER(v){return S.fromBytes(rt("sig",v),"der")}normalizeS(){return this.hasHighS()?new S(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Kn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Kn(this.toBytes("compact"))}}const L=s.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const v=no(y),O=y.length*8-c;return O>0?v>>BigInt(O):v},B=s.bits2int_modN||function(y){return o.create(L(y))},b=ti(c);function R(y){return fa("num < 2^"+c,y,As,b),o.toBytes(y)}function $(y,v){return pn(y,void 0,"message"),v?pn(e(y),void 0,"prehashed message"):y}function N(y,v,O){if(["recovered","canonical"].some(ie=>ie in O))throw new Error("sign() legacy options not supported");const{lowS:D,prehash:F,extraEntropy:I}=ko(O,g);y=$(y,F);const k=B(y),K=qn(o,v),z=[R(K),R(k)];if(I!=null&&I!==!1){const ie=I===!0?n(f.secretKey):I;z.push(rt("extraEntropy",ie))}const ae=Ws(...z),oe=k;function ne(ie){const de=L(ie);if(!o.isValidNot0(de))return;const Te=o.inv(de),ue=t.BASE.multiply(de).toAffine(),Ue=o.create(ue.x);if(Ue===As)return;const jt=o.create(Te*o.create(oe+Ue*K));if(jt===As)return;let ks=(ue.x===Ue?0:2)|Number(ue.y&zn),Qs=jt;return D&&w(jt)&&(Qs=o.neg(jt),ks^=1),new S(Ue,Qs,ks)}return{seed:ae,k2sig:ne}}function j(y,v,O={}){y=rt("message",y);const{seed:D,k2sig:F}=N(y,v,O);return Xw(e.outputLen,o.BYTES,r)(D,F)}function Y(y){let v;const O=typeof y=="string"||Xi(y),D=!O&&y!==null&&typeof y=="object"&&typeof y.r=="bigint"&&typeof y.s=="bigint";if(!O&&!D)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(D)v=new S(y.r,y.s);else if(O){try{v=S.fromBytes(rt("sig",y),"der")}catch(F){if(!(F instanceof Cs.Err))throw F}if(!v)try{v=S.fromBytes(rt("sig",y),"compact")}catch{return!1}}return v||!1}function P(y,v,O,D={}){const{lowS:F,prehash:I,format:k}=ko(D,g);if(O=rt("publicKey",O),v=$(rt("message",v),I),"strict"in D)throw new Error("options.strict was renamed to lowS");const K=k===void 0?Y(y):S.fromBytes(rt("sig",y),k);if(K===!1)return!1;try{const z=t.fromBytes(O);if(F&&K.hasHighS())return!1;const{r:ae,s:oe}=K,ne=B(v),ie=o.inv(oe),de=o.create(ne*ie),Te=o.create(ae*ie),ue=t.BASE.multiplyUnsafe(de).add(z.multiplyUnsafe(Te));return ue.is0()?!1:o.create(ue.x)===ae}catch{return!1}}function E(y,v,O={}){const{prehash:D}=ko(O,g);return v=$(v,D),S.fromBytes(y,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:f,Point:t,sign:j,verify:P,recoverPublicKey:E,Signature:S,hash:e})}function Ty(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},s=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const r=Zs(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),i={Fp:s,Fn:r,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function ky(t){const{CURVE:e,curveOpts:s}=Ty(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:s,hash:t.hash,ecdsaOpts:n}}function Oy(t,e){const s=e.Point;return Object.assign({},e,{ProjectivePoint:s,CURVE:Object.assign({},t,zu(s.Fn.ORDER,s.Fn.BITS))})}function Py(t){const{CURVE:e,curveOpts:s,hash:n,ecdsaOpts:r}=ky(t),i=Ny(e,s),o=Sy(i,n,r);return Oy(t,o)}function wa(t,e){const s=n=>Py({...t,hash:n});return{...s(e),create:s}}const sh={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},nh={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},rh={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Ry=Zs(sh.p),xy=Zs(nh.p),$y=Zs(rh.p),Uy=wa({...sh,Fp:Ry,lowS:!1},eo);wa({...nh,Fp:xy,lowS:!1},qm),wa({...rh,Fp:$y,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Fm);const Dy=Uy,ih="base10",at="base16",mt="base64pad",Hs="base64url",si="utf8",oh=0,Ns=1,ni=2,Ly=0,ml=1,Pr=12,tc=32;function My(){const t=ga.utils.randomPrivateKey(),e=ga.getPublicKey(t);return{privateKey:yt(t,at),publicKey:yt(e,at)}}function ya(){const t=Tn(tc);return yt(t,at)}function By(t,e){const s=ga.getSharedSecret(Dt(t,at),Dt(e,at)),n=Yw(so,s,void 0,void 0,tc);return yt(n,at)}function Ni(t){const e=so(Dt(t,at));return yt(e,at)}function $t(t){const e=so(Dt(t,si));return yt(e,at)}function ah(t){return Dt(`${t}`,ih)}function vn(t){return Number(yt(t,ih))}function ch(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function lh(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function jy(t){const e=ah(typeof t.type<"u"?t.type:oh);if(vn(e)===Ns&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?Dt(t.senderPublicKey,at):void 0,n=typeof t.iv<"u"?Dt(t.iv,at):Tn(Pr),r=Dt(t.symKey,at),i=Uu(r,n).encrypt(Dt(t.message,si)),o=dh({type:e,sealed:i,iv:n,senderPublicKey:s});return t.encoding===Hs?ch(o):o}function Fy(t){const e=Dt(t.symKey,at),{sealed:s,iv:n}=qr({encoded:t.encoded,encoding:t.encoding}),r=Uu(e,n).decrypt(s);if(r===null)throw new Error("Failed to decrypt");return yt(r,si)}function qy(t,e){const s=ah(ni),n=Tn(Pr),r=Dt(t,si),i=dh({type:s,sealed:r,iv:n});return e===Hs?ch(i):i}function Wy(t,e){const{sealed:s}=qr({encoded:t,encoding:e});return yt(s,si)}function dh(t){if(vn(t.type)===ni)return yt(Tr([t.type,t.sealed]),mt);if(vn(t.type)===Ns){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return yt(Tr([t.type,t.senderPublicKey,t.iv,t.sealed]),mt)}return yt(Tr([t.type,t.iv,t.sealed]),mt)}function qr(t){const e=(t.encoding||mt)===Hs?lh(t.encoded):t.encoded,s=Dt(e,mt),n=s.slice(Ly,ml),r=ml;if(vn(n)===Ns){const c=r+tc,l=c+Pr,d=s.slice(r,c),u=s.slice(c,l),h=s.slice(l);return{type:n,sealed:h,iv:u,senderPublicKey:d}}if(vn(n)===ni){const c=s.slice(r),l=Tn(Pr);return{type:n,sealed:c,iv:l}}const i=r+Pr,o=s.slice(r,i),a=s.slice(i);return{type:n,sealed:a,iv:o}}function Hy(t,e){const s=qr({encoded:t,encoding:e?.encoding});return uh({type:vn(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?yt(s.senderPublicKey,at):void 0,receiverPublicKey:e?.receiverPublicKey})}function uh(t){const e=t?.type||oh;if(e===Ns){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function wl(t){return t.type===Ns&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function yl(t){return t.type===ni}function Vy(t){const e=Buffer.from(t.x,"base64"),s=Buffer.from(t.y,"base64");return Tr([new Uint8Array([4]),e,s])}function Ky(t,e){const[s,n,r]=t.split("."),i=Buffer.from(lh(r),"base64");if(i.length!==64)throw new Error("Invalid signature length");const o=i.slice(0,32),a=i.slice(32,64),c=`${s}.${n}`,l=so(c),d=Vy(e);if(!Dy.verify(Tr([o,a]),l,d))throw new Error("Invalid signature");return Go(t).payload}const zy="irn";function Hi(t){return t?.relay||{protocol:zy}}function Wn(t){const e=pp[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var Gy=Object.defineProperty,Yy=Object.defineProperties,Jy=Object.getOwnPropertyDescriptors,bl=Object.getOwnPropertySymbols,Xy=Object.prototype.hasOwnProperty,Zy=Object.prototype.propertyIsEnumerable,Cl=(t,e,s)=>e in t?Gy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Oo=(t,e)=>{for(var s in e||(e={}))Xy.call(e,s)&&Cl(t,s,e[s]);if(bl)for(var s of bl(e))Zy.call(e,s)&&Cl(t,s,e[s]);return t},Qy=(t,e)=>Yy(t,Jy(e));function eb(t,e="-"){const s={},n="relay"+e;return Object.keys(t).forEach(r=>{if(r.startsWith(n)){const i=r.replace(n,""),o=t[r];s[i]=o}}),s}function El(t){if(!t.includes("wc:")){const l=gu(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),s=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),r=t.substring(e+1,s).split("@"),i=typeof s<"u"?t.substring(s):"",o=new URLSearchParams(i),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:tb(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:eb(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function tb(t){return t.startsWith("//")?t.substring(2):t}function sb(t,e="-"){const s="relay",n={};return Object.keys(t).forEach(r=>{const i=r,o=s+e+i;t[i]&&(n[o]=t[i])}),n}function vl(t){const e=new URLSearchParams,s=Oo(Oo(Qy(Oo({},sb(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(s).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!==void 0&&e.append(n,String(r))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function mi(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var nb=Object.defineProperty,rb=Object.defineProperties,ib=Object.getOwnPropertyDescriptors,Al=Object.getOwnPropertySymbols,ob=Object.prototype.hasOwnProperty,ab=Object.prototype.propertyIsEnumerable,Il=(t,e,s)=>e in t?nb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,cb=(t,e)=>{for(var s in e||(e={}))ob.call(e,s)&&Il(t,s,e[s]);if(Al)for(var s of Al(e))ab.call(e,s)&&Il(t,s,e[s]);return t},lb=(t,e)=>rb(t,ib(e));function cr(t){const e=[];return t.forEach(s=>{const[n,r]=s.split(":");e.push(`${n}:${r}`)}),e}function db(t){const e=[];return Object.values(t).forEach(s=>{e.push(...cr(s.accounts))}),e}function ub(t,e){const s=[];return Object.values(t).forEach(n=>{cr(n.accounts).includes(e)&&s.push(...n.methods)}),s}function hb(t,e){const s=[];return Object.values(t).forEach(n=>{cr(n.accounts).includes(e)&&s.push(...n.events)}),s}function io(t){return t.includes(":")}function Hn(t){return io(t)?t.split(":")[0]:t}function Nl(t){var e,s,n;const r={};if(!ls(t))return r;for(const[i,o]of Object.entries(t)){const a=io(i)?[i]:o.chains,c=o.methods||[],l=o.events||[],d=Hn(i);r[d]=lb(cb({},r[d]),{chains:cs(a,(e=r[d])==null?void 0:e.chains),methods:cs(c,(s=r[d])==null?void 0:s.methods),events:cs(l,(n=r[d])==null?void 0:n.events)})}return r}function pb(t){const e={};return t?.forEach(s=>{var n;const[r,i]=s.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(s),(n=e[r].chains)==null||n.push(`${r}:${i}`)}),e}function _l(t,e){e=e.map(n=>n.replace("did:pkh:",""));const s=pb(e);for(const[n,r]of Object.entries(s))r.methods?r.methods=cs(r.methods,t):r.methods=t,r.events=["chainChanged","accountsChanged"];return s}function fb(t,e){var s,n,r,i,o,a;const c=Nl(t),l=Nl(e),d={},u=Object.keys(c).concat(Object.keys(l));for(const h of u)d[h]={chains:cs((s=c[h])==null?void 0:s.chains,(n=l[h])==null?void 0:n.chains),methods:cs((r=c[h])==null?void 0:r.methods,(i=l[h])==null?void 0:i.methods),events:cs((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return d}const gb={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}},mb={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 q(t,e){const{message:s,code:n}=mb[t];return{message:e?`${s} ${e}
8`:s,code:n}}function Re(t,e){const{message:s,code:n}=gb[t];return{message:e?`${s} ${e}`:s,code:n}}function _s(t,e){return!!Array.isArray(t)}function ls(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function qe(t){return typeof t>"u"}function Be(t,e){return e&&qe(t)?!0:typeof t=="string"&&!!t.trim().length}function sc(t,e){return e&&qe(t)?!0:typeof t=="number"&&!isNaN(t)}function wb(t,e){const{requiredNamespaces:s}=e,n=Object.keys(t.namespaces),r=Object.keys(s);let i=!0;return hn(r,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],d=cr(a),u=s[o];(!hn(du(o,u),d)||!hn(u.methods,c)||!hn(u.events,l))&&(i=!1)}),i):!1}function Vi(t){return Be(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function yb(t){if(Be(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&Vi(s)}}return!1}function bb(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(Be(t,!1)){if(e(t))return!0;const s=gu(t);return e(s)}}catch{}return!1}function Cb(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function Eb(t){return t?.topic}function vb(t,e){let s=null;return Be(t?.publicKey,!1)||(s=q("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function Sl(t){let e=!0;return _s(t)?t.length&&(e=t.every(s=>Be(s,!1))):e=!1,e}function Ab(t,e,s){let n=null;return _s(e)&&e.length?e.forEach(r=>{n||Vi(r)||(n=Re("UNSUPPORTED_CHAINS",`${s}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Vi(t)||(n=Re("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function Ib(t,e,s){let n=null;return Object.entries(t).forEach(([r,i])=>{if(n)return;const o=Ab(r,du(r,i),`${e} ${s}`);o&&(n=o)}),n}function Nb(t,e){let s=null;return _s(t)?t.forEach(n=>{s||yb(n)||(s=Re("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):s=Re("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function _b(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=Nb(n?.accounts,`${e} namespace`);r&&(s=r)}),s}function Sb(t,e){let s=null;return Sl(t?.methods)?Sl(t?.events)||(s=Re("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=Re("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function hh(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=Sb(n,`${e}, namespace`);r&&(s=r)}),s}function Tb(t,e,s){let n=null;if(t&&ls(t)){const r=hh(t,e);r&&(n=r);const i=Ib(t,e,s);i&&(n=i)}else n=q("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return n}function Po(t,e){let s=null;if(t&&ls(t)){const n=hh(t,e);n&&(s=n);const r=_b(t,e);r&&(s=r)}else s=q("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function ph(t){return Be(t.protocol,!0)}function kb(t,e){let s=!1;return t?t&&_s(t)&&t.length&&t.forEach(n=>{s=ph(n)}):s=!0,s}function Ob(t){return typeof t=="number"}function ft(t){return typeof t<"u"&&typeof t!==null}function Pb(t){return!(!t||typeof t!="object"||!t.code||!sc(t.code,!1)||!t.message||!Be(t.message,!1))}function Rb(t){return!(qe(t)||!Be(t.method,!1))}function xb(t){return!(qe(t)||qe(t.result)&&qe(t.error)||!sc(t.id,!1)||!Be(t.jsonrpc,!1))}function $b(t){return!(qe(t)||!Be(t.name,!1))}function Tl(t,e){return!(!Vi(e)||!db(t).includes(e))}function Ub(t,e,s){return Be(s,!1)?ub(t,e).includes(s):!1}function Db(t,e,s){return Be(s,!1)?hb(t,e).includes(s):!1}function kl(t,e,s){let n=null;const r=Lb(t),i=Mb(e),o=Object.keys(r),a=Object.keys(i),c=Ol(Object.keys(t)),l=Ol(Object.keys(e)),d=c.filter(u=>!l.includes(u));return d.length&&(n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces. 9 Required: ${d.toString()} 10 Received: ${Object.keys(e).toString()}`)),hn(o,a)||(n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces. 11 Required: ${o.toString()} 12 Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||n)return;const h=cr(e[u].accounts);h.includes(u)||(n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${u} 13 Required: ${u} 14 Approved: ${h.toString()}`))}),o.forEach(u=>{n||(hn(r[u].methods,i[u].methods)?hn(r[u].events,i[u].events)||(n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${u}`)):n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${u}`))}),n}
vendor: 14,773 bytes, line 14
14function Lb(t){const e={};return Object.keys(t).forEach(s=>{var n;s.includes(":")?e[s]=t[s]:(n=t[s].chains)==null||n.forEach(r=>{e[r]={methods:t[s].methods,events:t[s].events}})}),e}function Ol(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Mb(t){const e={};return Object.keys(t).forEach(s=>{s.includes(":")?e[s]=t[s]:cr(t[s].accounts)?.forEach(r=>{e[r]={accounts:t[s].accounts.filter(i=>i.includes(`${r}:`)),methods:t[s].methods,events:t[s].events}})}),e}function Bb(t,e){return sc(t,!1)&&t<=e.max&&t>=e.min}function Pl(){const t=Qr();return new Promise(e=>{switch(t){case _t.browser:e(jb());break;case _t.reactNative:e(Fb());break;case _t.node:e(qb());break;default:e(!0)}})}function jb(){return ar()&&navigator?.onLine}async function Fb(){return Xs()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function qb(){return!0}function Wb(t){switch(Qr()){case _t.browser:Hb(t);break;case _t.reactNative:Vb(t);break}}function Hb(t){!Xs()&&ar()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function Vb(t){Xs()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function Kb(){var t;return ar()&&Ss.getDocument()?((t=Ss.getDocument())==null?void 0:t.visibilityState)==="visible":!0}const Ro={};class fr{static get(e){return Ro[e]}static set(e,s){Ro[e]=s}static delete(e){delete Ro[e]}}function zb(t){const e=nr.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function Gb({publicKey:t,signature:e,payload:s}){var n;const r=ba(s.method),i=128|parseInt(((n=s.version)==null?void 0:n.toString())||"4"),o=Xb(s.address),a=s.era==="00"?new Uint8Array([0]):ba(s.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(s.nonce,16),l=new Uint8Array([c&255,c>>8&255]),d=BigInt(`0x${Jb(s.tip)}`),u=Qb(d),h=new Uint8Array([0,...t,o,...e,...a,...l,...u,...r]),f=Zb(h.length+1);return new Uint8Array([...f,i,...h])}function Yb(t){const e=ba(t),s=yp.blake2b(e,void 0,32);return"0x"+Buffer.from(s).toString("hex")}function ba(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Jb(t){return t.startsWith("0x")?t.slice(2):t}function Xb(t){const e=nr.decode(t)[0];return e===42?0:e===60?2:1}function Zb(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function Qb(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function e0(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),s=zb(t.transaction.address),n=Gb({publicKey:s,signature:e,payload:t.transaction}),r=Buffer.from(n).toString("hex");return Yb(r)}var t0={};const fh="wc",gh=2,Ca="core",ds=`${fh}@2:${Ca}:`,s0={logger:"error"},n0={database:":memory:"},r0="crypto",Rl="client_ed25519_seed",i0=W.ONE_DAY,o0="keychain",a0="0.3",c0="messages",l0="0.3",d0=W.SIX_HOURS,u0="publisher",mh="irn",h0="error",wh="wss://relay.walletconnect.org",p0="relayer",De={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},f0="_subscription",Tt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},g0=.1,Ea="2.21.9",ke={link_mode:"link_mode",relay:"relay"},_i={inbound:"inbound",outbound:"outbound"},m0="0.3",w0="WALLETCONNECT_CLIENT_ID",xl="WALLETCONNECT_LINK_MODE_APPS",At={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},y0="subscription",b0="0.3",C0="pairing",E0="0.3",gr={wc_pairingDelete:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:W.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:W.ONE_DAY,prompt:!1,tag:0},res:{ttl:W.ONE_DAY,prompt:!1,tag:0}}},cn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},qt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},v0="history",A0="0.3",I0="expirer",xt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},N0="0.3",_0="verify-api",S0="https://verify.walletconnect.com",yh="https://verify.walletconnect.org",Rr=yh,T0=`${Rr}/v3`,k0=[S0,yh],O0="echo",P0="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"},ms={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"},Bs={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"},mr={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"},tn={authenticated_session_approve_started:"authenticated_session_approve_started",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"},wr={no_internet_connection:"no_internet_connection",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"},R0=.1,x0="event-client",$0=86400,U0="https://pulse.walletconnect.org/batch";function D0(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),n=0;n<s.length;n++)s[n]=255;for(var r=0;r<t.length;r++){var i=t.charAt(r),o=i.charCodeAt(0);if(s[o]!==255)throw new TypeError(i+" is ambiguous");s[o]=r}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,w=0,A=0,C=g.length;A!==C&&g[A]===0;)A++,m++;for(var S=(C-A)*d+1>>>0,L=new Uint8Array(S);A!==C;){for(var B=g[A],b=0,R=S-1;(B!==0||b<w)&&R!==-1;R--,b++)B+=256*L[R]>>>0,L[R]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");w=b,A++}for(var $=S-w;$!==S&&L[$]===0;)$++;for(var N=c.repeat(m);$<S;++$)N+=t.charAt(L[$]);return N}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var w=0,A=0;g[m]===c;)w++,m++;for(var C=(g.length-m)*l+1>>>0,S=new Uint8Array(C);g[m];){var L=s[g.charCodeAt(m)];if(L===255)return;for(var B=0,b=C-1;(L!==0||B<A)&&b!==-1;b--,B++)L+=a*S[b]>>>0,S[b]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");A=B,m++}if(g[m]!==" "){for(var R=C-A;R!==C&&S[R]===0;)R++;for(var $=new Uint8Array(w+(C-R)),N=w;R!==C;)$[N++]=S[R++];return $}}}function f(g){var m=h(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:f}}var L0=D0,M0=L0;const bh=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")},B0=t=>new TextEncoder().encode(t),j0=t=>new TextDecoder().decode(t);class F0{constructor(e,s,n){this.name=e,this.prefix=s,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class q0{constructor(e,s,n){if(this.name=e,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ch(this,e)}}class W0{constructor(e){this.decoders=e}or(e){return Ch(this,e)}decode(e){const s=e[0],n=this.decoders[s];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Ch=(t,e)=>new W0({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class H0{constructor(e,s,n,r){this.name=e,this.prefix=s,this.baseEncode=n,this.baseDecode=r,this.encoder=new F0(e,s,n),this.decoder=new q0(e,s,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const oo=({name:t,prefix:e,encode:s,decode:n})=>new H0(t,e,s,n),ri=({prefix:t,name:e,alphabet:s})=>{const{encode:n,decode:r}=M0(s,e);return oo({prefix:t,name:e,encode:n,decode:i=>bh(r(i))})},V0=(t,e,s,n)=>{const r={};for(let d=0;d<e.length;++d)r[e[d]]=d;let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*s/8|0);let a=0,c=0,l=0;for(let d=0;d<i;++d){const u=r[t[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<s|u,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},K0=(t,e,s)=>{const n=e[e.length-1]==="=",r=(1<<s)-1;let i="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,i+=e[r&a>>o];if(o&&(i+=e[r&a<<s-o]),n)for(;i.length*s&7;)i+="=";return i},Ze=({name:t,prefix:e,bitsPerChar:s,alphabet:n})=>oo({prefix:e,name:t,encode(r){return K0(r,n,s)},decode(r){return V0(r,n,s,t)}}),z0=oo({prefix:"\0",name:"identity",encode:t=>j0(t),decode:t=>B0(t)});var G0=Object.freeze({__proto__:null,identity:z0});const Y0=Ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var J0=Object.freeze({__proto__:null,base2:Y0});const X0=Ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Z0=Object.freeze({__proto__:null,base8:X0});const Q0=ri({prefix:"9",name:"base10",alphabet:"0123456789"});var eC=Object.freeze({__proto__:null,base10:Q0});const tC=Ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),sC=Ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var nC=Object.freeze({__proto__:null,base16:tC,base16upper:sC});const rC=Ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),iC=Ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),oC=Ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),aC=Ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),cC=Ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),lC=Ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dC=Ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),uC=Ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),hC=Ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var pC=Object.freeze({__proto__:null,base32:rC,base32upper:iC,base32pad:oC,base32padupper:aC,base32hex:cC,base32hexupper:lC,base32hexpad:dC,base32hexpadupper:uC,base32z:hC});const fC=ri({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),gC=ri({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var mC=Object.freeze({__proto__:null,base36:fC,base36upper:gC});const wC=ri({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),yC=ri({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bC=Object.freeze({__proto__:null,base58btc:wC,base58flickr:yC});const CC=Ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
14+/",bitsPerChar:6}),EC=Ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vC=Ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),AC=Ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var IC=Object.freeze({__proto__:null,base64:CC,base64pad:EC,base64url:vC,base64urlpad:AC});const Eh=Array.from("ððªâð°ðððððððððððððâð»ð¥ð¾ð¿ðâ¤ðð¤£ððððððð
ððð¥ð¥°ðððð¢ð¤ðððªðâºðð¤ððððð¹ð¤¦ððââ¨ð¤·ð±ðð¸ððððððððð¤©ððð¤ðð¯ððð¶ðð¤â£ððððªðð¥ððð©ð¡ð¤ªðð¥³ð¥ð¤¤ððð³âððð´ðð¬ððð·ð»ðââ
ð¥ºððð¤ð¦âð£ððâ¹ððð âððºðð»ððððð¹ð£ð«ðððµð¤ðð´ð¤ð¼ð«â½ð¤âðð¤«ðð®ðð»ðð¶ðð²ð¿ð§¡ðâ¡ððââðð°ð¤¨ð¶ð¤ð¶ð°ðð¢ð¤ðð¨ð¨ð¤¬âððºð¤ððð±ðð¶ð¥´â¶â¡âðð¸â¬ð¨ðð¦ð·ðºâ ð
ððµðð¤²ð¤ ð¤§ððµð
ð§ð¾ððð¤ðð¤¯ð·âð§ð¯ððð¤ððâð´ð£ð¸ððð¥ð¤¢ð
ð¡ð©ðð¸ð»ð¤ð¤®ð¼ð¥µð©ððð¼ðð£ð¥"),NC=Eh.reduce((t,e,s)=>(t[s]=e,t),[]),_C=Eh.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function SC(t){return t.reduce((e,s)=>(e+=NC[s],e),"")}function TC(t){const e=[];for(const s of t){const n=_C[s.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(n)}return new Uint8Array(e)}const kC=oo({prefix:"ð",name:"base256emoji",encode:SC,decode:TC});var OC=Object.freeze({__proto__:null,base256emoji:kC}),PC=vh,$l=128,RC=-128,xC=Math.pow(2,31);function vh(t,e,s){e=e||[],s=s||0;for(var n=s;t>=xC;)e[s++]=t&255|$l,t/=128;for(;t&RC;)e[s++]=t&255|$l,t>>>=7;return e[s]=t|0,vh.bytes=s-n+1,e}var $C=va,UC=128,Ul=127;function va(t,n){var s=0,n=n||0,r=0,i=n,o,a=t.length;do{if(i>=a)throw va.bytes=0,new RangeError("Could not decode varint");o=t[i++],s+=r<28?(o&Ul)<<r:(o&Ul)*Math.pow(2,r),r+=7}while(o>=UC);return va.bytes=i-n,s}var DC=Math.pow(2,7),LC=Math.pow(2,14),MC=Math.pow(2,21),BC=Math.pow(2,28),jC=Math.pow(2,35),FC=Math.pow(2,42),qC=Math.pow(2,49),WC=Math.pow(2,56),HC=Math.pow(2,63),VC=function(t){return t<DC?1:t<LC?2:t<MC?3:t<BC?4:t<jC?5:t<FC?6:t<qC?7:t<WC?8:t<HC?9:10},KC={encode:PC,decode:$C,encodingLength:VC},Ah=KC;const Dl=(t,e,s=0)=>(Ah.encode(t,e,s),e),Ll=t=>Ah.encodingLength(t),Aa=(t,e)=>{const s=e.byteLength,n=Ll(t),r=n+Ll(s),i=new Uint8Array(r+s);return Dl(t,i,0),Dl(s,i,n),i.set(e,r),new zC(t,s,e,i)};class zC{constructor(e,s,n,r){this.code=e,this.size=s,this.digest=n,this.bytes=r}}const Ih=({name:t,code:e,encode:s})=>new GC(t,e,s);class GC{constructor(e,s,n){this.name=e,this.code=s,this.encode=n}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?Aa(this.code,s):s.then(n=>Aa(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Nh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),YC=Ih({name:"sha2-256",code:18,encode:Nh("SHA-256")}),JC=Ih({name:"sha2-512",code:19,encode:Nh("SHA-512")});var XC=Object.freeze({__proto__:null,sha256:YC,sha512:JC});const _h=0,ZC="identity",Sh=bh,QC=t=>Aa(_h,Sh(t)),eE={code:_h,name:ZC,encode:Sh,digest:QC};var tE=Object.freeze({__proto__:null,identity:eE});new TextEncoder,new TextDecoder;const Ml={...G0,...J0,...Z0,...eC,...nC,...pC,...mC,...bC,...IC,...OC};({...XC,...tE});function Th(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function sE(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Th(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function kh(t,e,s,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:n}}}const Bl=kh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),xo=kh("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=sE(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),nE={utf8:Bl,"utf-8":Bl,hex:Ml.base16,latin1:xo,ascii:xo,binary:xo,...Ml};function rE(t,e="utf8"){const s=nE[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Th(globalThis.Buffer.from(t,"utf-8")):s.decoder.decode(`${s.prefix}${t}`)}var iE=Object.defineProperty,oE=(t,e,s)=>e in t?iE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Xt=(t,e,s)=>oE(t,typeof e!="symbol"?e+"":e,s);class aE{constructor(e,s){this.core=e,this.logger=s,Xt(this,"keychain",new Map),Xt(this,"name",o0),Xt(this,"version",a0),Xt(this,"initialized",!1),Xt(this,"storagePrefix",ds),Xt(this,"init",async()=>
vendor: 51,623 bytes, line 14
14{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Xt(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Xt(this,"set",async(n,r)=>{this.isInitialized(),this.keychain.set(n,r),await this.persist()}),Xt(this,"get",n=>{this.isInitialized();const r=this.keychain.get(n);if(typeof r>"u"){const{message:i}=q("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(i)}return r}),Xt(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=ct(s,this.name)}get context(){return bt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,oa(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?aa(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var cE=Object.defineProperty,lE=(t,e,s)=>e in t?cE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ke=(t,e,s)=>lE(t,typeof e!="symbol"?e+"":e,s);class dE{constructor(e,s,n){this.core=e,this.logger=s,Ke(this,"name",r0),Ke(this,"keychain"),Ke(this,"randomSessionIdentifier",ya()),Ke(this,"initialized",!1),Ke(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ke(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ke(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),i=pc(r);return vp(i.publicKey)}),Ke(this,"generateKeyPair",()=>{this.isInitialized();const r=My();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ke(this,"signJWT",async r=>{this.isInitialized();const i=await this.getClientSeed(),o=pc(i),a=this.randomSessionIdentifier;return await Ap(a,r,i0,o)}),Ke(this,"generateSharedKey",(r,i,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=By(a,i);return this.setSymKey(c,o)}),Ke(this,"setSymKey",async(r,i)=>{this.isInitialized();const o=i||Ni(r);return await this.keychain.set(o,r),o}),Ke(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ke(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ke(this,"encode",async(r,i,o)=>{this.isInitialized();const a=uh(o),c=zo(i);if(yl(a))return qy(c,o?.encoding);if(wl(a)){const h=a.senderPublicKey,f=a.receiverPublicKey;r=await this.generateSharedKey(h,f)}const l=this.getSymKey(r),{type:d,senderPublicKey:u}=a;return jy({type:d,symKey:l,message:c,senderPublicKey:u,encoding:o?.encoding})}),Ke(this,"decode",async(r,i,o)=>{this.isInitialized();const a=Hy(i,o);if(yl(a)){const c=Wy(i,o?.encoding);return fc(c)}if(wl(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=Fy({symKey:c,encoded:i,encoding:o?.encoding});return fc(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ke(this,"getPayloadType",(r,i=mt)=>{const o=qr({encoded:r,encoding:i});return vn(o.type)}),Ke(this,"getPayloadSenderPublicKey",(r,i=mt)=>{const o=qr({encoded:r,encoding:i});return o.senderPublicKey?yt(o.senderPublicKey,at):void 0}),this.core=e,this.logger=ct(s,this.name),this.keychain=n||new aE(this.core,this.logger)}get context(){return bt(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(Rl)}catch{e=ya(),await this.keychain.set(Rl,e)}return rE(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var uE=Object.defineProperty,hE=Object.defineProperties,pE=Object.getOwnPropertyDescriptors,jl=Object.getOwnPropertySymbols,fE=Object.prototype.hasOwnProperty,gE=Object.prototype.propertyIsEnumerable,Ia=(t,e,s)=>e in t?uE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mE=(t,e)=>{for(var s in e||(e={}))fE.call(e,s)&&Ia(t,s,e[s]);if(jl)for(var s of jl(e))gE.call(e,s)&&Ia(t,s,e[s]);return t},wE=(t,e)=>hE(t,pE(e)),Et=(t,e,s)=>Ia(t,typeof e!="symbol"?e+"":e,s);class yE extends ng{constructor(e,s){super(e,s),this.logger=e,this.core=s,Et(this,"messages",new Map),Et(this,"messagesWithoutClientAck",new Map),Et(this,"name",c0),Et(this,"version",l0),Et(this,"initialized",!1),Et(this,"storagePrefix",ds),Et(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),Et(this,"set",async(n,r,i)=>{this.isInitialized();const o=$t(r);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(n,a),i===_i.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,wE(mE({},c),{[o]:r}))}return await this.persist(),o}),Et(this,"get",n=>{this.isInitialized();let r=this.messages.get(n);return typeof r>"u"&&(r={}),r}),Et(this,"getWithoutAck",n=>{this.isInitialized();const r={};for(const i of n){const o=this.messagesWithoutClientAck.get(i)||{};r[i]=Object.values(o)}return r}),Et(this,"has",(n,r)=>{this.isInitialized();const i=this.get(n),o=$t(r);return typeof i[o]<"u"}),Et(this,"ack",async(n,r)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(n);if(typeof i>"u")return;const o=$t(r);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,i),await this.persist()}),Et(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=ct(e,this.name),this.core=s}get context(){return bt(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,oa(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,oa(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?aa(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?aa(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var bE=Object.defineProperty,CE=Object.defineProperties,EE=Object.getOwnPropertyDescriptors,Fl=Object.getOwnPropertySymbols,vE=Object.prototype.hasOwnProperty,AE=Object.prototype.propertyIsEnumerable,Na=(t,e,s)=>e in t?bE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$n=(t,e)=>{for(var s in e||(e={}))vE.call(e,s)&&Na(t,s,e[s]);if(Fl)for(var s of Fl(e))AE.call(e,s)&&Na(t,s,e[s]);return t},ql=(t,e)=>CE(t,EE(e)),kt=(t,e,s)=>Na(t,typeof e!="symbol"?e+"":e,s);class IE extends rg{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,kt(this,"events",new In.EventEmitter),kt(this,"name",u0),kt(this,"queue",new Map),kt(this,"publishTimeout",W.toMiliseconds(W.ONE_MINUTE)),kt(this,"initialPublishTimeout",W.toMiliseconds(W.ONE_SECOND*15)),kt(this,"needsTransportRestart",!1),kt(this,"publish",async(n,r,i)=>{var o,a,c,l,d;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:r,opts:i}});const u=i?.ttl||d0,h=i?.prompt||!1,f=i?.tag||0,g=i?.id||un().toString(),m=Wn(Hi().protocol),w={id:g,method:i?.publishMethod||m.publish,params:$n({topic:n,message:r,ttl:u,prompt:h,tag:f,attestation:i?.attestation},i?.tvf)},A=`Failed to publish payload, please try again. id:${g} tag:${f}`;try{qe((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),qe((c=w.params)==null?void 0:c.tag)&&((l=w.params)==null||delete l.tag);const C=new Promise(async S=>{const L=({id:b})=>{var R;((R=w.id)==null?void 0:R.toString())===b.toString()&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(De.publish,L),S())};this.relayer.events.on(De.publish,L);const B=is(new Promise((b,R)=>{this.rpcPublish(w,i).then(b).catch($=>{this.logger.warn($,$?.message),R($)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${g} tag:${f}`);try{await B,this.events.removeListener(De.publish,L)}catch(b){this.queue.set(g,{request:w,opts:i,attempt:1}),this.logger.warn(b,b?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:g,topic:n,message:r,opts:i}}),await is(C,this.publishTimeout,A)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(d=i?.internal)!=null&&d.throwOnFailedPublish)throw C}finally{this.queue.delete(g)}}),kt(this,"publishCustom",async n=>{var r,i,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:l,opts:d={}}=n,{attestation:u,tvf:h,publishMethod:f,prompt:g,tag:m,ttl:w=W.FIVE_MINUTES}=d,A=d.id||un().toString(),C=Wn(Hi().protocol),S=f||C.publish,L={id:A,method:S,params:$n(ql($n({},l),{ttl:w,prompt:g,tag:m,attestation:u}),h)},B=`Failed to publish custom payload, please try again. id:${A} tag:${m}`;try{qe((r=L.params)==null?void 0:r.prompt)&&((i=L.params)==null||delete i.prompt),qe((o=L.params)==null?void 0:o.tag)&&((a=L.params)==null||delete a.tag);const b=new Promise(async R=>{const $=({id:j})=>{var Y;((Y=L.id)==null?void 0:Y.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(De.publish,$),R())};this.relayer.events.on(De.publish,$);const N=is(new Promise((j,Y)=>{this.rpcPublish(L,d).then(j).catch(P=>{this.logger.warn(P,P?.message),Y(P)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${S} id:${A} tag:${m}`);try{await N,this.events.removeListener(De.publish,$)}catch(j){this.queue.set(A,{request:L,opts:d,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:A,payload:l,opts:d}}),await is(b,this.publishTimeout,B)}catch(b){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(b),(c=d?.internal)!=null&&c.throwOnFailedPublish)throw b}finally{this.queue.delete(A)}}),kt(this,"on",(n,r)=>{this.events.on(n,r)}),kt(this,"once",(n,r)=>{this.events.once(n,r)}),kt(this,"off",(n,r)=>{this.events.off(n,r)}),kt(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.relayer=e,this.logger=ct(s,this.name),this.registerEventListeners()}get context(){return bt(this.logger)}async rpcPublish(e,s){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(De.publish,$n($n({},e),s)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{var n;const r=e.attempt+1;this.queue.set(s,ql($n({},e),{attempt:r})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${r}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(rr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(De.connection_stalled);return}this.checkQueue()}),this.relayer.on(De.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var NE=Object.defineProperty,_E=(t,e,s)=>e in t?NE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Un=(t,e,s)=>_E(t,typeof e!="symbol"?e+"":e,s);class SE{constructor(){Un(this,"map",new Map),Un(this,"set",(e,s)=>{const n=this.get(e);this.exists(e,s)||this.map.set(e,[...n,s])}),Un(this,"get",e=>this.map.get(e)||[]),Un(this,"exists",(e,s)=>this.get(e).includes(s)),Un(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,s))return;const r=n.filter(i=>i!==s);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),Un(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var TE=Object.defineProperty,kE=Object.defineProperties,OE=Object.getOwnPropertyDescriptors,Wl=Object.getOwnPropertySymbols,PE=Object.prototype.hasOwnProperty,RE=Object.prototype.propertyIsEnumerable,_a=(t,e,s)=>e in t?TE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yr=(t,e)=>{for(var s in e||(e={}))PE.call(e,s)&&_a(t,s,e[s]);if(Wl)for(var s of Wl(e))RE.call(e,s)&&_a(t,s,e[s]);return t},$o=(t,e)=>kE(t,OE(e)),_e=(t,e,s)=>_a(t,typeof e!="symbol"?e+"":e,s);class xE extends ag{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,_e(this,"subscriptions",new Map),_e(this,"topicMap",new SE),_e(this,"events",new In.EventEmitter),_e(this,"name",y0),_e(this,"version",b0),_e(this,"pending",new Map),_e(this,"cached",[]),_e(this,"initialized",!1),_e(this,"storagePrefix",ds),_e(this,"subscribeTimeout",W.toMiliseconds(W.ONE_MINUTE)),_e(this,"initialSubscribeTimeout",W.toMiliseconds(W.ONE_SECOND*15)),_e(this,"clientId"),_e(this,"batchSubscribeTopicsLimit",500),_e(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),_e(this,"subscribe",async(n,r)=>{var i;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}});try{const o=Hi(r),a={topic:n,relay:o,transportType:r?.transportType};(i=r?.internal)!=null&&i.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,r);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),_e(this,"unsubscribe",async(n,r)=>{this.isInitialized(),typeof r?.id<"u"?await this.unsubscribeById(n,r.id,r):await this.unsubscribeByTopic(n,r)}),_e(this,"isSubscribed",n=>new Promise(r=>{r(this.topicMap.topics.includes(n))})),_e(this,"isKnownTopic",n=>new Promise(r=>{r(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(i=>i.topic===n))})),_e(this,"on",(n,r)=>{this.events.on(n,r)}),_e(this,"once",(n,r)=>{this.events.once(n,r)}),_e(this,"off",(n,r)=>{this.events.off(n,r)}),_e(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),_e(this,"start",async()=>{await this.onConnect()}),_e(this,"stop",async()=>{await this.onDisconnect()}),_e(this,"restart",async()=>{await this.restore(),await this.onRestart()}),_e(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(r=>{n.push(r)}),await this.batchSubscribe(n)}),_e(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(rr.pulse,async()=>{await this.checkPending()}),this.events.on(At.created,async n=>{const r=At.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()}),this.events.on(At.deleted,async n=>{const r=At.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()})}),this.relayer=e,this.logger=ct(s,this.name),this.clientId=""}get context(){return bt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,s){let n=!1;try{n=this.getSubscription(e).topic===s}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,s){const n=this.topicMap.get(e);await Promise.all(n.map(async r=>await this.unsubscribeById(e,r,s)))}async unsubscribeById(e,s,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}});try{const r=Hi(n);await this.restartToComplete({topic:e,id:s,relay:r}),await this.rpcUnsubscribe(e,s,r);const i=Re("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,s,n){var r,i;const o=await this.getSubscriptionId(e);if((r=n?.internal)!=null&&r.skipSubscribe)return o;(!n||n?.transportType===ke.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const a={method:Wn(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{if(n?.transportType===ke.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(u=>this.logger.warn(u))},W.toMiliseconds(W.ONE_SECOND)),o;const l=new Promise(async u=>{const h=f=>{f.topic===e&&(this.events.removeListener(At.created,h),u(f.id))};this.events.on(At.created,h);try{const f=await is(new Promise((g,m)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w?.message),m(w)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(At.created,h),u(f)}catch{}}),d=await is(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!d&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return d?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(De.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,n={method:Wn(s.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await is(new Promise(r=>{this.relayer.request(n).catch(i=>this.logger.warn(i)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(De.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,n={method:Wn(s.protocol).batchFetchMessages,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let r;try{r=await await is(new Promise((i,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(De.connection_stalled)}return r}rpcUnsubscribe(e,s,n){const r={method:Wn(n.protocol).unsubscribe,params:{topic:e,id:s}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,s){this.setSubscription(e,$o(yr({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,yr({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,n){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,s){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:s}),this.addSubscription(e,s)}addSubscription(e,s){this.subscriptions.set(e,yr({},s)),this.topicMap.set(s.topic,e),this.events.emit(At.created,s)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const s=this.subscriptions.get(e);if(!s){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(At.deleted,$o(yr({},n),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(At.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<s;n++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(At.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(s=>{var n;return s.topic===((n=this.subscriptions.get(s.id))==null?void 0:n.topic)})){const{message:s}=q("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=>$o(yr({},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 om(W.toMiliseconds(W.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}=q("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 $t(e+await this.getClientId())}}var $E=Object.defineProperty,Hl=Object.getOwnPropertySymbols,UE=Object.prototype.hasOwnProperty,DE=Object.prototype.propertyIsEnumerable,Sa=(t,e,s)=>e in t?$E(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Vl=(t,e)=>{for(var s in e||(e={}))UE.call(e,s)&&Sa(t,s,e[s]);if(Hl)for(var s of Hl(e))DE.call(e,s)&&Sa(t,s,e[s]);return t},Ee=(t,e,s)=>Sa(t,typeof e!="symbol"?e+"":e,s);class LE extends ig{constructor(e){super(e),Ee(this,"protocol","wc"),Ee(this,"version",2),Ee(this,"core"),Ee(this,"logger"),Ee(this,"events",new In.EventEmitter),Ee(this,"provider"),Ee(this,"messages"),Ee(this,"subscriber"),Ee(this,"publisher"),Ee(this,"name",p0),Ee(this,"transportExplicitlyClosed",!1),Ee(this,"initialized",!1),Ee(this,"connectionAttemptInProgress",!1),Ee(this,"relayUrl"),Ee(this,"projectId"),Ee(this,"packageName"),Ee(this,"bundleId"),Ee(this,"hasExperiencedNetworkDisruption",!1),Ee(this,"pingTimeout"),Ee(this,"heartBeatTimeout",W.toMiliseconds(W.THIRTY_SECONDS+W.FIVE_SECONDS)),Ee(this,"reconnectTimeout"),Ee(this,"connectPromise"),Ee(this,"reconnectInProgress",!1),Ee(this,"requestsInFlight",[]),Ee(this,"connectTimeout",W.toMiliseconds(W.ONE_SECOND*15)),Ee(this,"request",async s=>{var n,r;this.logger.debug("Publishing Request Payload");const i=s.id||un().toString();await this.toEstablishConnection();try{this.logger.trace({id:i,method:s.method,topic:(n=s.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${i}:${((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: ${i}`),o}}),Ee(this,"resetPingTimeout",()=>{Mi()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var s,n,r,i;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(i=(r=(n=(s=this.provider)==null?void 0:s.connection)==null?void 0:n.socket)==null?void 0:r.terminate)==null||i.call(r)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),Ee(this,"onPayloadHandler",s=>{this.onProviderPayload(s),this.resetPingTimeout()}),Ee(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected ð"),this.startPingTimeout(),this.events.emit(De.connect)}),Ee(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected ð"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ee(this,"onProviderErrorHandler",s=>{this.logger.fatal(`Fatal socket error: ${s.message}`),this.events.emit(De.error,s),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ee(this,"registerProviderListeners",()=>{this.provider.on(Tt.payload,this.onPayloadHandler),this.provider.on(Tt.connect,this.onConnectHandler),this.provider.on(Tt.disconnect,this.onDisconnectHandler),this.provider.on(Tt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ct(e.logger,this.name):Jr(Zr({level:e.logger||h0})),this.messages=new yE(this.logger,e.core),this.subscriber=new xE(this,this.logger),this.publisher=new IE(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||wh,Hg()?this.packageName=Bc():Vg()&&(this.bundleId=Bc()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return bt(this.logger)}get connected(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,n){this.isInitialized(),await this.publisher.publish(e,s,n),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:ke.relay},_i.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,s){var n,r,i;this.isInitialized(),(!(s!=null&&s.transportType)||s?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=s?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(r=s?.internal)==null?void 0:r.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",c;const l=d=>{d.topic===e&&(this.subscriber.off(At.created,l),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(At.created,l)}),new Promise(async(d,u)=>{a=await this.subscriber.subscribe(e,Vl({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 is(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(s,n)=>{await this.connect(e).then(s).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Pl())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const s=e.sort((n,r)=>n.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const n of s)try{await this.onMessageEvent(n)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+r?.message)}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:n}=e;if(!s.sessionExists){const r=Me(W.FIVE_MINUTES),i={topic:n,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,i)}this.events.emit(De.message,e),await this.recordMessageEvent(e,_i.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let s=1;for(;s<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${s}...`),await this.createProvider(),await new Promise(async(n,r)=>{const i=()=>{r(new Error("Connection interrupted while trying to connect"))};this.provider.once(Tt.disconnect,i),await is(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(Tt.disconnect,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Tt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Tt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const r=n;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${s}`);break}await new Promise(n=>setTimeout(n,W.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,n,r,i;if(Mi())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null||i.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ma(new Ep(Jg({sdkVersion:Ea,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,s){const{topic:n,message:r}=e;await this.messages.set(n,r,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const r=this.messages.has(s,n);return r&&this.logger.warn(`Ignoring duplicate message: ${n}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Ba(e)){if(!e.method.endsWith(f0))return;const s=e.params,{topic:n,message:r,publishedAt:i,attestation:o}=s.data,a={topic:n,message:r,publishedAt:i,transportType:ke.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Vl({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ja(e)&&this.events.emit(De.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,_i.inbound),this.events.emit(De.message,e))}async acknowledgePayload(e){const s=Dr(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Tt.payload,this.onPayloadHandler),this.provider.off(Tt.connect,this.onConnectHandler),this.provider.off(Tt.disconnect,this.onDisconnectHandler),this.provider.off(Tt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Pl();Wb(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(rr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Kb())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(De.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?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},W.toMiliseconds(g0)))))}isInitialized(){if(!this.initialized){const{message:e}=q("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 ME(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Kl(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function zl(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const BE="[object RegExp]",jE="[object String]",FE="[object Number]",qE="[object Boolean]",Gl="[object Arguments]",WE="[object Symbol]",HE="[object Date]",VE="[object Map]",KE="[object Set]",zE="[object Array]",GE="[object Function]",YE="[object ArrayBuffer]",Uo="[object Object]",JE="[object Error]",XE="[object DataView]",ZE="[object Uint8Array]",QE="[object Uint8ClampedArray]",ev="[object Uint16Array]",tv="[object Uint32Array]",sv="[object BigUint64Array]",nv="[object Int8Array]",rv="[object Int16Array]",iv="[object Int32Array]",ov="[object BigInt64Array]",av="[object Float32Array]",cv="[object Float64Array]";function lv(){}function Yl(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 dv(t,e,s){return Nr(t,e,void 0,void 0,void 0,void 0,s)}function Nr(t,e,s,n,r,i,o){const a=o(t,e,s,n,r,i);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return xr(t,e,i,o)}return xr(t,e,i,o)}function xr(t,e,s,n){if(Object.is(t,e))return!0;let r=zl(t),i=zl(e);if(r===Gl&&(r=Uo),i===Gl&&(i=Uo),r!==i)return!1;switch(r){case jE:return t.toString()===e.toString();case FE:{const c=t.valueOf(),l=e.valueOf();return ME(c,l)}case qE:case HE:case WE:return Object.is(t.valueOf(),e.valueOf());case BE:return t.source===e.source&&t.flags===e.flags;case GE: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 VE:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Nr(l,e.get(c),c,t,e,s,n))return!1;return!0}case KE:{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(f=>Nr(u,f,void 0,t,e,s,n));if(h===-1)return!1;l.splice(h,1)}return!0}case zE:case ZE:case QE:case ev:case tv:case sv:case nv:case rv:case iv:case ov:case av:case cv:{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(!Nr(t[c],e[c],c,t,e,s,n))return!1;return!0}case YE:return t.byteLength!==e.byteLength?!1:xr(new Uint8Array(t),new Uint8Array(e),s,n);case XE:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:xr(new Uint8Array(t),new Uint8Array(e),s,n);case JE:return t.name===e.name&&t.message===e.message;case Uo:{if(!(xr(t.constructor,e.constructor,s,n)||Yl(t)&&Yl(e)))return!1;const c=[...Object.keys(t),...Kl(t)],l=[...Object.keys(e),...Kl(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 f=e[u];if(!Nr(h,f,u,t,e,s,n))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function uv(t,e){return dv(t,e,lv)}var hv=Object.defineProperty,Jl=Object.getOwnPropertySymbols,pv=Object.prototype.hasOwnProperty,fv=Object.prototype.propertyIsEnumerable,Ta=(t,e,s)=>e in t?hv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Xl=(t,e)=>{for(var s in e||(e={}))pv.call(e,s)&&Ta(t,s,e[s]);if(Jl)for(var s of Jl(e))fv.call(e,s)&&Ta(t,s,e[s]);return t},pt=(t,e,s)=>Ta(t,typeof e!="symbol"?e+"":e,s);class kn extends og{constructor(e,s,n,r=ds,i=void 0){super(e,s,n,r),this.core=e,this.logger=s,this.name=n,pt(this,"map",new Map),pt(this,"version",m0),pt(this,"cached",[]),pt(this,"initialized",!1),pt(this,"getKey"),pt(this,"storagePrefix",ds),pt(this,"recentlyDeleted",[]),pt(this,"recentlyDeletedLimit",200),pt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!qe(o)?this.map.set(this.getKey(o),o):Cb(o)?this.map.set(o.id,o):Eb(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),pt(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())}),pt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),pt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>uv(a[c],o[c]))):this.values)),pt(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=Xl(Xl({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),pt(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=ct(s,this.name),this.storagePrefix=r,this.getKey=i}get context(){return bt(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}=q("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return s}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:s}=q("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}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var gv=Object.defineProperty,mv=(t,e,s)=>e in t?gv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pe=(t,e,s)=>mv(t,typeof e!="symbol"?e+"":e,s);class wv{constructor(e,s){this.core=e,this.logger=s,pe(this,"name",C0),pe(this,"version",E0),pe(this,"events",new Fa),pe(this,"pairings"),pe(this,"initialized",!1),pe(this,"storagePrefix",ds),pe(this,"ignoredPayloadTypes",[Ns]),pe(this,"registeredMethods",[]),pe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),pe(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),pe(this,"create",async n=>{this.isInitialized();const r=ya(),i=await this.core.crypto.setSymKey(r),o=Me(W.FIVE_MINUTES),a={protocol:mh},c={topic:i,expiry:o,relay:a,active:!1,methods:n?.methods},l=vl({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:r,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(cn.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:n?.transportType,internal:n?.internal}),{topic:i,uri:l}}),pe(this,"pair",async n=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Qt.pairing_started]}});this.isValidPair(n,r);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=El(n.uri);r.props.properties.topic=i,r.addTrace(Qt.pairing_uri_validation_success),r.addTrace(Qt.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(i)){if(d=this.pairings.get(i),r.addTrace(Qt.existing_pairing),d.active)throw r.setError(ms.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);r.addTrace(Qt.pairing_not_expired)}const u=c||Me(W.FIVE_MINUTES),h={topic:i,relay:a,expiry:u,active:!1,methods:l};this.core.expirer.set(i,u),await this.pairings.set(i,h),r.addTrace(Qt.store_new_pairing),n.activatePairing&&await this.activate({topic:i}),this.events.emit(cn.create,h),r.addTrace(Qt.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),r.addTrace(Qt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(ms.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(f){throw r.setError(ms.subscribe_pairing_topic_failure),f}return r.addTrace(Qt.subscribe_pairing_topic_success),h}),pe(this,"activate",async({topic:n})=>{this.isInitialized();const r=Me(W.FIVE_MINUTES);this.core.expirer.set(n,r),await this.pairings.update(n,{active:!0,expiry:r})}),pe(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=n;if(this.pairings.keys.includes(r)){const i=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=an();this.events.once(Ae("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}}),pe(this,"updateExpiry",async({topic:n,expiry:r})=>{this.isInitialized(),await this.pairings.update(n,{expiry:r})}),pe(this,"updateMetadata",async({topic:n,metadata:r})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:r})}),pe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),pe(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:r}=n;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Re("USER_DISCONNECTED")),await this.deletePairing(r))}),pe(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:r,relay:i,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(r);return vl({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:i,expiryTimestamp:o,methods:a})}),pe(this,"sendRequest",async(n,r,i)=>{const o=ts(r,i),a=await this.core.crypto.encode(n,o),c=gr[r].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),pe(this,"sendResult",async(n,r,i)=>{const o=Dr(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=gr[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),pe(this,"sendError",async(n,r,i)=>{const o=jd(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=gr[c]?gr[c].res:gr.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),pe(this,"deletePairing",async(n,r)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Re("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),r?Promise.resolve():this.core.expirer.del(n)])}),pe(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(r=>ss(r.expiry));await Promise.all(n.map(r=>this.deletePairing(r.topic)))}),pe(this,"onRelayEventRequest",async n=>{const{topic:r,payload:i}=n;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,i);default:return await this.onUnknownRpcMethodRequest(r,i)}}),pe(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i}=n,o=(await this.core.history.get(r,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,i);default:return this.onUnknownRpcMethodResponse(o)}}),pe(this,"onPairingPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult(i,n,!0),this.events.emit(cn.ping,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),pe(this,"onPairingPingResponse",(n,r)=>{const{id:i}=r;setTimeout(()=>{fs(r)?this.events.emit(Ae("pairing_ping",i),{}):es(r)&&this.events.emit(Ae("pairing_ping",i),{error:r.error})},500)}),pe(this,"onPairingDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(cn.delete,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),pe(this,"onUnknownRpcMethodRequest",async(n,r)=>{const{id:i,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Re("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,n,a),this.logger.error(a)}catch(a){await this.sendError(i,n,a),this.logger.error(a)}}),pe(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(Re("WC_METHOD_UNSUPPORTED",n))}),pe(this,"isValidPair",(n,r)=>{var i;if(!ft(n)){const{message:a}=q("MISSING_OR_INVALID",`pair() params: ${n}`);throw r.setError(ms.malformed_pairing_uri),new Error(a)}if(!bb(n.uri)){const{message:a}=q("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw r.setError(ms.malformed_pairing_uri),new Error(a)}const o=El(n?.uri);if(!((i=o?.relay)!=null&&i.protocol)){const{message:a}=q("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(ms.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=q("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(ms.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&W.toMiliseconds(o?.expiryTimestamp)<Date.now()){r.setError(ms.pairing_expired);const{message:a}=q("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),pe(this,"isValidPing",async n=>{if(!ft(n)){const{message:i}=q("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),pe(this,"isValidDisconnect",async n=>{if(!ft(n)){const{message:i}=q("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),pe(this,"isValidPairingTopic",async n=>{if(!Be(n,!1)){const{message:r}=q("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(r)}if(!this.pairings.keys.includes(n)){const{message:r}=q("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(r)}if(ss(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:r}=q("EXPIRED",`pairing topic: ${n}`);throw new Error(r)}}),this.core=e,this.logger=ct(s,this.name),this.pairings=new kn(this.core,this.logger,this.name,this.storagePrefix)}get context(){return bt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(De.message,async e=>{const{topic:s,message:n,transportType:r}=e;if(this.pairings.keys.includes(s)&&r!==ke.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const i=await this.core.crypto.decode(s,n);Ba(i)?(this.core.history.set(s,i),await this.onRelayEventRequest({topic:s,payload:i})):ja(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:s,payload:i}),this.core.history.delete(s,i.id)),await this.core.relayer.messages.ack(s,n)}catch(i){this.logger.error(i)}})}registerExpirerEvents(){this.core.expirer.on(xt.expired,async e=>{const{topic:s}=fu(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(cn.expire,{topic:s}))})}}var yv=Object.defineProperty,bv=(t,e,s)=>e in t?yv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ze=(t,e,s)=>bv(t,typeof e!="symbol"?e+"":e,s);class Cv extends sg{constructor(e,s){super(e,s),this.core=e,this.logger=s,ze(this,"records",new Map),ze(this,"events",new In.EventEmitter),ze(this,"name",v0),ze(this,"version",A0),ze(this,"cac
14hed",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",ds),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"set",(n,r,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:r,chainId:i}),this.records.has(r.id))return;const o={id:r.id,topic:n,request:{method:r.method,params:r.params||null},chainId:i,expiry:Me(W.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(qt.created,o)}),ze(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const r=await this.getRecord(n.id);typeof r.response>"u"&&(r.response=es(n)?{error:n.error}:{result:n.result},this.records.set(r.id,r),this.persist(),this.events.emit(qt.updated,r))}),ze(this,"get",async(n,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:r}),await this.getRecord(r))),ze(this,"delete",(n,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(i=>{if(i.topic===n){if(typeof r<"u"&&i.id!==r)return;this.records.delete(i.id),this.events.emit(qt.deleted,i)}}),this.persist()}),ze(this,"exists",async(n,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===n:!1)),ze(this,"on",(n,r)=>{this.events.on(n,r)}),ze(this,"once",(n,r)=>{this.events.once(n,r)}),ze(this,"off",(n,r)=>{this.events.off(n,r)}),ze(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=ct(s,this.name)}get context(){return bt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(s=>{if(typeof s.response<"u")return;const n={topic:s.topic,request:ts(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const s=this.records.get(e);if(!s){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(qt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=q("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(qt.created,e=>{const s=qt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(qt.updated,e=>{const s=qt.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(qt.deleted,e=>{const s=qt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(rr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{W.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(qt.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ev=Object.defineProperty,vv=(t,e,s)=>e in t?Ev(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,st=(t,e,s)=>vv(t,typeof e!="symbol"?e+"":e,s);class Av extends cg{constructor(e,s){super(e,s),this.core=e,this.logger=s,st(this,"expirations",new Map),st(this,"events",new In.EventEmitter),st(this,"name",I0),st(this,"version",N0),st
vendor: 60,166 bytes, line 14
14(this,"cached",[]),st(this,"initialized",!1),st(this,"storagePrefix",ds),st(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),st(this,"has",n=>{try{const r=this.formatTarget(n);return typeof this.getExpiration(r)<"u"}catch{return!1}}),st(this,"set",(n,r)=>{this.isInitialized();const i=this.formatTarget(n),o={target:i,expiry:r};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(xt.created,{target:i,expiration:o})}),st(this,"get",n=>{this.isInitialized();const r=this.formatTarget(n);return this.getExpiration(r)}),st(this,"del",n=>{if(this.isInitialized(),this.has(n)){const r=this.formatTarget(n),i=this.getExpiration(r);this.expirations.delete(r),this.events.emit(xt.deleted,{target:r,expiration:i})}}),st(this,"on",(n,r)=>{this.events.on(n,r)}),st(this,"once",(n,r)=>{this.events.once(n,r)}),st(this,"off",(n,r)=>{this.events.off(n,r)}),st(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=ct(s,this.name)}get context(){return bt(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 Xg(e);if(typeof e=="number")return Zg(e);const{message:s}=q("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(xt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const s=this.expirations.get(e);if(!s){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return s}checkExpiry(e,s){const{expiry:n}=s;W.toMiliseconds(n)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(xt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(rr.pulse,()=>this.checkExpirations()),this.events.on(xt.created,e=>{const s=xt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(xt.expired,e=>{const s=xt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(xt.deleted,e=>{const s=xt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Iv=Object.defineProperty,Nv=(t,e,s)=>e in t?Iv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Le=(t,e,s)=>Nv(t,typeof e!="symbol"?e+"":e,s);class _v extends lg{constructor(e,s,n){super(e,s,n),this.core=e,this.logger=s,this.store=n,Le(this,"name",_0),Le(this,"abortController"),Le(this,"isDevEnv"),Le(this,"verifyUrlV3",T0),Le(this,"storagePrefix",ds),Le(this,"version",gh),Le(this,"publicKey"),Le(this,"fetchPromise"),Le(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&W.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Le(this,"register",async r=>{if(!ar()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=Ss.getDocument(),d=this.startAbortTimer(W.ONE_SECOND*5),u=await new Promise((h,f)=>{const g=()=>{window.removeEventListener("message",w),l.body.removeChild(m),f("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const m=l.createElement("iframe");m.src=c,m.style.display="none",m.addEventListener("error",g,{signal:this.abortController.signal});const w=A=>{if(A.data&&typeof A.data=="string")try{const C=JSON.parse(A.data);if(C.type==="verify_attestation"){if(Go(C.attestation).payload.id!==o)return;clearInterval(d),l.body.removeChild(m),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",w),h(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};l.body.appendChild(m),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(l){this.logger.warn(l)}return""}),Le(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=r;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(Go(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(r?.verifyUrl);return this.fetchAttestation(o,c)}),Le(this,"fetchAttestation",async(r,i)=>{this.logger.debug(`resolving attestation: ${r} from url: ${i}`);const o=this.startAbortTimer(W.ONE_SECOND*5),a=await fetch(`${i}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),Le(this,"getVerifyUrl",r=>{let i=r||Rr;return k0.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Rr}`),i=Rr),i}),Le(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(W.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await i.json()}catch(r){this.logger.warn(r)}}),Le(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),Le(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Le(this,"isValidJwtAttestation",async r=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(r,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Le(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Le(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),Le(this,"validateAttestation",(r,i)=>{const o=Ky(r,i.publicKey),a={hasExpired:W.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=ct(s,this.name),this.abortController=new AbortController,this.isDevEnv=Va(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return bt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),W.toMiliseconds(e))}}var Sv=Object.defineProperty,Tv=(t,e,s)=>e in t?Sv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Zl=(t,e,s)=>Tv(t,typeof e!="symbol"?e+"":e,s);class kv extends dg{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,Zl(this,"context",O0),Zl(this,"registerDeviceToken",async n=>{const{clientId:r,token:i,notificationType:o,enableEncrypted:a=!1}=n,c=`${P0}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:i,always_raw:a})})}),this.logger=ct(s,this.context)}}var Ov=Object.defineProperty,Ql=Object.getOwnPropertySymbols,Pv=Object.prototype.hasOwnProperty,Rv=Object.prototype.propertyIsEnumerable,ka=(t,e,s)=>e in t?Ov(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,br=(t,e)=>{for(var s in e||(e={}))Pv.call(e,s)&&ka(t,s,e[s]);if(Ql)for(var s of Ql(e))Rv.call(e,s)&&ka(t,s,e[s]);return t},We=(t,e,s)=>ka(t,typeof e!="symbol"?e+"":e,s);class xv extends ug{constructor(e,s,n=!0){super(e,s,n),this.core=e,this.logger=s,We(this,"context",x0),We(this,"storagePrefix",ds),We(this,"storageVersion",R0),We(this,"events",new Map),We(this,"shouldPersist",!1),We(this,"init",async()=>{if(!Va())try{const r={eventId:Fc(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:hu(this.core.relayer.protocol,this.core.relayer.version,Ea)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),We(this,"createEvent",r=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=Fc(),d=this.core.projectId||"",u=Date.now(),h=br({eventId:l,timestamp:u,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),We(this,"getEvent",r=>{const{eventId:i,topic:o}=r;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return br(br({},a),this.setMethods(a.eventId))}),We(this,"deleteEvent",r=>{const{eventId:i}=r;this.events.delete(i),this.shouldPersist=!0}),We(this,"setEventListeners",()=>{this.core.heartbeat.on(rr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{W.fromMiliseconds(Date.now())-W.fromMiliseconds(r.timestamp)>$0&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),We(this,"setMethods",r=>({addTrace:i=>this.addTrace(r,i),setError:i=>this.setError(r,i)})),We(this,"addTrace",(r,i)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(i),this.events.set(r,o),this.shouldPersist=!0)}),We(this,"setError",(r,i)=>{const o=this.events.get(r);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),We(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),We(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(i=>{this.events.set(i.eventId,br(br({},i),this.setMethods(i.eventId)))})}catch(r){this.logger.warn(r)}}),We(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[i,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const i of r)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}}),We(this,"sendEvent",async r=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${U0}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ea}${i}`,{method:"POST",body:JSON.stringify(r)})}),We(this,"getAppDomain",()=>uu().url),this.logger=ct(s,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var $v=Object.defineProperty,ed=Object.getOwnPropertySymbols,Uv=Object.prototype.hasOwnProperty,Dv=Object.prototype.propertyIsEnumerable,Oa=(t,e,s)=>e in t?$v(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,td=(t,e)=>{for(var s in e||(e={}))Uv.call(e,s)&&Oa(t,s,e[s]);if(ed)for(var s of ed(e))Dv.call(e,s)&&Oa(t,s,e[s]);return t},Se=(t,e,s)=>Oa(t,typeof e!="symbol"?e+"":e,s);let Lv=class Oh extends Zf{constructor(e){var s;super(e),Se(this,"protocol",fh),Se(this,"version",gh),Se(this,"name",Ca),Se(this,"relayUrl"),Se(this,"projectId"),Se(this,"customStoragePrefix"),Se(this,"events",new In.EventEmitter),Se(this,"logger"),Se(this,"heartbeat"),Se(this,"relayer"),Se(this,"crypto"),Se(this,"storage"),Se(this,"history"),Se(this,"expirer"),Se(this,"pairing"),Se(this,"verify"),Se(this,"echoClient"),Se(this,"linkModeSupportedApps"),Se(this,"eventClient"),Se(this,"initialized",!1),Se(this,"logChunkController"),Se(this,"on",(a,c)=>this.events.on(a,c)),Se(this,"once",(a,c)=>this.events.once(a,c)),Se(this,"off",(a,c)=>this.events.off(a,c)),Se(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Se(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const d={topic:a,message:c,publishedAt:Date.now(),transportType:ke.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:l})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||wh,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Zr({level:typeof e?.logger=="string"&&e.logger?e.logger:s0.logger,name:Ca}),{logger:i,chunkLoggerController:o}=tu({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride: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=ct(i,this.name),this.heartbeat=new bp,this.crypto=new dE(this,this.logger,e?.keychain),this.history=new Cv(this,this.logger),this.expirer=new Av(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Cp(td(td({},n0),e?.storageOptions)),this.relayer=new LE({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new wv(this,this.logger),this.verify=new _v(this,this.logger,this.storage),this.echoClient=new kv(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new xv(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new Oh(e);await s.initialize();const n=await s.crypto.getClientId();return await s.storage.setItem(w0,n),s}get context(){return bt(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(xl,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(xl)||[],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}`,n=`${s}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[s]}catch(s){console.warn("Failed to get global WalletConnect core",s);return}}setGlobalCore(e){var s;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&t0.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const Mv=Lv,Ph="wc",Rh=2,xh="client",nc=`${Ph}@${Rh}:${xh}:`,Do={name:xh,logger:"error"},sd="WALLETCONNECT_DEEPLINK_CHOICE",Bv="proposal",nd="Proposal expired",jv="session",Dn=W.SEVEN_DAYS,Fv="engine",Ge={wc_sessionPropose:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1104},res:{ttl:W.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1106},res:{ttl:W.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1112},res:{ttl:W.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1114},res:{ttl:W.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:W.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:W.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1119}}},Lo={min:W.FIVE_MINUTES,max:W.SEVEN_DAYS},Zt={idle:"IDLE",active:"ACTIVE"},qv={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},Wv="request",Hv=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Vv="wc",Kv="auth",zv="authKeys",Gv="pairingTopics",Yv="requests",ao=`${Vv}@${1.5}:${Kv}:`,Si=`${ao}:PUB_KEY`;var Jv=Object.defineProperty,Xv=Object.defineProperties,Zv=Object.getOwnPropertyDescriptors,rd=Object.getOwnPropertySymbols,Qv=Object.prototype.hasOwnProperty,e1=Object.prototype.propertyIsEnumerable,Pa=(t,e,s)=>e in t?Jv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ie=(t,e)=>{for(var s in e||(e={}))Qv.call(e,s)&&Pa(t,s,e[s]);if(rd)for(var s of rd(e))e1.call(e,s)&&Pa(t,s,e[s]);return t},nt=(t,e)=>Xv(t,Zv(e)),x=(t,e,s)=>Pa(t,typeof e!="symbol"?e+"":e,s);class t1 extends gg{constructor(e){super(e),x(this,"name",Fv),x(this,"events",new Fa),x(this,"initialized",!1),x(this,"requestQueue",{state:Zt.idle,queue:[]}),x(this,"sessionRequestQueue",{state:Zt.idle,queue:[]}),x(this,"emittedSessionRequests",new am({limit:500})),x(this,"requestQueueDelay",W.ONE_SECOND),x(this,"expectedPairingMethodMap",new Map),x(this,"recentlyDeletedMap",new Map),x(this,"recentlyDeletedLimit",200),x(this,"relayMessageCache",[]),x(this,"pendingSessions",new Map),x(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(Ge)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},W.toMiliseconds(this.requestQueueDelay)))}),x(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=nt(Ie({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=fb(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=n;let d=r,u,h=!1;try{if(d){const b=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=b.active}}catch(b){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),b}if(!d||!h){const{topic:b,uri:R}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});d=b,u=R}if(!d){const{message:b}=q("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(b)}const f=await this.client.core.crypto.generateKeyPair(),g=Ge.wc_sessionPropose.req.ttl||W.FIVE_MINUTES,m=Me(g),w=nt(Ie(Ie({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:mh}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:d},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Os()}),A=Ae("session_connect",w.id),{reject:C,resolve:S,done:L}=an(g,nd),B=({id:b})=>{b===w.id&&(this.client.events.off("proposal_expire",B),this.pendingSessions.delete(w.id),this.events.emit(A,{error:{message:nd,code:0}}))};return this.client.events.on("proposal_expire",B),this.events.once(A,({error:b,session:R})=>{this.client.events.off("proposal_expire",B),b?C(b):R&&S(R)}),await this.sendProposeSession({proposal:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:w.id}}}),await this.setProposal(w.id,w),{uri:u,approval:L}}),x(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(n){throw this.client.logger.error("pair() failed"),n}}),x(this,"approve",async s=>{var n,r,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=s?.id)==null?void 0:n.toString(),trace:[Bs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(N){throw o.setError(mr.no_internet_connection),N}try{await this.isValidProposalId(s?.id)}catch(N){throw this.client.logger.error(`approve() -> proposal.get(${s?.id}) failed`),o.setError(mr.proposal_not_found),N}try{await this.isValidApprove(s)}catch(N){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(mr.session_approve_namespace_validation_failure),N}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=s,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:m,requiredNamespaces:w,optionalNamespaces:A}=f;let C=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});C||(C=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:Bs.session_approve_started,properties:{topic:g,trace:[Bs.session_approve_started,Bs.session_namespaces_validation_success]}}));const S=await this.client.core.crypto.generateKeyPair(),L=m.publicKey,B=await this.client.core.crypto.generateSharedKey(S,L),b=Ie(Ie(Ie({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:S,metadata:this.client.metadata},expiry:Me(Dn)},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),R=ke.relay;C.addTrace(Bs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(B,{transportType:R,internal:{skipSubscribe:!0}})}catch(N){throw C.setError(mr.subscribe_session_topic_failure),N}C.addTrace(Bs.subscribe_session_topic_success);const $=nt(Ie({},b),{topic:B,requiredNamespaces:w,optionalNamespaces:A,pairingTopic:g,acknowledged:!1,self:b.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:S,transportType:ke.relay});await this.client.session.set(B,$),C.addTrace(Bs.store_session);try{await this.sendApproveSession({sessionTopic:B,proposal:f,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:S},sessionSettleRequest:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),C.addTrace(Bs.session_approve_publish_success)}catch(N){throw this.client.logger.error(N),this.client.session.delete(B,Re("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(B),N}return this.client.core.eventClient.deleteEvent({eventId:C.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(B,Me(Dn)),{topic:B,acknowledged:()=>Promise.resolve(this.client.session.get(B))}}),x(this,"reject",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(s)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:r}=s;let i;try{i=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}i&&await this.sendError({id:n,topic:i,error:r,rpcOpts:Ge.wc_sessionPropose.reject}),await this.deleteProposal(n)}),x(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:n,namespaces:r}=s,{done:i,resolve:o,reject:a}=an(),c=Os(),l=un().toString(),d=this.client.session.get(n).namespaces;return this.events.once(Ae("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(n,{namespaces:r}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(u=>{this.client.logger.error(u),this.client.session.update(n,{namespaces:d}),a(u)}),{acknowledged:i}}),x(this,"extend",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(s)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=s,r=Os(),{done:i,resolve:o,reject:a}=an();return this.events.once(Ae("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,Me(Dn)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),x(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:r,topic:i,expiry:o=Ge.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(i);a?.transportType===ke.relay&&await this.confirmOnlineStateOrThrow();const c=Os(),l=un().toString(),{done:d,resolve:u,reject:h}=an(o,"Request expired. Please try again.");this.events.once(Ae("session_request",c),({error:w,result:A})=>{w?h(w):u(A)});const f="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:f,params:{request:nt(Ie({},r),{expiryTimestamp:Me(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>h(w)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),await d();const m={request:nt(Ie({},r),{expiryTimestamp:Me(o)}),chainId:n};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:f,params:m,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,m)}).catch(A=>h(A)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),w()}),new Promise(async w=>{var A;if(!((A=a.sessionConfig)!=null&&A.disableDeepLink)){const C=await sm(this.client.core.storage,sd);await Qg({id:c,topic:i,wcDeepLink:C})}w()}),d()]).then(w=>w[2])}),x(this,"respond",async s=>{this.isInitialized(),await this.isValidRespond(s);const{topic:n,response:r}=s,{id:i}=r,o=this.client.session.get(n);o.transportType===ke.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);fs(r)?await this.sendResult({id:i,topic:n,result:r.result,throwOnFailedPublish:!0,appLink:a}):es(r)&&await this.sendError({id:i,topic:n,error:r.error,appLink:a}),this.cleanupAfterResponse(s)}),x(this,"ping",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(s)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:n}=s;if(this.client.session.keys.includes(n)){const r=Os(),i=un().toString(),{done:o,resolve:a,reject:c}=an();this.events.once(Ae("session_ping",r),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:i}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))}),x(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:n,event:r,chainId:i}=s,o=un().toString(),a=Os();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:r,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),x(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:n}=s;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Re("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:r}=q("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(r)}}),x(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(n=>wb(n,s)))),x(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),x(this,"authenticate",async(s,n)=>{var r;this.isInitialized(),this.isValidAuthenticate(s);const i=n&&this.client.core.linkModeSupportedApps.includes(n)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=i?ke.link_mode:ke.relay;o===ke.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:d,nonce:u,type:h,exp:f,nbf:g,methods:m=[],expiry:w}=s,A=[...s.resources||[]],{topic:C,uri:S}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:C,uri:S}});const L=await this.client.core.crypto.generateKeyPair(),B=Ni(L);if(await Promise.all([this.client.auth.authKeys.set(Si,{responseTopic:B,publicKey:L}),this.client.auth.pairingTopics.set(B,{topic:B,pairingTopic:C})]),await this.client.core.relayer.subscribe(B,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),m.length>0){const{namespace:I}=Is(a[0]);let k=yw(I,"request",m);Ii(A)&&(k=Cw(k,A.pop())),A.push(k)}const b=w&&w>Ge.wc_sessionAuthenticate.req.ttl?w:Ge.wc_sessionAuthenticate.req.ttl,R={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:d,version:"1",nonce:u,iat:new Date().toISOString(),exp:f,nbf:g,resources:A},requester:{publicKey:L,metadata:this.client.metadata},expiryTimestamp:Me(b)},$={eip155:{chains:a,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},N={requiredNamespaces:{},optionalNamespaces:$,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:L,metadata:this.client.metadata},expiryTimestamp:Me(Ge.wc_sessionPropose.req.ttl),id:Os()},{done:j,resolve:Y,reject:P}=an(b,"Request expired"),E=Os(),y=Ae("session_connect",N.id),v=Ae("session_request",E),O=async({error:I,session:k})=>{this.events.off(v,D),I?P(I):k&&Y({session:k})},D=async I=>{var k,K,z;if(await this.deletePendingAuthRequest(E,{message:"fulfilled",code:0}),I.error){const ue=Re("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return I.error.code===ue.code?void 0:(this.events.off(y,O),P(I.error.message))}await this.deleteProposal(N.id),this.events.off(y,O);const{cacaos:ae,responder:oe}=I.result,ne=[],ie=[];for(const ue of ae){await Zc({cacao:ue,projectId:this.client.core.projectId})||(this.client.logger.error(ue,"Signature verification failed"),P(Re("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ue}=ue,jt=Ii(Ue.resources),ks=[ca(Ue.iss)],Qs=ji(Ue.iss);if(jt){const On=Qc(jt),np=el(jt);ne.push(...On),ks.push(...np)}for(const On of ks)ie.push(`${On}:${Qs}`)}const de=await this.client.core.crypto.generateSharedKey(L,oe.publicKey);let Te;ne.length>0&&(Te={topic:de,acknowledged:!0,self:{publicKey:L,metadata:this.client.metadata},peer:oe,controller:oe.publicKey,expiry:Me(Dn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:_l([...new Set(ne)],[...new Set(ie)]),transportType:o},await this.client.core.relayer.subscribe(de,{transportType:o}),await this.client.session.set(de,Te),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:oe.metadata}),Te=this.client.session.get(de)),(k=this.client.metadata.redirect)!=null&&k.linkMode&&(K=oe.metadata.redirect)!=null&&K.linkMode&&(z=oe.metadata.redirect)!=null&&z.universal&&n&&(this.client.core.addLinkModeSupportedApp(oe.metadata.redirect.universal),this.client.session.update(de,{transportType:ke.link_mode})),Y({auths:ae,session:Te})};this.events.once(y,O),this.events.once(v,D);let F;try{if(i){const I=ts("wc_sessionAuthenticate",R,E);this.client.core.history.set(C,I);const k=await this.client.core.crypto.encode("",I,{type:ni,encoding:Hs});F=mi(n,C,k)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:R,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:E}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:N,expiry:Ge.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:N.id})])}catch(I){throw this.events.off(y,O),this.events.off(v,D),I}return await this.setProposal(N.id,N),await this.setAuthRequest(E,{request:nt(Ie({},R),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:F??S,response:j}}),x(this,"approveSessionAuthenticate",async s=>{const{id:n,auths:r}=s,i=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[tn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw i.setError(wr.no_internet_connection),w}const o=this.getPendingAuthRequest(n);if(!o)throw i.setError(wr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||ke.relay;a===ke.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=Ni(c),u={type:Ns,receiverPublicKey:c,senderPublicKey:l},h=[],f=[];for(const w of r){if(!await Zc({cacao:w,projectId:this.client.core.projectId})){i.setError(wr.invalid_cacao);const B=Re("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:B,encodeOpts:u}),new Error(B.message)}i.addTrace(tn.cacaos_verified);const{p:A}=w,C=Ii(A.resources),S=[ca(A.iss)],L=ji(A.iss);if(C){const B=Qc(C),b=el(C);h.push(...B),S.push(...b)}for(const B of S)f.push(`${B}:${L}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(tn.create_authenticated_session_topic);let m;if(h?.length>0){m={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Me(Dn),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:_l([...new Set(h)],[...new Set(f)]),transportType:a},i.addTrace(tn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(w){throw i.setError(wr.subscribe_authenticated_session_topic_failure),w}i.addTrace(tn.subscribe_authenticated_session_topic_success),await this.client.session.set(g,m),i.addTrace(tn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(tn.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw i.setError(wr.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:m}}),x(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:n,reason:r}=s,i=this.getPendingAuthRequest(n);if(!i)throw new Error(`Could not find pending auth request with id ${n}`);i.transportType===ke.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ni(o),l={type:Ns,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:r,encodeOpts:l,rpcOpts:Ge.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),x(this,"formatAuthMessage",s=>{this.isInitialized();const{request:n,iss:r}=s;return Ou(n,r)}),x(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)}),x(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const n=this.client.core.pairing.pairings.get(s.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter(i=>{var o,a;return((o=i.peerMetadata)==null?void 0:o.url)&&((a=i.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&i.topic&&i.topic!==n.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),x(this,"deleteSession",async s=>{var n;const{topic:r,expirerHasDeleted:i=!1,emitEvent:o=!0,id:a=0}=s,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Re("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),i||this.client.core.expirer.del(r),this.client.core.storage.removeItem(sd).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,Re("USER_DISCONNECTED"))}),r===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Zt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),x(this,"deleteProposal",async(s,n)=>{if(n)try{const r=this.client.proposal.get(s);this.client.core.eventClient.getEvent({topic:r.pairingTopic})?.setError(mr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,Re("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),x(this,"deletePendingSessionRequest",async(s,n,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==s),r&&(this.sessionRequestQueue.state=Zt.idle,this.client.events.emit("session_request_expire",{id:s}))}),x(this,"deletePendingAuthRequest",async(s,n,r=!1)=>{await Promise.all([this.client.auth.requests.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)])}),x(this,"setExpiry",async(s,n)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,n),await this.client.session.update(s,{expiry:n}))}),x(this,"setProposal",async(s,n)=>{this.client.core.expirer.set(s,Me(Ge.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,n)}),x(this,"setAuthRequest",async(s,n)=>{const{request:r,pairingTopic:i,transportType:o=ke.relay}=n;this.client.core.expirer.set(s,r.expiryTimestamp),await this.client.auth.requests.set(s,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:s,pairingTopic:i,verifyContext:r.verifyContext,transportType:o})}),x(this,"setPendingSessionRequest",async s=>{const{id:n,topic:r,params:i,verifyContext:o}=s,a=i.request.expiryTimestamp||Me(Ge.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:r,params:i,verifyContext:o})}),x(this,"sendRequest",async s=>{const{topic:n,method:r,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:d,tvf:u,publishOpts:h={}}=s,f=ts(r,i,c);let g;const m=!!d;try{const C=m?Hs:mt;g=await this.client.core.crypto.encode(n,f,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),C}let w;if(Hv.includes(r)){const C=$t(JSON.stringify(f)),S=$t(g);w=await this.client.core.verify.register({id:S,decryptedId:C})}const A=Ie(Ie({},Ge[r].req),h);if(A.attestation=w,o&&(A.ttl=o),a&&(A.id=a),this.client.core.history.set(n,f),m){const C=mi(d,n,g);await global.Linking.openURL(C,this.client.name)}else A.tvf=nt(Ie({},u),{correlationId:f.id}),l?(A.internal=nt(Ie({},A.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,g,A)):this.client.core.relayer.publish(n,g,A).catch(C=>this.client.logger.error(C));return f.id}),x(this,"sendProposeSession",async s=>{const{proposal:n,publishOpts:r}=s,i=ts("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,i);const o=await this.client.core.crypto.encode(n.pairingTopic,i,{encoding:mt}),a=$t(JSON.stringify(i)),c=$t(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:o},opts:nt(Ie({},r),{publishMethod:"wc_proposeSession",attestation:l})})}),x(this,"sendApproveSession",async s=>{const{sessionTopic:n,pairingProposalResponse:r,proposal:i,sessionSettleRequest:o,publishOpts:a}=s,c=Dr(i.id,r),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:mt}),d=ts("wc_sessionSettle",o,a?.id),u=await this.client.core.crypto.encode(n,d,{encoding:mt});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:u},opts:nt(Ie({},a),{publishMethod:"wc_approveSession"})})}),x(this,"sendResult",async s=>{const{id:n,topic:r,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=Dr(n,i);let d;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const g=u?Hs:mt;d=await this.client.core.crypto.encode(r,l,nt(Ie({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let h,f;try{h=await this.client.core.history.get(r,n);const g=h.request;try{f=this.getTVFParams(n,g.params,i)}catch(m){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${m?.message}`)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${n}) failed`),g}if(u){const g=mi(c,r,d);await global.Linking.openURL(g,this.client.name)}else{const g=h.request.method,m=Ge[g].res;m.tvf=nt(Ie({},f),{correlationId:n}),o?(m.internal=nt(Ie({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,d,m)):this.client.core.relayer.publish(r,d,m).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(l)}),x(this,"sendError",async s=>{const{id:n,topic:r,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=jd(n,i);let d;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=u?Hs:mt;d=await this.client.core.crypto.encode(r,l,nt(Ie({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),f}let h;try{h=await this.client.core.history.get(r,n)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${r}, ${n}) failed`),f}if(u){const f=mi(c,r,d);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,g=a||Ge[f].res;this.client.core.relayer.publish(r,d,g)}await this.client.core.history.resolve(l)}),x(this,"cleanup",async()=>{const s=[],n=[];this.client.session.getAll().forEach(r=>{let i=!1;ss(r.expiry)&&(i=!0),this.client.core.crypto.keychain.has(r.topic)||(i=!0),i&&s.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{ss(r.expiryTimestamp)&&n.push(r.id)}),await Promise.all([...s.map(r=>this.deleteSession({topic:r})),...n.map(r=>this.deleteProposal(r))])}),x(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),x(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),x(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Zt.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=Zt.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Zt.idle}),x(this,"processRequest",async s=>{const{topic:n,payload:r,attestation:i,transportType:o,encryptedId:a}=s,c=r.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:r,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,r);case"wc_sessionPing":return await this.onSessionPingRequest(n,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),x(this,"onRelayEventResponse",async s=>{const{topic:n,payload:r,transportType:i}=s,o=(await this.client.core.history.get(n,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,r,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,r);case"wc_sessionExtend":return this.onSessionExtendResponse(n,r);case"wc_sessionPing":return this.onSessionPingResponse(n,r);case"wc_sessionRequest":return this.onSessionRequestResponse(n,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),x(this,"onRelayEventUnknownPayload",s=>{const{topic:n}=s,{message:r}=q("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),x(this,"shouldIgnorePairingRequest",s=>{const{topic:n,requestMethod:r}=s,i=this.expectedPairingMethodMap.get(n);return!i||i.includes(r)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),x(this,"onSessionProposeRequest",async s=>{const{topic:n,payload:r,attestation:i,encryptedId:o}=s,{params:a,id:c}=r;try{const l=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(ms.proposal_listener_not_found)),this.isValidConnect(Ie({},r.params));const d=a.expiryTimestamp||Me(Ge.wc_sessionPropose.req.ttl),u=Ie({id:c,pairingTopic:n,expiryTimestamp:d,attestation:i,encryptedId:o},a);await this.setProposal(c,u);const h=await this.getVerifyContext({attestationId:i,hash:$t(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});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:n,error:l,rpcOpts:Ge.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),x(this,"onSessionProposeResponse",async(s,n,r)=>{const{id:i}=n;if(fs(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const d=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(i,{sessionTopic:d,pairingTopic:s,proposalId:i,publicKey:c});const u=await this.client.core.relayer.subscribe(d,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:s})}else if(es(n)){await this.deleteProposal(i);const o=Ae("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),x(this,"onSessionSettleRequest",async(s,n)=>{const{id:r,params:i}=n;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=n.params,f=[...this.pendingSessions.values()].find(w=>w.sessionTopic===s);if(!f)return this.client.logger.error(`Pending session not found for topic ${s}`);const g=this.client.proposal.get(f.proposalId),m=nt(Ie(Ie(Ie({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),{transportType:ke.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(Ae("session_connect",f.proposalId),{session:m}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:n.id,topic:s,result:!0})}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),x(this,"onSessionSettleResponse",async(s,n)=>{const{id:r}=n;fs(n)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(Ae("session_approve",r),{})):es(n)&&(await this.client.session.delete(s,Re("USER_DISCONNECTED")),this.events.emit(Ae("session_approve",r),{error:n.error}))}),x(this,"onSessionUpdateRequest",async(s,n)=>{const{params:r,id:i}=n;try{const o=`${s}_session_update`,a=fr.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:s,error:Re("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ie({topic:s},r));try{fr.set(o,i),await this.client.session.update(s,{namespaces:r.namespaces}),await this.sendResult({id:i,topic:s,result:!0})}catch(c){throw fr.delete(o),c}this.client.events.emit("session_update",{id:i,topic:s,params:r})}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),x(this,"isRequestOutOfSync",(s,n)=>n.toString().slice(0,-3)<s.toString().slice(0,-3)),x(this,"onSessionUpdateResponse",(s,n)=>{const{id:r}=n,i=Ae("session_update",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);fs(n)?this.events.emit(Ae("session_update",r),{}):es(n)&&this.events.emit(Ae("session_update",r),{error:n.error})}),x(this,"onSessionExtendRequest",async(s,n)=>{const{id:r}=n;try{this.isValidExtend({topic:s}),await this.setExpiry(s,Me(Dn)),await this.sendResult({id:r,topic:s,result:!0}),this.client.events.emit("session_extend",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),x(this,"onSessionExtendResponse",(s,n)=>{const{id:r}=n,i=Ae("session_extend",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);fs(n)?this.events.emit(Ae("session_extend",r),{}):es(n)&&this.events.emit(Ae("session_extend",r),{error:n.error})}),x(this,"onSessionPingRequest",async(s,n)=>{const{id:r}=n;try{this.isValidPing({topic:s}),await this.sendResult({id:r,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),x(this,"onSessionPingResponse",(s,n)=>{const{id:r}=n,i=Ae("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);fs(n)?this.events.emit(Ae("session_ping",r),{}):es(n)&&this.events.emit(Ae("session_ping",r),{error:n.error})},500)}),x(this,"onSessionDeleteRequest",async(s,n)=>{const{id:r}=n;try{this.isValidDisconnect({topic:s,reason:n.params}),await Promise.all([new Promise(i=>{this.client.core.relayer.once(De.publish,async()=>{i(await this.deleteSession({topic:s,id:r}))})}),this.sendResult({id:r,topic:s,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:Re("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),x(this,"onSessionRequest",async s=>{var n,r,i;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:d}=s,{id:u,params:h}=a;try{await this.isValidRequest(Ie({topic:o},h));const f=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:$t(JSON.stringify(ts("wc_sessionRequest",h,u))),encryptedId:l,metadata:f.peer.metadata,transportType:d}),m={id:u,topic:o,params:h,verifyContext:g};await this.setPendingSessionRequest(m),d===ke.link_mode&&(n=f.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((r=f.peer.metadata.redirect)==null?void 0:r.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(f){await this.sendError({id:u,topic:o,error:f}),this.client.logger.error(f)}}),x(this,"onSessionRequestResponse",(s,n)=>{const{id:r}=n,i=Ae("session_request",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);fs(n)?this.events.emit(Ae("session_request",r),{result:n.result}):es(n)&&this.events.emit(Ae("session_request",r),{error:n.error})}),x(this,"onSessionEventRequest",async(s,n)=>{const{id:r,params:i}=n;try{const o=`${s}_session_event_${i.event.name}`,a=fr.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Ie({topic:s},i)),this.client.events.emit("session_event",{id:r,topic:s,params:i}),fr.set(o,r)}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),x(this,"onSessionAuthenticateResponse",(s,n)=>{const{id:r}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:n}),fs(n)?this.events.emit(Ae("session_request",r),{result:n.result}):es(n)&&this.events.emit(Ae("session_request",r),{error:n.error})}),x(this,"onSessionAuthenticateRequest",async s=>{var n;const{topic:r,payload:i,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:d,expiryTimestamp:u}=i.params,h=await this.getVerifyContext({attestationId:o,hash:$t(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:r,id:i.id,authPayload:d,verifyContext:h,expiryTimestamp:u};await this.setAuthRequest(i.id,{request:f,pairingTopic:r,transportType:c}),c===ke.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:i.params,id:i.id,verifyContext:h})}catch(l){this.client.logger.error(l);const d=i.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(i.params.requester.metadata,c),f={type:Ns,receiverPublicKey:d,senderPublicKey:u};await this.sendError({id:i.id,topic:r,error:l,encodeOpts:f,rpcOpts:Ge.wc_sessionAuthenticate.autoReject,appLink:h})}}),x(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),x(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Zt.idle,this.processSessionRequestQueue()},W.toMiliseconds(this.requestQueueDelay))}),x(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:n})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(i=>i.topic===s&&i.request.method==="wc_sessionRequest").forEach(i=>{const o=i.request.id,a=Ae("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ae("session_request",i.request.id),{error:n})})}),x(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Zt.active){this.client.logger.info("session request queue is already active.");return}const s=this.sessionRequestQueue.queue[0];if(!s){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(s)}catch(n){this.client.logger.error(n)}}),x(this,"emitSessionRequest",s=>{if(this.emittedSessionRequests.has(s.id)){this.client.logger.warn({id:s.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${s.id}`);return}this.sessionRequestQueue.state=Zt.active,this.emittedSessionRequests.add(s.id),this.client.events.emit("session_request",s)}),x(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const n=this.client.proposal.getAll().find(r=>r.pairingTopic===s.topic);
14n&&this.onSessionProposeRequest({topic:s.topic,payload:ts("wc_sessionPropose",nt(Ie({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),x(this,"isValidConnect",async s=>{if(!ft(s)){const{message:l}=q("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:n,requiredNamespaces:r,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=s;if(qe(n)||await this.isValidPairingTopic(n),!kb(c)){const{message:l}=q("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!qe(r)&&ls(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(!qe(i)&&ls(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),qe(o)||this.validateSessionProps(o,"sessionProperties"),!qe(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(r||{}).concat(Object.keys(i||{}));if(!Object.keys(a).every(d=>l.includes(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),x(this,"validateNamespaces",(s,n)=>{const r=Tb(s,"connect()",n);if(r)throw new Error(r.message)}),x(this,"isValidApprove",async s=>{if(!ft(s))throw new Error(q("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:n,namespaces:r,relayProtocol:i,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),l=Po(r,"approve()");if(l)throw new Error(l.message);const d=kl(c.requiredNamespaces,r,"approve()");if(d)throw new Error(d.message);if(!Be(i,!0)){const{message:u}=q("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(u)}if(qe(o)||this.validateSessionProps(o,"sessionProperties"),!qe(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(h=>u.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),x(this,"isValidReject",async s=>{if(!ft(s)){const{message:i}=q("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(i)}const{id:n,reason:r}=s;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!Pb(r)){const{message:i}=q("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(i)}}),x(this,"isValidSessionSettleRequest",s=>{if(!ft(s)){const{message:l}=q("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}
vendor: 13,410 bytes, line 14
14const{relay:n,controller:r,namespaces:i,expiry:o}=s;if(!ph(n)){const{message:l}=q("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=vb(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Po(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ss(o)){const{message:l}=q("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),x(this,"isValidUpdate",async s=>{if(!ft(s)){const{message:c}=q("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:n,namespaces:r}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const i=this.client.session.get(n),o=Po(r,"update()");if(o)throw new Error(o.message);const a=kl(i.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),x(this,"isValidExtend",async s=>{if(!ft(s)){const{message:r}=q("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(r)}const{topic:n}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),x(this,"isValidRequest",async s=>{if(!ft(s)){const{message:c}=q("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:n,request:r,chainId:i,expiry:o}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!Tl(a,i)){const{message:c}=q("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!Rb(r)){const{message:c}=q("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!Ub(a,i,r.method)){const{message:c}=q("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Bb(o,Lo)){const{message:c}=q("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Lo.min} and ${Lo.max}`);throw new Error(c)}}),x(this,"isValidRespond",async s=>{var n;if(!ft(s)){const{message:o}=q("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(o)}const{topic:r,response:i}=s;try{await this.isValidSessionTopic(r)}catch(o){throw(n=s?.response)!=null&&n.id&&this.cleanupAfterResponse(s),o}if(!xb(i)){const{message:o}=q("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}}),x(this,"isValidPing",async s=>{if(!ft(s)){const{message:r}=q("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),x(this,"isValidEmit",async s=>{if(!ft(s)){const{message:a}=q("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}const{topic:n,event:r,chainId:i}=s;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!Tl(o,i)){const{message:a}=q("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!$b(r)){const{message:a}=q("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Db(o,i,r.name)){const{message:a}=q("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),x(this,"isValidDisconnect",async s=>{if(!ft(s)){const{message:r}=q("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),x(this,"isValidAuthenticate",s=>{const{chains:n,uri:r,domain:i,nonce:o}=s;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!Be(r,!1))throw new Error("uri is required parameter");if(!Be(i,!1))throw new Error("domain is required parameter");if(!Be(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Is(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Is(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),x(this,"getVerifyContext",async s=>{const{attestationId:n,hash:r,encryptedId:i,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||Rr,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ke.link_mode){const d=this.getAppLinkIfEnabled(o,a);return c.verified.validation=d&&new URL(d).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:n,hash:r,encryptedId:i,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),x(this,"validateSessionProps",(s,n)=>{Object.values(s).forEach((r,i)=>{if(r==null){const{message:o}=q("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${r} for key ${Object.keys(s)[i]}`);throw new Error(o)}})}),x(this,"getPendingAuthRequest",s=>{const n=this.client.auth.requests.get(s);return typeof n=="object"?n:void 0}),x(this,"addToRecentlyDeleted",(s,n)=>{if(this.recentlyDeletedMap.set(s,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=i)break;this.recentlyDeletedMap.delete(o)}}}),x(this,"checkRecentlyDeleted",s=>{const n=this.recentlyDeletedMap.get(s);if(n){const{message:r}=q("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${s}`);throw new Error(r)}}),x(this,"isLinkModeEnabled",(s,n)=>{var r,i,o,a,c,l,d,u,h;return!s||n!==ke.link_mode?!1:((i=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:i.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((d=s?.redirect)==null?void 0:d.universal)!==void 0&&((u=s?.redirect)==null?void 0:u.universal)!==""&&((h=s?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),x(this,"getAppLinkIfEnabled",(s,n)=>{var r;return this.isLinkModeEnabled(s,n)?(r=s?.redirect)==null?void 0:r.universal:void 0}),x(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const n=jc(s,"topic")||"",r=decodeURIComponent(jc(s,"wc_ev")||""),i=this.client.session.keys.includes(n);i&&this.client.session.update(n,{transportType:ke.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:r,sessionExists:i})}),x(this,"registerLinkModeListeners",async()=>{var s;if(Va()||Xs()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await n.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),x(this,"getTVFParams",(s,n,r)=>{var i,o,a;if(!((i=n.request)!=null&&i.method))return{};const c={correlationId:s,rpcMethods:[n.request.method],chainId:n.chainId};try{const l=this.extractTxHashesFromResult(n.request,r);c.txHashes=l,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(o=n.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn("Error getting TVF params",l)}return c}),x(this,"isValidContractData",s=>{var n;if(!s)return!1;try{const r=s?.data||((n=s?.[0])==null?void 0:n.data);if(!r.startsWith("0x"))return!1;const i=r.slice(2);return/^[0-9a-fA-F]*$/.test(i)?i.length%2===0:!1}catch{}return!1}),x(this,"extractTxHashesFromResult",(s,n)=>{var r;try{if(!n)return[];const i=s.method,o=qv[i];if(i==="sui_signTransaction")return[tw(n.transactionBytes)];if(i==="near_signTransaction")return[Gc(n)];if(i==="near_signTransactions")return n.map(c=>Gc(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(r=n.tx_json)==null?void 0:r.hash];if(i==="polkadot_signTransaction")return[e0({transaction:s.params.transactionPayload,signature:n.signature})];if(i==="algo_signTxn")return _s(n)?n.map(c=>Yc(c)):[Yc(n)];if(i==="cosmos_signDirect")return[nw(n)];if(i==="wallet_sendCalls")return rw(n);if(typeof n=="string")return[n];const a=n[o.key];if(_s(a))return i==="solana_signAllTransactions"?a.map(c=>ew(c)):a;if(typeof a=="string")return[a]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,s=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,r]of Object.entries(s))for(const i of r)try{await this.onProviderMessageEvent({topic:n,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${i}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(De.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:n,attestation:r,transportType:i}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Si)?this.client.auth.authKeys.get(Si):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,n,{receiverPublicKey:o,encoding:i===ke.link_mode?Hs:mt});Ba(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:r,transportType:i,encryptedId:$t(n)})):ja(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:i}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:i}),await this.client.core.relayer.messages.ack(s,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(xt.expired,async e=>{const{topic:s,id:n}=fu(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,q("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,q("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(cn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(cn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Be(e,!1)){const{message:s}=q("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}=q("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(ss(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=q("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!Be(e,!1)){const{message:s}=q("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}=q("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(ss(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=q("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=q("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(Be(e,!1)){const{message:s}=q("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=q("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!Ob(e)){const{message:s}=q("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=q("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(ss(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=q("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class s1 extends kn{constructor(e,s){super(e,s,Bv,nc),this.core=e,this.logger=s}}let n1=class extends kn{constructor(e,s){super(e,s,jv,nc),this.core=e,this.logger=s}};class r1 extends kn{constructor(e,s){super(e,s,Wv,nc,n=>n.id),this.core=e,this.logger=s}}class i1 extends kn{constructor(e,s){super(e,s,zv,ao,()=>Si),this.core=e,this.logger=s}}class o1 extends kn{constructor(e,s){super(e,s,Gv,ao),this.core=e,this.logger=s}}class a1 extends kn{constructor(e,s){super(e,s,Yv,ao,n=>n.id),this.core=e,this.logger=s}}var c1=Object.defineProperty,l1=(t,e,s)=>e in t?c1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Mo=(t,e,s)=>l1(t,typeof e!="symbol"?e+"":e,s);class d1{constructor(e,s){this.core=e,this.logger=s,Mo(this,"authKeys"),Mo(this,"pairingTopics"),Mo(this,"requests"),this.authKeys=new i1(this.core,this.logger),this.pairingTopics=new o1(this.core,this.logger),this.requests=new a1(this.core,this.logger)}
14async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var u1=Object.defineProperty,h1=(t,e,s)=>e in t?u1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fe=(t,e,s)=>h1(t,typeof e!="symbol"?e+"":e,s);let p1=class $h extends fg{constructor(e){super(e),fe(this,"protocol",Ph),fe(this,"version",Rh),fe(this,"name",Do.name),fe(this,"metadata"),fe(this,"core"),fe(this,"logger"),fe(this,"events",new In.EventEmitter),fe(this,"engine"),fe(this,"session"),fe(this,"proposal"),fe(this,"pendingRequest"),fe(this,"auth"),fe(this,"signConfig"),fe(this,"on",(n,r)=>this.events.on(n,r)),fe(this,"once",(n,r)=>this.events.once(n,r)),fe(this,"off",(n,r)=>this.events.off(n,r)),fe(this,"removeListener",(n,r)=>this.events.removeListener(n,r)),fe(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),fe(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"update",async n=>{try{return await this.engine.update(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"request",async n=>{try{return await this.engine.request(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"find",n=>{try{return this.engine.find(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),fe(this,"authenticate",async(n,r)=>{try{return await this.engine.authenticate(n,r)}catch(i){throw this.logger.error(i.message),i}}),fe(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),fe(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),this.name=e?.name||Do.name,this.metadata=zg(e?.metadata),this.signConfig=e?.signConfig;const s=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Jr(Zr({level:e?.logger||Do.logger}));this.core=e?.core||new Mv(e),this.logger=ct(s,this.name),this.session=new n1(this.core,this.logger),this.proposal=new s1(this.core,this.logger),this.pendingRequest=new r1(this.core,this.logger),this.engine=new t1(this),this.auth=new d1(this.core,this.logger)}static async init(e){const s=new $h(e);return await s.initialize(),s}get context(){return bt(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const id="error",f1="wss://relay.walletconnect.org",g1="wc",m1="universal_provider",wi=`${g1}@2:${m1}:`,Uh="https://rpc.walletconnect.org/v1/",Dh="generic",w1=`${Uh}bundler`,Gn="call_status",y1=86400,rc={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function ic(t){return t==null||typeof t!="object"&&typeof t!="function"}function Lh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}
vendor: 37,941 bytes, line 14
14function Mh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const b1="[object RegExp]",Bh="[object String]",jh="[object Number]",Fh="[object Boolean]",qh="[object Arguments]",C1="[object Symbol]",E1="[object Date]",v1="[object Map]",A1="[object Set]",I1="[object Array]",N1="[object ArrayBuffer]",_1="[object Object]",S1="[object DataView]",T1="[object Uint8Array]",k1="[object Uint8ClampedArray]",O1="[object Uint16Array]",P1="[object Uint32Array]",R1="[object Int8Array]",x1="[object Int16Array]",$1="[object Int32Array]",U1="[object Float32Array]",D1="[object Float64Array]";function oc(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function L1(t,e){return Vn(t,void 0,t,new Map,e)}function Vn(t,e,s,n=new Map,r=void 0){const i=r?.(t,e,s,n);if(i!=null)return i;if(ic(t))return t;if(n.has(t))return n.get(t);if(Array.isArray(t)){const o=new Array(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=Vn(t[a],a,s,n,r);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;n.set(t,o);for(const[a,c]of t)o.set(a,Vn(c,a,s,n,r));return o}if(t instanceof Set){const o=new Set;n.set(t,o);for(const a of t)o.add(Vn(a,void 0,s,n,r));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(oc(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=Vn(t[a],a,s,n,r);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return n.set(t,o),ln(o,t,s,n,r),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return n.set(t,o),ln(o,t,s,n,r),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),ln(o,t,s,n,r),o}if(t instanceof Error){const o=new t.constructor;return n.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,ln(o,t,s,n,r),o}if(typeof t=="object"&&M1(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),ln(o,t,s,n,r),o}return t}function ln(t,e,s=t,n,r){const i=[...Object.keys(e),...Lh(e)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Vn(e[a],a,s,n,r))}}function M1(t){switch(Mh(t)){case qh:case I1:case N1:case S1:case Fh:case E1:case U1:case D1:case R1:case x1:case $1:case v1:case jh:case _1:case b1:case A1:case Bh:case C1:case T1:case k1:case O1:case P1:return!0;default:return!1}}function B1(t,e){return L1(t,(s,n,r,i)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case jh:case Bh:case Fh:{const o=new t.constructor(t?.valueOf());return ln(o,t),o}case qh:{const o={};return ln(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function od(t){return B1(t)}function ad(t){return t!==null&&typeof t=="object"&&Mh(t)==="[object Arguments]"}function cd(t){return typeof t=="object"&&t!==null}function j1(){}function F1(t){return oc(t)}function q1(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const s=t[Symbol.toStringTag];return s==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${s}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function W1(t){if(ic(t))return t;if(Array.isArray(t)||oc(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),s=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new s(t);if(t instanceof RegExp){const n=new s(t);return n.lastIndex=t.lastIndex,n}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const n=new s(t.message);return n.stack=t.stack,n.name=t.name,n.cause=t.cause,n}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const n=Object.create(e);return Object.assign(n,t)}return t}function H1(t,...e){const s=e.slice(0,-1),n=e[e.length-1];let r=t;for(let i=0;i<s.length;i++){const o=s[i];r=Ra(r,o,n,new Map)}return r}function Ra(t,e,s,n){if(ic(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return W1(n.get(e));if(n.set(e,t),Array.isArray(e)){e=e.slice();for(let i=0;i<e.length;i++)e[i]=e[i]??void 0}const r=[...Object.keys(e),...Lh(e)];for(let i=0;i<r.length;i++){const o=r[i];let a=e[o],c=t[o];if(ad(a)&&(a={...a}),ad(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=od(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 f=u[h];d[f]=c[f]}c=d}else c=[];const l=s(c,a,o,t,e,n);l!=null?t[o]=l:Array.isArray(a)||cd(c)&&cd(a)?t[o]=Ra(c,a,s,n):c==null&&q1(a)?t[o]=Ra({},a,s,n):c==null&&F1(a)?t[o]=od(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function V1(t,...e){return H1(t,...e,j1)}var K1=Object.defineProperty,z1=Object.defineProperties,G1=Object.getOwnPropertyDescriptors,ld=Object.getOwnPropertySymbols,Y1=Object.prototype.hasOwnProperty,J1=Object.prototype.propertyIsEnumerable,dd=(t,e,s)=>e in t?K1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yi=(t,e)=>{for(var s in e||(e={}))Y1.call(e,s)&&dd(t,s,e[s]);if(ld)for(var s of ld(e))J1.call(e,s)&&dd(t,s,e[s]);return t},X1=(t,e)=>z1(t,G1(e));function Wh(t,e,s){var n;const r=Is(t);return((n=e.rpcMap)==null?void 0:n[r.reference])||`${Uh}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function Z1(t){return t.includes(":")?t.split(":")[1]:t}function Hh(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function Q1(t,e){const s=Object.keys(e.namespaces).filter(r=>r.includes(t));if(!s.length)return[];const n=[];return s.forEach(r=>{const i=e.namespaces[r].accounts;n.push(...i)}),n}function ud(t){return Object.fromEntries(Object.entries(t).filter(([e,s])=>{var n,r;return((n=s?.chains)==null?void 0:n.length)&&((r=s?.chains)==null?void 0:r.length)>0}))}function bi(t={},e={}){const s=ud(hd(t)),n=ud(hd(e));return V1(s,n)}function hd(t){var e,s,n,r,i;const o={};if(!ls(t))return o;for(const[a,c]of Object.entries(t)){const l=io(a)?[a]:c.chains,d=c.methods||[],u=c.events||[],h=c.rpcMap||{},f=Hn(a);o[f]=X1(yi(yi({},o[f]),c),{chains:cs(l,(e=o[f])==null?void 0:e.chains),methods:cs(d,(s=o[f])==null?void 0:s.methods),events:cs(u,(n=o[f])==null?void 0:n.events)}),(ls(h)||ls(((r=o[f])==null?void 0:r.rpcMap)||{}))&&(o[f].rpcMap=yi(yi({},h),(i=o[f])==null?void 0:i.rpcMap))}return o}function pd(t){return t.includes(":")?t.split(":")[2]:t}function fd(t){const e={};for(const[s,n]of Object.entries(t)){const r=n.methods||[],i=n.events||[],o=n.accounts||[],a=io(s)?[s]:n.chains?n.chains:Hh(n.accounts);e[s]={chains:a,methods:r,events:i,accounts:o}}return e}function Bo(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function eA(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const Vh={},Yn=t=>Vh[t],jo=(t,e)=>{Vh[t]=e};var tA=Object.defineProperty,gd=Object.getOwnPropertySymbols,sA=Object.prototype.hasOwnProperty,nA=Object.prototype.propertyIsEnumerable,md=(t,e,s)=>e in t?tA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,wd=(t,e)=>{for(var s in e||(e={}))sA.call(e,s)&&md(t,s,e[s]);if(gd)for(var s of gd(e))nA.call(e,s)&&md(t,s,e[s]);return t};const yd="eip155",rA=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],iA=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,Fo=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,bd=t=>Object.keys(t).filter(e=>rA.includes(e)).reduce((e,s)=>(e[s]=oA(t[s]),e),{}),oA=t=>typeof t=="string"&&eA(t)?JSON.parse(t):t,aA=(t,e,s)=>{const{sessionProperties:n={},scopedProperties:r={}}=t,i={};if(!ls(r)&&!ls(n))return;const o=bd(n);for(const a of s){const c=iA(a);if(!c)continue;i[Fo(c)]=o;const l=r?.[`${yd}:${c}`];if(l){const d=l?.[`${yd}:${c}:${e}`];i[Fo(c)]=wd(wd({},i[Fo(c)]),bd(d||l))}}for(const[a,c]of Object.entries(i))Object.keys(c).length===0&&delete i[a];return Object.keys(i).length>0?i:void 0};var cA=Object.defineProperty,lA=(t,e,s)=>e in t?cA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,dA=(t,e,s)=>lA(t,e+"",s);let qo;class ac{constructor(e){dA(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,s){return await this.storage.setItem(e,s)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return qo||(qo=new ac(e)),qo}}var uA=Object.defineProperty,hA=Object.defineProperties,pA=Object.getOwnPropertyDescriptors,Cd=Object.getOwnPropertySymbols,fA=Object.prototype.hasOwnProperty,gA=Object.prototype.propertyIsEnumerable,Ed=(t,e,s)=>e in t?uA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mA=(t,e)=>{for(var s in e||(e={}))fA.call(e,s)&&Ed(t,s,e[s]);if(Cd)for(var s of Cd(e))gA.call(e,s)&&Ed(t,s,e[s]);return t},wA=(t,e)=>hA(t,pA(e));async function yA(t,e){const s=Is(t.result.capabilities.caip345.caip2),n=t.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(n.map(u=>bA(s.reference,u,e))),i=r.filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u);r.filter(u=>u.status==="rejected").forEach(u=>console.warn("Failed to fetch transaction receipt:",u.reason));const o=!i.length||i.some(u=>!u),a=i.every(u=>u?.status==="0x1"),c=i.every(u=>u?.status==="0x0"),l=i.some(u=>u?.status==="0x0");let d;return o?d=100:a?d=200:c?d=500:l&&(d=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:i,status:d}}async function bA(t,e,s){return await s(parseInt(t)).request(ts("eth_getTransactionReceipt",[e]))}async function CA({sendCalls:t,storage:e}){const s=await e.getItem(Gn);await e.setItem(Gn,wA(mA({},s),{[t.result.id]:{request:t.request,result:t.result,expiry:Me(y1)}}))}async function EA({resultId:t,storage:e}){const s=await e.getItem(Gn);if(s){delete s[t],await e.setItem(Gn,s);for(const n in s)ss(s[n].expiry)&&delete s[n];await e.setItem(Gn,s)}}async function vA({resultId:t,storage:e}){const s=await e.getItem(Gn),n=s?.[t];if(n&&!ss(n.expiry))return n;await EA({resultId:t,storage:e})}var AA=Object.defineProperty,IA=Object.defineProperties,NA=Object.getOwnPropertyDescriptors,vd=Object.getOwnPropertySymbols,_A=Object.prototype.hasOwnProperty,SA=Object.prototype.propertyIsEnumerable,xa=(t,e,s)=>e in t?AA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Wo=(t,e)=>{for(var s in e||(e={}))_A.call(e,s)&&xa(t,s,e[s]);if(vd)for(var s of vd(e))SA.call(e,s)&&xa(t,s,e[s]);return t},Ho=(t,e)=>IA(t,NA(e)),sn=(t,e,s)=>xa(t,typeof e!="symbol"?e+"":e,s);class TA{constructor(e){sn(this,"name","eip155"),sn(this,"client"),sn(this,"chainId"),sn(this,"namespace"),sn(this,"httpProviders"),sn(this,"events"),sn(this,"storage"),this.namespace=e.namespace,this.events=Yn("events"),this.client=Yn("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=ac.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s);const n=this.chainId;this.chainId=parseInt(e),this.events.emit(rc.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,s){const n=s||Wh(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ma(new Fd(n,Yn("disableProviderPing")))}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var n;const r=parseInt(Z1(s));e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[s])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}getHttpProvider(e){const s=e||this.chainId;return this.httpProviders[s]||(this.httpProviders=Ho(Wo({},this.httpProviders),{[s]:this.createHttpProvider(s)}),this.httpProviders[s])}async handleSwitchChain(e){var s,n;let r=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const i=parseInt(r,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${i}`);else throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,n,r,i,o;const a=(n=(s=e.request)==null?void 0:s.params)==null?void 0:n[0],c=((i=(r=e.request)==null?void 0:r.params)==null?void 0:i[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),d=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{},u=`${a}${c.join(",")}`,h=d?.[u];if(h)return h;let f;try{f=aA(l,a,c)}catch(m){console.warn("Failed to extract capabilities from session",m)}if(f)return f;const g=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Ho(Wo({},l.sessionProperties||{}),{capabilities:Ho(Wo({},d||{}),{[u]:g})})})}catch(m){console.warn("Failed to update session with capabilities",m)}return g}async getCallStatus(e){var s,n,r;const i=this.client.session.get(e.topic),o=(s=i.sessionProperties)==null?void 0:s.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(d){console.warn("Failed to fetch call status from bundler",d,l)}}const a=(n=i.sessionProperties)==null?void 0:n.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await vA({resultId:(r=e.request.params)==null?void 0:r[0],storage:this.storage});if(c)try{return await yA(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,s){var n;const r=new URL(e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ts("eth_getUserOperationReceipt",[(n=s.request.params)==null?void 0:n[0]]))});if(!i.ok)throw new Error(`Failed to fetch user operation receipt - ${i.status}`);return await i.json()}getBundlerUrl(e,s){return`${w1}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}async sendCalls(e){var s,n,r;const i=await this.client.request(e),o=(s=e.request.params)==null?void 0:s[0],a=i?.id,c=i?.capabilities||{},l=(n=c?.caip345)==null?void 0:n.caip2,d=(r=c?.caip345)==null?void 0:r.transactionHashes;return!a||!l||!(d!=null&&d.length)||await CA({sendCalls:{request:o,result:i},storage:this.storage}),i}}var kA=Object.defineProperty,OA=(t,e,s)=>e in t?kA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ln=(t,e,s)=>OA(t,typeof e!="symbol"?e+"":e,s);class PA{constructor(e){Ln(this,"name",Dh),Ln(this,"client"),Ln(this,"httpProviders"),Ln(this,"events"),Ln(this,"namespace"),Ln(this,"chainId"),this.namespace=e.namespace,this.events=Yn("events"),this.client=Yn("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s);const n=this.chainId;this.chainId=e,this.events.emit(rc.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return Is(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){var e,s;const n={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(r=>{var i,o;const a=Is(r),c=(o=(i=this.namespace)==null?void 0:i.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];n[a.reference]=this.createHttpProvider(r,c)}),n}getHttpProvider(e){const s=Is(e).reference,n=this.httpProviders[s];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProvider(e,s){const n=s||Wh(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ma(new Fd(n,Yn("disableProviderPing")))}}var RA=Object.defineProperty,xA=Object.defineProperties,$A=Object.getOwnPropertyDescriptors,Ad=Object.getOwnPropertySymbols,UA=Object.prototype.hasOwnProperty,DA=Object.prototype.propertyIsEnumerable,$a=(t,e,s)=>e in t?RA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Cr=(t,e)=>{for(var s in e||(e={}))UA.call(e,s)&&$a(t,s,e[s]);if(Ad)for(var s of Ad(e))DA.call(e,s)&&$a(t,s,e[s]);return t},Ci=(t,e)=>xA(t,$A(e)),Ot=(t,e,s)=>$a(t,typeof e!="symbol"?e+"":e,s);let LA=class Kh{constructor(e){Ot(this,"client"),Ot(this,"namespaces"),Ot(this,"optionalNamespaces"),Ot(this,"sessionProperties"),Ot(this,"scopedProperties"),Ot(this,"events",new Fa),Ot(this,"rpcProviders",{}),Ot(this,"session"),Ot(this,"providerOpts"),Ot(this,"logger"),Ot(this,"uri"),Ot(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Jr(Zr({level:e?.logger||id})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const s=new Kh(e);return await s.initialize(),s}async request(e,s,n){const[r,i]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Cr({},e),chainId:`${r}:${i}`,topic:this.session.topic,expiry:n})}sendAsync(e,s,n,r){const i=new Date().getTime();this.request(e,n,r).then(o=>s(null,Dr(i,o))).catch(o=>s(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Re("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,s){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:r}=await this.client.authenticate(e,s);n&&(this.uri=n,this.events.emit("display_uri",n));const i=await r();if(this.session=i.session,this.session){const o=fd(this.session.namespaces);this.namespaces=bi(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return i}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}removeListener(e,s){this.events.removeListener(e,s)}off(e,s){this.events.off(e,s)}get isWalletConnect(){return!0}async pair(e){const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});s&&(this.uri=s,this.events.emit("display_uri",s));const r=await n();this.session=r;const i=fd(r.namespaces);return this.namespaces=bi(this.namespaces,i),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,s){try{if(!this.session)return;const[n,r]=this.validateChain(e);this.getProvider(n).setDefaultChain(r,s)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(!_s(s))return;for(const n of s)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}catch(s){this.logger.warn("Failed to cleanup pending pairings",s)}}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 p1.init({core:this.providerOpts.core,logger:this.providerOpts.logger||id,relayUrl:this.providerOpts.relayUrl||f1,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(n){throw this.logger.error("Failed to get session",n),new Error(`The provided session: ${(s=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:s.topic} doesn't exist in the Sign client`)}else{const n=this.client.session.getAll();this.session=n[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(s=>Hn(s)))];jo("client",this.client),jo("events",this.events),jo("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const n=Q1(s,this.session);if(n?.length===0)return;const r=Hh(n),i=bi(this.namespaces,this.optionalNamespaces),o=Ci(Cr({},i[s]),{accounts:n,chains:r});switch(s){case"eip155":this.rpcProviders[s]=new TA({namespace:o});break;default:this.rpcProviders[s]=new PA({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var s;const{topic:n}=e;n===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:n,topic:r}=e;if(r!==((s=this.session)==null?void 0:s.topic))return;const{event:i}=n;if(i.name==="accountsChanged"){const o=i.data;o&&_s(o)&&this.events.emit("accountsChanged",o.map(pd))}else if(i.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Hn(o),l=Bo(o)!==Bo(a)?`${c}:${Bo(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var n,r;if(e!==((n=this.session)==null?void 0:n.topic))return;const{namespaces:i}=s,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Ci(Cr({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:s})}),this.client.on("session_delete",async e=>{var s;e.topic===((s=this.session)==null?void 0:s.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ci(Cr({},Re("USER_DISCONNECTED")),{data:e.topic})))}),this.on(rc.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(Ci(Cr({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Dh]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var s;this.getProvider(e).updateNamespace((s=this.session)==null?void 0:s.namespaces[e])})}setNamespaces(e){const{namespaces:s={},optionalNamespaces:n={},sessionProperties:r,scopedProperties:i}=e;this.optionalNamespaces=bi(s,n),this.sessionProperties=r,this.scopedProperties=i}validateChain(e){const[s,n]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,n];if(s&&!Object.keys(this.namespaces||{}).map(o=>Hn(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&n)return[s,n];const r=Hn(Object.keys(this.namespaces)[0]),i=this.rpcProviders[r].getDefaultChain();return[r,i]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:s,internal:n=!1}){if(!this.namespaces)return;const[r,i]=this.validateChain(e);i&&(this.updateNamespaceChain(r,i),n?(this.events.emit("chainChanged",i),this.emitAccountsChangedOnChainChange({namespace:r,currentCaipChainId:e,previousCaipChainId:s})):this.getProvider(r).setDefaultChain(i),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:s,previousCaipChainId:n}){var r,i;try{if(n===s)return;const o=(i=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:i.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(pd);if(!_s(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 n=this.namespaces[e]?e:`${e}:${s}`,r={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=s):this.namespaces[n]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,s){var n;const r=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${wi}/${e}${r}`,s)}async getFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${wi}/${e}${n}`)}async deleteFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${wi}/${e}${n}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const s=await this.client.core.storage.getKeys();for(const n of s)n.startsWith(wi)&&await this.client.core.storage.removeItem(n)}catch(s){this.logger.warn("Failed to cleanup storage",s)}}},nn=null;const ns={getSIWX(){return _.state.siwx},async initializeIfEnabled(t=p.getActiveCaipAddress()){const e=_.state.siwx;if(!(e&&t))return;const[s,n,r]=t.split(":");if(p.checkIfSupportedNetwork(s,`${s}:${n}`))try{if(_.state.remoteFeatures?.emailCapture){const o=p.getAccountData(s)?.user;await he.open({view:"DataCapture",data:{email:o?.email??void 0}});return}if(nn&&await nn,(await e.getSessions(`${s}:${n}`,r)).length)return;await he.open({view:"SIWXSignMessage"})}catch(i){console.error("SIWXUtil:initializeIfEnabled",i),le.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(i)}),await V._getClient()?.disconnect().catch(console.error),te.reset("Connect"),rs.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=_.state.siwx,e=J.getPlainAddress(p.getActiveCaipAddress()),s=li(),n=V._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!n)throw new Error("No ConnectionController client found");try{const r=await t.createMessage({chainId:s.caipNetworkId,accountAddress:e}),i=r.toString();M.getConnectorId(s.chainNamespace)===T.CONNECTOR_ID.AUTH&&te.pushTransactionStack({});const a=await n.signMessage(i);await t.addSession({data:r,message:i,signature:a}),p.setLastConnectedSIWECaipNetwork(s),he.close(),le.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){(!he.state.open||te.state.view==="ApproveTransaction")&&await he.open({view:"SIWXSignMessage"}),rs.showError("Error signing message"),le.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(r)}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){try{const t=this.getSIWX();if(t?.getRequired?.()){const s=p.getLastConnectedSIWECaipNetwork();if(s){const n=await t?.getSessions(s?.caipNetworkId,J.getPlainAddress(p.getActiveCaipAddress())||"");n&&n.length>0?await p.switchActiveNetwork(s):await V.disconnect()}else await V.disconnect()}else he.close();he.close(),le.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){console.error("SIWXUtil:cancelSignMessage",t)}},async getAllSessions(){const t=this.getSIWX(),e=p.getAllRequestedCaipNetworks(),s=[];return await Promise.all(e.map(async n=>{const r=await t?.getSessions(n.caipNetworkId,J.getPlainAddress(p.getActiveCaipAddress())||"");r&&s.push(...r)})),s},async getSessions(t){const e=_.state.siwx;let s=t?.address;if(!s){const r=p.getActiveCaipAddress();s=J.getPlainAddress(r)}let n=t?.caipNetworkId;return n||(n=p.getActiveCaipNetwork()?.caipNetworkId),e&&s&&n?e.getSessions(n,s):[]},async isSIWXCloseDisabled(){const t=this.getSIWX();if(t){const e=te.state.view==="ApproveTransaction",s=te.state.view==="SIWXSignMessage";if(e||s)return t.getRequired?.()&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:t,chainId:e,socialUri:s,preferredAccountType:n,chainNamespace:r}){const i=ns.getSIWX(),o=li();if(!i||!r.includes(T.CHAIN.EVM)||_.state.remoteFeatures?.emailCapture){const u=await t.connect({chainId:e,socialUri:s,preferredAccountType:n});return{address:u.address,chainId:u.chainId,accounts:u.accounts}}const a=`${r}:${e}`,c=await i.createMessage({chainId:a,accountAddress:"<<AccountAddress>>"}),l={accountAddress:c.accountAddress,chainId:c.chainId,domain:c.domain,uri:c.uri,version:c.version,nonce:c.nonce,notBefore:c.notBefore,statement:c.statement,resources:c.resources,requestId:c.requestId,issuedAt:c.issuedAt,expirationTime:c.expirationTime,serializedMessage:c.toString()},d=await t.connect({chainId:e,socialUri:s,siwxMessage:l,preferredAccountType:n});return l.accountAddress=d.address,l.serializedMessage=d.message||"",d.signature&&d.message&&await ns.addEmbeddedWalletSession(l,d.message,d.signature),p.setLastConnectedSIWECaipNetwork(o),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(t,e,s){if(nn)return nn;const n=ns.getSIWX();return n?(nn=n.addSession({data:t,message:e,signature:s}).finally(()=>{nn=null}),nn):Promise.resolve()},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){const n=ns.getSIWX(),r=li(),i=new Set(e.map(l=>l.split(":")[0]));if(!n||i.size!==1||!i.has("eip155"))return!1;const o=await n.createMessage({chainId:li()?.caipNetworkId||"",accountAddress:""}),a=await t.authenticate({nonce:o.nonce,domain:o.domain,uri:o.uri,exp:o.expirationTime,iat:o.issuedAt,nbf:o.notBefore,requestId:o.requestId,version:o.version,resources:o.resources,statement:o.statement,chainId:o.chainId,methods:s,chains:[o.chainId,...e.filter(l=>l!==o.chainId)]});rs.showLoading("Authenticating...",{autoClose:!1});const c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:a.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"};if(p.setAccountProp("connectedWalletInfo",c,Array.from(i)[0]),a?.auths?.length){const l=a.auths.map(d=>{const u=t.client.formatAuthMessage({request:d.p,iss:d.p.iss});return{data:{...d.p,accountAddress:d.p.iss.split(":").slice(-1).join(""),chainId:d.p.iss.split(":").slice(2,4).join(":"),uri:d.p.aud,version:d.p.version||o.version,expirationTime:d.p.exp,issuedAt:d.p.iat,notBefore:d.p.nbf},message:u,signature:d.s.s,cacao:d}});try{await n.setSessions(l),r&&p.setLastConnectedSIWECaipNetwork(r),le.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:ns.getSIWXEventProperties()})}catch(d){throw console.error("SIWX:universalProviderAuth - failed to set sessions",d),le.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:ns.getSIWXEventProperties(d)}),await t.disconnect().catch(console.error),d}finally{rs.hide()}}return!0},getSIWXEventProperties(t){const e=p.state.activeChain;if(!e)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:p.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:Lt(e)===Es.ACCOUNT_TYPES.SMART_ACCOUNT,message:t?J.parseError(t):void 0}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}},ws={EIP155:T.CHAIN.EVM,CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH"},Wr={NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700"},ConnectorImageIds:{[T.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[T.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[T.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[T.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[T.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[T.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-454
140-9e6a2b9cae00"},ConnectorNamesMap:{[T.CONNECTOR_ID.INJECTED]:"Browser Wallet",[T.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[T.CONNECTOR_ID.COINBASE]:"Coinbase",[T.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[T.CONNECTOR_ID.LEDGER]:"Ledger",[T.CONNECTOR_ID.SAFE]:"Safe"}},Ye={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,n])=>{e[`${ws.EIP155}:${s}`]=n}),e},isLowerCaseMatch(t,e){return t?.toLowerCase()===e?.toLowerCase()},getActiveNamespaceConnectedToAuth(){const t=p.state.activeChain;return T.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(e=>M.getConnectorId(e)===T.CONNECTOR_ID.AUTH&&e===t)},withRetry({conditionFn:t,intervalMs:e,maxRetries:s}){let n=0;return new Promise(r=>{async function i(){return n+=1,await t()?r(!0):n>=s?r(!1):(setTimeout(i,e),null)}i()})},userChainIdToChainNamespace(t){if(typeof t=="number")return T.CHAIN.EVM;const[e]=t.split(":");return e},getOtherAuthNamespaces(t){return t?T.AUTH_CONNECTOR_SUPPORTED_CHAINS.filter(n=>n!==t):[]},getConnectorStorageInfo(t,e){const n=U.getConnections()[e]??[];return{hasDisconnected:U.isConnectorDisconnected(t,e),hasConnected:n.some(r=>Ye.isLowerCaseMatch(r.connectorId,t))}}},MA={extractVersion(t){if(!t||typeof t!="string")return null;const e=/(?:[~^>=<]+\s*)?(?<version>\d+(?:\.\d+){0,2})(?:-[a-zA-Z]+\.\d+)?/u;return t.match(e)?.groups?.version||null},checkSDKVersion(t){this.extractVersion(t)},isValidVersion(t){return typeof t=="string"&&/^\d+\.\d+\.\d+$/u.test(t)},isOlder(t,e){const s=this.extractVersion(t),n=this.extractVersion(e);if(!s||!n)return!1;function r(a){const c=a.split(".").map(Number);for(;c.length<3;)c.push(0);return c}const i=r(s),o=r(n);for(let a=0;a<Math.max(i.length,o.length);a+=1){const c=i[a]||0,l=o[a]||0;if(c<l)return!0;if(c>l)return!1}return!1}},BA=new AbortController,Pt={EmbeddedWalletAbortController:BA,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"ORIGIN_NOT_ALLOWED"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{code:"APKT001",displayMessage:"Network Not Found",debugMessage:"The specified network is not recognized. Please ensure it is included in the `networks` array of your `createAppKit` configuration."},ORIGIN_NOT_ALLOWED:{code:"APKT002",displayMessage:"Invalid App Configuration",debugMessage:()=>`The origin ${vr()?window.origin:"unknown"} is not in your allow list. Please update your allowed domains at https://dashboard.reown.com.`},IFRAME_LOAD_FAILED:{code:"APKT003",displayMessage:"Network Error: Wallet Load Failed",debugMessage:()=>"Failed to load the embedded wallet. This may be due to network issues or server downtime. Please check your network connection and try again shortly. Contact support if the issue persists."},IFRAME_REQUEST_TIMEOUT:{code:"APKT004",displayMessage:"Wallet Request Timeout",debugMessage:()=>"The request to the embedded wallet timed out. Please check your network connection and try again shortly. Contact support if the issue persists."},UNVERIFIED_DOMAIN:{code:"APKT005",displayMessage:"Unverified Domain",debugMessage:()=>"Embedded wallet load failed. Ensure your domain is verified in https://dashboard.reown.com."},JWT_TOKEN_NOT_VALID:{code:"APKT006",displayMessage:"Session Expired",debugMessage:"Your session is invalid or expired. Please check your systemâs date and time settings, then reconnect."},INVALID_PROJECT_ID:{code:"APKT007",displayMessage:"Invalid Project ID",debugMessage:"The specified project ID is invali
14d. Please visit https://dashboard.reown.com to obtain a valid project ID."},PROJECT_ID_NOT_CONFIGURED:{code:"APKT008",displayMessage:"Project ID Missing",debugMessage:"No project ID is configured. You can create and configure a project ID at https://dashboard.reown.com."},SERVER_ERROR_APP_CONFIGURATION:{code:"APKT009",displayMessage:"Server Error",debugMessage:t=>`Unable to fetch App Configuration. ${t}. Please check your network connection and try again shortly. Contact support if the issue persists.`},RATE_LIMITED_APP_CONFIGURATION:{code:"APKT010",displayMessage:"Rate Limited",debugMessage:"You have been rate limited while retrieving App Configuration. Please wait a few minutes and try again. Contact support if the issue persists."}},ALERT_WARNINGS:{LOCAL_CONFIGURATION_IGNORED:{debugMessage:t=>`[Reown Config Notice] ${t}`},INACTIVE_NAMESPACE_NOT_CONNECTED:{code:"APKTW001",displayMessage:"Inactive Namespace Not Connected",debugMessage:(t,e)=>`An error occurred while connecting an inactive namespace ${t}: "${e}"`},INVALID_EMAIL:{code:"APKTW002",displayMessage:"Invalid Email Address",debugMessage:"Please enter a valid email address"}}},zh={TOKEN_ADDRESSES_BY_SYMBOL:{USDC:{8453:xf.asset,84532:$f.asset}},getTokenSymbolByAddress(t){if(!t)return;const[e]=Object.entries(zh.TOKEN_ADDRESSES_BY_SYMBOL).find(([s,n])=>Object.values(n).includes(t))??[];return e}},jA={createLogger(t,e="error"){const s=Zr({level:e}),{logger:n}=tu({opts:s});return n.error=(...r)=>{for(const i of r)if(i instanceof Error){t(i,...r);return}t(void 0,...r)},n}},FA="rpc.walletconnect.org";function Id(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 Vo=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","eip155:80094","eip155:80069","eip155:560048","eip155:31","eip155:2818","eip155:57054","eip155:911867","eip155:534351","eip155:1112","eip155:534352","eip155:1111","eip155:146","eip155:130","eip155:1284","eip155:30","eip155:2810","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],jn={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===FA}catch{s=!1}if(s){const n=new URL(t);return n.searchParams.has("projectId")||n.searchParams.set("projectId",e),n.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:T.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${T.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){const n=t.rpcUrls?.default?.http?.[0];return Vo.includes(e)?Id(e,s):n||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){const r=this.getChainNamespace(t),i=this.getCaipNetworkId(t),o=t.rpcUrls?.default?.http?.[0],a=this.getDefaultRpcUrl(t,i,s),c=t?.rpcUrls?.chainDefault?.http?.[0]||o,l=n?.[i]?.map(h=>h.url)||[],d=[...l,...a?[a]:[]],u=[...l];return c&&!u.includes(c)&&u.push(c),{...t,chainNamespace:r,caipNetworkId:i,assets:{imageId:Wr.NetworkImageIds[t.id],imageUrl:e?.[t.id]},rpcUrls:{...t.rpcUrls,default:{http:d},chainDefault:{http:u}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){return t.map(r=>jn.extendCaipNetwork(r,{customNetworkImageUrls:e,customRpcUrls:n,projectId:s}))},getViemTransport(t,e,s){const n=[];return s?.forEach(r=>{n.push(ai(r.url,r.config))}),Vo.includes(t.caipNetworkId)&&n.push(ai(Id(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),t?.rpcUrls?.default?.http?.forEach(r=>{n.push(ai(r))}),mc(n)},extendWagmiTransports(t,e,s){if(Vo.includes(t.caipNetworkId)){const n=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return mc([s,ai(n)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:T.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){const e=U.getActiveCaipNetworkId(),s=p.getAllRequestedCaipNetworks(),n=Array.from(p.state.chains?.keys()||[]),r=e?.split(":")[0],i=r?n.includes(r):!1,o=s?.find(c=>c.caipNetworkId===e);return i&&!o&&e?this.getUnsupportedNetwork(e):o||t||s?.[0]}},qA={ACCOUNT_TABS:[{label:"Tokens"},{label:"Activity"}],VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120},VIEWS_WITH_LEGAL_FOOTER:["Connect","ConnectWallets","OnRampTokenSelect","OnRampFiatSelect","OnRampProviders"],VIEWS_WITH_DEFAULT_FOOTER:["Networks"]},_r={filterOutDuplicatesByRDNS(t){const e=_.state.enableEIP6963?M.state.connectors:[],s=U.getRecentWallets(),n=e.map(a=>
vendor: 4,175 bytes, line 14
14a.info?.rdns).filter(Boolean),r=s.map(a=>a.rdns).filter(Boolean),i=n.concat(r);if(i.includes("io.metamask.mobile")&&J.isMobile()){const a=i.indexOf("io.metamask.mobile");i[a]="io.metamask"}return t.filter(a=>!(a?.rdns&&i.includes(String(a.rdns))||!a?.rdns&&e.some(l=>l.name===a.name)))},filterOutDuplicatesByIds(t){const e=M.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=U.getRecentWallets(),n=e.map(a=>a.explorerId),r=s.map(a=>a.id),i=n.concat(r);return t.filter(a=>!i.includes(a?.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=M.state,{featuredWalletIds:s}=_.state,n=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>(a.info?.rdns&&(o[a.info.rdns]=!0),o),{});return t.map(o=>({...o,installed:!!o.rdns&&!!n[o.rdns??""]})).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(s?.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){const s=t?.connectMethodsOrder||_.state.features?.connectMethodsOrder,n=e||M.state.connectors;if(s)return s;const{injected:r,announced:i}=Ti.getConnectorsByType(n,ee.state.recommended,ee.state.featured),o=r.filter(Ti.showConnector),a=i.filter(Ti.showConnector);return o.length||a.length?["wallet","email","social"]:qA.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&ee.state.excludedWallets.some(n=>n.rdns===t.rdns),s=!!t.name&&ee.state.excludedWallets.some(n=>Ye.isLowerCaseMatch(n.name,t.name));return e||s},markWalletsWithDisplayIndex(t){return t.map((e,s)=>({...e,display_index:s}))}},Ti={getConnectorsByType(t,e,s){const{customWallets:n}=_.state,r=U.getRecentWallets(),i=_r.filterOutDuplicateWallets(e),o=_r.filterOutDuplicateWallets(s),a=t.filter(u=>u.type==="MULTI_CHAIN"),c=t.filter(u=>u.type==="ANNOUNCED"),l=t.filter(u=>u.type==="INJECTED"),d=t.filter(u=>u.type==="EXTERNAL");return{custom:n,recent:r,external:d,multiChain:a,announced:c,injected:l,recommended:i,featured:o}},showConnector(t){const e=t.info?.rdns,s=!!e&&ee.state.excludedWallets.some(r=>!!r.rdns&&r.rdns===e),n=!!t.name&&ee.state.excludedWallets.some(r=>Ye.isLowerCaseMatch(r.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!J.isMobile()||J.isMobile()&&!e&&!V.checkInstalled())||s||n)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||n))},getIsConnectedWithWC(){return Array.from(p.state.chains.values()).some(s=>M.getConnectorId(s.namespace)===T.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:n,announced:r,injected:i,multiChain:o,external:a,overriddenConnectors:c=_.state.features?.connectorTypeOrder??[]}){const d=[{type:"walletConnect",isEnabled:!0},{type:"recent",isEnabled:n.length>0},{type:"injected",isEnabled:[...i,...r,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(g=>g.isEnabled),u=new Set(d.map(g=>g.type)),h=c.filter(g=>u.has(g)).map(g=>({type:g,isEnabled:!0})),f=d.filter(({type:g})=>!h.some(({type:w})=>w===g));return Array.from(new Set([...h,...f].map(({type:g})=>g)))},sortConnectorsByExplorerWallet(t){return[...t].sort((e,s)=>e.explorerWallet&&s.explorerWallet?(e.explorerWallet.order??0)-(s.explorerWallet.order??0):e.explorerWallet?-1:s.explorerWallet?1:0)},getAuthName({email:t,socialUsername:e,socialProvider:s}){return e?s&&s==="discord"&&e.endsWith("0")?e.slice(0,-1):e:t.length>30?`${t.slice(0,-3)}...`:t},async fetchProviderData(t){try{if(t.name==="Browser Wallet"&&!J.isMobile())return{accounts:[],chainId:void 0};if(t.id===T.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};const[e,s]=await Promise.all([t.provider?.request({method:"eth_accounts"}),t.provider?.request({method:"eth_chainId"}).then(n=>Number(n))]);return{accounts:e,chainId:s}}catch(e){return console.warn(`Failed to fetch provider data for ${t.name}`,e),{accounts:[],chainId:void 0}}},getFilteredCustomWallets(t){const e=U.getRecentWallets(),s=M.state.connectors.map(o=>
14o.info?.rdns).filter(Boolean),n=e.map(o=>o.rdns).filter(Boolean),r=s.concat(n);if(r.includes("io.metamask.mobile")&&J.isMobile()){const o=r.indexOf("io.metamask.mobile");r[o]="io.metamask"}return t.filter(o=>!r.includes(String(o?.rdns)))},hasWalletConnector(t){return M.state.connectors.some(e=>e.id===t.id||e.name===t.name)},isWalletCompatibleWithCurrentChain(t){const e=p.state.activeChain;return e&&t.chains?t.chains.some(s=>{const n=s.split(":")[0];return e===n}):!0},getFilteredRecentWallets(){return U.getRecentWallets().filter(s=>!_r.isExcluded(s)).filter(s=>!this.hasWalletConnector(s)).filter(s=>this.isWalletCompatibleWithCurrentChain(s))},getCappedRecommendedWallets(t){const{connectors:e}=M.state,{customWallets:s,featuredWalletIds:n}=_.state,r=e.find(C=>C.id==="walletConnect"),i=e.filter(C=>C.type==="INJECTED"||C.type==="ANNOUNCED"||C.type==="MULTI_CHAIN");if(!r&&!i.length&&!s?.length)return[];const o=Xo.isEmailEnabled(),a=Xo.isSocialsEnabled(),c=i.filter(C=>C.name!=="Browser Wallet"),l=n?.length||0,d=s?.length||0,u=c.length||0,h=o?1:0,f=a?1:0,g=l+d+u+h+f,w=Math.max(0,4-g);return w<=0?[]:_r.filterOutDuplicateWallets(t).slice(0,w)}};const ki=globalThis,cc=ki.ShadowRoot&&(ki.ShadyCSS===void 0||ki.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,lc=Symbol(),Nd=new WeakMap;let Gh=class{constructor(e,s,n){if(this._$cssResult$=!0,n!==lc)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=s}get styleSheet(){let e=this.o;const s=this.t;if(cc&&e===void 0){const n=s!==void 0&&s.length===1;n&&(e=Nd.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&Nd.set(s,e))}return e}toString(){return this.cssText}};const Vt=t=>new Gh(typeof t=="string"?t:t+"",void 0,lc),Vs=(t,...e)=>{const s=t.length===1?t[0]:e.reduce(((n,r,i)=>n+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+t[i+1]),t[0]);return new Gh(s,t,lc)},WA=(t,e)=>{if(cc)t.adoptedStyleSheets=e.map((s=>s instanceof CSSStyleSheet?s:s.styleSheet));else for(const s of e){const n=document.createElement("style"),r=ki.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=s.cssText,t.appendChild(n)}},_d=cc?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const n of e.cssRules)s+=n.cssText;return Vt(s)})(t):t;const{is:HA,defineProperty:VA,getOwnPropertyDescriptor:KA,getOwnPropertyNames:zA,getOwnPropertySymbols:GA,getPrototypeOf:YA}=Object,co=globalThis,Sd=co.trustedTypes,JA=Sd?Sd.emptyScript:"",XA=co.reactiveElementPolyfillSupport,$r=(t,e)=>t,Ua={toAttribute(t,e){switch(e){case Boolean:t=t?JA:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,e){let s=t;switch(e){case Boolean:s=t!==null;break;case Number:s=t===null?null:Number(t);break;case Object:case Array:try{s=JSON.parse(t)}catch{s=null}}return s}},Yh=(t,e)=>!HA(t,e),Td={attribute:!0,type:String,converter:Ua,reflect:!1,useDefault:!1,hasChanged:Yh};Symbol.metadata??=Symbol("metadata"),co.litPropertyMetadata??=new WeakMap;let Fn=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,s=Td){if(s.state&&(s.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((s=Object.create(s)).wrapped=!0),this.elementProperties.set(e,s),!s.noAccessor){const n=Symbol(),r=this.getPropertyDescriptor(e,n,s);r!==void 0&&VA(this.prototype,e,r)}}static getPropertyDescriptor(e,s,n){const{get:r,set:i}=KA(this.prototype,e)??{get(){return this[s]},set(o){this[s]=o}};return{get:r,set(o){const a=r?.call(this);i?.call(this,o),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Td}static _$Ei(){if(this.hasOwnProperty($r("elementProperties")))return;const e=YA(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty($r("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty($r("properties"))){const s=this.properties,n=[...zA(s),...GA(s)];for(const r of n)this.createProperty(r,s[r])}const e=this[Symbol.metadata];if(e!==null){const s=litPropertyMetadata.get(e);if(s!==void 0)for(const[n,r]of s)this.elementProperties.set(n,r)}this._$Eh=new Map;for(const[s,n]of this.elementProperties){const r=this._$Eu(s,n);r!==void 0&&this._$Eh.set(r,s)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const s=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const r of n)s.unshift(_d(r))}else e!==void 0&&s.push(_d(e));return s}static _$Eu(e,s){const n=s.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}
vendor: 7,000 bytes, lines 14-16
14removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,s=this.constructor.elementProperties;for(const n of s.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return WA(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,s,n){this._$AK(e,n)}_$ET(e,s){const n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&n.reflect===!0){const i=(n.converter?.toAttribute!==void 0?n.converter:Ua).toAttribute(s,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,s){const n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const i=n.getPropertyOptions(r),o=typeof i.converter=="function"?{fromAttribute:i.converter}:i.converter?.fromAttribute!==void 0?i.converter:Ua;this._$Em=r;const a=o.fromAttribute(s,i.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,s,n){if(e!==void 0){const r=this.constructor,i=this[e];if(n??=r.getPropertyOptions(e),!((n.hasChanged??Yh)(i,s)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(r._$Eu(e,n))))return;this.C(e,s,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,s,{useDefault:n,reflect:r,wrapped:i},o){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,o??s??this[e]),i!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(s=void 0),this._$AL.set(e,s)),r===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(s){Promise.reject(s)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[r,i]of this._$Ep)this[r]=i;this._$Ep=void 0}const n=this.constructor.elementProperties;if(n.size>0)for(const[r,i]of n){const{wrapped:o}=i,a=this[r];o!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,i,a)}}let e=!1;const s=this._$AL;try{e=this.shouldUpdate(s),e?(this.willUpdate(s),this._$EO?.forEach((n=>n.hostUpdate?.())),this.update(s)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(s)}willUpdate(e){}_$AE(e){this._$EO?.forEach((s=>s.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach((s=>this._$ET(s,this[s]))),this._$EM()}updated(e){}firstUpdated(e){}};Fn.elementStyles=[],Fn.shadowRootOptions={mode:"open"},Fn[$r("elementProperties")]=new Map,Fn[$r("finalized")]=new Map,XA?.({ReactiveElement:Fn}),(co.reactiveElementVersions??=[]).push("2.1.1");const dc=globalThis,Ki=dc.trustedTypes,kd=Ki?Ki.createPolicy("lit-html",{createHTML:t=>t}):void 0,Jh="$lit$",Ks=`lit$${Math.random().toFixed(9).slice(2)}$`,Xh="?"+Ks,ZA=`<${Xh}>`,An=document,Hr=()=>An.createComment(""),Vr=t=>t===null||typeof t!="object"&&typeof t!="function",uc=Array.isArray,QA=t=>uc(t)||typeof t?.[Symbol.iterator]=="function",Ko=`[ 15\f\r]`,Er=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Od=/-->/g,Pd=/>/g,rn=RegExp(`>|${Ko}(?:([^\\s"'>=/]+)(${Ko}*=${Ko}*(?:[^ 16\f\r"'\`<>=]|("|')|))|$)`,"g"),Rd=/'/g,xd=/"/g,Zh=/^(?:script|style|textarea|title)$/i,Qh=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),nN=Qh(1),rN=Qh(2),er=Symbol.for("lit-noChange"),He=Symbol.for("lit-nothing"),$d=new WeakMap,mn=An.createTreeWalker(An,129);function ep(t,e){if(!uc(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return kd!==void 0?kd.createHTML(e):e}const eI=(t,e)=>{const s=t.length-1,n=[];let r,i=e===2?"<svg>":e===3?"<math>":"",o=Er;for(let a=0;a<s;a++){const c=t[a];let l,d,u=-1,h=0;for(;h<c.length&&(o.lastIndex=h,d=o.exec(c),d!==null);)h=o.lastIndex,o===Er?d[1]==="!--"?o=Od:d[1]!==void 0?o=Pd:d[2]!==void 0?(Zh.test(d[2])&&(r=RegExp("</"+d[2],"g")),o=rn):d[3]!==void 0&&(o=rn):o===rn?d[0]===">"?(o=r??Er,u=-1):d[1]===void 0?u=-2:(u=o.lastIndex-d[2].length,l=d[1],o=d[3]===void 0?rn:d[3]==='"'?xd:Rd):o===xd||o===Rd?o=rn:o===Od||o===Pd?o=Er:(o=rn,r=void 0);const f=o===rn&&t[a+1].startsWith("/>")?" ":"";i+=o===Er?c+ZA:u>=0?(n.push(l),c.slice(0,u)+Jh+c.slice(u)+Ks+f):c+Ks+(u===-2?a:f)}return[ep(t,i+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class Kr{constructor({strings:e,_$litType$:s},n){let r;this.parts=[];let i=0,o=0;const a=e.length-1,c=this.parts,[l,d]=eI(e,s);if(this.el=Kr.createElement(l,n),mn.currentNode=this.el.content,s===2||s===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(r=mn.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const u of r.getAttributeNames())if(u.endsWith(Jh)){const h=d[o++],f=r.getAttribute(u).split(Ks),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:i,name:g[2],strings:f,ctor:g[1]==="."?sI:g[1]==="?"?nI:g[1]==="@"?rI:lo}),r.removeAttribute(u)}else u.startsWith(Ks)&&(c.push({type:6,index:i}),r.removeAttribute(u));if(Zh.test(r.tagName)){const u=r.textContent.split(Ks),h=u.length-1;if(h>0){r.textContent=Ki?Ki.emptyScript:"";for(let f=0;f<h;f++)r.append(u[f],Hr()),mn.nextNode(),c.push({type:2,index:++i});r.append(u[h],Hr())}}}else if(r.nodeType===8)if(r.data===Xh)c.push({type:2,index:i});else{let u=-1;for(;(u=r.data.indexOf(Ks,u+1))!==-1;)c.push({type:7,index:i}),u+=Ks.length-1}i++}}static createElement(e,s){const n=An.createElement("template");return n.innerHTML=e,n}}function tr(t,e,s=t,n){if(e===er)return e;let r=n!==void 0?s._$Co?.[n]:s._$Cl;const i=Vr(e)?void 0:e._$litDirective$;return r?.constructor!==i&&(r?._$AO?.(!1),i===void 0?r=void 0:(r=new i(t),r._$AT(t,s,n)),n!==void 0?(s._$Co??=[])[n]=r:s._$Cl=r),r!==void 0&&(e=tr(t,r._$AS(t,e.values),r,n)),e}class tI{constructor(e,s){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=s}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:s},parts:n}=this._$AD,r=(e?.creationScope??An).importNode(s,!0);mn.currentNode=r;let i=mn.nextNode(),o=0,a=0,c=n[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new ii(i,i.nextSibling,this,e):c.type===1?l=new c.ctor(i,c.name,c.strings,this,e):c.type===6&&(l=new iI(i,this,e)),this._$AV.push(l),c=n[++a]}o!==c?.index&&(i=mn.nextNode(),o++)}return mn.currentNode=An,r}p(e){let s=0;for(const n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,s),s+=n.strings.length-2):n._$AI(e[s])),s++}}class ii{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,s,n,r){this.type=2,this._$AH=He,this._$AN=void 0,this._$AA=e,this._$AB=s,this._$AM=n,this.options=r,this._$Cv=r?.
vendor: 10,634 bytes, line 16
16isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const s=this._$AM;return s!==void 0&&e?.nodeType===11&&(e=s.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,s=this){e=tr(this,e,s),Vr(e)?e===He||e==null||e===""?(this._$AH!==He&&this._$AR(),this._$AH=He):e!==this._$AH&&e!==er&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):QA(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==He&&Vr(this._$AH)?this._$AA.nextSibling.data=e:this.T(An.createTextNode(e)),this._$AH=e}$(e){const{values:s,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=Kr.createElement(ep(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(s);else{const i=new tI(r,this),o=i.u(this.options);i.p(s),this.T(o),this._$AH=i}}_$AC(e){let s=$d.get(e.strings);return s===void 0&&$d.set(e.strings,s=new Kr(e)),s}k(e){uc(this._$AH)||(this._$AH=[],this._$AR());const s=this._$AH;let n,r=0;for(const i of e)r===s.length?s.push(n=new ii(this.O(Hr()),this.O(Hr()),this,this.options)):n=s[r],n._$AI(i),r++;r<s.length&&(this._$AR(n&&n._$AB.nextSibling,r),s.length=r)}_$AR(e=this._$AA.nextSibling,s){for(this._$AP?.(!1,!0,s);e!==this._$AB;){const n=e.nextSibling;e.remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}}class lo{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,n,r,i){this.type=1,this._$AH=He,this._$AN=void 0,this.element=e,this.name=s,this._$AM=r,this.options=i,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=He}_$AI(e,s=this,n,r){const i=this.strings;let o=!1;if(i===void 0)e=tr(this,e,s,0),o=!Vr(e)||e!==this._$AH&&e!==er,o&&(this._$AH=e);else{const a=e;let c,l;for(e=i[0],c=0;c<i.length-1;c++)l=tr(this,a[n+c],s,c),l===er&&(l=this._$AH[c]),o||=!Vr(l)||l!==this._$AH[c],l===He?e=He:e!==He&&(e+=(l??"")+i[c+1]),this._$AH[c]=l}o&&!r&&this.j(e)}j(e){e===He?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class sI extends lo{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===He?void 0:e}}class nI extends lo{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==He)}}class rI extends lo{constructor(e,s,n,r,i){super(e,s,n,r,i),this.type=5}_$AI(e,s=this){if((e=tr(this,e,s,0)??He)===er)return;const n=this._$AH,r=e===He&&n!==He||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==He&&(n===He||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}}class iI{constructor(e,s,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=s,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){tr(this,e)}}const oI=dc.litHtmlPolyfillSupport;oI?.(Kr,ii),(dc.litHtmlVersions??=[]).push("3.3.1");const aI=(t,e,s)=>{const n=s?.renderBefore??e;let r=n._$litPart$;if(r===void 0){const i=s?.renderBefore??null;n._$litPart$=r=new ii(e.insertBefore(Hr(),i),i,void 0,s??{})}return r._$AI(t),r};const hc=globalThis;class Oi extends Fn{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=aI(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return er}}Oi._$litElement$=!0,Oi.finalized=!0,hc.litElementHydrateSupport?.({LitElement:Oi});const cI=hc.litElementPolyfillSupport;cI?.({LitElement:Oi});(hc.litElementVersions??=[]).push("4.2.1");const lI={black:"#202020",white:"#FFFFFF",white010:"rgba(255, 255, 255, 0.1)",accent010:"rgba(9, 136, 240, 0.1)",accent020:"rgba(9, 136, 240, 0.2)",accent030:"rgba(9, 136, 240, 0.3)",accent040:"rgba(9, 136, 240, 0.4)",accent050:"rgba(9, 136, 240, 0.5)",accent060:"rgba(9, 136, 240, 0.6)",accent070:"rgba(9, 136, 240, 0.7)",accent080:"rgba(9, 136, 240, 0.8)",accent090:"rgba(9, 136, 240, 0.9)",accent100:"rgba(9, 136, 240, 1.0)",accentSecondary010:"rgba(199, 185, 148, 0.1)",accentSecondary020:"rgba(199, 185, 148, 0.2)",accentSecondary030:"rgba(199, 185, 148, 0.3)",accentSecondary040:"rgba(199, 185, 148, 0.4)",accentSecondary050:"rgba(199, 185, 148, 0.5)",accentSecondary060:"rgba(199, 185, 148, 0.6)",accentSecondary070:"rgba(199, 185, 148, 0.7)",accentSecondary080:"rgba(199, 185, 148, 0.8)",accentSecondary090:"rgba(199, 185, 148, 0.9)",accentSecondary100:"rgba(199, 185, 148, 1.0)",productWalletKit:"#FFB800",productAppKit:"#FF573B",productCloud:"#0988F0",productDocumentation:"#008847",neutrals050:"#F6F6F6",neutrals100:"#F3F3F3",neutrals200:"#E9E9E9",neutrals300:"#D0D0D0",neutrals400:"#BBB",neutrals500:"#9A9A9A",neutrals600:"#6C6C6C",neutrals700:"#4F4F4F",neutrals800:"#363636",neutrals900:"#2A2A2A",neutrals1000:"#252525",semanticSuccess010:"rgba(48, 164, 107, 0.1)",semanticSuccess020:"rgba(48, 164, 107, 0.2)",semanticSuccess030:"rgba(48, 164, 107, 0.3)",semanticSuccess040:"rgba(48, 164, 107, 0.4)",semanticSuccess050:"rgba(48, 164, 107, 0.5)",semanticSuccess060:"rgba(48, 164, 107, 0.6)",semanticSuccess070:"rgba(48, 164, 107, 0.7)",semanticSuccess080:"rgba(48, 164, 107, 0.8)",semanticSuccess090:"rgba(48, 164, 107, 0.9)",semanticSuccess100:"rgba(48, 164, 107, 1.0)",semanticError010:"rgba(223, 74, 52, 0.1)",semanticError020:"rgba(223, 74, 52, 0.2)",semanticError030:"rgba(223, 74, 52, 0.3)",semanticError040:"rgba(223, 74, 52, 0.4)",semanticError050:"rgba(223, 74, 52, 0.5)",semanticError060:"rgba(223, 74, 52, 0.6)",semanticError070:"rgba(223, 74, 52, 0.7)",semanticError080:"rgba(223, 74, 52, 0.8)",semanticError090:"rgba(223, 74, 52, 0.9)",semanticError100:"rgba(223, 74, 52, 1.0)",semanticWarning010:"rgba(243, 161, 63, 0.1)",semanticWarning020:"rgba(243, 161, 63, 0.2)",semanticWarning030:"rgba(243, 161, 63, 0.3)",semanticWarning040:"rgba(243, 161, 63, 0.4)",semanticWarning050:"rgba(243, 161, 63, 0.5)",semanticWarning060:"rgba(243, 161, 63, 0.6)",semanticWarning070:"rgba(243, 161, 63, 0.7)",semanticWarning080:"rgba(243, 161, 63, 0.8)",semanticWarning090:"rgba(243, 161, 63, 0.9)",semanticWarning100:"rgba(243, 161, 63, 1.0)"},zi={core:{backgroundAccentPrimary:"#0988F0",backgroundAccentCertified:"#C7B994",backgroundWalletKit:"#FFB800",backgroundAppKit:"#FF573B",backgroundCloud:"#0988F0",backgroundDocumentation:"#008847",backgroundSuccess:"rgba(48, 164, 107, 0.20)",backgroundError:"rgba(223, 74, 52, 0.20)",backgroundWarning:"rgba(243, 161, 63, 0.20)",textAccentPrimary:"#0988F0",textAccentCertified:"#C7B994",textWalletKit:"#FFB800",textAppKit:"#FF573B",textCloud:"#0988F0",textDocumentation:"#008847",textSuccess:"#30A46B",textError:"#DF4A34",textWarning:"#F3A13F",borderAccentPrimary:"#0988F0",borderSecondary:"#C7B994",borderSuccess:"#30A46B",borderError:"#DF4A34",borderWarning:"#F3A13F",foregroundAccent010:"rgba(9, 136, 240, 0.1)",foregroundAccent020:"rgba(9, 136, 240, 0.2)",foregroundAccent040:"rgba(9, 136, 240, 0.4)",foregroundAccent060:"rgba(9, 136, 240, 0.6)",foregroundSecondary020:"rgba(199, 185, 148, 0.2)",foregroundSecondary040:"rgba(199, 185, 148, 0.4)",foregroundSecondary060:"rgba(199, 185, 148, 0.6)",iconAccentPrimary:"#0988F0",iconAccentCertified:"#C7B994",iconSuccess:"#30A46B",iconError:"#DF4A34",iconWarning:"#F3A13F",glass010:"rgba(255, 255, 255, 0.1)",zIndex:"9999"},dark:{overlay:"rgba(0, 0, 0, 0.50)",backgroundPrimary:"#202020",backgroundInvert:"#FFFFFF",textPrimary:"#FFFFFF",textSecondary:"#9A9A9A",textTertiary:"#BBBBBB",textInvert:"#202020",borderPrimary:"#2A2A2A",borderPrimaryDark:"#363636",borderSecondary:"#4F4F4F",foregroundPrimary:"#252525",foregroundSecondary:"#2A2A2A",foregroundTertiary:"#363636",iconDefault:"#9A9A9A",iconInverse:"#FFFFFF"},light:{overlay:"rgba(230 , 230, 230, 0.5)",backgroundPrimary:"#FFFFFF",borderPrimaryDark:"#E9E9E9",backgroundInvert:"#202020",textPrimary:"#202020",textSecondary:"#9A9A9A",textTertiary:"#6C6C6C",textInvert:"#FFFFFF",borderPrimary:"#E9E9E9",borderSecondary:"#D0D0D0",foregroundPrimary:"#F3F3F3",foregroundSecondary:"#E9E9E9",foregroundTertiary:"#D0D0D0",iconDefault:"#9A9A9A",iconInverse:"#202020"}},dI={1:"4px",2:"8px",10:"10px",3:"12px",4:"16px",6:"24px",5:"20px",8:"32px",16:"64px",20:"80px",32:"128px",64:"256px",128:"512px",round:"9999px"},uI={0:"0px","01":"2px",1:"4px",2:"8px",3:"12px",4:"16px",5:"20px",6:"24px",7:"28px",8:"32px",9:"36px",10:"40px",12:"48px",14:"56px",16:"64px",20:"80px",32:"128px",64:"256px"},hI={regular:"KHTeka",mono:"KHTekaMono"},pI={regular:"400",medium:"500"},fI={h1:"50px",h2:"44px",h3:"38px",h4:"32px",h5:"26px",h6:"20px",large:"16px",medium:"14px",small:"12px"},gI={"h1-regular-mono":{lineHeight:"50px",letterSpacing:"-3px"},"h1-regular":{lineHeight:"50px",letterSpacing:"-1px"},"h1-medium":{lineHeight:"50px",letterSpacing:"-0.84px"},"h2-regular-mono":{lineHeight:"44px",letterSpacing:"-2.64px"},"h2-regular":{lineHeight:"44px",letterSpacing:"-0.88px"},"h2-medium":{lineHeight:"44px",letterSpacing:"-0.88px"},"h3-regular-mono":{lineHeight:"38px",letterSpacing:"-2.28px"},"h3-regular":{lineHeight:"38px",letterSpacing:"-0.76px"},"h3-medium":{lineHeight:"38px",letterSpacing:"-0.76px"},"h4-regular-mono":{lineHeight:"32px",letterSpacing:"-1.92px"},"h4-regular":{lineHeight:"32px",letterSpacing:"-0.32px"},"h4-medium":{lineHeight:"32px",letterSpacing:"-0.32px"},"h5-regular-mono":{lineHeight:"26px",letterSpacing:"-1.56px"},"h5-regular":{lineHeight:"26px",letterSpacing:"-0.26px"},"h5-medium":{lineHeight:"26px",letterSpacing:"-0.26px"},"h6-regular-mono":{lineHeight:"20px",letterSpacing:"-1.2px"},"h6-regular":{lineHeight:"20px",letterSpacing:"-0.6px"},"h6-medium":{lineHeight:"20px",letterSpacing:"-0.6px"},"lg-regular-mono":{lineHeight:"16px",letterSpacing:"-0.96px"},"lg-regular":{lineHeight:"18px",letterSpacing:"-0.16px"},"lg-medium":{lineHeight:"18px",letterSpacing:"-0.16px"},"md-regular-mono":{lineHeight:"14px",letterSpacing:"-0.84px"},"md-regular":{lineHeight:"16px",letterSpacing:"-0.14px"},"md-medium":{lineHeight:"16px",letterSpacing:"-0.14px"},"sm-regular-mono":{lineHeight:"12px",letterSpacing:"-0.72px"},"sm-regular":{lineHeight:"14px",letterSpacing:"-0.12px"},"sm-medium":{lineHeight:"14px",letterSpacing:"-0.12px"}}
16,mI={"ease-out-power-2":"cubic-bezier(0.23, 0.09, 0.08, 1.13)","ease-out-power-1":"cubic-bezier(0.12, 0.04, 0.2, 1.06)","ease-in-power-2":"cubic-bezier(0.92, -0.13, 0.77, 0.91)","ease-in-power-1":"cubic-bezier(0.88, -0.06, 0.8, 0.96)","ease-inout-power-2":"cubic-bezier(0.77, 0.09, 0.23, 1.13)","ease-inout-power-1":"cubic-bezier(0.88, 0.04, 0.12, 1.06)"},wI={xl:"400ms",lg:"200ms",md:"125ms",sm:"75ms"},Da={colors:lI,fontFamily:hI,fontWeight:pI,textSize:fI,typography:gI,tokens:{core:zi.core,theme:zi.dark},borderRadius:dI,spacing:uI,durations:wI,easings:mI},Ud="--apkt",bs={createCSSVariables(t){const e={},s={};function n(i,o,a=""){for(const[c,l]of Object.entries(i)){const d=a?`${a}-${c}`:c;l&&typeof l=="object"&&Object.keys(l).length?(o[c]={},n(l,o[c],d)):typeof l=="string"&&(o[c]=`${Ud}-${d}`)}}function r(i,o){for(const[a,c]of Object.entries(i))c&&typeof c=="object"?(o[a]={},r(c,o[a])):typeof c=="string"&&(o[a]=`var(${c})`)}return n(t,e),r(e,s),{cssVariables:e,cssVariablesVarPrefix:s}},assignCSSVariables(t,e){const s={};function n(r,i,o){for(const[a,c]of Object.entries(r)){const l=o?`${o}-${a}`:a,d=i[a];c&&typeof c=="object"?n(c,d,l):typeof d=="string"&&(s[`${Ud}-${l}`]=d)}}return n(t,e),s},createRootStyles(t,e){const s={...Da,tokens:{...Da.tokens,theme:t==="light"?zi.light:zi.dark}},{cssVariables:n}=bs.createCSSVariables(s),r=bs.assignCSSVariables(n,s),i=bs.generateW3MVariables(e),o=bs.generateW3MOverrides(e),a=bs.generateScaledVariables(e),c=bs.generateBaseVariables(r),l={...r,...c,...i,...o,...a},d=bs.applyColorMixToVariables(e,l),u={...l,...d};return`:root {${Object.entries(u).map(([f,g])=>`${f}:${g.replace("/[:;{}</>]/g","")};`).join("")}}`},generateW3MVariables(t){if(!t)return{};const e={};return e["--w3m-font-family"]=t["--w3m-font-family"]||"KHTeka",e["--w3m-accent"]=t["--w3m-accent"]||"#0988F0",e["--w3m-color-mix"]=t["--w3m-color-mix"]||"#000",e["--w3m-color-mix-strength"]=`${t["--w3m-color-mix-strength"]||0}%`,e["--w3m-font-size-master"]=t["--w3m-font-size-master"]||"10px",e["--w3m-border-radius-master"]=t["--w3m-border-radius-master"]||"4px",e},generateW3MOverrides(t){if(!t)return{};const e={};if(t["--w3m-accent"]){const s=t["--w3m-accent"];e["--apkt-tokens-core-iconAccentPrimary"]=s,e["--apkt-tokens-core-borderAccentPrimary"]=s,e["--apkt-tokens-core-textAccentPrimary"]=s,e["--apkt-tokens-core-backgroundAccentPrimary"]=s}return t["--w3m-font-family"]&&(e["--apkt-fontFamily-regular"]=t["--w3m-font-family"]),t["--w3m-z-index"]&&(e["--apkt-tokens-core-zIndex"]=`${t["--w3m-z-index"]}`),e},generateScaledVariables(t){if(!t)return{};const e={};if(t["--w3m-font-size-master"]){const s=parseFloat(t["--w3m-font-size-master"].replace("px",""));e["--apkt-textSize-h1"]=`${Number(s)*5}px`,e["--apkt-textSize-h2"]=`${Number(s)*4.4}px`,e["--apkt-textSize-h3"]=`${Number(s)*3.8}px`,e["--apkt-textSize-h4"]=`${Number(s)*3.2}px`,e["--apkt-textSize-h5"]=`${Number(s)*2.6}px`,e["--apkt-textSize-h6"]=`${Number(s)*2}px`,e["--apkt-textSize-large"]=`${Number(s)*1.6}px`,e["--apkt-textSize-medium"]=`${Number(s)*1.4}px`,e["--apkt-textSize-small"]=`${Number(s)*1.2}px`}if(t["--w3m-border-radius-master"]){const s=parseFloat(t["--w3m-border-radius-master"].replace("px",""));e["--apkt-borderRadius-1"]=`${Number(s)}px`,e["--apkt-borderRadius-2"]=`${Number(s)*2}px`,e["--apkt-borderRadius-3"]=`${Number(s)*3}px`,e["--apkt-borderRadius-4"]=`${Number(s)*4}px`,e["--apkt-borderRadius-5"]=`${Number(s)*5}px`,e["--apkt-borderRadius-6"]=`${Number(s)*6}px`,e["--apkt-borderRadius-8"]=`${Number(s)*8}px`,e["--apkt-borderRadius-16"]=`${Number(s)*16}px`,e["--apkt-borderRadius-20"]=`${Number(s)*20}px`,e["--apkt-borderRadius-32"]=`${Number(s)*32}px`,e["--apkt-borderRadius-64"]=`${Number(s)*64}px`,e["--apkt-borderRadius-128"]=`${Number(s)*128}px`}return e},generateColorMixCSS(t,e){if(!t?.["--w3m-color-mix"]||!t["--w3m-color-mix-strength"])return"";const s=t["--w3m-color-mix"],n=t["--w3m-color-mix-strength"];if(!n||n===0)return"";const r=Object.keys(e||{}).filter(o=>{const a=o.includes("-tokens-core-background")||o.includes("-tokens-core-text")||o.includes("-tokens-core-border")||o.includes("-tokens-core-foreground")||o.includes("-tokens-core-icon")||o.includes("-tokens-theme-background")||o.includes("-tokens-theme-text")||o.includes("-tokens-theme-border")||o.includes("-tokens-theme-foreground")||o.includes("-tokens-theme-icon"),c=o.includes("-borderRadius-")||o.includes("-spacing-")||o.includes("-textSize-")||o.includes("-fontFamily-")||o.includes("-fontWeight-")||o.includes("-typography-")||o.includes("-duration-")||o.includes("-ease-")||o.includes("-path-")||o.includes("-width-")||o.includes("-height-")||o.includes("-visual-size-")||o.includes("-modal-width")||o.includes("-cover");return a&&!c});return r.length===0?"":` @supports (background: color-mix(in srgb, white 50%, black)) { 17 :root { 18 ${r.map(o=>{const a=e?.[o]||"";return a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?`${o}: color-mix(in srgb, ${s} ${n}%, ${a});`:`${o}: color-mix(in srgb, ${s} ${n}%, var(${o}-base, ${a}));`}).join("")} 19 } 20 }`},generateBaseVariables(t){const e={},s=t["--apkt-tokens-theme-backgroundPrimary"];s&&(e["--apkt-tokens-theme-backgroundPrimary-base"]=s);const n=t["--apkt-tokens-core-backgroundAccentPrimary"];return n&&(e["--apkt-tokens-core-backgroundAccentPrimary-base"]=n),e},applyColorMixToVariables(t,e){const s={};if(e?.["--apkt-tokens-theme-backgroundPrimary"]&&(s["--apkt-tokens-theme-backgroundPrimary"]="var(--apkt-tokens-theme-backgroundPrimary-base)"),e?.["--apkt-tokens-core-backgroundAccentPrimary"]&&(s["--apkt-tokens-core-backgroundAccentPrimary"]="var(--apkt-tokens-core-backgroundAccentPrimary-base)"),!t?.["--w3m-color-mix"]||!t["--w3m-color-mix-strength"])return s;const n=t["--w3m-color-mix"],r=t["--w3m-color-mix-strength"];if(!r||r===0)return s;const i=Object.keys(e||{}).filter(o=>{const a=o.includes("-tokens-core-background")||o.includes("-tokens-core-text")||o.includes("-tokens-core-border")||o.includes("-tokens-core-foreground")||o.includes("-tokens-core-icon")||o.includes("-tokens-theme-background")||o.includes("-tokens-theme-text")||o.includes("-tokens-theme-border")||o.includes("-tokens-theme-foreground")||o.includes("-tokens-theme-icon")||o.includes("-tokens-theme-overlay"),c=o.includes("-borderRadius-")||o.includes("-spacing-")||o.includes("-textSize-")||o.includes("-fontFamily-")||o.includes("-fontWeight-")||o.includes("-typography-")||o.includes("-duration-")||o.includes("-ease-")||o.includes("-path-")||o.includes("-width-")||o.includes("-height-")||o.includes("-visual-size-")||o.includes("-modal-width")||o.includes("-cover");return a&&!c});
20return i.length===0||i.forEach(o=>{const a=e?.[o]||"";o.endsWith("-base")||(o==="--apkt-tokens-theme-backgroundPrimary"||o==="--apkt-tokens-core-backgroundAccentPrimary"?s[o]=`color-mix(in srgb, ${n} ${r}%, var(${o}-base))`:a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?s[o]=`color-mix(in srgb, ${n} ${r}%, ${a})`:s[o]=`color-mix(in srgb, ${n} ${r}%, var(${o}-base, ${a}))`)}),s}},{cssVariablesVarPrefix:yI}=bs.createCSSVariables(Da);function iN(t,...e){return Vs(t,...e.map(s=>Vt(typeof s=="function"?s(yI):s)))}let dn,wn,os,Kt,Gi;const ys={"KHTeka-500-woff2":"https://fonts.reown.com/KHTeka-Medium.woff2","KHTeka-400-woff2":"https://fonts.reown.com/KHTeka-Regular.woff2","KHTeka-300-woff2":"https://fonts.reown.com/KHTeka-Light.woff2","KHTekaMono-400-woff2":"https://fonts.reown.com/KHTekaMono-Regular.woff2","KHTeka-500-woff":"https://fonts.reown.com/KHTeka-Light.woff","KHTeka-400-woff":"https://fonts.reown.com/KHTeka-Regular.woff","KHTeka-300-woff":"https://fonts.reown.com/KHTeka-Light.woff","KHTekaMono-400-woff":"https://fonts.reown.com/KHTekaMono-Regular.woff"};function Yi(t,e="dark"){dn&&document.head.removeChild(dn),dn=document.createElement("style"),dn.textContent=bs.createRootStyles(e,t),document.head.appendChild(dn)}function oN(t,e="dark"){if(Gi=t,wn=document.createElement("style"),os=document.createElement("style"),Kt=document.createElement("style"),wn.textContent=Jn(t).core.cssText,os.textContent=Jn(t).dark.cssText,Kt.textContent=Jn(t).light.cssText,document.head.appendChild(wn),document.head.appendChild(os),document.head.appendChild(Kt),Yi(t,e),La(e),!t?.["--w3m-font-family"])for(const[s,n]of Object.entries(ys)){const r=document.createElement("link");r.rel="preload",r.href=n,r.as="font",r.type=s.includes("woff2")?"font/woff2":"font/woff",r.crossOrigin="anonymous",document.head.appendChild(r)}La(e)}function La(t="dark"){os&&Kt&&dn&&(t==="light"?(Yi(Gi,t),os.removeAttribute("media"),Kt.media="enabled"):(Yi(Gi,t),Kt.removeAttribute("media"),os.media="enabled"))}function bI(t){if(Gi=t,wn&&os&&Kt&&(wn.textContent=Jn(t).core.cssText,os.textContent=Jn(t).dark.cssText,Kt.textContent=Jn(t).light.cssText,t?.["--w3m-font-family"])){const e=t["--w3m-font-family"];wn.textContent=wn.textContent?.replace("font-family: KHTeka",`font-family: ${e}`),os.textContent=os.textContent?.replace("font-family: KHTeka",`font-family: ${e}`),Kt.textContent=Kt.textContent?.replace("font-family: KHTeka",`font-family: ${e}`)}if(dn){const e=Kt?.media==="enabled"?"light":"dark";Yi(t,e)}}function Jn(t){const e=!!t?.["--w3m-font-family"];return{core:Vs` 21 ${e?Vs``:Vs` 22 @font-face { 23 font-family: 'KHTeka'; 24 src: 25 url(${Vt(ys["KHTeka-400-woff2"])}) format('woff2'), 26 url(${Vt(ys["KHTeka-400-woff"])}) format('woff'); 27 font-weight: 400; 28 font-style: normal; 29 font-display: swap; 30 } 31 32 @font-face { 33 font-family: 'KHTeka'; 34 src: 35 url(${Vt(ys["KHTeka-300-woff2"])}) format('woff2'), 36 url(${Vt(ys["KHTeka-300-woff"])}) format('woff'); 37 font-weight: 300; 38 font-style: normal; 39 } 40 41 @font-face { 42 font-family: 'KHTekaMono'; 43 src: 44 url(${Vt(ys["KHTekaMono-400-woff2"])}) format('woff2'), 45 url(${Vt(ys["KHTekaMono-400-woff"])}) format('woff'); 46 font-weight: 400; 47 font-style: normal; 48 } 49 50 @font-face { 51 font-family: 'KHTeka'; 52 src: 53 url(${Vt(ys["KHTeka-400-woff2"])}) format('woff2'), 54 url(${Vt(ys["KHTeka-400-woff"])}) format('woff'); 55 font-weight: 400; 56 font-style: normal; 57 } 58 `} 59 60 @keyframes w3m-shake { 61 0% { 62 transform: scale(1) rotate(0deg); 63 } 64 20% { 65 transform: scale(1) rotate(-1deg); 66 } 67 40% { 68 transform: scale(1) rotate(1.5deg); 69 } 70 60% { 71 transform: scale(1) rotate(-1.5deg); 72 } 73 80% { 74 transform: scale(1) rotate(1deg); 75 } 76 100% { 77 transform: scale(1) rotate(0deg); 78 } 79 } 80 @keyframes w3m-iframe-fade-out { 81 0% { 82 opacity: 1; 83 } 84 100% { 85 opacity: 0; 86 } 87 } 88 @keyframes w3m-iframe-zoom-in { 89 0% { 90 transform: translateY(50px); 91 opacity: 0; 92 } 93 100% { 94 transform: translateY(0px); 95 opacity: 1; 96 } 97 } 98 @keyframes w3m-iframe-zoom-in-mobile { 99 0% { 100 transform: scale(0.95); 101 opacity: 0; 102 } 103 100% { 104 transform: scale(1); 105 opacity: 1; 106 } 107 } 108 :root { 109 --apkt-modal-width: 370px; 110 111 --apkt-visual-size-inherit: inherit; 112 --apkt-visual-size-sm: 40px; 113 --apkt-visual-size-md: 55px; 114 --apkt-visual-size-lg: 80px; 115 116 --apkt-path-network-sm: path( 117 '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.
11761 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' 118 ); 119 120 --apkt-path-network-md: path( 121 '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' 122 ); 123 124 --apkt-path-network-lg: path( 125 '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' 126 ); 127 128 --apkt-width-network-sm: 36px; 129 --apkt-width-network-md: 48px; 130 --apkt-width-network-lg: 86px; 131 132 --apkt-duration-dynamic: 0ms; 133 --apkt-height-network-sm: 40px; 134 --apkt-height-network-md: 54px; 135 --apkt-height-network-lg: 96px; 136 } 137 `,dark:Vs` 138 :root { 139 } 140 `,light:Vs` 141 :root { 142 } 143 `}}const aN=Vs` 144 div, 145 span, 146 iframe, 147 a, 148 img, 149 form, 150 button, 151 label, 152 *::after, 153 *::before { 154 margin: 0; 155 padding: 0; 156 box-sizing: border-box; 157 font-style: normal; 158 text-rendering: optimizeSpeed; 159 -webkit-font-smoothing: antialiased; 160 -moz-osx-font-smoothing: grayscale; 161 -webkit-tap-highlight-color: transparent; 162 backface-visibility: hidden; 163 } 164 165 :host { 166 font-family: var(--apkt-fontFamily-regular); 167 } 168`,cN=Vs` 169 button, 170 a { 171 cursor: pointer; 172 display: flex; 173 justify-content: center; 174 align-items: center; 175 position: relative; 176 177 will-change: background-color, color, border, box-shadow, width, height, transform, opacity; 178 outline: none; 179 border: none; 180 text-decoration: none; 181 transition: 182 background-color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), 183 color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), 184 border var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), 185 box-shadow var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), 186 width var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), 187 height var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), 188 transform var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), 189 opacity var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), 190 scale var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2), 191 border-radius var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2); 192 will-change: 193 background-color, color, border, box-shadow, width, height, transform, opacity, scale, 194 border-radius; 195 } 196 197 a:active:not([disabled]), 198 button:active:not([disabled]) { 199 scale: 0.975; 200 transform-origin: center; 201 } 202 203 button:disabled { 204 cursor: default; 205 } 206 207 input { 208 border: none; 209 outline: none; 210 appearance: none; 211 } 212`,Pi={hexStringToNumber(t){const e=t.startsWith("0x")?t.slice(2):t;return parseInt(e,16)},numberToHexString(t){return`0x${t.toString(16)}`},async getUserInfo(t){const[e,s]=await Promise.all([Pi.getAddresses(t),Pi.getChainId(t)]);return{chainId:s,addresses:e}},async getChainId(t){const e=await t.request({method:"eth_chainId"});return Number(e)},async getAddress(t){const[e]=await t.request({method:"eth_accounts"});return e},async getAddresses(t){return await t.request({method:"eth_accounts"})},async addEthereumChain(t,e){const s=e.rpcUrls.chainDefault?.http||[];await t.request({method:"wallet_addEthereumChain",params:[{chainId:Pi.numberToHexString(e.id),rpcUrls:[...s],chainName:e.name,nativeCurrency:{name:e.nativeCurrency.name,decimals:e.nativeCurrency.decimals,symbol:e.nativeCurrency.symbol},blockExplorerUrls:[e.blockExplorers?.default.url],iconUrls:[Wr.NetworkImageIds[e.id]]}]})}},Mn={ACCOUNT_INDEXES:{PAYMENT:0,ORDINAL:1}};function lr(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const Dd=lr({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"}
212),Ld=lr({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"});lr({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"});lr({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});lr({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});lr({id:"00000008819873e925422c1ff0f99f7c",caipNetworkId:"bip122:00000008819873e925422c1ff0f99f7c",chainNamespace:"bip122",name:"Bitcoin Signet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const CI={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"]},Gt={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace(t){return CI[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const s={...t},n=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>n.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>n.add(r)),e.events&&Object.keys(e.events).forEach(r=>n.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[i]=r.split(":");i&&n.add(i)}),n.forEach(r=>{s[r]||(s[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,i])=>{s[r]&&(s[r].methods=i)}),e.chains&&Object.entries(e.chains).forEach(([r,i])=>{s[r]&&(s[r].chains=i)}),e.events&&Object.entries(e.events).forEach(([r,i])=>{s[r]&&(s[r].events=i)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([i,o])=>{const[a,c]=i.split(":");!a||!c||!s[a]||(s[a].rpcMap||(s[a].rpcMap={}),r.has(a)||(s[a].rpcMap={},r.add(a)),s[a].rpcMap[c]=o)})}return s},createNamespaces(t,e){const s=t.reduce((n,r)=>{const{id:i,chainNamespace:o,rpcUrls:a}=r,c=a.default.http[0];n[o]||(n[o]=this.createDefaultNamespace(o));const l=`${o}:${i}`,d=n[o];switch(d.chains.push(l),l){case Dd.caipNetworkId:d.chains.push(Dd.deprecatedCaipNetworkId);break;case Ld.caipNetworkId:d.chains.push(Ld.deprecatedCaipNetworkId);break}return d?.rpcMap&&c&&(d.rpcMap[i]=c),n},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{const e=await Or.resolveName(t);return(Object.values(e?.addresses)||[])[0]?.address||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],n=e.accounts.map(r=>{const[i,o]=r.split(":");return`${i}:${o}`});return Array.from(new Set([...s,...n]))})}
212,isSessionEventData(t){return typeof t=="object"&&t!==null&&"id"in t&&"topic"in t&&"params"in t&&typeof t.params=="object"&&t.params!==null&&"chainId"in t.params&&"event"in t.params&&typeof t.params.event=="object"&&t.params.event!==null},isUserRejectedRequestError(t){try{if(typeof t=="object"&&t!==null){const e=t,s=typeof e.code=="number",n=s&&e.code===Gt.RPC_ERROR_CODE.USER_REJECTED_METHODS,r=s&&e.code===Gt.RPC_ERROR_CODE.USER_REJECTED;return n||r}return!1}catch{return!1}},isOriginAllowed(t,e,s){for(const n of[...e,...s])if(n.includes("*")){const i=`^${n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(i,"u").test(t))return!0}else try{if(new URL(n).origin===t)return!0}catch{if(n===t)return!0}return!1},listenWcProvider({universalProvider:t,namespace:e,onConnect:s,onDisconnect:n,onAccountsChanged:r,onChainChanged:i,onDisplayUri:o}){s&&t.on("connect",()=>{const a=Gt.getWalletConnectAccounts(t,e);s(a)}),n&&t.on("disconnect",()=>{n()}),r&&t.on("accountsChanged",a=>{try{const c=t.session?.namespaces?.[e]?.accounts||[],l=t.rpcProviders?.[e]?.getDefaultChain(),d=a.map(u=>{const h=c.find(m=>m.includes(`${e}:${l}:${u}`));if(!h)return;const{chainId:f,chainNamespace:g}=it.parseCaipAddress(h);return{address:u,chainId:f,chainNamespace:g}}).filter(u=>u!==void 0);d.length>0&&r(d)}catch(c){console.warn("Failed to parse accounts for namespace on accountsChanged event",e,a,c)}}),i&&t.on("chainChanged",a=>{i(a)}),o&&t.on("display_uri",a=>{o(a)})},getWalletConnectAccounts(t,e){const s=new Set,n=t?.session?.namespaces?.[e]?.accounts?.map(r=>it.parseCaipAddress(r)).filter(({address:r})=>s.has(r.toLowerCase())?!1:(s.add(r.toLowerCase()),!0));return n&&n.length>0?n:[]}};class EI{constructor(e){this.namespace=e.namespace}async syncConnections(e){switch(this.namespace){case T.CHAIN.EVM:await this.syncEVMConnections(e);break;case T.CHAIN.SOLANA:await this.syncSolanaConnections(e);break;case T.CHAIN.BITCOIN:await this.syncBitcoinConnections(e);break;default:throw new Error(`Unsupported chain namespace: ${this.namespace}`)}}async syncEVMConnections({connectors:e,caipNetworks:s,universalProvider:n,onConnection:r,onListenProvider:i}){await Promise.all(e.filter(o=>{const{hasDisconnected:a,hasConnected:c}=Ye.getConnectorStorageInfo(o.id,this.namespace);return!a&&c}).map(async o=>{if(o.id===T.CONNECTOR_ID.WALLET_CONNECT){const a=Gt.getWalletConnectAccounts(n,this.namespace),c=s.find(l=>l.chainNamespace===this.namespace&&l.id.toString()===a[0]?.chainId?.toString());a.length>0&&r({connectorId:o.id,accounts:a.map(l=>({address:l.address})),caipNetwork:c})}else{const{accounts:a,chainId:c}=await Ti.fetchProviderData(o);if(a.length>0&&c){const l=s.find(d=>d.chainNamespace===this.namespace&&d.id.toString()===c.toString());r({connectorId:o.id,accounts:a.map(d=>({address:d})),caipNetwork:l}),o.provider&&o.id!==T.CONNECTOR_ID.AUTH&&o.id!==T.CONNECTOR_ID.WALLET_CONNECT&&i(o.id,o.provider)}}}))}async syncSolanaConnections({connectors:e,caipNetwork:s,universalProvider:n,onConnection:r,onListenProvider:i}){await Promise.all(e.filter(o=>{const{hasDisconnected:a,hasConnected:c}=Ye.getConnectorStorageInfo(o.id,this.namespace);return!a&&c}).map(async o=>{if(o.id===T.CONNECTOR_ID.WALLET_CONNECT){const a=Gt.getWalletConnectAccounts(n,this.namespace);a.length>0&&r({connectorId:o.id,accounts:a.map(c=>({address:c.address})),caipNetwork:s})}else{const a=await o.connect({chainId:s?.id});a&&(r({connectorId:o.id,accounts:[{address:a}],caipNetwork:s}),i(o.id,o.provider))}}))}async syncBitcoinConnections({connectors:e,caipNetwork:s,universalProvider:n,onConnection:r,onListenProvider:i}){await Promise.all(e.filter(o=>{const{hasDisconnected:a,hasConnected:c}=Ye.getConnectorStorageInfo(o.id,this.namespace);return!a&&c}).map(async o=>{if(o.id===T.CONNECTOR_ID.WALLET_CONNECT){const u=Gt.getWalletConnectAccounts(n,this.namespace);u.length>0&&r({connectorId:o.id,accounts:u.map(h=>({address:h.address})),caipNetwork:s});return}const a=await o.connect();let l=(await o.getAccountAddresses())?.map(u=>J.createAccount(T.CHAIN.BITCOIN,u.address,u.purpose||"payment",u.publicKey,u.path));if(l&&l.length>1&&(l=[{namespace:T.CHAIN.BITCOIN,publicKey:l[Mn.ACCOUNT_INDEXES.PAYMENT]?.publicKey??"",path:l[Mn.ACCOUNT_INDEXES.PAYMENT]?.path??"",address:l[Mn.ACCOUNT_INDEXES.PAYMENT]?.address??"",type:"payment"},{namespace:T.CHAIN.BITCOIN,publicKey:l[Mn.ACCOUNT_INDEXES.ORDINAL]?.publicKey??"",path:l[Mn.ACCOUNT_INDEXES.ORDINAL]?.path??"",address:l[Mn.ACCOUNT_INDEXES.ORDINAL]?.address??"",type:"ordinal"}
212]),!(o.chains.find(u=>u.id===s?.id)||o.chains[0]))throw new Error("The connector does not support any of the requested chains");a&&(i(o.id,o.provider),r({connectorId:o.id,accounts:l.map(u=>({address:u.address,type:u.type,publicKey:u.publicKey,path:u.path})),caipNetwork:s}))}))}getConnection({address:e,connectorId:s,connections:n,connectors:r}){if(s){const o=n.find(l=>Ye.isLowerCaseMatch(l.connectorId,s));if(!o)return null;const a=r.find(l=>Ye.isLowerCaseMatch(l.id,o.connectorId)),c=e?o.accounts.find(l=>Ye.isLowerCaseMatch(l.address,e)):o.accounts[0];return{...o,account:c,connector:a}}const i=n.find(o=>o.accounts.length>0&&r.some(a=>Ye.isLowerCaseMatch(a.id,o.connectorId)));if(i){const[o]=i.accounts,a=r.find(c=>Ye.isLowerCaseMatch(c.id,i.connectorId));return{...i,account:o,connector:a}}return null}}const Sr={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]};class tp{constructor({provider:e,namespace:s}){this.id=T.CONNECTOR_ID.WALLET_CONNECT,this.name=Wr.ConnectorNamesMap[T.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Wr.ConnectorImageIds[T.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(),n=_.state.universalProviderConfigOverride,r=Gt.createNamespaces(s,n);await this.provider.connect({optionalNamespaces:r})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(s=>s.caipNetworkId);return ns.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:vI})}}const vI=["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"],AI=[T.CONNECTOR_ID.AUTH,T.CONNECTOR_ID.WALLET_CONNECT];class II{constructor(e){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=s=>p.getCaipNetworks(s),this.getConnectorId=s=>M.getConnectorId(s),e&&this.construct(e),e?.namespace&&(this.connectionManager=new EI({namespace:e.namespace}))}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get connections(){return this.availableConnections}get networks(){return this.getCaipNetworks(this.namespace)}onAuthConnected({accounts:e,chainId:s}){const n=this.getCaipNetworks().filter(r=>r.chainNamespace===this.namespace).find(r=>r.id.toString()===s?.toString());e&&n&&this.addConnection({connectorId:T.CONNECTOR_ID.AUTH,accounts:e,caipNetwork:n})}setAuthProvider(e){e.onConnect(this.onAuthConnected.bind(this)),e.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:T.CONNECTOR_ID.AUTH,type:"AUTH",name:T.CONNECTOR_NAMES.AUTH,provider:e,imageId:Wr.ConnectorImageIds[T.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const s=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(n=>s.has(n.id)?!1:(s.add(n.id),!0)),this.emit("connectors",this.availableConnectors)}addConnection(...e){const s=new Set;this.availableConnections=[...e,...this.availableConnections].filter(n=>s.has(n.connectorId.toLowerCase())?!1:(s.add(n.connectorId.toLowerCase()),!0)),this.emit
212("connections",this.availableConnections)}deleteConnection(e){this.availableConnections=this.availableConnections.filter(s=>!Ye.isLowerCaseMatch(s.connectorId,e)),this.emit("connections",this.availableConnections)}clearConnections(e=!1){this.availableConnections=[],e&&this.emit("connections",this.availableConnections)}setStatus(e,s){p.setAccountProp("status",e,s)}on(e,s){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(s)}off(e,s){const n=this.eventListeners.get(e);n&&n.delete(s)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const n=this.eventListeners.get(e);n&&n.forEach(r=>r(s))}async connectWalletConnect(e){try{return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}catch(s){throw Gt.isUserRejectedRequestError(s)?new Kd(s):s}}async switchNetwork(e){const{caipNetwork:s,providerType:n}=e;if(!e.provider)return;const r="provider"in e.provider?e.provider.provider:e.provider;if(n==="WALLET_CONNECT"){r.setDefaultChain(s.caipNetworkId);return}if(r&&n==="AUTH"){const i=r,o=Lt(s.chainNamespace);await i.switchNetwork({chainId:s.caipNetworkId});const a=await i.getUser({chainId:s.caipNetworkId,preferredAccountType:o});this.emit("switchNetwork",a)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s instanceof tp);if(!e)throw new Error("WalletConnectConnector not found");return e}onConnect(e,s){if(e.length>0){const{address:n,chainId:r}=J.getAccount(e[0]),i=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===r?.toString()),o=this.connectors.find(a=>a.id===s);n&&(this.emit("accountChanged",{address:n,chainId:r,connector:o}),this.addConnection({connectorId:s,accounts:e.map(a=>{const{address:c}=J.getAccount(a);return{address:c}}),caipNetwork:i}))}}onAccountsChanged(e,s,n=!0){if(e.length>0){const{address:r}=J.getAccount(e[0]),i=this.connectionManager?.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors});r&&Ye.isLowerCaseMatch(this.getConnectorId(T.CHAIN.EVM),s)&&this.emit("accountChanged",{address:r,chainId:i?.caipNetwork?.id,connector:i?.connector}),this.addConnection({connectorId:s,accounts:e.map(o=>{const{address:a}=J.getAccount(o);return{address:a}}),caipNetwork:i?.caipNetwork})}else n&&this.onDisconnect(s)}onDisconnect(e){this.removeProviderListeners(e),this.deleteConnection(e),Ye.isLowerCaseMatch(this.getConnectorId(T.CHAIN.EVM),e)&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(e,s){const n=typeof e=="string"&&e.startsWith("0x")?Pi.hexStringToNumber(e).toString():e.toString(),r=this.connectionManager?.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors}),i=this.getCaipNetworks().filter(o=>o.chainNamespace===this.namespace).find(o=>o.id.toString()===n);r&&this.addConnection({connectorId:s,accounts:r.accounts,caipNetwork:i}),Ye.isLowerCaseMatch(this.getConnectorId(T.CHAIN.EVM),s)&&this.emit("switchNetwork",{chainId:n})}listenProviderEvents(e,s){if(AI.includes(e))return;const n=o=>this.onAccountsChanged(o,e),r=o=>this.onChainChanged(o,e),i=()=>this.onDisconnect(e);this.providerHandlers[e]||(s.on("disconnect",i),s.on("accountsChanged",n),s.on("chainChanged",r),this.providerHandlers[e]={provider:s,disconnect:i,accountsChanged:n,chainChanged:r})}removeProviderListeners(e){if(this.providerHandlers[e]){const{provider:s,disconnect:n,accountsChanged:r,chainChanged:i}=this.providerHandlers[e];s.removeListener("disconnect",n),s.removeListener("accountsChanged",r),s.removeListener("chainChanged",i),this.providerHandlers[e]=null}}emitFirstAvailableConnection(){const e=this.connectionManager?.getConnection({connections:this.connections,connectors:this.connectors});if(e){const[s]=e.accounts;this.emit("accountChanged",{address:s?.address,chainId:e.caipNetwork?.id,connector:e.connector})}}}class NI extends II{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new tp({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit
212("disconnect")}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}return{connections:[]}}syncConnections(){return Promise.resolve()}async getAccounts({namespace:e}){const n=this.provider?.session?.namespaces?.[e]?.accounts?.map(r=>{const[,,i]=r.split(":");return i}).filter((r,i,o)=>o.indexOf(r)===i)||[];return Promise.resolve({accounts:n.map(r=>J.createAccount(e,r,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&me.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};const n=p.getAccountData();if(n?.balanceLoading&&e.chainId===p.state.activeCaipNetwork?.id)return{balance:n?.balance||"0.00",symbol:n?.balanceSymbol||""};const i=(await p.fetchTokenBalance()).find(o=>o.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&o.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:i?.quantity.numeric||"0.00",symbol:i?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:s,message:n,address:r}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let i="";return p.state.activeCaipNetwork?.chainNamespace===T.CHAIN.SOLANA?i=(await s.request({method:"solana_signMessage",params:{message:nr.encode(new TextEncoder().encode(n)),pubkey:r}},p.state.activeCaipNetwork?.caipNetworkId)).signature:i=await s.request({method:"personal_sign",params:[n,r]},p.state.activeCaipNetwork?.caipNetworkId),{signature:i}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:s}=e,n=this.getWalletConnectConnector();if(s.chainNamespace===T.CHAIN.EVM)try{await n.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:gc(s.id)}]})}catch(r){if(r.code===Sr.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||r.code===Sr.ERROR_INVALID_CHAIN_ID||r.code===Sr.ERROR_CODE_DEFAULT||r?.data?.originalError?.code===Sr.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await n.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:gc(s.id),rpcUrls:[s?.rpcUrls.chainDefault?.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[s.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}n.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(n=>n.type==="WALLET_CONNECT")?.provider}}const _I=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication"],Ei={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?me.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!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?me.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?me.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?me.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?me.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?me.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?me.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?me.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?me.DEFAULT_REMOTE_FEATURES.reownBranding:!!t},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>t.isEnabled&&(t.config??[]),processFallback:t=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>me.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>me.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>me.DEFAULT_REMOTE_FEATURES.payments},reownAuthentication:{apiFeatureName:"reown_authentication",localFeatureName:"reownAuthentication",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>typeof t>"u"?me.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!t}},SI={localSettingsOverridden:new Set,getApiConfig(t,e){return e?.find(s=>
vendor: 38,284 bytes, line 212
212s.id===t)},addWarning(t,e){if(t!==void 0){const s=Ei[e],n=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(n)}},processFeature(t,e,s,n,r){const i=Ei[t],o=e[i.localFeatureName];if(r&&!i.isAvailableOnBasic)return!1;if(n){const a=this.getApiConfig(i.apiFeatureName,s);return a?.config===null?this.processFallbackFeature(t,o):a?.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return Ei[t].processApi(e)},processFallbackFeature(t,e){return Ei[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let n=null,r=!1;try{n=await ee.fetchProjectConfig(),r=n!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const i=r&&!e?me.DEFAULT_REMOTE_FEATURES:me.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of _I){const a=this.processFeature(o,s,n,r,e);Object.assign(i,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),me.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.`;vt.open({debugMessage:Pt.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(o)},"warning")}return i}};class TI{constructor(e){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,n)=>{if(s){const r=p.getCaipNetworks(s)?.find(a=>a.id===n);if(r)return r;const i=p.getNetworkData(s)?.caipNetwork;return i||p.getRequestedCaipNetworks(s).filter(a=>a.chainNamespace===s)?.[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,n)=>{p.setRequestedCaipNetworks(s,n)},this.getApprovedCaipNetworkIds=()=>p.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>p.state.activeChain===s||!s?p.state.activeCaipAddress:p.state.chains.get(s)?.accountState?.caipAddress,this.setClientId=s=>{se.setClientId(s)},this.getProvider=s=>xe.getProvider(s),this.getProviderType=s=>xe.getProviderId(s),this.getPreferredAccountType=s=>Lt(s),this.setCaipAddress=(s,n,r=!1)=>{p.setAccountProp("caipAddress",s,n,r),p.setAccountProp("address",J.getPlainAddress(s),n,r)},this.setBalance=(s,n,r)=>{p.setAccountProp("balance",s,r),p.setAccountProp("balanceSymbol",n,r)},this.setProfileName=(s,n)=>{p.setAccountProp("profileName",s,n)},this.setProfileImage=(s,n)=>{p.setAccountProp("profileImage",s,n)},this.setUser=(s,n)=>{p.setAccountProp("user",s,n)},this.resetAccount=s=>{p.resetAccount(s)},this.setCaipNetwork=s=>{p.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,n)=>{p.setChainNetworkData(n,{caipNetwork:s})},this.setStatus=(s,n)=>{p.setAccountProp("status",s,n),M.isConnected()?U.setConnectionStatus("connected"):U.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>p.getAccountData(s)?.address,this.setConnectors=s=>{const n=[...M.state.allConnectors,...s];M.setConnectors(n)},this.setConnections=(s,n)=>{U.setConnections(s,n),V.setConnections(s,n)},this.fetchIdentity=s=>se.fetchIdentity(s),this.getReownName=s=>Or.getNamesForAddress(s),this.getConnectors=()=>M.getConnectors(),this.getConnectorImage=s=>Jd.getConnectorImage(s),this.getConnections=s=>this.remoteFeatures.multiWallet?$i.getConnectionsData(s).connections:(vt.open(T.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=s=>this.remoteFeatures.multiWallet?$i.getConnectionsData(s).recentConnections:(vt.open(T.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async s=>{if(!this.remoteFeatures.multiWallet){vt.open(T.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await V.switchConnection(s)},this.deleteConnection=s=>{if(!this.remoteFeatures.multiWallet){vt.open(T.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}U.deleteAddressFromConnection(s),V.syncStorageConnections()},this.setConnectedWalletInfo=(s,n)=>{const r=xe.getProviderId(n),i=s?{...s,type:r}:void 0;p.setAccountProp("connectedWalletInfo",i,n)},this.getIsConnectedState=()=>!!p.state.activeCaipAddress,this.addAddressLabel=(s,n,r)=>{const i=p.getAccountData(r)?.addressLabels||{};p.setAccountProp("addressLabels",{...i,[s]:n},r)},this.removeAddressLabel=(s,n)=>{const r=p.getAccountData(n)?.addressLabels||{};p.setAccountProp("addressLabels",{...r,[s]:void 0},n)},this.getAddress=s=>{const n=s||p.state.activeChain;return p.getAccountData(n)?.address},this.setApprovedCaipNetworksData=s=>p.setApprovedCaipNetworksData(s),this.resetNetwork=s=>{p.resetNetwork(s)},this.addConnector=s=>{M.addConnector(s)},this.resetWcConnection=()=>{V.resetWcConnection()},this.setAddressExplorerUrl=(s,n)=>{p.setAccountProp("addressExplorerUrl",s,n)},this.setSmartAccountDeployed=(s,n)=>{p.setAccountProp("smartAccountDeployed",s,n)},this.setPreferredAccountType=(s,n)=>{p.setAccountProp("preferredAccountType",s,n)},this.setEIP6963Enabled=s=>{_.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),MA.checkSDKVersion(e.sdkVersion)}getChainNamespacesSet(e,s){const n=e?.map(i=>i.namespace).filter(i=>!!i);if(n?.length)return[...new Set(n)];const r=s?.map(i=>i.chainNamespace);return[...new Set(r)]}async initialize(e){if(this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),_.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),this.remoteFeatures=await SI.fetchRemoteFeatures(e),_.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&ta.setOnrampProviders(this.remoteFeatures.onramp),(_.state.remoteFeatures?.email||Array.isArray(_.state.remoteFeatures?.socials)&&_.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins(),_.state.features?.reownAuthentication||_.state.remoteFeatures?.reownAuthentication){const{ReownAuthentication:s}=await Ur(async()=>{const{ReownAuthentication:r}=await import("./features-DTjur7ym.js");return{ReownAuthentication:r}},__vite__mapDeps([8,1,2])),n=_.state.siwx;n instanceof s||(n&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),_.setSIWX(new s))}}async openSend(e){const s=e.namespace||p.state.activeChain,n=this.getCaipAddress(s),r=this.getCaipNetwork(s)?.id;if(!n)throw new Error("openSend: caipAddress not found");if(r?.toString()!==e.chainId.toString()){const i=p.getCaipNetworkById(e.chainId,s);if(!i)throw new Error(`openSend: caipNetwork with chainId ${e.chainId} not found`);await this.switchNetwork(i,{throwOnFailure:!0})}try{const i=zh.getTokenSymbolByAddress(e.assetAddress);i&&await ee.fetchTokenImages([i])}catch{}return await he.open({view:"WalletSend",data:{send:e}}),new Promise((i,o)=>{const a=ce.subscribeKey("hash",d=>{d&&(l(),i({hash:d}))}),c=he.subscribe(d=>{d.open||(l(),o(new Error("Modal closed")))}),l=this.createCleanupHandler([a,c])})}toModalOptions(){function e(n){return n?.view==="Swap"}function s(n){return n?.view==="WalletSend"}return{isSwap:e,isSend:s}}async checkAllowedOrigins(){try{const e=await ee.fetchAllowedOrigins();if(!J.isClient())return;const s=window.location.origin;Gt.isOriginAllowed(s,e,Sr.DEFAULT_ALLOWED_ANCESTORS)||vt.open(Pt.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error))return;switch(e.message){case"RATE_LIMITED":vt.open(Pt.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const s=e.cause instanceof Error?e.cause:e;vt.open({displayMessage:Pt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:Pt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(s.message)},"error");break}}}}createCleanupHandler(e){return()=>{e.forEach(s=>{try{s()}catch{}})}}sendInitializeEvent(e){const{...s}=e;delete s.adapters,delete s.universalProvider,le.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(n=>n.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&It.setThemeMode(e.themeMode),e.themeVariables&&It.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){V.initialize(e.adapters??[]),V.setWcBasic(e.basic??!1)}initializeConnectorController(){M.initialize(this.chainNamespaces)}initializeProjectSettings(e){_.setProjectId(e.projectId),_.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){_.setDebug(e.debug!==!1),_.setEnableWalletGuide(e.enableWalletGuide!==!1),_.setEnableWallets(e.enableWallets!==!1),_.setEIP6963Enabled(e.enableEIP6963!==!1),_.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),_.setEnableReconnect(e.enableReconnect!==!1),_.setEnableMobileFullScreen(e.enableMobileFullScreen===!0),_.setEnableAuthLogger(e.enableAuthLogger!==!1),_.setCustomRpcUrls(e.customRpcUrls),_.setEnableEmbedded(e.enableEmbedded),_.setAllWallets(e.allWallets),_.setIncludeWalletIds(e.includeWalletIds),_.setExcludeWalletIds(e.excludeWalletIds),_.setFeaturedWalletIds(e.featuredWalletIds),_.setTokens(e.tokens),_.setTermsConditionsUrl(e.termsConditionsUrl),_.setPrivacyPolicyUrl(e.privacyPolicyUrl),_.setCustomWallets(e.customWallets),_.setFeatures(e.features),_.setAllowUnsupportedChain(e.allowUnsupportedChain),_.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),_.setPreferUniversalLinks(e.experimental_preferUniversalLinks),_.setDefaultAccountTypes(e.defaultAccountTypes);const s=this.getDefaultMetaData();if(!e.metadata&&s&&(e.metadata=s),_.setMetadata(e.metadata),_.setDisableAppend(e.disableAppend),_.setEnableEmbedded(e.enableEmbedded),_.setSIWX(e.siwx),this.features=_.state.features??{},!e.projectId){vt.open(Pt.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(r=>r.namespace===T.CHAIN.EVM)&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");_.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return J.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const n=jn.getUnsupportedNetwork(`${s}:${e}`);p.setActiveCaipNetwork(n)}}getDefaultNetwork(){return jn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,s){return jn.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return jn.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(r=>r.id===e.defaultNetwork?.id);return s?jn.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectConnector(e,s){try{this.setLoading(!0,e);let n={connections:[]};const r=this.getAdapter(e);return(p.state.chains.get(e)?.accountState?.caipAddress||!_.state.enableReconnect)&&r?.disconnect&&(n=await r.disconnect({id:s})),this.setLoading(!1,e),n}catch(n){throw this.setLoading(!1,e),new Error(`Failed to disconnect chains: ${n.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=p.state.activeChain,s=this.getAdapter(e),n=this.getCaipNetwork(e)?.id,r=V.getConnections(e),i=this.remoteFeatures.multiWallet,o=r.length>0;if(!s)throw new Error("Adapter not found");const a=await s.connectWalletConnect(n);(!o||!i)&&this.close(),this.setClientId(a?.clientId||null),U.setConnectedNamespaces([...p.state.chains.keys()]),await this.syncWalletConnectAccount(),await ns.initializeIfEnabled()},connectExternal:async e=>{const s=await this.onConnectExternal(e);return await this.connectInactiveNamespaces(e,s),s?{address:s.address}:void 0},reconnectExternal:async({id:e,info:s,type:n,provider:r})=>{const i=p.state.activeChain,o=this.getAdapter(i);if(!i)throw new Error("reconnectExternal: namespace not found");if(!o)throw new Error("reconnectExternal: adapter not found");o?.reconnect&&(await o?.reconnect({id:e,info:s,type:n,provider:r,chainId:this.getCaipNetwork()?.id}),U.addConnectedNamespace(i),this.syncConnectedWalletInfo(i))},disconnectConnector:async e=>{await this.disconnectConnector(e.namespace,e.id)},disconnect:async e=>{const{id:s,chainNamespace:n,initialDisconnect:r}=e||{},i=n||p.state.activeChain,o=M.getConnectorId(i),a=s===T.CONNECTOR_ID.AUTH||o===T.CONNECTOR_ID.AUTH,c=s===T.CONNECTOR_ID.WALLET_CONNECT||o===T.CONNECTOR_ID.WALLET_CONNECT;try{const l=Array.from(p.state.chains.keys());let d=n?[n]:l;(c||a)&&(d=l);const u=d.map(async g=>{const m=M.getConnectorId(g),w=s||m,A=await this.disconnectConnector(g,w);A&&(a&&U.deleteConnectedSocialProvider(),A.connections.forEach(C=>{U.addDisconnectedConnectorId(C.connectorId,g)})),r&&this.onDisconnectNamespace({chainNamespace:g,closeModal:!1})}),h=await Promise.allSettled(u);ce.resetSend(),V.resetWcConnection(),ns.getSIWX()?.signOutOnDisconnect&&await ns.clearSessions(),M.setFilterByNamespace(void 0),V.syncStorageConnections();const f=h.filter(g=>g.status==="rejected");if(f.length>0)throw new Error(f.map(g=>g.reason.message).join(", "));le.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:n||"all"}})}catch(l){throw new Error(`Failed to disconnect chains: ${l.message}`)}},checkInstalled:e=>e?e.some(s=>!!window.ethereum?.[String(s)]):!!window.ethereum,signMessage:async e=>{const s=p.state.activeChain,n=this.getAdapter(p.state.activeChain);if(!s)throw new Error("signMessage: namespace not found");if(!n)throw new Error("signMessage: adapter not found");const r=this.getAddress(s);if(!r)throw new Error("signMessage: address not found");return(await n?.signMessage({message:e,address:r,provider:xe.getProvider(s)}))?.signature||""},sendTransaction:async e=>{const s=e.chainNamespace;if(!s)throw new Error("sendTransaction: namespace not found");if(me.SEND_SUPPORTED_NAMESPACES.includes(s)){const n=this.getAdapter(s);if(!n)throw new Error("sendTransaction: adapter not found");const r=xe.getProvider(s);return(await n?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:r}))?.hash||""}return""},estimateGas:async e=>{const s=e.chainNamespace;if(s===T.CHAIN.EVM){const n=this.getAdapter(s);if(!n)throw new Error("estimateGas: adapter is required but got undefined");const r=xe.getProvider(s),i=this.getCaipNetwork();if(!i)throw new Error("estimateGas: caipNetwork is required but got undefined");return(await n?.estimateGas({...e,provider:r,caipNetwork:i}))?.gas||0n}return 0n},getEnsAvatar:async()=>{const e=p.state.activeChain;if(!e)throw new Error("getEnsAvatar: namespace is required but got undefined");const s=this.getAddress(e);if(!s)throw new Error("getEnsAvatar: address not found");return await this.syncIdentity({address:s,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:e}),p.getAccountData()?.profileImage||!1},getEnsAddress:async e=>await Gt.resolveReownName(e),writeContract:async e=>{const s=p.state.activeChain,n=this.getAdapter(s);if(!s)throw new Error("writeContract: namespace is required but got undefined");if(!n)throw new Error("writeContract: adapter is required but got undefined");const r=this.getCaipNetwork(),i=this.getCaipAddress(),o=xe.getProvider(s);if(!r||!i)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");return(await n?.writeContract({...e,caipNetwork:r,provider:o,caipAddress:i}))?.hash},parseUnits:(e,s)=>{const n=this.getAdapter(p.state.activeChain);if(!n)throw new Error("parseUnits: adapter is required but got undefined");return n?.parseUnits({value:e,decimals:s})??0n},formatUnits:(e,s)=>{const n=this.getAdapter(p.state.activeChain);if(!n)throw new Error("formatUnits: adapter is required but got undefined");return n?.formatUnits({value:e,decimals:s})??"0"},getCapabilities:async e=>{const s=this.getAdapter(p.state.activeChain);if(!s)throw new Error("getCapabilities: adapter is required but got undefined");return await s?.getCapabilities(e)},grantPermissions:async e=>{const s=this.getAdapter(p.state.activeChain);if(!s)throw new Error("grantPermissions: adapter is required but got undefined");return await s?.grantPermissions(e)},revokePermissions:async e=>{const s=this.getAdapter(p.state.activeChain);if(!s)throw new Error("revokePermissions: adapter is required but got undefined");return s?.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(p.state.activeChain);if(!s)throw new Error("walletGetAssets: adapter is required but got undefined");return await s?.walletGetAssets(e)??{}},updateBalance:e=>{const s=this.getAddress(e),n=this.getCaipNetwork(e);!n||!s||this.updateNativeBalance(s,n?.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},V.setClient(this.connectionControllerClient)}async onConnectExternal(e){const s=p.state.activeChain,n=e.chain||s,r=this.getAdapter(n);let i=!0;if(e.type===ws.CONNECTOR_TYPE_AUTH&&T.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(u=>M.getConnectorId(u)===T.CONNECTOR_ID.AUTH)&&e.chain!==s&&(i=!1),e.chain&&e.chain!==s&&!e.caipNetwork){const l=this.getCaipNetworks().find(d=>d.chainNamespace===e.chain);l&&i&&this.setCaipNetwork(l)}if(!n)throw new Error("connectExternal: namespace not found");if(!r)throw new Error("connectExternal: adapter not found");const o=this.getCaipNetwork(n),a=e.caipNetwork||o,c=await r.connect({id:e.id,address:e.address,info:e.info,type:e.type,provider:e.provider,socialUri:e.socialUri,chainId:e.caipNetwork?.id||o?.id,rpcUrl:e.caipNetwork?.rpcUrls?.default?.http?.[0]||o?.rpcUrls?.default?.http?.[0]});if(c)return U.addConnectedNamespace(n),this.syncProvider({...c,chainNamespace:n}),this.setStatus("connected",n),this.syncConnectedWalletInfo(n),U.removeDisconnectedConnectorId(e.id,n),{address:c.address,connectedCaipNetwork:a}}async connectInactiveNamespaces(e,s){const n=e.type===ws.CONNECTOR_TYPE_AUTH,r=Ye.getOtherAuthNamespaces(s?.connectedCaipNetwork?.chainNamespace),i=p.state.activeCaipNetwork,o=this.getAdapter(i?.chainNamespace),a=xe.getProvider(i?.chainNamespace);n&&(await Promise.all(r.map(async c=>{try{const l=xe.getProvider(c),d=this.getCaipNetwork(c);await this.getAdapter(c)?.connect({...e,provider:l,socialUri:void 0,chainId:d?.id,rpcUrl:d?.rpcUrls?.default?.http?.[0]})&&(U.addConnectedNamespace(c),U.removeDisconnectedConnectorId(e.id,c),this.setStatus("connected",c),this.syncConnectedWalletInfo(c))}catch(l){vt.warn(Pt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,Pt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(c,l instanceof Error?l.message:void 0),Pt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),i&&await o?.switchNetwork({caipNetwork:i,provider:a,providerType:e.type}))}getApprovedCaipNetworksData(){if(xe.getProviderId(p.state.activeChain)===ws.CONNECTOR_TYPE_WALLET_CONNECT){const s=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(s)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=xe.getProvider(s),i=xe.getProviderId(s);if(e.chainNamespace===p.state.activeChain)await this.getAdapter(s)?.switchNetwork({caipNetwork:e,provider:r,providerType:i});else if(this.setCaipNetwork(e),i===ws.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 n=s.chains||[],r=s.accounts.map(i=>{const{chainId:o,chainNamespace:a}=it.parseCaipAddress(i);return`${a}:${o}`});return Array.from(new Set([...n,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,n)=>{const r=e?.find(i=>i.namespace===n);return r?(r.construct({namespace:n,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:i})=>i===n)}),s[n]=r):s[n]=new NI({namespace:n,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e),await this.chainAdapters?.[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){this.getAdapter(e)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const n=U.getConnectionStatus();_.state.enableReconnect===!1?this.setStatus("disconnected",e):n==="connected"?this.setStatus("connecting",e):n==="disconnected"?(U.clearAddressCache(),this.setStatus(n,e)):this.setStatus(n,e),s.on("switchNetwork",({address:r,chainId:i})=>{const o=this.getCaipNetworks().find(l=>l.id.toString()===i.toString()||l.caipNetworkId.toString()===i.toString()),a=p.state.activeChain===e,c=p.state.chains.get(e)?.accountState?.address;if(o){const l=a&&r?r:c;l&&this.syncAccount({address:l,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(i)}),s.on("disconnect",()=>{const r=this.remoteFeatures.multiWallet,i=Array.from(V.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:e,closeModal:!r||i.length===0})}),s.on("connections",r=>{this.setConnections(r,e)}),s.on("pendingTransactions",()=>{const r=this.getAddress(e),i=p.state.activeCaipNetwork;!r||!i?.id||this.updateNativeBalance(r,i.id,i.chainNamespace)}),s.on("accountChanged",({address:r,chainId:i,connector:o})=>{this.handlePreviousConnectorConnection(o);const a=p.state.activeChain===e;o?.provider&&(this.syncProvider({id:o.id,type:o.type,provider:o?.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e));const c=p.getNetworkData(e)?.caipNetwork?.id,l=i||c;a&&l?this.syncAccount({address:r,chainId:l,chainNamespace:e}):!a&&l?(this.syncAccountInfo(r,l,e),this.syncBalance({address:r,chainId:l,chainNamespace:e})):this.syncAccountInfo(r,i,e),U.addConnectedNamespace(e)})}async handlePreviousConnectorConnection(e){const s=e?.chain,n=e?.id,r=M.getConnectorId(s),i=_.state.remoteFeatures?.multiWallet,a=s&&n&&r&&r!==n&&!i;try{a&&await V.disconnect({id:r,namespace:s})}catch(c){console.warn("Error disconnecting previous connector",c)}}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&await this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(e=>V.disconnect({namespace:e,initialDisconnect:!0})))}catch(e){console.error("Error disconnecting existing connections:",e)}}async reconnectWalletConnect(){await this.syncWalletConnectAccount();const e=this.getAddress();this.getCaipAddress()||U.deleteRecentWallet();const s=U.getRecentWallet();le.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:J.isMobile()?"mobile":"qrcode",name:s?.name||"Unknown",reconnect:!0,view:te.state.view,walletRank:s?.order}})}async syncNamespaceConnection(e){try{e===T.CHAIN.EVM&&J.isSafeApp()&&M.setConnectorId(T.CONNECTOR_ID.SAFE,e);const s=M.getConnectorId(e);switch(this.setStatus("connecting",e),s){case T.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case T.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}onDisconnectNamespace(e){const{chainNamespace:s,closeModal:n}=e||{};p.resetAccount(s),p.resetNetwork(s),U.removeConnectedNamespace(s);const r=Array.from(p.state.chains.keys());(s?[s]:r).forEach(o=>U.addDisconnectedConnectorId(M.getConnectorId(o)||"",o)),M.removeConnectorId(s),xe.resetChain(s),this.setUser(null,s),this.setStatus("disconnected",s),this.setConnectedWalletInfo(null,s),n!==!1&&he.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(e=>{const s=this.getAdapter(e),n=this.getCaipAddress(e),r=this.getCaipNetwork(e);return s?.syncConnections({connectToFirstConnector:!n,caipNetwork:r})}))}async syncAdapterConnection(e){const s=this.getAdapter(e),n=this.getCaipNetwork(e),r=M.getConnectorId(e),o=M.getConnectors(e).find(a=>a.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!n?.id)throw new Error("CaipNetwork not found");const a=await s?.syncConnection({namespace:e,id:o.id,chainId:n.id,rpcUrl:n?.rpcUrls?.default?.http?.[0]});a?(this.syncProvider({...a,chainNamespace:e}),await this.syncAccount({...a,chainNamespace:e}),this.setStatus("connected",e),le.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:a.address,properties:{method:"browser",name:o.info?.name||o.name||"Unknown",reconnect:!0,view:te.state.view,walletRank:void 0}})):this.setStatus("disconnected",e)}catch{this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})}}async syncWalletConnectAccount(){const e=Object.keys(this.universalProvider?.session?.namespaces||{}),s=this.chainNamespaces.map(async n=>{const r=this.getAdapter(n);if(!r)return;const i=this.universalProvider?.session?.namespaces?.[n]?.accounts||[],o=p.state.activeCaipNetwork?.id,a=i.find(c=>{const{chainId:l}=it.parseCaipAddress(c);return l===o?.toString()})||i[0];if(a){const c=it.validateCaipAddress(a),{chainId:l,address:d}=it.parseCaipAddress(c);if(xe.setProviderId(n,ws.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&p.state.activeCaipNetwork&&r.namespace!==T.CHAIN.EVM){const u=r.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:p.state.activeCaipNetwork});xe.setProvider(n,u)}else xe.setProvider(n,this.universalProvider);M.setConnectorId(T.CONNECTOR_ID.WALLET_CONNECT,n),U.addConnectedNamespace(n),await this.syncAccount({address:d,chainId:l,chainNamespace:n})}else e.includes(n)&&this.setStatus("disconnected",n);this.syncConnectedWalletInfo(n),await p.setApprovedCaipNetworksData(n)});await Promise.all(s)}syncProvider({type:e,provider:s,id:n,chainNamespace:r}){xe.setProviderId(r,e),xe.setProvider(r,s),M.setConnectorId(n,r)}async syncAccount(e){const s=e.chainNamespace===p.state.activeChain,n=p.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:i,chainNamespace:o}=e,{chainId:a}=U.getActiveNetworkProps(),c=i||a,l=p.state.activeCaipNetwork?.name===T.UNSUPPORTED_NETWORK_NAME,d=p.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!d)&&c){let u=this.getCaipNetworks().find(m=>m.id.toString()===c.toString()),h=this.getCaipNetworks().find(m=>m.chainNamespace===o);if(!d&&!u&&!h){const m=this.getApprovedCaipNetworkIds()||[],w=m.find(C=>it.parseCaipNetworkId(C)?.chainId===c.toString()),A=m.find(C=>it.parseCaipNetworkId(C)?.chainNamespace===o);u=this.getCaipNetworks().find(C=>C.caipNetworkId===w),h=this.getCaipNetworks().find(C=>C.caipNetworkId===A||"deprecatedCaipNetworkId"in C&&C.deprecatedCaipNetworkId===A)}const f=u||h;f?.chainNamespace===p.state.activeChain?_.state.enableNetworkSwitch&&!_.state.allowUnsupportedChain&&p.state.activeCaipNetwork?.name===T.UNSUPPORTED_NETWORK_NAME?p.showUnsupportedChainUI():this.setCaipNetwork(f):s||n&&this.setCaipNetworkOfNamespace(n,o),this.syncConnectedWalletInfo(o);const g=this.getAddress(o);Ye.isLowerCaseMatch(r,g)||this.syncAccountInfo(r,f?.id,o),s?await this.syncBalance({address:r,chainId:f?.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:n?.id,chainNamespace:o}),this.syncIdentity({address:r,chainId:i,chainNamespace:o})}}async syncAccountInfo(e,s,n){const r=this.getCaipAddress(n),i=s||r?.split(":")[1];if(!i)return;const o=`${n}:${i}:${e}`;this.setCaipAddress(o,n,!0),await this.syncIdentity({address:e,chainId:i,chainNamespace:n})}async syncReownName(e,s){try{const n=await this.getReownName(e);if(n[0]){const r=n[0];this.setProfileName(r.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){const s=M.getConnectorId(e),n=xe.getProviderId(e);if(n===ws.CONNECTOR_TYPE_ANNOUNCED||n===ws.CONNECTOR_TYPE_INJECTED){if(s){const i=this.getConnectors().find(o=>{const a=o.id===s,c=o.info?.rdns===s,l=o.connectors?.some(d=>d.id===s||d.info?.rdns===s);return a||c||!!l});if(i){const{info:o,name:a,imageUrl:c}=i,l=c||this.getConnectorImage(i);this.setConnectedWalletInfo({name:a,icon:l,...o},e)}}}else if(n===ws.CONNECTOR_TYPE_WALLET_CONNECT){const r=xe.getProvider(e);r?.session&&this.setConnectedWalletInfo({...r.session.peer.metadata,name:r.session.peer.metadata.name,icon:r.session.peer.metadata.icons?.[0]},e)}else if(s&&(s===T.CONNECTOR_ID.COINBASE_SDK||s===T.CONNECTOR_ID.COINBASE)){const r=this.getConnectors().find(c=>c.id===s),i=r?.name||"Coinbase Wallet",o=r?.imageUrl||this.getConnectorImage(r),a=r?.info;this.setConnectedWalletInfo({...a,name:i,icon:o},e)}}async syncBalance(e){!qd.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(n=>n.id.toString()===e.chainId?.toString())||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,n){const r=this.getAdapter(n),i=p.getCaipNetworkByNamespace(n,s);if(r){const o=await r.getBalance({address:e,chainId:s,caipNetwork:i,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,n),o}}async initializeUniversalAdapter(){const e=jA.createLogger((n,...r)=>{n&&this.handleAlertError(n),console.error(...r)}),s={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};_.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await LA.init(s),_.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(e=>{Gt.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:s=>{V.setUri(s)},onConnect:s=>{const{address:n}=J.getAccount(s[0]);V.finalizeWcConnection(n)},onDisconnect:()=>{p.state.noAdapters&&this.resetAccount(e),V.resetWcConnection()},onChainChanged:s=>{const n=p.state.activeChain,r=n&&M.state.activeConnectorIds[n]===T.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(p.state.noAdapters||r)){const i=this.getCaipNetworks().find(a=>a.id.toString()===s.toString()||a.caipNetworkId.toString()===s.toString()),o=this.getCaipNetwork();if(!i){this.setUnsupportedNetwork(s);return}o?.id.toString()!==i?.id.toString()&&o?.chainNamespace===i?.chainNamespace&&this.setCaipNetwork(i)}},onAccountsChanged:s=>{const n=p.state.activeChain,r=n&&M.state.activeConnectorIds[n]===T.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(p.state.noAdapters||r)){const i=s?.[0];i&&this.syncAccount({address:i.address,chainId:i.chainId,chainNamespace:i.chainNamespace})}}})})}createUniversalProvider(){return!this.universalProviderInitPromise&&J.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){le.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}getDisabledCaipNetworks(){const e=p.getAllApprovedCaipNetworkIds(),s=p.getAllRequestedCaipNetworks();return J.sortRequestedNetworks(e,s).filter(r=>p.isCaipNetworkDisabled(r))}handleAlertError(e){const s=Object.entries(Pt.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[n,r]=s??[],{message:i,alertErrorKey:o}=r??{};if(n&&i&&!this.reportedAlertErrors[n]){const a=Pt.ALERT_ERRORS[o];a&&(vt.open(a,"error"),this.reportedAlertErrors[n]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const n=e;n.namespace=s,n.construct({namespace:s,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:r})=>r===s)}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=n)}async open(e){await this.injectModalUi(),e?.uri&&V.setUri(e.uri);const{isSwap:s,isSend:n}=this.toModalOptions();return s(e)?he.open({...e,data:{swap:e.arguments}}):n(e)&&e.arguments?this.openSend(e.arguments):he.open(e)}async close(){await this.injectModalUi(),he.close()}setLoading(e,s){he.setLoading(e,s)}async disconnect(e){await V.disconnect({namespace:e})}getSIWX(){return _.state.siwx}getError(){return""}getChainId(){return p.state.activeCaipNetwork?.id}async switchNetwork(e,{throwOnFailure:s=!1}={}){const n=this.getCaipNetworks().find(r=>r.id===e.id);if(!n){vt.open(Pt.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await p.switchActiveNetwork(n,{throwOnFailure:s})}getWalletProvider(){return p.state.activeChain?xe.state.providers[p.state.activeChain]:null}getWalletProviderType(){return xe.getProviderId(p.state.activeChain)}subscribeProviders(e){return xe.subscribeProviders(e)}getThemeMode(){return It.state.themeMode}getThemeVariables(){return It.state.themeVariables}setThemeMode(e){It.setThemeMode(e),La(It.state.themeMode)}setTermsConditionsUrl(e){_.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){_.setPrivacyPolicyUrl(e)}setThemeVariables(e){It.setThemeVariables(e),bI(It.state.themeVariables)}subscribeTheme(e){return It.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?V.subscribe(e):(vt.open(T.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){return e?p.state.chains.get(e)?.accountState?.connectedWalletInfo:p.getAccountData()?.connectedWalletInfo}getAccount(e){const s=e||p.state.activeChain,n=M.getAuthConnector(s),r=p.getAccountData(s),i=U.getConnectedConnectorId(p.state.activeChain),o=V.getConnections(s);if(!s)throw new Error("AppKit:getAccount - namespace is required");const a=o.flatMap(c=>c.accounts.map(({address:l,type:d,publicKey:u})=>J.createAccount(s,l,d||"eoa",u)));if(r)return{allAccounts:a,caipAddress:r.caipAddress,address:J.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:n&&i===T.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:U.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:Lt(s),isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const n=()=>{const r=this.getAccount(s);r&&e(r)};s?p.subscribeChainProp("accountState",n,s):p.subscribe(n),M.subscribe(n)}subscribeNetwork(e){return p.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s?.id,caipNetworkId:s?.caipNetworkId})})}subscribeWalletInfo(e,s){return s?p.subscribeChainProp("accountState",n=>e(n?.connectedWalletInfo),s):p.subscribeChainProp("accountState",n=>e(n?.connectedWalletInfo))}subscribeShouldUpdateToAddress(e){p.subscribeChainProp("accountState",s=>e(s?.shouldUpdateToAddress))}subscribeCaipNetworkChange(e){p.subscribeKey("activeCaipNetwork",e)}getState(){return vs.state}getRemoteFeatures(){return _.state.remoteFeatures}subscribeState(e){return vs.subscribe(e)}subscribeRemoteFeatures(e){return _.subscribeKey("remoteFeatures",e)}showErrorMessage(e){rs.showError(e)}showSuccessMessage(e){rs.showSuccess(e)}getEvent(){return{...le.state}}subscribeEvents(e){return le.subscribe(e)}replace(e){te.replace(e)}redirect(e){te.push(e)}popTransactionStack(e){te.popTransactionStack(e)}isOpen(){return he.state.open}isTransactionStackEmpty(){return te.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){_.setFeatures(e)}updateRemoteFeatures(e){_.setRemoteFeatures(e)}updateOptions(e){const n={..._.state||{},...e};_.setOptions(n)}setConnectMethodsOrder(e){_.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){_.setWalletFeaturesOrder(e)}setCollapseWallets(e){_.setCollapseWallets(e)}setSocialsOrder(e){_.setSocialsOrder(e)}getConnectMethodsOrder(){return _r.getConnectOrderMethod(_.state.features,M.getConnectors())}
212addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const n=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(r=>r.id===n.id)||p.addNetwork(n)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(r=>r.id===s)&&p.removeNetwork(e,s)}}let Md=!1;class sp extends TI{async open(e){M.isConnected()||await super.open(e)}async close(){if(await super.close(),this.options.manualWCControl){const e=p.getAccountData(this.activeChainNamespace)?.address;V.finalizeWcConnection(e)}}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!Md&&J.isClient()){if(await Ur(()=>import("./basic-C22azmFS.js"),__vite__mapDeps([9,10,1,2,11])),await Ur(()=>import("./w3m-modal-BGdqyti6.js"),__vite__mapDeps([12,10,1,2])),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!_.state.disableAppend&&!_.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}Md=!0}}}const kI="1.8.7";function OI(t){return new sp({...t,basic:!0,sdkVersion:`html-core-${kI}`})}const lN=Object.freeze(Object.defineProperty({__proto__:null,AppKit:sp,createAppKit:OI},Symbol.toStringTag,{value:"Module"}));export{jn as $,ee as A,se as B,p as C,yI as D,le as E,Jd as F,Ut as G,qA as H,Vs as I,oN as J,Yh as K,Ua as L,he as M,qd as N,_ as O,it as P,He as Q,te as R,Q as S,It as T,rN as U,er as V,Es as W,Ti as X,Ye as Y,bn as Z,zs as _,T as a,U as a0,_r as a1,lN as a2,X as b,$p as c,rs as d,V as e,mc as f,li as g,Lt as h,J as i,If as j,vt as k,Wa as l,me as m,Zd as n,M as o,Oe as p,Xe as q,Je as r,Ip as s,ns as t,iN as u,aN as v,Bt as w,Oi as x,nN as y,cN as z};
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.