PageSourceSearch

https://the-republic-ashy.vercel.app/assets/core-cpVmb7nU.js

js the-republic-ashy.vercel.app collected 2026-10-03 07:52:02 UTC 597,012 bytes, 228 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-pP58dVRi.js","assets/index-MOhYIfAn.js","assets/index-lTqkEuON.css","assets/custom-B1sl-I0e.js","assets/parseUnits-C94s6_IG.js","assets/parseSignature-B_GJeFbz.js","assets/ccip-CMpVbM-g.js","assets/parseEther-7oiNqOCo.js","assets/secp256k1-CIdmKGEy.js","assets/features-BkQdjCPz.js","assets/basic-B1jP2ajb.js","assets/index-CmKukRcY.js","assets/dijkstra-COg3n3zL.js","assets/w3m-modal-CLBw97XS.js"])))=>i.map(i=>d[i]);
2import{bt as tf,aU as sf,b5 as nf,hg as rf,V as of,hh as af,bY as Su,g_ as Vr,bM as yi,hi as lc,hj as wi,hk as Gi,hl as In,hb as cf,hm as lf,hn as df,hd as uf,hc as hf,he as Mc,g4 as Tu,ho as ur,hp as pf,hq as Mt,hr as vt,hs as V,ht as ks,hu as ff,hv as gf,hw as Mr,hx as wa,hy as hr,hz as mf,hA as yf,hB as wf,hC as bf,hD as kn,hE as vf,hF as ns,hG as pr,hH as dc,hI as Ef,hJ as uc,hK as hc,hL as Gr,hM as pc,hN as jc,hO as Cf,hP as If,hQ as gn,hR as Ou,hS as ys,hT as ss,hU as Rs,hV as ku,h as bi,cU as Fc}from"./index-MOhYIfAn.js";function qc(t,e={}){const{key:s="fallback",name:n="Fallback",rank:r=!1,shouldThrow:i=Af,retryCount:o,retryDelay:a}=e;return(({chain:c,pollingInterval:l=4e3,timeout:d,...u})=>{let h=t,p=()=>{};const y=tf({key:s,name:n,async request({method:m,params:w}){let E;const I=async(k=0)=>{const D=h[k]({...u,chain:c,retryCount:0,timeout:d});try{const j=await D.request({method:m,params:w});return p({method:m,params:w,response:j,transport:D,status:"success"}),j}catch(j){if(p({error:j,method:m,params:w,transport:D,status:"error"}),i(j)||k===h.length-1||(E??(E=h.slice(k+1).some(f=>{const{include:v,exclude:C}=f({chain:c}).config.methods||{};return v?v.includes(m):C?!C.includes(m):!0})),!E))throw j;return I(k+1)}};return I()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:m=>p=m,transports:h.map(m=>m({chain:c,retryCount:0}))});if(r){const m=typeof r=="object"?r:{};Nf({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 y})}function Af(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===sf.code||t.code===nf.code||t.code===rf.code||of.nodeMessage.test(t.message)||t.code===5e3))}function Nf({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}),E=Date.now();let I,k;try{await(n?n({transport:w}):w.request({method:"net_listening"})),k=1}catch{k=0}finally{I=Date.now()}return{latency:I-E,success:k}}));d.push(h),d.length>r&&d.shift();const p=Math.max(...d.map(m=>Math.max(...m.map(({latency:w})=>w)))),y=o.map((m,w)=>{const E=d.map(f=>f[w].latency),k=1-E.reduce((f,v)=>f+v,0)/E.length/p,D=d.map(f=>f[w].success),j=D.reduce((f,v)=>f+v,0)/D.length;return j===0?[0,w]:[l*k+c*j,w]}).sort((m,w)=>w[0]-m[0]);s(y.map(([,m])=>o[m])),await af(e),u()};u()}var Wc={};const $={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},Pu={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return(t==null?void 0:t.filter(s=>s.chainNamespace===e))||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){var r;if(!e)return;const s=t.find(i=>i.caipNetworkId===e);if(s)return s.name;const[n]=e.split(":");return((r=$.CHAIN_NAME_MAP)==null?void 0:r[n])||void 0}},xu=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var _f=20,Sf=1,An=1e6,zc=1e6,Tf=-7,Of=21,kf=!1,ii="[big.js] ",Pn=ii+"Invalid ",yo=Pn+"decimal places",Pf=Pn+"rounding mode",Ru=ii+"Division by zero",Ne={},ls=void 0,xf=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function $u(){function t(e){var s=this;if(!(s instanceof t))return e===ls?$u():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(Pn+"value");e=e===0&&1/e<0?"-0":String(e)}Rf(s,e)}s.constructor=t}return t.prototype=Ne,t.DP=_f,t.RM=Sf,t.NE=Tf,t.PE=Of,t.strict=kf,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function Rf(t,e){var s,n,r;if(!xf.test(e))throw Error(Pn+"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 xn(t,e,s,n){var r=t.c;if(s===ls&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(Pf);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]!==ls))),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]!==ls||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 Rn(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>An)throw Error(yo);if(!r[0])throw Error(Ru);if(!n[0])return t.s=i,t.c=[t.e=0],t;
2var a,c,l,d,u,h=r.slice(),p=a=r.length,y=n.length,m=n.slice(0,a),w=m.length,E=t,I=E.c=[],k=0,D=o+(E.e=e.e-t.e)+1;for(E.s=i,i=D<0?0:D,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}I[k++]=d?l:++l,m[0]&&d?m[w]=n[p]||0:m=[n[p]]}while((p++<y||m[0]!==ls)&&i--);return!I[0]&&k!=1&&(I.shift(),E.e--,D--),k>D&&xn(E,D,s.RM,m[0]!==ls),E};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(Ru);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<-zc||t>zc)throw Error(Pn+"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>An)throw Error(Pn+"precision");return xn(new this.constructor(this),t,e)};Ne.round=function(t,e){if(t===ls)t=0;else if(t!==~~t||t<-An||t>An)throw Error(yo);return xn(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(ii+"No square root");i=Math.sqrt(+Rn(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 xn(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!==ls){if(t!==~~t||t<0||t>An)throw Error(yo);for(s=xn(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return Rn(s,!0,!!n)};Ne.toFixed=function(t,e){var s=this,n=s.c[0];if(t!==ls){if(t!==~~t||t<0||t>An)throw Error(yo);for(s=xn(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return Rn(s,!1,!!n)};Ne[Symbol.for("nodejs.util.inspect.custom")]=Ne.toJSON=Ne.toString=function(){var t=this,e=t.constructor;return Rn(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};Ne.toNumber=function(){var t=+Rn(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(ii+"Imprecise conversion");return t};Ne.toPrecision=function(t,e){var s=this,n=s.constructor,r=s.c[0];if(t!==ls){if(t!==~~t||t<1||t>An)throw Error(Pn+"precision");for(s=xn(new n(s),t,e);s.c.length<t;)s.c.push(0)}return Rn(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(ii+"valueOf disallowed");return Rn(t,t.e<=e.NE||t.e>=e.PE,!0)};var $s=$u();const $f={bigNumber(t){return t?new $s(t):new $s(0)},multiply(t,e){if(t===void 0||e===void 0)return new $s(0);const s=new $s(t),n=new $s(e);return s.times(n)},toFixed(t,e=2){return t===void 0||t===""?new $s(0).toFixed(e):new $s(t).toFixed(e)},formatNumberToLocalString(t,e=2){return t===void 0||t===""?"0.00":typeof t=="number"?t.toLocaleStr
2ing("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 $s(e).toNumber()}},Uf=[{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"}]}],Df=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Lf=[{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"}]}],Bf={getERC20Abi:t=>$.USDT_CONTRACT_ADDRESSES.includes(t)?Lf:Uf,getSwapAbi:()=>Df},ot={validateCaipAddress(t){var e;if(((e=t.split(":"))==null?void 0:e.length)!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,n,r]=e;if(!s||!n||!r)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:n,address:r}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,n]=e;if(!s||!n)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:n}}},Js={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 Js.isRpcProviderError(t)?t.code===Js.RPC_ERROR_CODE.USER_REJECTED_REQUEST||Js.isUserRejectedMessage(t.message):t instanceof Error?Js.isUserRejectedMessage(t.message):!1}};class Mf extends Error{constructor(e,s){super(s.message,{cause:e}),this.name=Js.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=s.code}}class Uu extends Mf{constructor(e){super(e,{code:Js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=Js.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const ee={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",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 Po(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Z={setItem(t,e){Rr()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(Rr())return localStorage.getItem(t)||void 0},removeItem(t){Rr()&&localStorage.removeItem(t)},clear(){Rr()&&localStorage.clear()}};function Rr(){return typeof window<"u"&&typeof localStorage<"u"}function Yi(t,e){return e==="light"?{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const jf=Symbol(),Hc=Object.getPrototypeOf,ba=new WeakMap,Ff=t=>t&&(ba.has(t)?ba.get(t):Hc(t)===Object.prototype||Hc(t)===Array.prototype),qf=t=>Ff(t)&&t[jf]||null,Kc=(t,e=!0)=>{ba.set(t,e)},Ji={},fc=t=>typeof t=="object"&&t!==null,Wf=t=>fc(t)&&!oi.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),Du=(t,e)=>{const s=va.get(t);if((s==null?void 0:s[0])===e)return s[1];const n=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return Kc(n,!0),va.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(oi.has(i))Kc(i,!1);else if(Qs.has(i)){const[c,l]=Qs.get(i);a.value=Du(c,l())}Object.defineProperty(n,r,a)}),Object.preventExtensions(n)},zf=(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&&(Vc(l,o)||Yr.has(o)&&Vc(l,Yr.get(o))))return!0;s(i),fc(o)&&(o=qf(o)||o);const d=!Qs.has(o)&&Kf(o)?ke(o):o;return e(i,d),Reflect.set(r,i,d,a),n(["set",[i],o,l]),!0}}),Qs=new WeakMap,oi=new WeakSet,va=new WeakMap,Di=[1],Yr=new WeakMap;let Vc=Object.is,Hf=(t,e)=>new Proxy(t,e),Kf=Wf,Vf=Du,Gf=zf;function ke(t={}){if(!fc(t))throw new Error("object required");const e=Yr.get(t);if(e)return e;let s=Di[0];const n=new Set,r=(w,E=++Di[0])=>
2{s!==E&&(i=s=E,n.forEach(I=>I(w,E)))};let i=s;const o=(w=Di[0])=>(i!==w&&(i=w,c.forEach(([E])=>{const I=E[1](w);I>s&&(s=I)})),s),a=w=>(E,I)=>{const k=[...E];k[1]=[w,...k[1]],r(k,I)},c=new Map,l=(w,E)=>{const I=!oi.has(E)&&Qs.get(E);if(I){if((Ji?"production":void 0)!=="production"&&c.has(w))throw new Error("prop listener already exists");if(n.size){const k=I[2](a(w));c.set(w,[I,k])}else c.set(w,[I])}},d=w=>{var E;const I=c.get(w);I&&(c.delete(w),(E=I[1])==null||E.call(I))},u=w=>(n.add(w),n.size===1&&c.forEach(([I,k],D)=>{if((Ji?"production":void 0)!=="production"&&k)throw new Error("remove already exists");const j=I[2](a(D));c.set(D,[I,j])}),()=>{n.delete(w),n.size===0&&c.forEach(([I,k],D)=>{k&&(k(),c.set(D,[I]))})});let h=!0;const p=Gf(()=>h,l,d,r),y=Hf(t,p);Yr.set(t,y);const m=[t,o,u];return Qs.set(y,m),Reflect.ownKeys(t).forEach(w=>{const E=Object.getOwnPropertyDescriptor(t,w);"value"in E&&E.writable&&(y[w]=t[w])}),h=!1,y}function Xe(t,e,s){const n=Qs.get(t);(Ji?"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 Jr(t){const e=Qs.get(t);(Ji?"production":void 0)!=="production"&&!e&&console.warn("Please use proxy object");const[s,n]=e;return Vf(s,n())}function ir(t){return oi.add(t),t}function Yf(){return{proxyStateMap:Qs,refSet:oi,snapCache:va,versionHolder:Di,proxyCache:Yr}}function Ze(t,e,s,n){let r=t[e];return Xe(t,()=>{const i=t[e];Object.is(r,i)||s(r=i)})}const{proxyStateMap:Jf,snapCache:Xf}=Yf(),vi=t=>Jf.has(t);function Zf(t){const e=[];let s=0;const n=new Map,r=new WeakMap,i=()=>{const l=Xf.get(a),d=l==null?void 0:l[1];if(d&&!r.has(d)){const u=new Map(n);r.set(d,u)}},o=l=>r.get(l)||n,a={data:e,index:s,epoch:0,get size(){return vi(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(!vi(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(!vi(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(!vi(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,n.clear()},forEach(l){this.epoch,o(this).forEach((u,h)=>{l(this.data[u],h,this)})},*entries(){this.epoch;const l=o(this);for(const[d,u]of l)yield[d,this.data[u]]},*keys(){this.epoch;const l=o(this);for(const d of l.keys())yield d},*values(){this.epoch;const l=o(this);for(const d of l.values())yield this.data[d]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=ke(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}var Gc={};const xo=(typeof process<"u"&&typeof Gc<"u"?Gc.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Lu=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Qf="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",ye={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:xo,SECURE_SITE_DASHBOARD:`${xo}/dashboard`,SECURE_SITE_FAVICON:`${xo}/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:[$.CHAIN.EVM,$.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[$.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:[$.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[$.CHAIN.EVM,$.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[$.CHAIN.EVM,$.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[$.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:[$.CHAIN.EVM,$.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}},M={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=M.getActiveNamespace(),e=M.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{Z.setItem(ee.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Z.getItem(ee.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Z.removeItem(ee.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Z.setItem(ee.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Z.setItem(ee.ACTIVE_CAIP_NETWORK_ID,t),M.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Z.getItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Z.removeItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=Po(t);Z.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=M.getRecentWallets();e.find(n=>n.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Z.setItem(ee.RECENT_WALLETS,JSON.stringify(e)),Z.setItem(ee.RECENT_WALLET,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Z.getItem(ee.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const t=Z.getItem(ee.RECENT_WALLET);return t?JSON.parse(t):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Z.removeItem(ee.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(t,e){try{const s=Po(t);Z.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Z.getItem(ee.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=Po(t);return Z.getItem(e)}catch{console.info("Unable to get connected connector id in namespace",t)}},setConnectedSocialProvider(t){try{Z.setItem(ee.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Z.getItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Z.removeItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Z.getItem(ee.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var s;const t=Z.getItem(ee.ACTIVE_CAIP_NETWORK_ID);return(s=t==null?void 0:t.split(":"))==null?void 0:s[1]},setConnectionStatus(t){try{Z.setItem(ee.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Z.getItem(ee.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Z.getItem(ee.CONNECTED_NAMESPACES);return t!=null&&t.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Z.setItem(ee.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=M.getConnectedNamespaces();e.includes(t)||(e.push(t),M.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=M.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),M.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Z.getItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Z.setItem(ee.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Z.removeItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Z.getItem(ee.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=M.getBalanceCache();Z.setItem(ee.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=M.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;M.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=M.getBalanceCache();e[t.caipAddress]=t,Z.setItem(ee.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Z.getItem(ee.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=M.getBalanceCache();Z.setItem(ee.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const s=M.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),M.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=M.getNativeBalanceCache();e[t.caipAddress]=t,Z.setItem(ee.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Z.getItem(ee.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t}
vendor: 4,522 bytes, line 2
2,getEnsFromCacheForAddress(t){try{const s=M.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;M.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=M.getEnsCache();e[t.address]=t,Z.setItem(ee.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=M.getEnsCache();Z.setItem(ee.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Z.getItem(ee.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=M.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;M.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=M.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Z.setItem(ee.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=M.getIdentityCache();Z.setItem(ee.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Z.removeItem(ee.PORTFOLIO_CACHE),Z.removeItem(ee.NATIVE_BALANCE_CACHE),Z.removeItem(ee.ENS_CACHE),Z.removeItem(ee.IDENTITY_CACHE),Z.removeItem(ee.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Z.setItem(ee.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Z.getItem(ee.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s=M.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===$.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())};Z.setItem(ee.CONNECTIONS,JSON.stringify(i))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=Z.getItem(ee.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}},deleteAddressFromConnection({connectorId:t,address:e,namespace:s}){try{const n=M.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())})),Z.setItem(ee.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=Z.getItem(ee.DISCONNECTED_CONNECTOR_IDS);return t?JSON.parse(t):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(t,e){try{const s=M.getDisconnectedConnectorIds(),n=s[e]??[];n.push(t),Z.setItem(ee.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=M.getDisconnectedConnectorIds();let n=s[e]??[];n=n.filter(r=>r.toLowerCase()!==t.toLowerCase()),Z.setItem(ee.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(M.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=Z.getItem(ee.HISTORY_TRANSACTIONS_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:t,chainId:e=""}){var s;try{const r=(s=M.getTransactionsCache()[t])==null?void 0:s[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory)
2)return r.transactions;M.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=M.getTransactionsCache();r[t]={...r[t],[e]:{timestamp:s,transactions:n}},Z.setItem(ee.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=M.getTransactionsCache(),n=(s==null?void 0:s[t])||{},{[e]:r,...i}=n;Z.setItem(ee.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...s,[t]:i}))}catch{console.info("Unable to remove transactions cache",{address:t,chainId:e})}},getTokenPriceCache(){try{const t=Z.getItem(ee.TOKEN_PRICE_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(t){try{const s=M.getTokenPriceCache()[t.join(",")];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.tokenPrice))return s.tokenPrice;M.removeTokenPriceCache(t)}catch{console.info("Unable to get token price cache for addresses",t)}},updateTokenPriceCache(t){try{const e=M.getTokenPriceCache();e[t.addresses.join(",")]={timestamp:t.timestamp,tokenPrice:t.tokenPrice},Z.setItem(ee.TOKEN_PRICE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update token price cache",t)}},removeTokenPriceCache(t){try{const e=M.getTokenPriceCache();Z.setItem(ee.TOKEN_PRICE_CACHE,JSON.stringify({...e,[t.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",t)}},getLatestAppKitVersion(){try{const t=this.getLatestAppKitVersionCache(),e=t==null?void 0:t.version;return e&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.latestAppKitVersion)?e:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const t=Z.getItem(ee.LATEST_APPKIT_VERSION);return t?JSON.parse(t):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(t){try{const e=M.getLatestAppKitVersionCache();e.timestamp=t.timestamp,e.version=t.version,Z.setItem(ee.LATEST_APPKIT_VERSION,JSON.stringify(e))}catch{console.info("Unable to update latest AppKit version on local storage",t)}}},J={isMobile(){var t;return this.isClient()?!!(window!=null&&window.matchMedia&&typeof window.matchMedia=="function"&&((t=window.matchMedia("(pointer:coarse)"))!=null&&t.matches)||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t==null?void 0:t.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return J.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window==null?void 0:window.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=ye.TEN_SEC_MS:!0},isAllowedRetry(t,e=ye.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return(window==null?void 0:window.self)!==(window==null?void 0:window.top)}catch{return!1}},isSafeApp(){var t,e;if(J.isClient()&&window.self!==window.top)try{const s=(e=(t=window==null?void 0:window.location)==null?void 0:t.ancestorOrigins)==null?void 0:e[0],n="https://app.safe.global";if(s){const r=new URL(s),i=new URL(n);return r.hostname===i.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+ye.FOUR_MINUTES_MS},getNetworkId(t){return t==null?void 0:t.split(":")[1]},getPlainAddress(t){return t==null?void 0:t.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let s;return(...n)=>{function r(){t(...n)}s&&clearTimeout(s),s=setTimeout(r,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(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!=null&&r.endsWith("/"))&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${n}wc?uri=${i}`,redirectUniversalLink:r?`${r}wc?uri=${i}`:void 0,href:n}},formatUniversalUrl(t,e){if(!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()?M.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window==null||window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window==null?void 0:window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){var s,n;if(typeof window>"u")return!1;const t=window!=null&&window.matchMedia&&typeof window.matchMedia=="function"?(s=window.matchMedia("(display-mode: standalone)"))==null?void 0:s.matches:!1,e=(n=window==null?void 0:window.navigator)==null?void 0:n.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,n)=>{const r=new Image;r.onload=s,r.onerror=n,r.crossOrigin="anonymous",r.src=t});return Promise.race([e,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 $.W3M_API_URL},getBlockchainApiUrl(){return $.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return $.PULSE_API_URL},getUUID(){return crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){var e,s;return typeof t=="string"?t:typeof((s=(e=t==null?void 0:t.issues)==null?void 0:e[0])==null?void 0:s.message)=="str
2ing"?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?ye.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 $.CHAIN_NAME_MAP},getAccount(t){return t?typeof t=="string"?{address:t,chainId:void 0}:{address:t.address,chainId:t.chainId}:{address:void 0,chainId:void 0}},isMac(){const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window==null?void 0:window.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const r="provider_authorization_url=",i=t.substring(t.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(i),s,e);return t.replace(i,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const n=t.indexOf(e);if(n===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const r=t.indexOf("&",n),i=e.length,o=r!==-1?r:t.length,a=t.substring(0,n+i),c=t.substring(n+i,o),l=t.substring(r),d=c+s;return a+d+l}};async function br(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class ai{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 br(i,{method:"GET",headers:e,signal:s,cache:n})).json()}async getBlob({headers:e,signal:s,...n}){const r=this.createUrl(n);return(await br(r,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await br(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 br(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 br(i,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}createUrl({path:e,params:s}){const n=new URL(e,this.baseUrl);return s&&Object.entries(s).forEach(([r,i])=>{i&&n.searchParams.append(r,i)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}sendBeacon({body:e,...s}){const n=this.createUrl(s);return navigator.sendBeacon(n.toString(),e?JSON.stringify(e):void 0)}}const Ea={getFeatureValue(t,e){const s=e==null?void 0:e[t];return s===void 0?ye.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(){var t,e,s,n;return Array.isArray((t=R.state.features)==null?void 0:t.socials)&&((e=R.state.features)==null?void 0:e.socials.length)>0||Array.isArray((s=R.state.remoteFeatures)==null?void 0:s.socials)&&((n=R.state.remoteFeatures)==null?void 0:n.socials.length)>0},isEmailEnabled(){var t,e;return!!((t=R.state.features)!=null&&t.email||(e=R.state.remoteFeatures)!=null&&e.email)}},Q=ke({features:ye.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:ye.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1}),R={state:Q,subscribeKey(t,e){return Ze(Q,t,e)},setOptions(t){Object.assign(Q,t)},setRemoteFeatures(t){var s,n;if(!t)return;const e={...Q.remoteFeatures,...t};Q.remoteFeatures=e,(s=Q.remoteFeatures)!=null&&s.socials&&(Q.remoteFeatures.socials=Ea.filterS
2ocialsByPlatform(Q.remoteFeatures.socials)),(n=Q.features)!=null&&n.pay&&(Q.remoteFeatures.email=!1,Q.remoteFeatures.socials=!1)},setFeatures(t){var s;if(!t)return;Q.features||(Q.features=ye.DEFAULT_FEATURES);const e={...Q.features,...t};Q.features=e,(s=Q.features)!=null&&s.pay&&Q.remoteFeatures&&(Q.remoteFeatures.email=!1,Q.remoteFeatures.socials=!1)},setProjectId(t){Q.projectId=t},setCustomRpcUrls(t){Q.customRpcUrls=t},setAllWallets(t){Q.allWallets=t},setIncludeWalletIds(t){Q.includeWalletIds=t},setExcludeWalletIds(t){Q.excludeWalletIds=t},setFeaturedWalletIds(t){Q.featuredWalletIds=t},setTokens(t){Q.tokens=t},setTermsConditionsUrl(t){Q.termsConditionsUrl=t},setPrivacyPolicyUrl(t){Q.privacyPolicyUrl=t},setCustomWallets(t){Q.customWallets=t},setIsSiweEnabled(t){Q.isSiweEnabled=t},setIsUniversalProvider(t){Q.isUniversalProvider=t},setSdkVersion(t){Q.sdkVersion=t},setMetadata(t){Q.metadata=t},setDisableAppend(t){Q.disableAppend=t},setEIP6963Enabled(t){Q.enableEIP6963=t},setDebug(t){Q.debug=t},setEnableWalletGuide(t){Q.enableWalletGuide=t},setEnableAuthLogger(t){Q.enableAuthLogger=t},setEnableWallets(t){Q.enableWallets=t},setPreferUniversalLinks(t){Q.experimental_preferUniversalLinks=t},setSIWX(t){if(t)for(const[e,s]of Object.entries(ye.SIWX_DEFAULTS))t[e]??(t[e]=s);Q.siwx=t},setConnectMethodsOrder(t){Q.features={...Q.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){Q.features={...Q.features,walletFeaturesOrder:t}},setSocialsOrder(t){Q.remoteFeatures={...Q.remoteFeatures,socials:t}},setCollapseWallets(t){Q.features={...Q.features,collapseWallets:t}},setEnableEmbedded(t){Q.enableEmbedded=t},setAllowUnsupportedChain(t){Q.allowUnsupportedChain=t},setManualWCControl(t){Q.manualWCControl=t},setEnableNetworkSwitch(t){Q.enableNetworkSwitch=t},setEnableMobileFullScreen(t){Q.enableMobileFullScreen=J.isMobile()&&t},setEnableReconnect(t){Q.enableReconnect=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(Q.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){Q.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return Q.universalProviderConfigOverride},getSnapshot(){return Jr(Q)}},dn=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),je=ke({...dn}),eg={state:je,subscribeKey(t,e){return Ze(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=dn.message,je.variant=dn.variant,je.svg=dn.svg,je.open=dn.open,je.autoClose=dn.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:n=dn.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)}},os=eg,tg={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"}]}]},Bu=J.getBlockchainApiUrl(),dt=ke({clientId:null,api:new ai({baseUrl:Bu,clientId:null}),supportedChains:{http:[],ws:[]}}),re={state:dt,async get(t){const{st:e,sv:s}=re.getSdkProperties(),n=R.state.projectId,r={...t.params||{},st:e,sv:s,projectId:n};return dt.api.get({...t,params:r})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=R.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;
2try{dt.supportedChains.http.length||await re.getSupportedNetworks()}catch{return!1}return dt.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await re.get({path:"v1/supported-chains"});return dt.supportedChains=t,t}catch{return dt.supportedChains}},async fetchIdentity({address:t}){const e=M.getIdentityFromCacheForAddress(t);if(e)return e;const s=await re.get({path:`/v1/identity/${t}`,params:{sender:g.state.activeCaipAddress?J.getPlainAddress(g.state.activeCaipAddress):void 0}});return M.updateIdentityCache({address:t,identity:s,timestamp:Date.now()}),s},async fetchTransactions({account:t,cursor:e,signal:s,cache:n,chainId:r}){var c;if(!await re.isNetworkSupported((c=g.state.activeCaipNetwork)==null?void 0:c.caipNetworkId))return{data:[],next:void 0};const o=M.getTransactionsCacheForAddress({address:t,chainId:r});if(o)return o;const a=await re.get({path:`/v1/account/${t}/history`,params:{cursor:e,chainId:r},signal:s,cache:n});return M.updateTransactionsCache({address:t,chainId:r,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:n,gasPrice:r}){var o;return await re.isNetworkSupported((o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?re.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:s,to:n,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){var s;return await re.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?re.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){var r;if(!await re.isNetworkSupported((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))return{fungibles:[]};const s=M.getTokenPriceCacheForAddresses(t);if(s)return s;const n=await dt.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:R.state.projectId},headers:{"Content-Type":"application/json"}});return M.updateTokenPriceCache({addresses:t,timestamp:Date.now(),tokenPrice:n}),n},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){var n;return await re.isNetworkSupported((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?re.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){var r;const{st:e,sv:s}=re.getSdkProperties();if(!await re.isNetworkSupported((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))throw new Error("Network not supported for Gas Price");return re.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:s}})},async generateSwapCalldata({amount:t,from:e,to:s,userAddress:n,disableEstimate:r}){var o;if(!await re.isNetworkSupported((o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return dt.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:ye.CONVERT_SLIPPAGE_TOLERANCE},projectId:R.state.projectId,from:e,to:s,userAddress:n,disableEstimate:r}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){var o;const{st:n,sv:r}=re.getSdkProperties();if(!await re.isNetworkSupported((o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return re.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:t,to:e,st:n,sv:r}})},async getBalance(t,e,s){var l;const{st:n,sv:r}=re.getSdkProperties();if(!await re.isNetworkSupported((l=g.state.activeCaipNetwork)==null?void 0:l.caipNetworkId))return os.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=M.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await re.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:n,sv:r}});return M.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){var s;return await re.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?re.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){var n,r;if(!await re.isNetworkSupported((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId))return[];const s=(r=g.getAccountData())==null?void 0:r.address;return re.get({path:`/v1/profile/reverse/${t}`,params:{sender:s,apiVersion:"2"}})},async getEnsNameSuggestions(t){var s;return await re.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?re.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:n}){var i;return await re.isNetworkSupported((i=g.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?dt.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:s,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:s,purchaseAmount:n,paymentAmount:r}){var a;return await re.isNetworkSupported((a=g.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await dt.api.post({path:"/v1/generators/onrampurl",params:{projectId:R.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:r}})).url:""},async getOnrampOptions(){var e;if(!await re.isNetworkSupported((e=g.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await re.get({path:"/v1/onramp/options"})}catch{return tg}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}){var r;try{return await re.isNetworkSupported((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?await dt.api.post({path:"/v1/onramp/quote",params:{projectId:R.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}}):null}catch{return{networkFee:{amount:s,currency:e.id},paymentSubtotal:{amount:s,currency:e.id},paymentTotal:{amount:s,currency:e.id},purchaseAmount:{amount:s,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){var s;return await re.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?re.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){var r;return await re.isNetworkSupported((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?dt.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:R.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){dt.clientId=t,dt.api=new ai({baseUrl:Bu,clientId:t})}}
2,As={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"}},Ut={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"}},sg={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,n=encodeURIComponent(s);if(t===Ut.PHANTOM.id&&!("phantom"in window)){const r=s.startsWith("https")?"https":"http",i=s.split("/")[2],o=encodeURIComponent(`${r}://${i}`);window.location.href=`${Ut.PHANTOM.url}/ul/browse/${n}?ref=${o}`}if(t===Ut.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Ut.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),e===$.CHAIN.SOLANA&&t===Ut.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Ut.COINBASE.url}/dapp?cb_url=${n}`),e===$.CHAIN.BITCOIN&&t===Ut.BINANCE.id&&!("binancew3w"in window)){const r=g.state.activeCaipNetwork,i=window.btoa("/pages/browser/index"),o=window.btoa(`url=${n}&defaultChainId=${(r==null?void 0:r.id)??1}`),a=new URL(Ut.BINANCE.deeplink);a.searchParams.set("appId",Ut.BINANCE.appId),a.searchParams.set("startPagePath",i),a.searchParams.set("startPageQuery",o);const c=new URL(Ut.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}},ng=Object.freeze({enabled:!0,events:[]}
2),rg=new ai({baseUrl:J.getAnalyticsUrl(),clientId:null}),ig=5,og=60*1e3,Us=ke({...ng}),ag={state:Us,subscribeKey(t,e){return Ze(Us,t,e)},async sendError(t,e){if(!Us.enabled)return;const s=Date.now();if(Us.events.filter(i=>{const o=new Date(i.properties.timestamp||"").getTime();return s-o<og}).length>=ig)return;const r={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Us.events.push(r);try{if(typeof window>"u")return;const{projectId:i,sdkType:o,sdkVersion:a}=R.state;await rg.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(){Us.enabled=!0},disable(){Us.enabled=!1},clearEvents(){Us.events=[]}};class Nn 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,Nn.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,Nn):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Yc(t,e){let s="";try{t instanceof Error?s=t.message:typeof t=="string"?s=t:typeof t=="object"&&t!==null?Object.keys(t).length===0?s="Unknown error":s=(t==null?void 0:t.message)||JSON.stringify(t):s=String(t)}catch(r){s="Unknown error",console.error("Error parsing error message",r)}const n=t instanceof Nn?t:new Nn(s,e,t);throw ag.sendError(n,n.category),n}function qt(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 Yc(a,e)}}:i=(...o)=>{try{return r(...o)}catch(a){return Yc(a,e)}},s[n]=i}else s[n]=r}),s}const Ct=ke({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),cg={state:Ct,subscribeNetworkImages(t){return Xe(Ct.networkImages,()=>t(Ct.networkImages))},subscribeKey(t,e){return Ze(Ct,t,e)},subscribe(t){return Xe(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}},Bt=qt(cg),lg={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:""},Ro=ke({networkImagePromises:{}}),Mu={async fetchWalletImage(t){if(t)return await te._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(Ro.networkImagePromises[t]||(Ro.networkImagePromises[t]=te._fetchNetworkImage(t)),await Ro.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return Bt.state.walletImages[t]},getWalletImage(t){if(t!=null&&t.image_url)return t==null?void 0:t.image_url;if(t!=null&&t.image_id)return Bt.state.walletImages[t.image_id]},getNetworkImage(t){var e,s,n;if((e=t==null?void 0:t.assets)!=null&&e.imageUrl)return(s=t==null?void 0:t.assets)==null?void 0:s.imageUrl;if((n=t==null?void 0:t.assets)!=null&&n.imageId)return Bt.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return Bt.state.networkImages[t]},getConnectorImage(t){var e;if(t!=null&&t.imageUrl)return t.imageUrl;if((e=t==null?void 0:t.info)!=null&&e.icon)return t.info.icon;if(t!=null&&t.imageId)return Bt.state.connectorImages[t.imageId]},getChainImage(t){return Bt.state.networkImages[lg[t]]},getTokenImage(t){if(t)return Bt.state.tokenImages[t]}},dg=J.getAnalyticsUrl(),ug=new ai({baseUrl:dg,clientId:null}
4),hg=["MODAL_CREATED"],pg=45,Jc=1e3*10,$e=ke({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),le={state:$e,subscribe(t){return Xe($e,()=>t($e))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=R.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},shouldFlushEvents(){const t=JSON.stringify($e.pendingEvents).length/1024>pg,e=$e.lastFlush+Jc<Date.now();return t||e},_setPendingEvent(t){var e,s;try{let n=(e=g.getAccountData())==null?void 0:e.address;if("address"in t.data&&t.data.address&&(n=t.data.address),hg.includes(t.data.event)||typeof window>"u")return;const r=(s=g.getActiveCaipNetwork())==null?void 0:s.caipNetworkId;this.state.pendingEvents.push({eventId:J.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:n,properties:{..."properties"in t.data?t.data.properties:{},caipNetworkId:r}}}),$e.reportedErrors.FORBIDDEN=!1,le.shouldFlushEvents()&&le._submitPendingEvents()}catch(n){console.warn("_setPendingEvent",n)}},sendEvent(t){var s;$e.timestamp=Date.now(),$e.data=t;const e=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];((s=R.state.features)!=null&&s.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]}}),ug.sendBeacon({path:"/batch",params:le.getSdkProperties(),body:t}),$e.reportedErrors.FORBIDDEN=!1,$e.pendingEvents=[],$e.walletImpressions=[]}catch{$e.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){var t,e,s;$e.subscribedToVisibilityChange||typeof document>"u"||($e.subscribedToVisibilityChange=!0,(t=document==null?void 0:document.addEventListener)==null||t.call(document,"visibilitychange",()=>{document.visibilityState==="hidden"&&le._submitPendingEvents()}),(e=document==null?void 0:document.addEventListener)==null||e.call(document,"freeze",()=>{le._submitPendingEvents()}),(s=window==null?void 0:window.addEventListener)==null||s.call(window,"pagehide",()=>{le._submitPendingEvents()}),setInterval(()=>{le._submitPendingEvents()},Jc))}},fg=J.getApiUrl(),ut=new ai({baseUrl:fg,clientId:null}),gg=40,Xc=4,mg=20,ae=ke({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1,explorerWallets:[],explorerFilteredWallets:[]}),te={state:ae,subscribeKey(t,e){return Ze(ae,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=R.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return R.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${ut.baseUrl}/getWalletImage/${t}`,s=await ut.getBlob({path:e,params:te._getSdkProperties()});Bt.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${ut.baseUrl}/public/getAssetImage/${t}`,s=await ut.getBlob({path:e,params:te._getSdkProperties()});Bt.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${ut.baseUrl}/public/getAssetImage/${t}`,s=await ut.getBlob({path:e,params:te._getSdkProperties()});Bt.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${ut.baseUrl}/public/getCurrencyImage/${t}`,s=await ut.getBlob({path:e,params:te._getSdkProperties()});Bt.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${ut.baseUrl}/public/getTokenImage/${t}`,s=await ut.getBlob({path:e,params:te._getSdkProperties()});Bt.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){const e=t.length,s=J.isMobile()?t==null?void 0:t.filter(r=>r.mobile_link||r.webapp_link?!0:Object.values(Ut).map(o=>o.id).includes(r.id)):t,n=e-s.length;return{filteredWallets:s,mobileFilteredOutWalletsLength:n}},async fetchProjectConfig(){return(await ut.get({path:"/appkit/v1/config",params:te._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await ut.get({path:"/projects/v1/origins",params:te._getSdkProperties()});return t}catch(t){if(t instanceof Error&&t.cause instanceof Response){const e=t.cause.status;if(e===$.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:t});if(e>=$.HTTP_STATUS_CODES.SERVER_ERROR&&e<600)throw new Error("SERVER_ERROR",{cause:t});return[]}return[]}},async fetchNetworkImages(){const t=g.getAllRequestedCaipNetworks(),e=t==null?void 0:t.map(({assets:s})=>
4s==null?void 0:s.imageId).filter(Boolean).filter(s=>!Mu.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>te._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=q.state,e=t.map(({imageId:s})=>s).filter(Boolean);await Promise.allSettled(e.map(s=>te._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>te._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>te._fetchTokenImage(e)))},async fetchWallets(t){var o;const e=t.exclude??[];te._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Ut).map(a=>a.id));const n=await ut.get({path:"/getWallets",params:{...te._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:(o=t.include)==null?void 0:o.join(","),exclude:e.join(",")}}),{filteredWallets:r,mobileFilteredOutWalletsLength:i}=te._filterWalletsByPlatform(n==null?void 0:n.data);return{data:r||[],count:n==null?void 0:n.count,mobileFilteredOutWalletsLength:i}},async prefetchWalletRanks(){const t=q.state.connectors;if(!(t!=null&&t.length))return;const e={page:1,entries:20,badge:"certified"};if(e.names=t.map(r=>r.name).join(","),g.state.activeChain===$.CHAIN.EVM){const r=[...t.flatMap(i=>{var o;return((o=i.connectors)==null?void 0:o.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}))||[]}),...t.map(i=>{var o;return(o=i.info)==null?void 0:o.rdns})].filter(i=>typeof i=="string"&&i.length>0);r.length&&(e.rdns=r.join(","))}const{data:s}=await te.fetchWallets(e);ae.explorerWallets=s;const n=g.getRequestedCaipNetworkIds().join(",");ae.explorerFilteredWallets=s.filter(r=>{var i;return(i=r.chains)==null?void 0:i.some(o=>n.includes(o))})},async fetchFeaturedWallets(){const{featuredWalletIds:t}=R.state;if(t!=null&&t.length){const e={...te._getSdkProperties(),page:1,entries:(t==null?void 0:t.length)??Xc,include:t},{data:s}=await te.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=>te._fetchWalletImage(i))),ae.featured=n,ae.allFeatured=n}},async fetchRecommendedWallets(){try{ae.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=R.state,n=[...e??[],...s??[]].filter(Boolean),r=g.getRequestedCaipNetworkIds().join(","),i={page:1,entries:Xc,include:t,exclude:n,chains:r},{data:o,count:a}=await te.fetchWallets(i),c=M.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=>te._fetchWalletImage(u))),ae.recommended=o,ae.allRecommended=o,ae.count=a??0}catch{}finally{ae.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:n}=R.state,r=g.getRequestedCaipNetworkIds().join(","),i=[...ae.recommended.map(({id:u})=>u),...s??[],...n??[]].filter(Boolean),o={page:t,entries:gg,include:e,exclude:i,chains:r},{data:a,count:c,mobileFilteredOutWalletsLength:l}=await te.fetchWallets(o);ae.mobileFilteredOutWalletsLength=l+(ae.mobileFilteredOutWalletsLength??0);const d=a.slice(0,mg).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(d.map(u=>te._fetchWalletImage(u))),ae.wallets=J.uniqueBy([...ae.wallets,...te._filterOutExtensions(a)],"id").filter(u=>{var h;return(h=u.chains)==null?void 0:h.some(p=>r.includes(p))}),ae.count=c>ae.count?c:ae.count,ae.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await te.fetchWallets(e);s&&s.forEach(n=>{ae.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:n}=R.state,r=g.getRequestedCaipNetworkIds().join(",");ae.search=[];const i={page:1,entries:100,search:t==null?void 0:t.trim(),badge_type:e,include:s,exclude:n,chains:r},{data:o}=await te.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=>te._fetchWalletImage(c)),J.wait(300)]),ae.search=te._filterOutExtensions(o)},initPromise(t,e){const s=ae.promises[t];
4return s||(ae.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:n=!0,fetchWalletRanks:r=!0}={}){const i=[t&&te.initPromise("connectorImages",te.fetchConnectorImages),e&&te.initPromise("featuredWallets",te.fetchFeaturedWallets),s&&te.initPromise("recommendedWallets",te.fetchRecommendedWallets),n&&te.initPromise("networkImages",te.fetchNetworkImages),r&&te.initPromise("walletRanks",te.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){var t;(t=R.state.features)!=null&&t.analytics&&te.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await ut.get({path:"/getAnalyticsConfig",params:te._getSdkProperties()});R.setFeatures({analytics:t})}catch{R.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!(t!=null&&t.length)){ae.featured=ae.allFeatured,ae.recommended=ae.allRecommended;return}const e=g.getRequestedCaipNetworkIds().join(",");ae.featured=ae.allFeatured.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),ae.recommended=ae.allRecommended.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),ae.filteredWallets=ae.wallets.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))})},clearFilterByNamespaces(){ae.filteredWallets=[]},setFilterByNamespace(t){if(!t){ae.featured=ae.allFeatured,ae.recommended=ae.allRecommended;return}const e=g.getRequestedCaipNetworkIds().join(",");ae.featured=ae.allFeatured.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),ae.recommended=ae.allRecommended.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),ae.filteredWallets=ae.wallets.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))})}},Ce=ke({view:"Connect",history:["Connect"],transactionStack:[]}),yg={state:Ce,subscribeKey(t,e){return Ze(Ce,t,e)},pushTransactionStack(t){Ce.transactionStack.push(t)},popTransactionStack(t){const e=Ce.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:n,onCancel:r}=e;switch(t){case"success":s==null||s();break;case"error":n==null||n(),ne.goBack();break;case"cancel":r==null||r(),ne.goBack();break}},push(t,e){t!==Ce.view&&(Ce.view=t,Ce.history.push(t),Ce.data=e)},reset(t,e){Ce.view=t,Ce.history=[t],Ce.data=e},replace(t,e){Ce.history.at(-1)===t||(Ce.view=t,Ce.history[Ce.history.length-1]=t,Ce.data=e)},goBack(){var n,r;const t=g.state.activeCaipAddress,e=ne.state.view==="ConnectingFarcaster",s=!t&&e;if(Ce.history.length>1){Ce.history.pop();const[i]=Ce.history.slice(-1);i&&(t&&i==="Connect"?Ce.view="Account":Ce.view=i)}else he.close();(n=Ce.data)!=null&&n.wallet&&(Ce.data.wallet=void 0),(r=Ce.data)!=null&&r.redirectView&&(Ce.data.redirectView=void 0),setTimeout(()=>{var i,o,a;if(s){g.setAccountProp("farcasterUrl",void 0,g.state.activeChain);const c=q.getAuthConnector();(i=c==null?void 0:c.provider)==null||i.reload();const l=Jr(R.state);(a=(o=c==null?void 0:c.provider)==null?void 0:o.syncDappData)==null||a.call(o,{metadata:l.metadata,sdkVersion:l.sdkVersion,projectId:l.projectId,sdkType:l.sdkType})}},100)},goBackToIndex(t){if(Ce.history.length>1){Ce.history=Ce.history.slice(0,t+1);const[e]=Ce.history.slice(-1);e&&(Ce.view=e)}},goBackOrCloseModal(){ne.state.history.length>1?ne.goBack():he.close()}},ne=qt(yg),ps=ke({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Ca={state:ps,subscribe(t){return Xe(ps,()=>t(ps))},setThemeMode(t){ps.themeMode=t;try{const e=q.getAuthConnector();if(e){const s=Ca.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:Yi(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){ps.themeVariables={...ps.themeVariables,...t};try{const e=q.getAuthConnector();if(e){const s=Ca.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:Yi(ps.themeVariables,ps.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Jr(ps)}},_t=qt(Ca),ju=Object.fromEntries(xu.map(t=>[t,void 0])),wg=Object.fromEntries(xu.map(t=>[t,!0])),be=ke({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:ju,filterByNamespaceMap:wg}),bg={state:be,subscribe(t){return Xe(be,()=>{t(be)})},subscribeKey(t,e){return Ze(be,t,e)}
4,initialize(t){t.forEach(e=>{const s=M.getConnectedConnectorId(e);s&&q.setConnectorId(s,e)})},setActiveConnector(t){t&&(be.activeConnector=ir(t))},setConnectors(t){t.filter(r=>!be.allConnectors.some(i=>i.id===r.id&&q.getConnectorName(i.name)===q.getConnectorName(r.name)&&i.chain===r.chain)).forEach(r=>{r.type!=="MULTI_CHAIN"&&be.allConnectors.push(ir(r))});const s=q.getEnabledNamespaces(),n=q.getEnabledConnectors(s);be.connectors=q.mergeMultiChainConnectors(n)},filterByNamespaces(t){Object.keys(be.filterByNamespaceMap).forEach(e=>{be.filterByNamespaceMap[e]=!1}),t.forEach(e=>{be.filterByNamespaceMap[e]=!0}),q.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){be.filterByNamespaceMap[t]=e,q.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=q.getEnabledNamespaces(),e=q.getEnabledConnectors(t),s=q.areAllNamespacesEnabled();be.connectors=q.mergeMultiChainConnectors(e),s?te.clearFilterByNamespaces():te.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(be.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return be.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(be.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=q.generateConnectorMapByName(t),s=[];return e.forEach(n=>{const r=n[0],i=(r==null?void 0:r.id)===$.CONNECTOR_ID.AUTH;n.length>1&&r?s.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...n],type:i?"AUTH":"MULTI_CHAIN",chain:"eip155",id:(r==null?void 0:r.id)||""}):r&&s.push(r)}),s},generateConnectorMapByName(t){const e=new Map;return t.forEach(s=>{const{name:n}=s,r=q.getConnectorName(n);if(!r)return;const i=e.get(r)||[];i.find(a=>a.chain===s.chain)||i.push(s),e.set(r,i)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(s=>{e.find(n=>n.chain===s.chain)||e.push(s)}),e},addConnector(t){var e,s,n;if(t.id===$.CONNECTOR_ID.AUTH){const r=t,i=Jr(R.state),o=_t.getSnapshot().themeMode,a=_t.getSnapshot().themeVariables;(s=(e=r==null?void 0:r.provider)==null?void 0:e.syncDappData)==null||s.call(e,{metadata:i.metadata,sdkVersion:i.sdkVersion,projectId:i.projectId,sdkType:i.sdkType}),(n=r==null?void 0:r.provider)==null||n.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:Yi(a,o)}),q.setConnectors([t])}else q.setConnectors([t])},getAuthConnector(t){var n;const e=t||g.state.activeChain,s=be.connectors.find(r=>r.id===$.CONNECTOR_ID.AUTH);if(s)return(n=s==null?void 0:s.connectors)!=null&&n.length?s.connectors.find(i=>i.chain===e):s},getAnnouncedConnectorRdns(){return be.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>{var e;return(e=t.info)==null?void 0:e.rdns})},getConnectorById(t){return be.allConnectors.find(e=>e.id===t)},getConnector({id:t,rdns:e,namespace:s}){const n=s||g.state.activeChain;return be.allConnectors.filter(i=>i.chain===n).find(i=>{var o;return i.explorerId===t||((o=i.info)==null?void 0:o.rdns)===e})},syncIfAuthConnector(t){var i,o;if(t.id!=="ID_AUTH")return;const e=t,s=Jr(R.state),n=_t.getSnapshot().themeMode,r=_t.getSnapshot().themeVariables;(o=(i=e==null?void 0:e.provider)==null?void 0:i.syncDappData)==null||o.call(i,{metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:Yi(r,n)})},getConnectorsByNamespace(t){const e=be.allConnectors.filter(s=>s.chain===t);return q.mergeMultiChainConnectors(e)},canSwitchToSmartAccount(t){return g.checkIfSmartAccountEnabled()&&jt(t)===As.ACCOUNT_TYPES.EOA},selectWalletConnector(t){var n;const e=(n=ne.state.data)==null?void 0:n.redirectView,s=q.getConnector({id:t.id,rdns:t.rdns});sg.handleMobileDeeplinkRedirect((s==null?void 0:s.explorerId)||t.id,g.state.activeChain),s?ne.push("ConnectingExternal",{connector:s,wallet:t,redirectView:e}):ne.push("ConnectingWalletConnect",{wallet:t,redirectView:e})},getConnectors(t){return t?q.getConnectorsByNamespace(t):q.mergeMultiChainConnectors(be.allConnectors)},setFilterByNamespace(t){be.filterByNamespace=t,be.connectors=q.getConnectors(t),te.setFilterByNamespace(t)},setConnectorId(t,e){t&&(be.activeConnectorIds={...be.activeConnectorIds,[e]:t},M.setConnectedConnectorId(e,t))},removeConnectorId(t){be.activeConnectorIds={...be.activeConnectorIds,[t]:void 0},M.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return be.activeConnectorIds[t]},isConnected(t){return t?!!be.activeConnectorIds[t]:Object.values(be.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){be.activeConnectorIds={...ju}}},q=qt(bg),vg=1e3,vr={checkNamespaceConnectorId(t,e){return q.getConnectorId(t)===e},isSocialProvider(t){return ye.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)=>
4{if(t&&q.setActiveConnector(e),r==null||r(J.isMobile()&&t),n){const l=he.subscribeKey("open",d=>{d||(ne.state.view!==n&&ne.replace(n),l(),a(new Error("Modal closed")))})}const c=g.subscribeKey("activeCaipAddress",l=>{l&&(i==null||i(),s&&he.close(),c(),o(ot.parseCaipAddress(l)))})})},connectExternal(t){return new Promise((e,s)=>{const n=g.subscribeKey("activeCaipAddress",r=>{r&&(he.close(),n(),e(ot.parseCaipAddress(r)))});H.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=g.getAccountData(e);let o=i==null?void 0:i.socialWindow,a=i==null?void 0:i.socialProvider,c=!1,l=null;const d=e||g.state.activeChain,u=g.subscribeKey("activeCaipAddress",h=>{h&&(s&&he.close(),u())});return new Promise((h,p)=>{async function y(w){var E;if((E=w.data)!=null&&E.resultUri)if(w.origin===$.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",y,!1);try{const I=q.getAuthConnector(d);if(I&&!c){const k=g.getAccountData(d);o&&(o.close(),g.setAccountProp("socialWindow",void 0,d),o=k==null?void 0:k.socialWindow),c=!0;const D=w.data.resultUri;if(a&&le.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:a}}),a){M.setConnectedSocialProvider(a),await H.connectExternal({id:I.id,type:I.type,socialUri:D},I.chain);const j=g.state.activeCaipAddress;if(!j){p(new Error("Failed to connect"));return}h(ot.parseCaipAddress(j)),le.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:a}})}}}catch(I){a&&le.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:a,message:J.parseError(I)}}),p(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=g.getAccountData(d);g.setAccountProp("socialProvider",t,d),a=w==null?void 0:w.socialProvider,le.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:a}})}if(a==="farcaster"){n==null||n();const w=he.subscribeKey("open",I=>{!I&&t==="farcaster"&&(p(new Error("Popup closed")),r==null||r(),w())}),E=q.getAuthConnector();if(E){const I=g.getAccountData(d);if(!(I!=null&&I.farcasterUrl))try{const{url:k}=await E.provider.getFarcasterUri();g.setAccountProp("farcasterUrl",k,d)}catch{p(new Error("Failed to connect to farcaster"))}}}else{const w=q.getAuthConnector();l=J.returnOpenHref(`${$.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(w&&a){const{uri:E}=await w.provider.getSocialRedirectUri({provider:a});if(l&&E){g.setAccountProp("socialWindow",ir(l),d),o=i==null?void 0:i.socialWindow,l.location.href=E;const I=setInterval(()=>{o!=null&&o.closed&&!c&&(p(new Error("Popup closed")),clearInterval(I))},1e3);window.addEventListener("message",y,!1)}else l==null||l.close(),p(new Error("Failed to initiate social connection"))}}catch{p(new Error("Failed to initiate social connection")),l==null||l.close()}}}m()})},connectEmail({closeModalOnConnect:t=!0,redirectViewOnModalClose:e="Connect",onOpen:s,onConnect:n}){return new Promise((r,i)=>{if(s==null||s(),e){const a=he.subscribeKey("open",c=>{c||(ne.state.view!==e&&ne.replace(e),a(),i(new Error("Modal closed")))})}const o=g.subscribeKey("activeCaipAddress",a=>{a&&(n==null||n(),t&&he.close(),o(),r(ot.parseCaipAddress(a)))})})},async updateEmail(){const t=M.getConnectedConnectorId(g.state.activeChain),e=q.getAuthConnector();if(!e)throw new Error("No auth connector found");if(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}))},vg),o=he.subscribeKey("open",a=>{a||(ne.state.view!=="Connect"&&ne.push("Connect"),clearInterval(i),o(),r(new Error("Modal closed")))})})},canSwitchToSmartAccount(t){return g.checkIfSmartAccountEnabled()&&jt(t)===As.ACCOUNT_TYPES.EOA}};function Fu(){var n,r;const t=((n=g.state.activeCaipNetwork)==null?void 0:n.chainNamespace)||"eip155",e=((r=g.state.activeCaipNetwork)==null?void 0:r.id)||1,s=ye.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`}function jt(t){var s;return(s=g.getAccountData(t))==null?void 0:s.preferredAccountType}function Ei(t){return g.state.activeCaipNetwork}const Xi={getConnectionStatus(t,e){const s=q.state.activeConnectorIds[e],n=H.getConnections(e);return!!s&&t.connectorId===s?"connected":n.some(o=>o.connectorId.toLowerCase()===t.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:t,connectorId:e,addresses:s}){return t.map(n=>{if((e?n.connectorId.toLowerCase()===e.toLowerCase():!1)&&s){const i=n.accounts.filter(o=>!s.some(c=>c.toLowerCase()===o.address.toLowerCase()));return{...n,accounts:i}}return n})},excludeExistingConnections(t,e){const s=new Set(t);return e.filter(n=>!s.has(n.connectorId))},getConnectionsByConnectorId(t,e){return t.filter(s=>s.connectorId.toLowerCase()===e.toLowerCase())},getConnectionsData(t){var a;const e=!!((a=R.state.remoteFeatures)!=null&&a.multiWallet),s=q.state.activeConnectorIds[t],n=H.getConnections(t),i=(H.state.recentConnections.get(t)??[]).filter(c=>q.getConnectorById(c.connectorId)),o=Xi.excludeExistingConnections([...n.map(c=>c.connectorId),...s?[s]:[]],i);return e?{connections:n,recentConnections:o}:{connections:n.filter(c=>c.connectorId.toLowerCase()===(s==null?void 0:s.toLowerCase())),recentConnections:[]}}},Pe=ke({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Eg={state:Pe,subscribe(t){return Xe(Pe,()=>t(Pe))},setLastNetworkInView(t){Pe.lastNetworkInView=t},async fetchTransactions(t){var e;if(!t)throw new Error("Transactions can't be fetched without an accountAddress");Pe.loading=!0;try{const s=await re.fetchTransactions({account:t,cursor:Pe.next,chainId:(e=g.state.activeCaipNetwork)==null?void 0:e.caipNetworkId}),n=Li.filterSpamTransactions(s.data),r=Li.filterByConnectedChain(n),i=[...Pe.transactions,...r];Pe.loading=!1,Pe.transactions=i,Pe.transactionsByYear=Li.groupTransactionsByYearAndMonth(Pe.transactionsByYear,r),Pe.empty=i.length===0,Pe.next=s.next?s.next:void 0}catch{const n=g.state.activeChain;le.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:R.state.projectId,cursor:Pe.next,isSmartAccount:jt(n)===As.ACCOUNT_TYPES.SMART_ACCOUNT}}),os.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=>{var r;return((r=n.nft_info)==null?void 0:r.flags.is_spam)===!0}))},filterByConnectedChain(t){var n;const e=(n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId;return t.filter(r=>r.metadata.chain===e)},clearCursor(){Pe.next=void 0},resetTransactions(){Pe.transactions=[],Pe.transactionsByYear={},Pe.lastNetworkInView=void 0,Pe.loading=!1,Pe.empty=!1,Pe.next=void 0}},Li=qt(Eg,"API_ERROR"),ge=ke({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,buffering:!1,status:"disconnected"});let rn;const Cg={state:ge,subscribe(t){return Xe(ge,()=>t(ge))},subscribeKey(t,e){return Ze(ge,t,e)},_getClient(){return ge._client},setClient(t){ge._client=ir(t)},initialize(t){const e=t.filter(s=>!!s.namespace).map(s=>s.namespace);H.syncStorageConnections(e)},syncStorageConnections(t){const e=M.getConnections(),s=t??Array.from(g.state.chains.keys());for(const n of s){const r=e[n]??[],i=new Map(ge.recentConnections);i.set(n,r),ge.recentConnections=i}},getConnections(t){return t?ge.connections.get(t)??[]:[]},hasAnyConnection(t){const e=H.state.connections;return Array.from(e.values()).flatMap(s=>s).some(({connectorId:s})=>s===t)},async connectWalletConnect({cache:t="auto"}={}){var s,n,r,i;const e=J.isTelegram()||J.isSafari()&&J.isIos();if(t==="always"||t==="auto"&&e){if(rn){await rn,rn=void 0;return}if(!J.isPairingExpired(ge==null?void 0:ge.wcPairingExpiry)){const o=ge.wcUri;ge.wcUri=o;return}rn=(n=(s=H._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:n.call(s).catch(()=>{}),H.state.status="connecting",await rn,rn=void 0,ge.wcPairingExpiry=void 0,H.state.status="connected"}else await((i=(r=H._getClient())==null?void 0:r.connectWalletConnect)==null?void 0:i.call(r))},async connectExternal(t,e,s=!0){var r,i;const n=await((i=(r=H._getClient())==null?void 0:r.connectExternal)==null?void 0:i.call(r,t));return s&&g.setActiveNamespace(e),n},async reconnectExternal(t){var s,n;await((n=(s=H._getClient())==null?void 0:s.reconnectExternal)==null?void 0:n.call(s,t));const e=t.chain||g.state.activeChain;e&&q.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){var n;if(!e)return;he.setLoading(!0,g.state.activeChain);const s=q.getAuthConnector();s&&(g.setAccountProp("preferredAccountType",t,e),await s.provider.setPreferredAccount(t),M.setPreferredAccountTypes(Object.entries(g.state.chains).reduce((r,[i,o])=>{const a=i,c=jt(a);return c!==void 0&&(r[a]=c),r},{})),await H.reconnectExternal(s),he.setLoading(!1,g.state.activeChain),le.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}}))},async signMessage(t){var e;return(e=H._getClient())==null?void 0:e.signMessage(t)},parseUnits(t,e){var s;return(s=H._getClient())==null?void 0:s.parseUnits(t,e)},formatUnits(t,e){var s;return(s=H._getClient())==null?void 0:s.formatUnits(t,e)},updateBalance(t){var e;return(e=H._getClient())==null?void 0:e.updateBalance(t)},async sendTransaction(t){var e;return(e=H._getClient())==null?void 0:e.sendTransaction(t)},async getCapabilities(t){var e;return(e=H._getClient())==null?void 0:e.getCapabilities(t)},async grantPermissions(t){var e;return(e=H._getClient())==null?void 0:e.grantPermissions(t)},async walletGetAssets(t){var e;return((e=H._getClient())==null?void 0:e.walletGetAssets(t))??{}},async estimateGas(t){var e;return(e=H._getClient())==null?void 0:e.estimateGas(t)},async writeContract(t){var e;return(e=H._getClient())==null?void 0:e.writeContract(t)},async getEnsAddress(t){var e;return(e=H._getClient())==null?void 0:e.getEnsAddress(t)},async getEnsAvatar(t){var e;return(e=H._getClient())==null?void 0:e.getEnsAvatar(t)},checkInstalled(t){var e,s;return((s=(e=H._getClient())==null?void 0:e.checkInstalled)==null?void 0:s.call(e,t))||!1},resetWcConnection(){ge.wcUri=void 0,ge.wcPairingExpiry=void 0,ge.wcLinking=void 0,ge.recentWallet=void 0,ge.status="disconnected",Li.resetTransactions(),M.deleteWalletConnectDeepLink(),M.deleteRecentWallet()},resetUri(){ge.wcUri=void 0,ge.wcPairingExpiry=void 0,rn=void 0},finalizeWcConnection(t){var n,r;const{wcLinking:e,recentWallet:s}=H.state;e&&M.setWalletConnectDeepLink(e),s&&M.setAppKitRecent(s),t&&le.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:t,properties:{method:e?"mobile":"qrcode",name:((r=(n=ne.state.data)==null?void 0:n.wallet)==null?void 0:r.name)||"Unknown",view:ne.state.view,walletRank:s==null?void 0:s.order}})},setWcBasic(t){ge.wcBasic=t},setUri(t){ge.wcUri=t,ge.wcPairingExpiry=J.getPairingExpiry()},setWcLinking(t){ge.wcLinking=t},setWcError(t){ge.wcError=t,ge.buffering=!1},setRecentWallet(t){ge.recentWallet=t},setBuffering(t){ge.buffering=t},setStatus(t){ge.status=t},setIsSwitchingConnection(t){ge.isSwitchingConnection=t},async disconnect({id:t,namespace:e,initialDisconnect:s}={}){var n;try{await((n=H._getClient())==null?void 0:n.disconnect({id:t,chainNamespace:e,initialDisconnect:s}))}catch(r){throw new Nn("Failed to disconnect","INTERNAL_SDK_ERROR",r)}},async disconnectConnector({id:t,namespace:e}){var s;try{await((s=H._getClient())==null?void 0:s.disconnectConnector({id:t,namespace:e}))}catch(n){throw new Nn("Failed to disconnect connector","INTERNAL_SDK_ERROR",n)}},setConnections(t,e){const s=new Map(ge.connections);s.set(e,t),ge.connections=s},async handleAuthAccountSwitch({address:t,namespace:e}){var i,o;const s=g.getAccountData(e),n=(o=(i=s==null?void 0:s.user)==null?void 0:i.accounts)==null?void 0:o.find(a=>a.type==="smartAccount"),r=n&&n.address.toLowerCase()===t.toLowerCase()&&vr.canSwitchToSmartAccount(e)?"smartAccount":"eoa";await H.setPreferredAccountType(r,e)},async handleActiveConnection({connection:t,namespace:e,address:s}
4){const n=q.getConnectorById(t.connectorId),r=t.connectorId===$.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${t.connectorId}`);if(r)r&&s&&await H.handleAuthAccountSwitch({address:s,namespace:e});else{const i=await H.connectExternal({id:n.id,type:n.type,provider:n.provider,address:s,chain:e},e);return i==null?void 0:i.address}return s},async handleDisconnectedConnection({connection:t,namespace:e,address:s,closeModalOnConnect:n}){var l,d;const r=q.getConnectorById(t.connectorId),i=(d=(l=t.auth)==null?void 0:l.name)==null?void 0:d.toLowerCase(),o=t.connectorId===$.CONNECTOR_ID.AUTH,a=t.connectorId===$.CONNECTOR_ID.WALLET_CONNECT;if(!r)throw new Error(`No connector found for connection: ${t.connectorId}`);let c;if(o)if(i&&vr.isSocialProvider(i)){const{address:u}=await vr.connectSocial({social:i,closeModalOnConnect:n,onOpenFarcaster(){he.open({view:"ConnectingFarcaster"})},onConnect(){ne.replace("ProfileWallets")}});c=u}else{const{address:u}=await vr.connectEmail({closeModalOnConnect:n,onOpen(){he.open({view:"EmailLogin"})},onConnect(){ne.replace("ProfileWallets")}});c=u}else if(a){const{address:u}=await vr.connectWalletConnect({walletConnect:!0,connector:r,closeModalOnConnect:n,onOpen(h){const p=h?"AllWallets":"ConnectingWalletConnect";he.state.open?ne.push(p):he.open({view:p})},onConnect(){ne.replace("ProfileWallets")}});c=u}else{const u=await H.connectExternal({id:r.id,type:r.type,provider:r.provider,chain:e},e);u&&(c=u.address)}return o&&s&&await H.handleAuthAccountSwitch({address:s,namespace:e}),c},async switchConnection({connection:t,address:e,namespace:s,closeModalOnConnect:n,onChange:r}){var c;let i;const o=(c=g.getAccountData(s))==null?void 0:c.caipAddress;if(o){const{address:l}=ot.parseCaipAddress(o);i=l}const a=Xi.getConnectionStatus(t,s);switch(a){case"connected":case"active":{const l=await H.handleActiveConnection({connection:t,namespace:s,address:e});if(i&&l){const d=l.toLowerCase()!==i.toLowerCase();r==null||r({address:l,namespace:s,hasSwitchedAccount:d,hasSwitchedWallet:a==="active"})}break}case"disconnected":{const l=await H.handleDisconnectedConnection({connection:t,namespace:s,address:e,closeModalOnConnect:n});l&&(r==null||r({address:l,namespace:s,hasSwitchedAccount:!0,hasSwitchedWallet:!0}));break}default:throw new Error(`Invalid connection status: ${a}`)}}},H=qt(Cg),$o={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 Su(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 Uo;async function Zc(){if(!Uo){const{createPublicClient:t,http:e,defineChain:s}=await Vr(async()=>{const{createPublicClient:n,http:r,defineChain:i}=await import("./index-pP58dVRi.js");return{createPublicClient:n,http:r,defineChain:i}},__vite__mapDeps([0,1,2,3,4,5,6,7]));Uo={createPublicClient:t,http:e,defineChain:s}}return Uo}const Ia={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 Zc(),{chainId:s}=ot.parseCaipNetworkId(t.caipNetworkId);return e({...t,id:Number(s)})},async createViemPublicClient(t){const{createPublicClient:e,http:s}=await Zc(),n=R.state.projectId,r=await Ia.getViemChain(t);if(!r)throw new Error(`Chain ${t.caipNetworkId} not found in viem/chains`);return e({chain:r,transport:s(Ia.getBlockchainApiRpcUrl(t.caipNetworkId,n))})}},gc={async getMyTokensWithBalance(t){var a;const e=(a=g.getAccountData())==null?void 0:a.address,s=g.state.activeCaipNetwork,n=q.getConnectorId("eip155")===$.CONNECTOR_ID.AUTH;if(!e||!s)return[];const r=`${s.caipNetworkId}:${e}`,i=M.getBalanceCacheForCaipAddress(r);if(i)return i.balances;if(s.chainNamespace===$.CHAIN.EVM&&n){const c=await this.getEIP155Balances(e,s
4);if(c)return this.filterLowQualityTokens(c)}const o=await re.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(t,e){var s,n;try{const r=$o.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),i=await H.getCapabilities(t);if(!((n=(s=i==null?void 0:i[r])==null?void 0:s.assetDiscovery)!=null&&n.supported))return null;const o=await H.walletGetAssets({account:t,chainFilter:[r]});if(!$o.isWalletGetAssetsResponse(o))return null;const c=(o[r]||[]).map(l=>$o.createBalance(l,e.caipNetworkId));return M.updateBalanceCache({caipAddress:`${e.caipNetworkId}:${t}`,balance:{balances:c},timestamp:Date.now()}),c}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:t,assetAddress:e,caipNetwork:s}){const n=await Ia.createViemPublicClient(s),{address:r}=ot.parseCaipAddress(t),[{result:i},{result:o},{result:a},{result:c}]=await n.multicall({contracts:[{address:e,functionName:"name",args:[],abi:yi},{address:e,functionName:"symbol",args:[],abi:yi},{address:e,functionName:"balanceOf",args:[r],abi:yi},{address:e,functionName:"decimals",args:[],abi:yi}]});return{name:i,symbol:o,decimals:c,balance:a&&c?Su(a,c):"0"}}},Ln=ke({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),Ns={state:Ln,subscribe(t){return Xe(Ln,()=>t(Ln))},subscribeOpen(t){return Ze(Ln,"open",t)},set(t){Object.assign(Ln,{...Ln,...t})}},Ig={async getTokenList(t){var n;const e=await re.fetchSwapTokens({chainId:t});return((n=e==null?void 0:e.tokens)==null?void 0:n.map(r=>({...r,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0})))||[]},async fetchGasPrice(){var e;const t=g.state.activeCaipNetwork;if(!t)return null;try{switch(t.chainNamespace){case"solana":const s=(e=await(H==null?void 0:H.estimateGas({chainNamespace:"solana"})))==null?void 0:e.toString();return{standard:s,fast:s,instant:s};case"eip155":default:return await re.fetchGasPrice({chainId:t.caipNetworkId})}}catch{return null}},async fetchSwapAllowance({tokenAddress:t,userAddress:e,sourceTokenAmount:s,sourceTokenDecimals:n}){const r=await re.fetchSwapAllowance({tokenAddress:t,userAddress:e});if(r!=null&&r.allowance&&s&&n){const i=H.parseUnits(s,n)||0;return BigInt(r.allowance)>=i}return!1},async getMyTokensWithBalance(t){const e=await gc.getMyTokensWithBalance(t);return g.setAccountProp("tokenBalance",e,g.state.activeChain),this.mapBalancesToSwapTokens(e)},mapBalancesToSwapTokens(t){return(t==null?void 0:t.map(e=>({...e,address:e!=null&&e.address?e.address:Fu(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]},async handleSwapError(t){var e,s;try{const n=t==null?void 0:t.cause;if(!(n!=null&&n.json))return;const r=await n.json(),i=(s=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:s.description;return i!=null&&i.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}},me=ke({tokenBalances:[],loading:!1}),Ag={state:me,subscribe(t){return Xe(me,()=>t(me))},subscribeKey(t,e){return Ze(me,t,e)},setToken(t){t&&(me.token=ir(t))},setTokenAmount(t){me.sendTokenAmount=t},setReceiverAddress(t){me.receiverAddress=t},setReceiverProfileImageUrl(t){me.receiverProfileImageUrl=t},setReceiverProfileName(t){me.receiverProfileName=t},setNetworkBalanceInUsd(t){me.networkBalanceInUSD=t},setLoading(t){me.loading=t},getSdkEventProperties(t){var e,s;return{message:J.parseError(t),isSmartAccount:jt(g.state.activeChain)===As.ACCOUNT_TYPES.SMART_ACCOUNT,token:((e=me.token)==null?void 0:e.symbol)||"",amount:me.sendTokenAmount??0,network:((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||""}},async sendToken(){var t;try{switch(ce.setLoading(!0),(t=g.state.activeCaipNetwork)==null?void 0:t.chainNamespace){case"eip155":await ce.sendEvmToken();return;case"solana":await ce.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(e){throw Js.isUserRejectedRequestError(e)?new Uu(e):e}finally{ce.setLoading(!1)}},async sendEvmToken(){var s,n,r;const t=g.state.activeChain;if(!t)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const e=jt(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((s=ce.state.token)!=null&&s.address){le.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===As.ACCOUNT_TYPES.SMART_ACCOUNT,token:ce.state.token.address,amount:ce.state.sendTokenAmount,network:((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}});const{hash:i}=await ce.sendERC20Token({receiverAddress:ce.state.receiverAddress,tokenAddress:ce.state.token.address,sendTokenAmount:ce.state.sendTokenAmount,decimals:ce.state.token.quantity.decimals});i&&(me.hash=i)}else{le.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===As.ACCOUNT_TYPES.SMART_ACCOUNT,token:ce.state.token.symbol||"",amount:ce.state.sendTokenAmount,network:((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}});const{hash:i}=await ce.sendNativeToken({receiverAddress:ce.state.receiverAddress,sendTokenAmount:ce.state.sendTokenAmount,decimals:ce.state.token.quantity.decimals});i&&(me.hash=i)}},async fetchTokenBalance(t){var o,a,c;me.loading=!0;const e=g.state.activeChain,s=(o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId,n=(a=g.state.activeCaipNetwork)==null?void 0:a.chainNamespace,r=((c=g.getAccountData(e))==null?void 0:c.caipAddress)??g.state.activeCaipAddress,i=r?J.getPlainAddress(r):void 0;if(me.lastRetry&&!J.isAllowedRetry(me.lastRetry,30*ye.ONE_SEC_MS))return me.loading=!1,[];try{if(i&&s&&n){const l=await gc.getMyTokensWithBalance();return me.tokenBalances=l,me.lastRetry=void 0,l}}catch(l){me.lastRetry=Date.now(),t==null||t(l),os.showError("Token Balance Unavailable")}finally{me.loading=!1}return[]},fetchNetworkBalance(){if(me.tokenBalances.length===0)return;const t=Ig.mapBalancesToSwapTokens(me.tokenBalances);if(!t)return;const e=t.find(s=>
4s.address===Fu());e&&(me.networkBalanceInUSD=e?$f.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){var o,a,c,l;ne.pushTransactionStack({});const e=t.receiverAddress,s=(o=g.getAccountData())==null?void 0:o.address,n=H.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),i=await H.sendTransaction({chainNamespace:$.CHAIN.EVM,to:e,address:s,data:"0x",value:n??BigInt(0)});return le.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:jt("eip155")===As.ACCOUNT_TYPES.SMART_ACCOUNT,token:((a=ce.state.token)==null?void 0:a.symbol)||"",amount:t.sendTokenAmount,network:((c=g.state.activeCaipNetwork)==null?void 0:c.caipNetworkId)||"",hash:i||""}}),(l=H._getClient())==null||l.updateBalance("eip155"),ce.resetSend(),{hash:i}},async sendERC20Token(t){var n,r,i;ne.pushTransactionStack({onSuccess(){ne.replace("Account")}});const e=H.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),s=(n=g.getAccountData())==null?void 0:n.address;if(s&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const o=J.getPlainAddress(t.tokenAddress);if(!o)throw new Error("SendController:sendERC20Token - tokenAddress is required");const a=await H.writeContract({fromAddress:s,tokenAddress:o,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:Bf.getERC20Abi(o),chainNamespace:$.CHAIN.EVM});return le.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:jt("eip155")===As.ACCOUNT_TYPES.SMART_ACCOUNT,token:((r=ce.state.token)==null?void 0:r.symbol)||"",amount:t.sendTokenAmount,network:((i=g.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||"",hash:a||""}}),ce.resetSend(),{hash:a}}return{hash:void 0}},async sendSolanaToken(){var s;if(!ce.state.sendTokenAmount||!ce.state.receiverAddress)throw new Error("An amount and receiver address are required");ne.pushTransactionStack({onSuccess(){ne.replace("Account")}});let t;ce.state.token&&ce.state.token.address!==ye.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 H.sendTransaction({chainNamespace:"solana",tokenMint:t,to:ce.state.receiverAddress,value:ce.state.sendTokenAmount});e&&(me.hash=e),(s=H._getClient())==null||s.updateBalance("solana"),ce.resetSend()},resetSend(){me.token=void 0,me.sendTokenAmount=void 0,me.receiverAddress=void 0,me.receiverProfileImageUrl=void 0,me.receiverProfileName=void 0,me.loading=!1,me.tokenBalances=[]}},ce=qt(Ag),Do={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},Ci={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},G=ke({chains:Zf(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),qu={state:G,subscribe(t){return Xe(G,()=>{t(G)})},subscribeKey(t,e){return Ze(G,t,e)},subscribeAccountStateProp(t,e,s){var r;const n=s||G.activeChain;return n?Ze(((r=G.chains.get(n))==null?void 0:r.accountState)||{},t,e):()=>{}},subscribeChainProp(t,e,s){let n;return Xe(G.chains,()=>{var i;const r=s||G.activeChain;if(r){const o=(i=G.chains.get(r))==null?void 0:i[t];n!==o&&(n=o,e(o))}})},initialize(t,e,s){const{chainId:n,namespace:r}=M.getActiveNetworkProps(),i=e==null?void 0:e.find(d=>d.id.toString()===(n==null?void 0:n.toString())),a=t.find(d=>(d==null?void 0:d.namespace)===r)||(t==null?void 0:t[0]),c=t.map(d=>d.namespace).filter(d=>d!==void 0),l=R.state.enableEmbedded?new Set([...c]):new Set([...(e==null?void 0:e.map(d=>d.chainNamespace))??[]]);((t==null?void 0:t.length)===0||!a)&&(G.noAdapters=!0),G.noAdapters||(G.activeChain=a==null?void 0:a.namespace,G.activeCaipNetwork=i,g.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:i}),G.activeChain&&Ns.set({activeChain:a==null?void 0:a.namespace})),l.forEach(d=>{const u=e==null?void 0:e.filter(y=>y.chainNamespace===d),h=M.getPreferredAccountTypes()||{},p={...R.state.defaultAccountTypes,...h};g.state.chains.set(d,{namespace:d,networkState:ke({...Ci,caipNetwork:u==null?void 0:u[0]}),accountState:ke({...Do,preferredAccountType:p[d]}),caipNetworks:u??[],...s}),g.setRequestedCaipNetworks(u??[],d)})},removeAdapter(t){var e,s;if(G.activeChain===t){const n=Array.from(G.chains.entries()).find(([r])=>r!==t);if(n){const r=(s=(e=n[1])==null?void 0:e.caipNetworks)==null?void 0:s[0];r&&g.setActiveCaipNetwork(r)}}G.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:s},n){if(!t.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");G.chains.set(t.namespace,{namespace:t.namespace,networkState:{...Ci,caipNetwork:n[0]},accountState:{...Do},caipNetworks:n,connectionControllerClient:s,networkControllerClient:e}),g.setRequestedCaipNetworks((n==null?void 0:n.filter(r=>r.chainNamespace===t.namespace))??[],t.namespace)},addNetwork(t){var s;const e=G.chains.get(t.chainNamespace);if(e){const n=[...e.caipNetworks||[]];(s=e.caipNetworks)!=null&&s.find(r=>r.id===t.id)||n.push(t),G.chains.set(t.chainNamespace,{...e,caipNetworks:n}),g.setRequestedCaipNetworks(n,t.chainNamespace),q.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){var n,r,i;const s=G.chains.get(t);if(s){const o=((n=G.activeCaipNetwork)==null?void 0:n.id)===e,a=[...((r=s.caipNetworks)==null?void 0:r.filter(c=>c.id!==e))||[]];o&&((i=s==null?void 0:s.caipNetworks)!=null&&i[0])&&g.setActiveCaipNetwork(s.caipNetworks[0]),G.chains.set(t,{...s,caipNetworks:a}),g.setRequestedCaipNetworks(a||[],t),a.length===0&&q.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=G.chains.get(t);s&&(s.networkState={...s.networkState||Ci,...e},G.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const n=G.chains.get(t);if(n){const r={...n.accountState||Do,...e};G.chains.set(t,{...n,accountState:r}),(G.chains.size===1||G.activeChain===t)&&e.caipAddress&&(G.activeCaipAddress=e.caipAddress)}},setChainNetworkData(t,e){if(!t)return;const s=G.chains.get(t);if(s){const n={...s.networkState||Ci,...e};G.chains.set(t,{...s,networkState:n})}}
4,setAccountProp(t,e,s,n=!0){g.setChainAccountData(s,{[t]:e},n)},setActiveNamespace(t){var n,r;G.activeChain=t;const e=t?G.chains.get(t):void 0,s=(n=e==null?void 0:e.networkState)==null?void 0:n.caipNetwork;s!=null&&s.id&&t&&(G.activeCaipAddress=(r=e==null?void 0:e.accountState)==null?void 0:r.caipAddress,G.activeCaipNetwork=s,g.setChainNetworkData(t,{caipNetwork:s}),M.setActiveCaipNetworkId(s==null?void 0:s.caipNetworkId),Ns.set({activeChain:t,selectedNetworkId:s==null?void 0:s.caipNetworkId}))},setActiveCaipNetwork(t){var i,o;if(!t)return;const e=G.activeChain===t.chainNamespace;e||g.setIsSwitchingNamespace(!0);const s=G.chains.get(t.chainNamespace);G.activeChain=t.chainNamespace,G.activeCaipNetwork=t,g.setChainNetworkData(t.chainNamespace,{caipNetwork:t});let n=(i=s==null?void 0:s.accountState)==null?void 0:i.address;if(n)G.activeCaipAddress=`${t.chainNamespace}:${t.id}:${n}`;else if(e&&G.activeCaipAddress){const{address:a}=ot.parseCaipAddress(G.activeCaipAddress);n=a,G.activeCaipAddress=`${t.caipNetworkId}:${n}`}else G.activeCaipAddress=void 0;g.setChainAccountData(t.chainNamespace,{address:n,caipAddress:G.activeCaipAddress}),ce.resetSend(),Ns.set({activeChain:G.activeChain,selectedNetworkId:(o=G.activeCaipNetwork)==null?void 0:o.caipNetworkId}),M.setActiveCaipNetworkId(t.caipNetworkId),!g.checkIfSupportedNetwork(t.chainNamespace)&&R.state.enableNetworkSwitch&&!R.state.allowUnsupportedChain&&!H.state.wcBasic&&g.showUnsupportedChainUI()},addCaipNetwork(t){var s;if(!t)return;const e=G.chains.get(t.chainNamespace);e&&((s=e==null?void 0:e.caipNetworks)==null||s.push(t))},async switchActiveNamespace(t){var r;if(!t)return;const e=t!==g.state.activeChain,s=(r=g.getNetworkData(t))==null?void 0:r.caipNetwork,n=g.getCaipNetworkByNamespace(t,s==null?void 0:s.id);e&&n&&await g.switchActiveNetwork(n)},async switchActiveNetwork(t,{throwOnFailure:e=!1}={}){var o;const s=g.state.activeChain;if(!s)throw new Error("ChainController:switchActiveNetwork - namespace is required");const n=g.state.chains.get(s),r=!((o=n==null?void 0:n.caipNetworks)!=null&&o.some(a=>{var c;return a.id===((c=G.activeCaipNetwork)==null?void 0:c.id)})),i=g.getNetworkControllerClient(t.chainNamespace);if(i){try{await i.switchCaipNetwork(t),r&&he.close()}catch(a){if(e)throw a;ne.goBack()}le.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})}},getNetworkControllerClient(t){const e=t||G.activeChain;if(!e)throw new Error("ChainController:getNetworkControllerClient - chain is required");const s=G.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||G.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=G.chains.get(e);if(!(s!=null&&s.connectionControllerClient))throw new Error("ConnectionController client not set");return s.connectionControllerClient},getNetworkProp(t,e){var n;const s=(n=G.chains.get(e))==null?void 0:n.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=G.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:n=[]}=(e==null?void 0:e.networkState)||{};return J.sortRequestedNetworks(s,n).filter(o=>o==null?void 0:o.id)},getAllRequestedCaipNetworks(){const t=[];return G.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const s=g.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){g.setAdapterNetworkState(e,{requestedCaipNetworks:t});const n=g.getAllRequestedCaipNetworks().map(i=>i.chainNamespace),r=Array.from(new Set(n));q.filterByNamespaces(r)},getAllApprovedCaipNetworkIds(){const t=[];return G.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const s=g.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(t){var e,s;return t?(s=(e=G.chains.get(t))==null?void 0:e.networkState)==null?void 0:s.caipNetwork:G.activeCaipNetwork},getActiveCaipAddress(){return G.activeCaipAddress},getApprovedCaipNetworkIds(t){var n;const e=G.chains.get(t);return((n=e==null?void 0:e.networkState)==null?void 0:n.approvedCaipNetworkIds)||[]},async setApprovedCaipNetworksData(t){const e=g.getNetworkControllerClient(),s=await(e==null?void 0:e.getApprovedCaipNetworksData());g.setAdapterNetworkState(t,{approvedCaipNetworkIds:s==null?void 0:s.approvedCaipNetworkIds,supportsAllNetworks:s==null?void 0:s.supportsAllNetworks})},checkIfSupportedNetwork(t,e){var r;const s=e||((r=G.activeCaipNetwork)==null?void 0:r.caipNetworkId),n=g.getRequestedCaipNetworks(t);return n.length?n==null?void 0:n.some(i=>i.caipNetworkId===s):!0},checkIfSupportedChainId(t){if(!G.activeChain)return!0;const e=g.getRequestedCaipNetworks(G.activeChain);return e==null?void 0:e.some(s=>s.id===t)},setSmartAccountEnabledNetworks(t,e){g.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){var n;const t=Pu.caipNetworkIdToNumber((n=G.activeCaipNetwork)==null?void 0:n.caipNetworkId),e=G.activeChain;if(!e||!t)return!1;const s=g.getNetworkProp("smartAccountEnabledNetworks",e);return!!(s!=null&&s.includes(Number(t)))},showUnsupportedChainUI(){he.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=G.activeCaipNetwork;return!!(t!=null&&t.chainNamespace&&ye.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){g.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(t){var r,i;const e=t;if(!e)throw new Error("Chain is required to set account prop");const s=(i=(r=g.state.chains.get(e))==null?void 0:r.accountState)==null?void 0:i.preferredAccountType,n=R.state.defaultAccountTypes[e];G.activeCaipAddress=void 0,g.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol
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"}),q.removeConnectorId(e)},setIsSwitchingNamespace(t){G.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){var s,n;const t=[];let e;if(G.chains.forEach(r=>{$.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(i=>i===r.namespace)&&r.namespace&&t.push(r.namespace)}),t.length>0){const r=t[0];return e=r?(n=(s=G.chains.get(r))==null?void 0:s.caipNetworks)==null?void 0:n[0]:void 0,e}},getAccountData(t){var s;const e=t||G.activeChain;if(e)return(s=g.state.chains.get(e))==null?void 0:s.accountState},getNetworkData(t){var s;const e=t||G.activeChain;if(e)return(s=g.state.chains.get(e))==null?void 0:s.networkState},getCaipNetworkByNamespace(t,e){var r,i,o;if(!t)return;const s=g.state.chains.get(t),n=(r=s==null?void 0:s.caipNetworks)==null?void 0:r.find(a=>a.id===e);return n||((i=s==null?void 0:s.networkState)==null?void 0:i.caipNetwork)||((o=s==null?void 0:s.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const t=q.state.filterByNamespace;return(t?[G.chains.get(t)]:Array.from(G.chains.values())).flatMap(s=>(s==null?void 0:s.caipNetworks)||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?g.getRequestedCaipNetworks(t):g.getAllRequestedCaipNetworks()},getCaipNetworkById(t,e){return qu.getCaipNetworks(e).find(s=>s.id.toString()===t.toString()||s.caipNetworkId.toString()===t.toString())}
4,setLastConnectedSIWECaipNetwork(t){G.lastConnectedSIWECaipNetwork=t},getLastConnectedSIWECaipNetwork(){return G.lastConnectedSIWECaipNetwork},async fetchTokenBalance(t){var o,a;const e=g.getAccountData();if(!e)return[];const s=(o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId,n=(a=g.state.activeCaipNetwork)==null?void 0:a.chainNamespace,r=g.state.activeCaipAddress,i=r?J.getPlainAddress(r):void 0;if(g.setAccountProp("balanceLoading",!0,n),e.lastRetry&&!J.isAllowedRetry(e.lastRetry,30*ye.ONE_SEC_MS))return g.setAccountProp("balanceLoading",!1,n),[];try{if(i&&s&&n){const c=await gc.getMyTokensWithBalance();return g.setAccountProp("tokenBalance",c,n),g.setAccountProp("lastRetry",void 0,n),g.setAccountProp("balanceLoading",!1,n),c}}catch(c){g.setAccountProp("lastRetry",Date.now(),n),t==null||t(c),os.showError("Token Balance Unavailable")}finally{g.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(t){var c;const e=t.chainNamespace,s=!!((c=g.getAccountData(e))!=null&&c.caipAddress),n=g.getAllApprovedCaipNetworkIds(),r=g.getNetworkProp("supportsAllNetworks",e)!==!1,i=q.getConnectorId(e),o=q.getAuthConnector(),a=i===$.CONNECTOR_ID.AUTH&&o;return!s||r||a?!1:!(n!=null&&n.includes(t.caipNetworkId))}},g=qt(qu),Ng={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){var h,p;const s=g.state.activeCaipNetwork,n=g.state.activeChain,r=ne.state.data;if(t.id===(s==null?void 0:s.id))return;const o=!!((h=g.getAccountData(n))!=null&&h.address),a=!!((p=g.getAccountData(t.chainNamespace))!=null&&p.address),c=t.chainNamespace!==n,d=q.getConnectorId(n)===$.CONNECTOR_ID.AUTH,u=$.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(y=>y===t.chainNamespace);e||d&&u?ne.push("SwitchNetwork",{...r,network:t}):o&&c&&!a?ne.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):ne.push("SwitchNetwork",{...r,network:t})}},ht=ke({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),_g={state:ht,subscribe(t){return Xe(ht,()=>t(ht))},subscribeKey(t,e){return Ze(ht,t,e)},async open(t){var o,a;const e=t==null?void 0:t.namespace,s=g.state.activeChain,n=e&&e!==s,r=(o=g.getAccountData(t==null?void 0:t.namespace))==null?void 0:o.caipAddress,i=g.state.noAdapters;if(H.state.wcBasic?te.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await te.prefetch(),q.setFilterByNamespace(t==null?void 0:t.namespace),he.setLoading(!0,e),e&&n){const c=((a=g.getNetworkData(e))==null?void 0:a.caipNetwork)||g.getRequestedCaipNetworks(e)[0];c&&(i?(await g.switchActiveNetwork(c),ne.push("ConnectingWalletConnectBasic")):Ng.onSwitchNetwork({network:c,ignoreSwitchConfirmation:!0}))}else R.state.manualWCControl||i&&!r?J.isMobile()?ne.reset("AllWallets"):ne.reset("ConnectingWalletConnectBasic"):t!=null&&t.view?ne.reset(t.view,t.data):r?ne.reset("Account"):ne.reset("Connect");ht.open=!0,Ns.set({open:!0}),le.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!r}})},close(){const t=R.state.enableEmbedded,e=!!g.state.activeCaipAddress;ht.open&&le.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),ht.open=!1,ne.reset("Connect"),he.clearLoading(),t?e?ne.replace("Account"):ne.push("Connect"):Ns.set({open:!1}),H.resetUri()},setLoading(t,e){e&&ht.loadingNamespaceMap.set(e,t),ht.loading=t,Ns.set({loading:t})},clearLoading(){ht.loadingNamespaceMap.clear(),ht.loading=!1,Ns.set({loading:!1})},shake(){ht.shake||(ht.shake=!0,setTimeout(()=>{ht.shake=!1},500))}},he=qt(_g),Zi={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0},pt=ke({providers:{...Zi},providerIds:{...Zi}}),Re={state:pt,subscribeKey(t,e){return Ze(pt,t,e)},subscribe(t){return Xe(pt,()=>{t(pt)})},subscribeProviders(t){return Xe(pt.providers,()=>t(pt.providers))},setProvider(t,e){t&&e&&(pt.providers[t]=ir(e))},getProvider(t){if(t)return pt.providers[t]},setProviderId(t,e){e&&(pt.providerIds[t]=e)},getProviderId(t){if(t)return pt.providerIds[t]},reset(){pt.providers={...Zi},pt.providerIds={...Zi}},resetChain(t){pt.providers[t]=void 0,pt.providerIds[t]=void 0}}
4,jr={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"}]},Aa={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},Sg={providers:Lu,selectedProvider:null,error:null,purchaseCurrency:jr,paymentCurrency:Aa,purchaseCurrencies:[jr],paymentCurrencies:[],quotesLoading:!1},we=ke(Sg),Tg={state:we,subscribe(t){return Xe(we,()=>t(we))},subscribeKey(t,e){return Ze(we,t,e)},setSelectedProvider(t){var e,s;if(t&&t.name==="meld"){const n=g.state.activeChain,r=n===$.CHAIN.SOLANA?"SOL":"USDC",i=n?((s=(e=g.state.chains.get(n))==null?void 0:e.accountState)==null?void 0:s.address)??"":"",o=new URL(t.url);o.searchParams.append("publicKey",Qf),o.searchParams.append("destinationCurrencyCode",r),o.searchParams.append("walletAddress",i),o.searchParams.append("externalCustomerId",R.state.projectId),we.selectedProvider={...t,url:o.toString()}}else we.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=Lu.filter(n=>e.includes(n.name));we.providers=s}else we.providers=[]},setPurchaseCurrency(t){we.purchaseCurrency=t},setPaymentCurrency(t){we.paymentCurrency=t},setPurchaseAmount(t){Na.state.purchaseAmount=t},setPaymentAmount(t){Na.state.paymentAmount=t},async getAvailableCurrencies(){const t=await re.getOnrampOptions();we.purchaseCurrencies=t.purchaseCurrencies,we.paymentCurrencies=t.paymentCurrencies,we.paymentCurrency=t.paymentCurrencies[0]||Aa,we.purchaseCurrency=t.purchaseCurrencies[0]||jr,await te.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await te.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){var t,e;we.quotesLoading=!0;try{const s=await re.getOnrampQuote({purchaseCurrency:we.purchaseCurrency,paymentCurrency:we.paymentCurrency,amount:((t=we.paymentAmount)==null?void 0:t.toString())||"0",network:(e=we.purchaseCurrency)==null?void 0:e.symbol});return we.quotesLoading=!1,we.purchaseAmount=Number(s==null?void 0:s.purchaseAmount.amount),s}catch(s){return we.error=s.message,we.quotesLoading=!1,null}finally{we.quotesLoading=!1}},resetState(){we.selectedProvider=null,we.error=null,we.purchaseCurrency=jr,we.paymentCurrency=Aa,we.purchaseCurrencies=[jr],we.paymentCurrencies=[],we.paymentAmount=void 0,we.purchaseAmount=void 0,we.quotesLoading=!1}},Na=qt(Tg),zt=ke({message:"",variant:"info",open:!1}),Og={state:zt,subscribeKey(t,e){return Ze(zt,t,e)},open(t,e){const{debug:s}=R.state,{code:n,displayMessage:r,debugMessage:i}=t;r&&s&&(zt.message=r,zt.variant=e,zt.open=!0),i&&console.error(typeof i=="function"?i():i,n?{code:n}:void 0)},warn(t,e,s){zt.open=!0,zt.message=t,zt.variant="warning",e&&console.warn(e,s)},close(){zt.open=!1,zt.message="",zt.variant="info"}},At=qt(Og),Qc=2147483648,kg={convertEVMChainIdToCoinType(t){if(t>=Qc)throw new Error("Invalid chainId");return(Qc|t)>>>0}},kt=ke({suggestions:[],loading:!1}),Pg={state:kt,subscribe(t){return Xe(kt,()=>t(kt))},subscribeKey(t,e){return Ze(kt,t,e)},async resolveName(t){var e,s;try{return await re.lookupEnsName(t)}catch(n){const r=n;throw new Error(((s=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:s.description)||"Error resolving name")}},async isNameRegistered(t){try{return await re.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{kt.loading=!0,kt.suggestions=[];const e=await re.getEnsNameSuggestions(t);return kt.suggestions=e.suggestions||[],kt.suggestions}catch(e){const s=Fr.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{kt.loading=!1}},async getNamesForAddress(t){try{if(!g.state.activeCaipNetwork)return[];const s=M.getEnsFromCacheForAddress(t);if(s)return s;const n=await re.reverseLookupEnsName({address:t});return M.updateEnsCache({address:t,ens:n,timestamp:Date.now()}),n}catch(e){const s=Fr.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){var r;const e=g.state.activeCaipNetwork,s=(r=g.getAccountData(e==null?void 0:e.chainNamespace))==null?void 0:r.address,n=q.getAuthConnector();if(!e)throw new Error("Network not found");if(!s||!n)throw new Error("Address or auth connector not found");kt.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});ne.pushTransactionStack({onCancel(){ne.replace("RegisterAccountName")}});const o=await H.signMessage(i);kt.loading=!1;const a=e.id;if(!a)throw new Error("Network not found");const c=kg.convertEVMChainIdToCoinType(Number(a));await re.registerEnsName({coinType:c,address:s,signature:o,message:i}),g.setAccountProp("profileName",t,e.chainNamespace),M.updateEnsCache({address:s,ens:[{name:t,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),ne.replace("RegisterAccountNameSuccess")}catch(i){const o=Fr.parseEnsApiError(i,`Error registering name ${t}`);throw ne.replace("RegisterAccountName"),new Error(o)}finally{kt.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){var n,r;const s=t;return((r=(n=s==null?void 0:s.reasons)==null?void 0:n[0])==null?void 0:r.description)||e}},Fr=qt(Pg),xg={asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"},Rg={asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"};var Lo,el;function $g(){if(el)return Lo;el=1;const t=lc();
4Lo=r;const e=j().console||{},s={mapHttpRequest:y,mapHttpResponse:y,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:y,res:y,err:h};function n(f,v){return Array.isArray(f)?f.filter(function(_){return _!=="!stdSerializers.err"}):f===!0?Object.keys(v):!1}function r(f){f=f||{},f.browser=f.browser||{};const v=f.browser.transmit;if(v&&typeof v.send!="function")throw Error("pino: transmit option must have a send function");const C=f.browser.write||e;f.browser.write&&(f.browser.asObject=!0);const _=f.serializers||{},S=n(f.browser.serialize,_);let U=f.browser.serialize;Array.isArray(f.browser.serialize)&&f.browser.serialize.indexOf("!stdSerializers.err")>-1&&(U=!1);const O=["error","fatal","warn","info","debug","trace"];typeof C=="function"&&(C.error=C.fatal=C.warn=C.info=C.debug=C.trace=C),f.enabled===!1&&(f.level="silent");const A=f.level||"info",b=Object.create(C);b.log||(b.log=w),Object.defineProperty(b,"levelVal",{get:x}),Object.defineProperty(b,"level",{get:L,set:F});const N={transmit:v,serialize:S,asObject:f.browser.asObject,levels:O,timestamp:p(f)};b.levels=r.levels,b.level=A,b.setMaxListeners=b.getMaxListeners=b.emit=b.addListener=b.on=b.prependListener=b.once=b.prependOnceListener=b.removeListener=b.removeAllListeners=b.listeners=b.listenerCount=b.eventNames=b.write=b.flush=w,b.serializers=_,b._serialize=S,b._stdErrSerialize=U,b.child=P,v&&(b._logEvent=u());function x(){return this.level==="silent"?1/0:this.levels.values[this.level]}function L(){return this._level}function F(T){if(T!=="silent"&&!this.levels.values[T])throw Error("unknown level "+T);this._level=T,i(N,b,"error","log"),i(N,b,"fatal","error"),i(N,b,"warn","error"),i(N,b,"info","log"),i(N,b,"debug","log"),i(N,b,"trace","log")}function P(T,W){if(!T)throw new Error("missing bindings for child Pino");W=W||{},S&&T.serializers&&(W.serializers=T.serializers);const K=W.serializers;if(S&&K){var ie=Object.assign({},_,K),oe=f.browser.serialize===!0?Object.keys(ie):S;delete T.serializers,c([T],oe,ie,this._stdErrSerialize)}function se(X){this._childLevel=(X._childLevel|0)+1,this.error=l(X,T,"error"),this.fatal=l(X,T,"fatal"),this.warn=l(X,T,"warn"),this.info=l(X,T,"info"),this.debug=l(X,T,"debug"),this.trace=l(X,T,"trace"),ie&&(this.serializers=ie,this._serialize=oe),v&&(this._logEvent=u([].concat(X._logEvent.bindings,T)))}return se.prototype=this,new se(this)}return b}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:E,epochTime:I,unixTime:k,isoTime:D});function i(f,v,C,_){const S=Object.getPrototypeOf(v);v[C]=v.levelVal>v.levels.values[C]?w:S[C]?S[C]:e[C]||e[_]||w,o(f,v,C)}function o(f,v,C){!f.transmit&&v[C]===w||(v[C]=(function(_){return function(){const U=f.timestamp(),O=new Array(arguments.length),A=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var b=0;b<O.length;b++)O[b]=arguments[b];if(f.serialize&&!f.asObject&&c(O,this._serialize,this.serializers,this._stdErrSerialize),f.asObject?_.call(A,a(this,C,O,U)):_.apply(A,O),f.transmit){const N=f.transmit.level||v.level,x=r.levels.values[N],L=r.levels.values[C];if(L<x)return;d(this,{ts:U,methodLevel:C,methodValue:L,transmitValue:r.levels.values[f.transmit.level||v.level],send:f.transmit.send,val:v.levelVal},O)}}})(v[C]))}function a(f,v,C,_){f._serialize&&c(C,f._serialize,f.serializers,f._stdErrSerialize);const S=C.slice();let U=S[0];const O={};_&&(O.time=_),O.level=r.levels.values[v];let A=(f._childLevel|0)+1;if(A<1&&(A=1),U!==null&&typeof U=="object"){for(;A--&&typeof S[0]=="object";)Object.assign(O,S.shift());
4U=S.length?t(S.shift(),S):void 0}else typeof U=="string"&&(U=t(S.shift(),S));return U!==void 0&&(O.msg=U),O}function c(f,v,C,_){for(const S in f)if(_&&f[S]instanceof Error)f[S]=r.stdSerializers.err(f[S]);else if(typeof f[S]=="object"&&!Array.isArray(f[S]))for(const U in f[S])v&&v.indexOf(U)>-1&&U in C&&(f[S][U]=C[U](f[S][U]))}function l(f,v,C){return function(){const _=new Array(1+arguments.length);_[0]=v;for(var S=1;S<_.length;S++)_[S]=arguments[S-1];return f[C].apply(this,_)}}function d(f,v,C){const _=v.send,S=v.ts,U=v.methodLevel,O=v.methodValue,A=v.val,b=f._logEvent.bindings;c(C,f._serialize||Object.keys(f.serializers),f.serializers,f._stdErrSerialize===void 0?!0:f._stdErrSerialize),f._logEvent.ts=S,f._logEvent.messages=C.filter(function(N){return b.indexOf(N)===-1}),f._logEvent.level.label=U,f._logEvent.level.value=O,_(U,f._logEvent,A),f._logEvent=u(b)}function u(f){return{ts:0,messages:[],bindings:f||[],level:{label:"",value:0}}}function h(f){const v={type:f.constructor.name,msg:f.message,stack:f.stack};for(const C in f)v[C]===void 0&&(v[C]=f[C]);return v}function p(f){return typeof f.timestamp=="function"?f.timestamp:f.timestamp===!1?E:I}function y(){return{}}function m(f){return f}function w(){}function E(){return!1}function I(){return Date.now()}function k(){return Math.round(Date.now()/1e3)}function D(){return new Date(Date.now()).toISOString()}function j(){function f(v){return typeof v<"u"&&v}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 f(self)||f(window)||f(this)||{}}}return Lo}$g();let on=null;const rs={getSIWX(){return R.state.siwx},async initializeIfEnabled(t=g.getActiveCaipAddress()){var i,o,a;const e=R.state.siwx;if(!(e&&t))return;const[s,n,r]=t.split(":");if(g.checkIfSupportedNetwork(s,`${s}:${n}`))try{if((i=R.state.remoteFeatures)!=null&&i.emailCapture){const l=(o=g.getAccountData(s))==null?void 0:o.user;await he.open({view:"DataCapture",data:{email:(l==null?void 0:l.email)??void 0}});return}if(on&&await on,(await e.getSessions(`${s}:${n}`,r)).length)return;await he.open({view:"SIWXSignMessage"})}catch(c){console.error("SIWXUtil:initializeIfEnabled",c),le.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(c)}),await((a=H._getClient())==null?void 0:a.disconnect().catch(console.error)),ne.reset("Connect"),os.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=R.state.siwx,e=J.getPlainAddress(g.getActiveCaipAddress()),s=Ei(),n=H._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();q.getConnectorId(s.chainNamespace)===$.CONNECTOR_ID.AUTH&&ne.pushTransactionStack({});const a=await n.signMessage(i);await t.addSession({data:r,message:i,signature:a}),g.setLastConnectedSIWECaipNetwork(s),he.close(),le.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){(!he.state.open||ne.state.view==="ApproveTransaction")&&await he.open({view:"SIWXSignMessage"}),os.showError("Error signing message"),le.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(r)}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){var t;try{const e=this.getSIWX();if((t=e==null?void 0:e.getRequired)==null?void 0:t.call(e)){const n=g.getLastConnectedSIWECaipNetwork();if(n){const r=await(e==null?void 0:e.getSessions(n==null?void 0:n.caipNetworkId,J.getPlainAddress(g.getActiveCaipAddress())||""));r&&r.length>0?await g.switchActiveNetwork(n):await H.disconnect()}else await H.disconnect()}else he.close();he.close(),le.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getAllSessions(){const t=this.getSIWX(),e=g.getAllRequestedCaipNetworks(),s=[];return await Promise.all(e.map(async n=>{const r=await(t==null?void 0:t.getSessions(n.caipNetworkId,J.getPlainAddress(g.getActiveCaipAddress())||""));r&&s.push(...r)})),s},async getSessions(t){const e=R.state.siwx;let s=t==null?void 0:t.address;if(!s){const r=g.getActiveCaipAddress();s=J.getPlainAddress(r)}let n=t==null?void 0:t.caipNetworkId;if(!n){const r=g.getActiveCaipNetwork();n=r==null?void 0:r.caipNetworkId}return e&&s&&n?e.getSessions(n,s):[]},async isSIWXCloseDisabled(){var e;const t=this.getSIWX();if(t){const s=ne.state.view==="ApproveTransaction",n=ne.state.view==="SIWXSignMessage";if(s||n)return((e=t.getRequired)==null?void 0:e.call(t))&&(await this.get
4Sessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:t,chainId:e,socialUri:s,preferredAccountType:n,chainNamespace:r}){var u;const i=rs.getSIWX(),o=Ei();if(!i||!r.includes($.CHAIN.EVM)||(u=R.state.remoteFeatures)!=null&&u.emailCapture){const h=await t.connect({chainId:e,socialUri:s,preferredAccountType:n});return{address:h.address,chainId:h.chainId,accounts:h.accounts}}const a=`${r}:${e}`,c=await i.createMessage({chainId:a,accountAddress:"<<AccountAddress>>"}),l={accountAddress:c.accountAddress,chainId:c.chainId,domain:c.domain,uri:c.uri,version:c.version,nonce:c.nonce,notBefore:c.notBefore,statement:c.statement,resources:c.resources,requestId:c.requestId,issuedAt:c.issuedAt,expirationTime:c.expirationTime,serializedMessage:c.toString()},d=await t.connect({chainId:e,socialUri:s,siwxMessage:l,preferredAccountType:n});return l.accountAddress=d.address,l.serializedMessage=d.message||"",d.signature&&d.message&&await rs.addEmbeddedWalletSession(l,d.message,d.signature),g.setLastConnectedSIWECaipNetwork(o),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(t,e,s){if(on)return on;const n=rs.getSIWX();return n?(on=n.addSession({data:t,message:e,signature:s}).finally(()=>{on=null}),on):Promise.resolve()},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){var l,d,u;const n=rs.getSIWX(),r=Ei(),i=new Set(e.map(h=>h.split(":")[0]));if(!n||i.size!==1||!i.has("eip155"))return!1;const o=await n.createMessage({chainId:((l=Ei())==null?void 0:l.caipNetworkId)||"",accountAddress:""}),a=await t.authenticate({nonce:o.nonce,domain:o.domain,uri:o.uri,exp:o.expirationTime,iat:o.issuedAt,nbf:o.notBefore,requestId:o.requestId,version:o.version,resources:o.resources,statement:o.statement,chainId:o.chainId,methods:s,chains:[o.chainId,...e.filter(h=>h!==o.chainId)]});os.showLoading("Authenticating...",{autoClose:!1});const c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:(d=a.session.peer.metadata.icons)==null?void 0:d[0],type:"WALLET_CONNECT"};if(g.setAccountProp("connectedWalletInfo",c,Array.from(i)[0]),(u=a==null?void 0:a.auths)!=null&&u.length){const h=a.auths.map(p=>{const y=t.client.formatAuthMessage({request:p.p,iss:p.p.iss});return{data:{...p.p,accountAddress:p.p.iss.split(":").slice(-1).join(""),chainId:p.p.iss.split(":").slice(2,4).join(":"),uri:p.p.aud,version:p.p.version||o.version,expirationTime:p.p.exp,issuedAt:p.p.iat,notBefore:p.p.nbf},message:y,signature:p.s.s,cacao:p}});try{await n.setSessions(h),r&&g.setLastConnectedSIWECaipNetwork(r),le.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:rs.getSIWXEventProperties()})}catch(p){throw console.error("SIWX:universalProviderAuth - failed to set sessions",p),le.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:rs.getSIWXEventProperties(p)}),await t.disconnect().catch(console.error),p}finally{os.hide()}}return!0},getSIWXEventProperties(t){var s;const e=g.state.activeChain;if(!e)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||"",isSmartAccount:jt(e)===As.ACCOUNT_TYPES.SMART_ACCOUNT,message:t?J.parseError(t):void 0}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};function Ug(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}
vendor: 10,055 bytes, line 4
4function ze(t,...e){try{return Ug(t(...e))}catch(s){return Promise.reject(s)}}function Dg(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function Lg(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Bi(t){if(Dg(t))return String(t);if(Lg(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Bi(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const _a="base64:";function Bg(t){return typeof t=="string"?t:_a+Fg(t)}function Mg(t){return typeof t!="string"||!t.startsWith(_a)?t:jg(t.slice(_a.length))}function jg(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function Fg(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function gt(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function qg(...t){return gt(t.join(":"))}function Ii(t){return t=gt(t),t?t+":":""}function Wg(t,e){if(e===void 0)return!0;let s=0,n=t.indexOf(":");for(;n>-1;)s++,n=t.indexOf(":",n+1);return s<=e}function zg(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const Hg="memory",Kg=()=>{const t=new Map;return{name:Hg,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,s){t.set(e,s)},setItemRaw(e,s){t.set(e,s)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Vg(t={}){const e={mounts:{"":t.driver||Kg()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},s=l=>{for(const d of e.mountpoints)if(l.startsWith(d))return{base:d,relativeKey:l.slice(d.length),driver:e.mounts[d]};return{base:"",relativeKey:l,driver:e.mounts[""]}},n=(l,d)=>e.mountpoints.filter(u=>u.startsWith(l)||d&&l.startsWith(u)).map(u=>({relativeBase:l.length>u.length?l.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(l,d)=>{if(e.watching){d=gt(d);for(const u of e.watchListeners)u(l,d)}},i=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await tl(e.mounts[l],r,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,d,u)=>{const h=new Map,p=y=>{let m=h.get(y.base);return m||(m={driver:y.driver,base:y.base,items:[]},h.set(y.base,m)),m};for(const y of l){const m=typeof y=="string",w=gt(m?y:y.key),E=m?void 0:y.value,I=m||!y.options?d:{...d,...y.options},k=s(w);p(k).items.push({key:w,value:E,relativeKey:k.relativeKey,options:I})}return Promise.all([...h.values()].map(y=>u(y))).then(y=>y.flat())},c={hasItem(l,d={}){l=gt(l);const{relativeKey:u,driver:h}=s(l);return ze(h.hasItem,u,d)},getItem(l,d={}){l=gt(l);const{relativeKey:u,driver:h}=s(l);return ze(h.getItem,u,d).then(p=>wi(p))},getItems(l,d={}){return a(l,d,u=>u.driver.getItems?ze(u.driver.getItems,u.items.map(h=>({key:h.relativeKey,options:h.options})),d).then(h=>h.map(p=>({key:qg(u.base,p.key),value:wi(p.value)}))):Promise.all(u.items.map(h=>ze(u.driver.getItem,h.relativeKey,h.options).then(p=>({key:h.key,value:wi(p)})))))},getItemRaw(l,d={}){l=gt(l);const{relativeKey:u,driver:h}=s(l);return h.getItemRaw?ze(h.getItemRaw,u,d):ze(h.getItem,u,d).then(p=>Mg(p))},async setItem(l,d,u={}){if(d===void 0)return c.removeItem(l);l=gt(l);const{relativeKey:h,driver:p}=s(l);p.setItem&&(await ze(p.setItem,h,Bi(d),u),p.watch||r("update",l))},async setItems(l,d){await a(l,d,async u=>{if(u.driver.setItems)return ze(u.driver.setItems,u.items.map(h=>({key:h.relativeKey,value:Bi(h.value),options:h.options})),d);u.driver.setItem&&await Promise.all(u.items.map(h=>ze(u.driver.setItem,h.relativeKey,Bi(h.value),h.options)))})},async setItemRaw(l,d,u={}){if(d===void 0)return c.removeItem(l,u);l=gt(l);const{relativeKey:h,driver:p}=s(l);if(p.setItemRaw)await ze(p.setItemRaw,h,d,u);else if(p.setItem)await ze(p.setItem,h,Bg(d),u);else return;p.watch||r("update",l)},async removeItem(l,d={}){typeof d=="boolean"&&(d={removeMeta:d}),l=gt(l);const{relativeKey:u,driver:h}=s(l);h.removeItem&&(await ze(h.removeItem,u,d),(d.removeMeta||d.removeMata)&&await ze(h.removeItem,u+"$",d),h.watch||r("remove",l))},async getMeta(l,d={}){typeof d=="boolean"&&(d={nativeOnly:d}),l=gt(l);const{relativeKey:u,driver:h}=s(l),p=Object.create(null);if(h.getMeta&&Object.assign(p,await ze(h.getMeta,u,d)),!d.nativeOnly){const y=await ze(h.getItem,u+"$",d).then(m=>wi(m));y&&typeof y=="object"&&(typeof y.atime=="string"&&(y.atime=new Date(y.atime)),typeof y.mtime=="string"&&(y.mtime=new Date(y.mtime)),Object.assign(p,y))}return p},setMeta(l,d,u={}){return this.setItem(l+"$",d,u)},removeMeta(l,d={}){return this.removeItem(l+"$",d)},async getKeys(l,d={}){var w;l=Ii(l);const u=n(l,!0);let h=[];const p=[];let y=!0;for(const E of u){(w=E.driver.flags)!=null&&w.maxDepth||(y=!1);const I=await ze(E.driver.getKeys,E.relativeBase,d);for(const k of I){const D=E.mountpoint+gt(k);h.some(j=>D.startsWith(j))||p.push(D)}h=[E.mountpoint,...h.filter(k=>!k.startsWith(E.mountpoint))]}const m=d.maxDepth!==void 0&&!y;return p.filter(E=>(!m||Wg(E,d.maxDepth))&&zg(E,l))},async clear(l,d={}){l=Ii(l),await Promise.all(n(l,!1).map(async u=>{if(u.driver.clear)return ze(u.driver.clear,u.relativeBase,d);if(u.driver.removeItem){const h=await u.driver.getKeys(u.relativeBase||"",d);return Promise.all(h.map(p=>u.driver.removeItem(p,d)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>sl(l)))},async watch(l){return await i(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(d=>d!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,d){if(l=Ii(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((u,h)=>h.length-u.length)),e.mounts[l]=d,e.watching&&Promise.resolve(tl(d,r,l)).then(u=>{e.unwatch[l]=u}).catch(console.error),c},async unmount(l,d=!0){var u,h;l=Ii(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&((h=(u=e.unwatch)[l])==null||h.call(u),delete e.unwatch[l]),d&&await sl(e.mounts[l]),e.mountpoints=e.mountpoints.filter(p=>p!==l),delete e.mounts[l])},getMount(l=""){l=gt(l)+":";const d=s(l);return{driver:d.driver,base:d.base}},getMounts(l="",d={}){return l=gt(l),n(l,d.parents).map(h=>({driver:h.driver,base:h.mountpoint}))},keys:(l,d={})=>c.getKeys(l,d),get:(l,d={})=>c.getItem(l,d),set:(l,d,u={})=>c.setItem(l,d,u),has:(l,d={})=>c.hasItem(l,d),del:(l,d={})=>c.removeItem(l,d),remove:(l,d={})=>c.removeItem(l,d)};return c}function tl(t,e,s){return t.watch?t.watch((n,r)=>e(n,s+r)):()=>{}}async function sl(t){typeof t.dispose=="function"&&await ze(t.dispose)}const Gg="idb-keyval";var Yg=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",s=r=>e+r;let n;return t.dbName&&t.storeName&&(n=cf(t.dbName,t.storeName)),{name:Gg,options:t,async hasItem(r){return!(typeof await Mc(s(r),n)>"u")},async getItem(r){return await Mc(s(r),n)??null},setItem(r,i){return hf(s(r),i,n)},removeItem(r){return uf(s(r),n)},getKeys(){return df(n)},clear(){return lf(n)}}};const Jg="WALLET_CONNECT_V2_INDEXED_DB",Xg="keyvaluestorage";let Zg=class{constructor(){this.indexedDb=Vg({driver:Yg({dbName:Jg,storeName:Xg})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const s=await this.indexedDb.getItem(e);if(s!==null)return s}async setItem(e,s){await this.indexedDb.setItem(e,In(s))}async removeItem(e){await this.indexedDb.removeItem(e)}};var Bo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Mi={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(s){return this.hasOwnProperty(s)?String(this[s]):null},t.prototype.setItem=function(s,n){this[s]=String(n)},t.prototype.removeItem=function(s){delete this[s]},t.prototype.clear=function(){const s=this;Object.keys(s).forEach(function(n){s[n]=void 0,delete s[n]})},t.prototype.key=function(s){return s=s||0,Object.keys(this)[s]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Bo<"u"&&Bo.localStorage?Mi.exports=Bo.localStorage:typeof window<"u"&&window.localStorage?Mi.exports=window.localStorage:Mi.exports=new e})();function Qg(t){var e;return[t[0],Gi((e=t[1])!=null?e:"")]}let em=class{constructor(){this.localStorage=Mi.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Qg)}async getItem(e){const s=this.localStorage.getItem(e);if(s!==null)return Gi(s)}async setItem(e,s){this.localStorage.setItem(e,In(s))}async removeItem(e){this.localStorage.removeItem(e)}};const tm="wc_storage_version",nl=1,sm=async(t,e,s)=>{const n=tm,r=await e.getItem(n);if(r&&r>=nl){s(e);return}const i=await t.getKeys();if(!i.length){s(e);return}const o=[];for(;i.length;){const a=i.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(n,nl),s(e),nm(t,o)},nm=async(t,e)=>{e.length&&e.forEach(async s=>{await t.removeItem(s)})};let rm=class{constructor(){this.initialized=!1,this.setInitialized=s=>{this.storage=s,this.initialized=!0};const e=new em;this.storage=e;try{const s=new Zg;sm(e,s,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,s){return await this.initialize(),this.storage.setItem(e,s)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const s=setInterval(()=>{this.initialized&&(clearInterval(s),e())},20)})}};var Mo,rl;
4function im(){if(rl)return Mo;rl=1;const t=lc();Mo=r;const e=j().console||{},s={mapHttpRequest:y,mapHttpResponse:y,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:y,res:y,err:h};function n(f,v){return Array.isArray(f)?f.filter(function(_){return _!=="!stdSerializers.err"}):f===!0?Object.keys(v):!1}function r(f){f=f||{},f.browser=f.browser||{};const v=f.browser.transmit;if(v&&typeof v.send!="function")throw Error("pino: transmit option must have a send function");const C=f.browser.write||e;f.browser.write&&(f.browser.asObject=!0);const _=f.serializers||{},S=n(f.browser.serialize,_);let U=f.browser.serialize;Array.isArray(f.browser.serialize)&&f.browser.serialize.indexOf("!stdSerializers.err")>-1&&(U=!1);const O=["error","fatal","warn","info","debug","trace"];typeof C=="function"&&(C.error=C.fatal=C.warn=C.info=C.debug=C.trace=C),f.enabled===!1&&(f.level="silent");const A=f.level||"info",b=Object.create(C);b.log||(b.log=w),Object.defineProperty(b,"levelVal",{get:x}),Object.defineProperty(b,"level",{get:L,set:F});const N={transmit:v,serialize:S,asObject:f.browser.asObject,levels:O,timestamp:p(f)};b.levels=r.levels,b.level=A,b.setMaxListeners=b.getMaxListeners=b.emit=b.addListener=b.on=b.prependListener=b.once=b.prependOnceListener=b.removeListener=b.removeAllListeners=b.listeners=b.listenerCount=b.eventNames=b.write=b.flush=w,b.serializers=_,b._serialize=S,b._stdErrSerialize=U,b.child=P,v&&(b._logEvent=u());function x(){return this.level==="silent"?1/0:this.levels.values[this.level]}function L(){return this._level}function F(T){if(T!=="silent"&&!this.levels.values[T])throw Error("unknown level "+T);this._level=T,i(N,b,"error","log"),i(N,b,"fatal","error"),i(N,b,"warn","error"),i(N,b,"info","log"),i(N,b,"debug","log"),i(N,b,"trace","log")}function P(T,W){if(!T)throw new Error("missing bindings for child Pino");W=W||{},S&&T.serializers&&(W.serializers=T.serializers);const K=W.serializers;if(S&&K){var ie=Object.assign({},_,K),oe=f.browser.serialize===!0?Object.keys(ie):S;delete T.serializers,c([T],oe,ie,this._stdErrSerialize)}function se(X){this._childLevel=(X._childLevel|0)+1,this.error=l(X,T,"error"),this.fatal=l(X,T,"fatal"),this.warn=l(X,T,"warn"),this.info=l(X,T,"info"),this.debug=l(X,T,"debug"),this.trace=l(X,T,"trace"),ie&&(this.serializers=ie,this._serialize=oe),v&&(this._logEvent=u([].concat(X._logEvent.bindings,T)))}return se.prototype=this,new se(this)}return b}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:E,epochTime:I,unixTime:k,isoTime:D});function i(f,v,C,_){const S=Object.getPrototypeOf(v);v[C]=v.levelVal>v.levels.values[C]?w:S[C]?S[C]:e[C]||e[_]||w,o(f,v,C)}function o(f,v,C){!f.transmit&&v[C]===w||(v[C]=(function(_){return function(){const U=f.timestamp(),O=new Array(arguments.length),A=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var b=0;b<O.length;b++)O[b]=arguments[b];if(f.serialize&&!f.asObject&&c(O,this._serialize,this.serializers,this._stdErrSerialize),f.asObject?_.call(A,a(this,C,O,U)):_.apply(A,O),f.transmit){const N=f.transmit.level||v.level,x=r.levels.values[N],L=r.levels.values[C];if(L<x)return;d(this,{ts:U,methodLevel:C,methodValue:L,transmitValue:r.levels.values[f.transmit.level||v.level],send:f.transmit.send,val:v.levelVal},O)}}})(v[C]))}function a(f,v,C,_){f._serialize&&c(C,f._serialize,f.serializers,f._stdErrSerialize);const S=C.slice();let U=S[0];const O={};_&&(O.time=_),O.level=r.levels.values[v];let A=(f._childLevel|0)+1;if(A<1&&(A=1),U!==null&&typeof U=="object"){for(;A--&&typeof S[0]=="object";)Object.assign(O,S.shift());
4U=S.length?t(S.shift(),S):void 0}else typeof U=="string"&&(U=t(S.shift(),S));return U!==void 0&&(O.msg=U),O}function c(f,v,C,_){for(const S in f)if(_&&f[S]instanceof Error)f[S]=r.stdSerializers.err(f[S]);else if(typeof f[S]=="object"&&!Array.isArray(f[S]))for(const U in f[S])v&&v.indexOf(U)>-1&&U in C&&(f[S][U]=C[U](f[S][U]))}function l(f,v,C){return function(){const _=new Array(1+arguments.length);_[0]=v;for(var S=1;S<_.length;S++)_[S]=arguments[S-1];return f[C].apply(this,_)}}function d(f,v,C){const _=v.send,S=v.ts,U=v.methodLevel,O=v.methodValue,A=v.val,b=f._logEvent.bindings;c(C,f._serialize||Object.keys(f.serializers),f.serializers,f._stdErrSerialize===void 0?!0:f._stdErrSerialize),f._logEvent.ts=S,f._logEvent.messages=C.filter(function(N){return b.indexOf(N)===-1}),f._logEvent.level.label=U,f._logEvent.level.value=O,_(U,f._logEvent,A),f._logEvent=u(b)}function u(f){return{ts:0,messages:[],bindings:f||[],level:{label:"",value:0}}}function h(f){const v={type:f.constructor.name,msg:f.message,stack:f.stack};for(const C in f)v[C]===void 0&&(v[C]=f[C]);return v}function p(f){return typeof f.timestamp=="function"?f.timestamp:f.timestamp===!1?E:I}function y(){return{}}function m(f){return f}function w(){}function E(){return!1}function I(){return Date.now()}function k(){return Math.round(Date.now()/1e3)}function D(){return new Date(Date.now()).toISOString()}function j(){function f(v){return typeof v<"u"&&v}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 f(self)||f(window)||f(this)||{}}}return Mo}var Kn=im();const ci=Tu(Kn),om={level:"info"},li="custom_context",mc=1e3*1024;let am=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}},il=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const s=new am(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}}}}},Wu=class{constructor(e,s=mc){this.level=e??"error",this.levelValue=Kn.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=s,this.logs=new il(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,s){s===Kn.levels.values.error?console.error(e):s===Kn.levels.values.warn?console.warn(e):s===Kn.levels.values.debug?console.debug(e):s===Kn.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(In({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 il(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const s=this.getLogArray();return s.push(In({extraMetadata:e})),new Blob(s,{type:"application/json"})}},cm=class{constructor(e,s=mc){this.baseChunkLogger=new Wu(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)}},lm=class{constructor(e,s=mc){this.baseChunkLogger=new Wu(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 dm=Object.defineProperty,um=Object.defineProperties,hm=Object.getOwnPropertyDescriptors,ol=Object.getOwnPropertySymbols,pm=Object.prototype.hasOwnProperty,fm=Object.prototype.propertyIsEnumerable,al=(t,e,s)=>e in t?dm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qi=(t,e)=>{for(var s in e||(e={}))pm.call(e,s)&&al(t,s,e[s]);if(ol)for(var s of ol(e))fm.call(e,s)&&al(t,s,e[s]);return t},eo=(t,e)=>um(t,hm(e));function wo(t){return eo(Qi({},t),{level:(t==null?void 0:t.level)||om.level})}function gm(t,e=li){return t[e]||""}function mm(t,e,s=li){return t[s]=e,t}function Et(t,e=li){let s="";return typeof t.bindings>"u"?s=gm(t,e):s=t.bindings().context||"",s}function ym(t,e,s=li){const n=Et(t,s);return n.trim()?`${n}/${e}`:e}function lt(t,e,s=li){const n=ym(t,e,s),r=t.child({context:n});return mm(r,n,s)}function wm(t){var e,s;const n=new cm((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ci(eo(Qi({},t.opts),{level:"trace",browser:eo(Qi({},(s=t.opts)==null?void 0:s.browser),{write:r=>n.write(r)})}
4)),chunkLoggerController:n}}function bm(t){var e;const s=new lm((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ci(eo(Qi({},t.opts),{level:"trace"}),s),chunkLoggerController:s}}function vm(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?wm(t):bm(t)}var Em=Object.defineProperty,Cm=(t,e,s)=>e in t?Em(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,cl=(t,e,s)=>Cm(t,typeof e!="symbol"?e+"":e,s);let Im=class extends ur{constructor(e){super(),this.opts=e,cl(this,"protocol","wc"),cl(this,"version",2)}};var Am=Object.defineProperty,Nm=(t,e,s)=>e in t?Am(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_m=(t,e,s)=>Nm(t,e+"",s);let Sm=class extends ur{constructor(e,s){super(),this.core=e,this.logger=s,_m(this,"records",new Map)}},Tm=class{constructor(e,s){this.logger=e,this.core=s}},Om=class extends ur{constructor(e,s){super(),this.relayer=e,this.logger=s}},km=class extends ur{constructor(e){super()}},Pm=class{constructor(e,s,n,r){this.core=e,this.logger=s,this.name=n}},xm=class extends ur{constructor(e,s){super(),this.relayer=e,this.logger=s}},Rm=class extends ur{constructor(e,s){super(),this.core=e,this.logger=s}},$m=class{constructor(e,s,n){this.core=e,this.logger=s,this.store=n}},Um=class{constructor(e,s){this.projectId=e,this.logger=s}},Dm=class{constructor(e,s,n){this.core=e,this.logger=s,this.telemetryEnabled=n}};var Lm=Object.defineProperty,Bm=(t,e,s)=>e in t?Lm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ll=(t,e,s)=>Bm(t,typeof e!="symbol"?e+"":e,s);let Mm=class{constructor(e){this.opts=e,ll(this,"protocol","wc"),ll(this,"version",2)}},jm=class{constructor(e){this.client=e}};function Xr(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 Xr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const zu="2.36.0";let Er={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${zu}`};class _n extends Error{constructor(e,s={}){var a;const n=(()=>{var c;return s.cause instanceof _n?s.cause.details:(c=s.cause)!=null&&c.message?s.cause.message:s.details})(),r=s.cause instanceof _n&&s.cause.docsPath||s.docsPath,i=(a=Er.getDocsUrl)==null?void 0:a.call(Er,{...s,docsPath:r}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...Er.version?[`Version: ${Er.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=zu}walk(e){return Hu(this,e)}}function Hu(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Hu(t.cause,e):e?null:t}class Ku extends _n{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 fr(t,{dir:e,size:s=32}={}){return typeof t=="string"?Fm(t,{dir:e,size:s}):qm(t,{dir:e,size:s})}function Fm(t,{dir:e,size:s=32}={}){if(s===null)return t;const n=t.replace("0x","");if(n.length>s*2)throw new Ku({size:Math.ceil(n.length/2),targetSize:s,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function qm(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new Ku({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 Wm extends _n{constructor({max:e,min:s,signed:n,size:r,value:i}
5){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 zm extends _n{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function gr(t,{size:e}){if(Sa(t)>e)throw new zm({givenSize:Sa(t),maxSize:e})}function Ta(t,e={}){const{signed:s}=e;e.size&&gr(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 Hm(t,e={}){return Number(Ta(t,e))}const Km=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Oa(t,e={}){return typeof t=="number"||typeof t=="bigint"?Gu(t,e):typeof t=="string"?Ym(t,e):typeof t=="boolean"?Vm(t,e):Vu(t,e)}function Vm(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(gr(s,{size:e.size}),fr(s,{size:e.size})):s}function Vu(t,e={}){let s="";for(let r=0;r<t.length;r++)s+=Km[t[r]];const n=`0x${s}`;return typeof e.size=="number"?(gr(n,{size:e.size}),fr(n,{dir:"right",size:e.size})):n}function Gu(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 Wm({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:s,size:n,value:`${t}${c}`})}const a=`0x${(s&&r<0?(1n<<BigInt(n*8))+BigInt(r):r).toString(16)}`;return n?fr(a,{size:n}):a}const Gm=new TextEncoder;function Ym(t,e={}){const s=Gm.encode(t);return Vu(s,e)}const Jm=new TextEncoder;function Xm(t,e={}){return typeof t=="number"||typeof t=="bigint"?Qm(t,e):typeof t=="boolean"?Zm(t,e):Xr(t)?Yu(t,e):Ju(t,e)}function Zm(t,e={}){const s=new Uint8Array(1);return s[0]=Number(t),typeof e.size=="number"?(gr(s,{size:e.size}),fr(s,{size:e.size})):s}const fs={zero:48,nine:57,A:65,F:70,a:97,f:102};function dl(t){if(t>=fs.zero&&t<=fs.nine)return t-fs.zero;if(t>=fs.A&&t<=fs.F)return t-(fs.A-10);if(t>=fs.a&&t<=fs.f)return t-(fs.a-10)}function Yu(t,e={}){let s=t;e.size&&(gr(s,{size:e.size}),s=fr(s,{dir:"right",size:e.size}));let n=s.slice(2);n.length%2&&(n=`0${n}`);const r=n.length/2,i=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=dl(n.charCodeAt(a++)),l=dl(n.charCodeAt(a++));if(c===void 0||l===void 0)throw new _n(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);i[o]=c*16+l}return i}function Qm(t,e){const s=Gu(t,e);return Yu(s)}function Ju(t,e={}){const s=Jm.encode(t);return typeof e.size=="number"?(gr(s,{size:e.size}),fr(s,{dir:"right",size:e.size})):s}const Ai=BigInt(2**32-1),ul=BigInt(32);function ey(t,e=!1){return e?{h:Number(t&Ai),l:Number(t>>ul&Ai)}:{h:Number(t>>ul&Ai)|0,l:Number(t&Ai)|0}}function ty(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}=ey(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const sy=(t,e,s)=>t<<s|e>>>32-s,ny=(t,e,s)=>e<<s|t>>>32-s,ry=(t,e,s)=>e<<s-32|t>>>64-s,iy=(t,e,s)=>t<<s-32|e>>>64-s,Bn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function oy(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function to(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function or(t,...e){if(!oy(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 aS(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");to(t.outputLen),to(t.blockLen)}function hl(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 ay(t,e){or(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function cy(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Xu(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function cS(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function lS(t,e){return t<<32-e|t>>>e}const ly=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function dy(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function uy(t){for(let e=0;e<t.length;e++)t[e]=dy(t[e]);return t}const pl=ly?t=>t:uy,Zu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function dS(t){if(or(t),Zu)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=hy[t[s]];return e}const gs={_0:48,_9:57,A:65,F:70,a:97,f:102};function fl(t){if(t>=gs._0&&t<=gs._9)return t-gs._0;if(t>=gs.A&&t<=gs.F)return t-(gs.A-10);if(t>=gs.a&&t<=gs.f)return t-(gs.a-10)}function uS(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);
vendor: 24,625 bytes, line 5
5if(Zu)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=fl(t.charCodeAt(i)),a=fl(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 py(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Qu(t){return typeof t=="string"&&(t=py(t)),or(t),t}function hS(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];or(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 fy{}function gy(t){const e=n=>t().update(Qu(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function pS(t=32){if(Bn&&typeof Bn.getRandomValues=="function")return Bn.getRandomValues(new Uint8Array(t));if(Bn&&typeof Bn.randomBytes=="function")return Uint8Array.from(Bn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const my=BigInt(0),Cr=BigInt(1),yy=BigInt(2),wy=BigInt(7),by=BigInt(256),vy=BigInt(113),eh=[],th=[],sh=[];for(let t=0,e=Cr,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],eh.push(2*(5*n+s)),th.push((t+1)*(t+2)/2%64);let r=my;for(let i=0;i<7;i++)e=(e<<Cr^(e>>wy)*vy)%by,e&yy&&(r^=Cr<<(Cr<<BigInt(i))-Cr);sh.push(r)}const nh=ty(sh,!0),Ey=nh[0],Cy=nh[1],gl=(t,e,s)=>s>32?ry(t,e,s):sy(t,e,s),ml=(t,e,s)=>s>32?iy(t,e,s):ny(t,e,s);function Iy(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=gl(l,d,1)^s[a],h=ml(l,d,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=th[o],c=gl(r,i,a),l=ml(r,i,a),d=eh[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]^=Ey[n],t[1]^=Cy[n]}Xu(s)}class yc extends fy{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,to(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=cy(this.state)}clone(){return this._cloneInto()}keccak(){pl(this.state32),Iy(this.state32,this.rounds),pl(this.state32),this.posOut=0,this.pos=0}update(e){hl(this),e=Qu(e),or(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){hl(this,!1),or(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 to(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ay(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,Xu(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new yc(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 Ay=(t,e,s)=>gy(()=>new yc(e,t,s)),Ny=Ay(1,136,256/8);function rh(t,e){const s=e||"hex",n=Ny(Xr(t,{strict:!1})?Xm(t):t);return s==="bytes"?n:Oa(n)}class _y 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 jo=new _y(8192);function Sy(t,e){if(jo.has(`${t}.${e}`))return jo.get(`${t}.${e}`);const s=t.substring(2).toLowerCase(),n=rh(Ju(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 jo.set(`${t}.${e}`,i),i}function Ty(t){const e=rh(`0x${t.substring(4)}`).substring(26);return Sy(`0x${e}`)}async function Oy({hash:t,signature:e}){const s=Xr(t)?t:Oa(t),{secp256k1:n}=await Vr(async()=>{const{secp256k1:o}=await import("./secp256k1-CIdmKGEy.js");return{secp256k1:o}},__vite__mapDeps([8,1,2]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:d,v:u,yParity:h}=e,p=Number(h??u),y=yl(p);return new n.Signature(Ta(l),Ta(d)).addRecoveryBit(y)}const o=Xr(e)?e:Oa(e);if(Sa(o)!==65)throw new Error("invalid signature length");const a=Hm(`0x${o.slice(130)}`),c=yl(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(s.substring(2)).toHex(!1)}`}function yl(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 ky({hash:t,signature:e}){return Ty(await Oy({hash:t,signature:e}))}var Py={};const xy=":";function Ss(t){const[e,s]=t.split(xy);return{namespace:e,reference:s}}function ih(t,e){return t.includes(":")?[t]:e.chains||[]}var Ry=Object.defineProperty,$y=Object.defineProperties,Uy=Object.getOwnPropertyDescriptors,wl=Object.getOwnPropertySymbols,Dy=Object.prototype.hasOwnProperty,Ly=Object.prototype.propertyIsEnumerable,ka=(t,e,s)=>e in t?Ry(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,bl=(t,e)=>{for(var s in e||(e={}))Dy.call(e,s)&&ka(t,s,e[s]);if(wl)for(var s of wl(e))Ly.call(e,s)&&ka(t,s,e[s]);return t},By=(t,e)=>$y(t,Uy(e)),vl=(t,e,s)=>ka(t,typeof e!="symbol"?e+"":e,s);const My="ReactNative",Ot={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},jy="js";function so(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function tn(){return!ks.getDocument()&&!!ks.getNavigator()&&navigator.product===My}function Fy(){return tn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function qy(){return tn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function mr(){return!so()&&!!ks.getNavigator()&&!!ks.getDocument()}function di(){return tn()?Ot.reactNative:so()?Ot.node:mr()?Ot.browser:Ot.unknown}function El(){var t;try{return tn()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Wy(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 zy(t){var e,s;const n=oh();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(r=>r!=="")),By(bl(bl({},n),t),{url:(t==null?void 0:t.url)||n.url,name:(t==null?void 0:t.name)||n.name,description:(t==null?void 0:t.description)||n.description,icons:(s=t==null?void 0:t.icons)!=null&&s.length&&t.icons.length>0?t.icons:n.icons})}catch(r){return console.warn("Error populating app metadata",r),t||n}}function oh(){return pf.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Hy(){if(di()===Ot.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=gf();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 Ky(){var t;const e=di();return e===Ot.browser?[e,((t=ks.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function ah(t,e,s){const n=Hy(),r=Ky();return[[t,e].join("-"),[jy,s].join("-"),n,r].join("/")}function Vy({protocol:t,version:e,relayUrl:s,sdkVersion:n,auth:r,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d=ah(t,e,n),u={auth:r,ua:d,projectId:i,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=Wy(l[1]||"",u);return l[0]+"?"+h}function mn(t,e){return t.filter(s=>e.includes(s)).length===t.length}function Pa(t){return Object.fromEntries(t.entries())}function xa(t){return new Map(Object.entries(t))}function un(t=V.FIVE_MINUTES,e){const s=V.toMiliseconds(t||V.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 as(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 ch(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 Gy(t){return ch("topic",t)}function Yy(t){return ch("id",t)}function lh(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 Be(t,e){return V.fromMiliseconds(Date.now()+V.toMiliseconds(t))}function is(t){return Date.now()>=V.toMiliseconds(t)}function Ie(t,e){return`${t}${e?`:${e}`:""}`}function ds(t=[],e=[]){return[...new Set([...t,...e])]}async function Jy({id:t,topic:e,wcDeepLink:s}){var n;try{if(!s)return;const r=typeof s=="string"?JSON.parse(s):s,i=r==null?void 0:r.href;if(typeof i!="string")return;const o=Xy(i,t,e),a=di();if(a===Ot.browser){if(!((n=ks.getDocument())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Zy(o)}else a===Ot.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(r){console.error(r)}}function Xy(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}${sw(n,!0)}`}else r=`${r}/wc?${n}`;return r}function Zy(t){let e="_self";tw()?e="_top":(ew()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function Qy(t,e){let s="";try{if(mr()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(n){console.error(n)}return s}function Cl(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),n=s.indexOf(e);return s[n+2]}function Il(){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 wc(){return typeof process<"u"&&Py.IS_VITEST==="true"}function ew(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function tw(){try{return window.self!==window.top}catch{return!1}}function sw(t,e=!1){const s=Buffer.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function dh(t){return Buffer.from(t,"base64").toString("utf-8")}function nw(t){return new Promise(e=>setTimeout(e,t))}let rw=class{constructor({limit:e}){vl(this,"limit"),vl(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 Ni=BigInt(2**32-1),Al=BigInt(32);function uh(t,e=!1){return e?{h:Number(t&Ni),l:Number(t>>Al&Ni)}:{h:Number(t>>Al&Ni)|0,l:Number(t&Ni)|0}}function hh(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}=uh(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const Nl=(t,e,s)=>t>>>s,_l=(t,e,s)=>t<<32-s|e>>>s,Ws=(t,e,s)=>t>>>s|e<<32-s,zs=(t,e,s)=>t<<32-s|e>>>s,$r=(t,e,s)=>t<<64-s|e>>>s-32,Ur=(t,e,s)=>t>>>s-32|e<<64-s,iw=(t,e)=>e,ow=(t,e)=>t,aw=(t,e,s)=>t<<s|e>>>32-s,cw=(t,e,s)=>e<<s|t>>>32-s,lw=(t,e,s)=>e<<s-32|t>>>64-s,dw=(t,e,s)=>t<<s-32|e>>>64-s;function Vt(t,e,s,n){const r=(e>>>0)+(n>>>0);return{h:t+s+(r/2**32|0)|0,l:r|0}}const bc=(t,e,s)=>(t>>>0)+(e>>>0)+(s>>>0),vc=(t,e,s,n)=>e+s+n+(t/2**32|0)|0,uw=(t,e,s,n)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0),hw=(t,e,s,n,r)=>e+s+n+r+(t/2**32|0)|0,pw=(t,e,s,n,r)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0)+(r>>>0),fw=(t,e,s,n,r,i)=>e+s+n+r+i+(t/2**32|0)|0,Mn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function bo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ps(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Xt(t,...e){if(!bo(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 vo(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ps(t.outputLen),Ps(t.blockLen)}function en(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 Ec(t,e){Xt(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Zr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ft(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Fo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Zt(t,e){return t<<32-e|t>>>e}const ph=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function fh(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const ws=ph?t=>t:t=>fh(t);function gw(t){for(let e=0;e<t.length;e++)t[e]=fh(t[e]);return t}const Hs=ph?t=>t:gw,gh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",mw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function er(t){if(Xt(t),gh)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=mw[t[s]];return e}const ms={_0:48,_9:57,A:65,F:70,a:97,f:102};function Sl(t){if(t>=ms._0&&t<=ms._9)return t-ms._0;if(t>=ms.A&&t<=ms.F)return t-(ms.A-10);if(t>=ms.a&&t<=ms.f)return t-(ms.a-10)}function no(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(gh)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=Sl(t.charCodeAt(i)),a=Sl(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 mh(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Yt(t){return typeof t=="string"&&(t=mh(t)),Xt(t),t}function Ks(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];Xt(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 Eo{}function ui(t){const e=n=>t().update(Yt(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function yw(t){const e=(n,r)=>t(r).update(Yt(n)).digest(),s=t({});return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}function $n(t=32){if(Mn&&typeof Mn.getRandomValues=="function")return Mn.getRandomValues(new Uint8Array(t));if(Mn&&typeof Mn.randomBytes=="function")return Uint8Array.from(Mn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const ww=BigInt(0),Ir=BigInt(1),bw=BigInt(2),vw=BigInt(7),Ew=BigInt(256),Cw=BigInt(113),yh=[],wh=[],bh=[];for(let t=0,e=Ir,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],yh.push(2*(5*n+s)),wh.push((t+1)*(t+2)/2%64);let r=ww;for(let i=0;i<7;i++)e=(e<<Ir^(e>>vw)*Cw)%Ew,e&bw&&(r^=Ir<<(Ir<<BigInt(i))-Ir);bh.push(r)}const vh=hh(bh,!0),Iw=vh[0],Aw=vh[1],Tl=(t,e,s)=>s>32?lw(t,e,s):aw(t,e,s),Ol=(t,e,s)=>s>32?dw(t,e,s):cw(t,e,s);function Nw(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=Tl(l,d,1)^s[a],h=Ol(l,d,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=wh[o],c=Tl(r,i,a),l=Ol(r,i,a),d=yh[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]^=Iw[n],t[1]^=Aw[n]}Ft(s)}let _w=class Eh extends Eo{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,Ps(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Zr(this.state)}clone(){return this._cloneInto()}keccak(){Hs(this.state32),Nw(this.state32,this.rounds),Hs(this.state32),this.posOut=0,this.pos=0}update(e){en(this),e=Yt(e),Xt(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){en(this,!1),Xt(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 Ps(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ec(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,Ft(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new Eh(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 Sw=(t,e,s)=>ui(()=>new _w(e,t,s)),Tw=Sw(1,136,256/8);function Ow(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 kw(t,e,s){return t&e^~t&s}function Pw(t,e,s){return t&e^t&s^e&s}let Ch=class extends Eo{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=Fo(this.buffer)}update(e){en(this),e=Yt(e),Xt(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=Fo(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){en(this),Ec(e,this),this.finished=!0;const{buffer:s,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,Ft(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)s[u]=0;Ow(n,r-8,BigInt(this.length*8),i),this.process(n,0);const a=Fo(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 Ds=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),et=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),tt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),xw=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]),Ls=new Uint32Array(64);class Rw extends Ch{constructor(e=32){super(64,e,8,!1),this.A=Ds[0]|0,this.B=Ds[1]|0,this.C=Ds[2]|0,this.D=Ds[3]|0,this.E=Ds[4]|0,this.F=Ds[5]|0,this.G=Ds[6]|0,this.H=Ds[7]|0}get(){const{A:e,B:s,C: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)Ls[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const h=Ls[u-15],p=Ls[u-2],y=Zt(h,7)^Zt(h,18)^h>>>3,m=Zt(p,17)^Zt(p,19)^p>>>10;Ls[u]=m+Ls[u-7]+y+Ls[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=Zt(a,6)^Zt(a,11)^Zt(a,25),p=d+h+kw(a,c,l)+xw[u]+Ls[u]|0,y=(Zt(n,2)^Zt(n,13)^Zt(n,22))+Pw(n,r,i)|0;d=l,l=c,c=a,a=o+p|0,o=i,i=r,r=n,n=p+y|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(){Ft(Ls)}destroy(){this.set(0,0,0,0,0,0,0,0),Ft(this.buffer)}}const Ih=hh(["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))),$w=Ih[0],Uw=Ih[1],Bs=new Uint32Array(80),Ms=new Uint32Array(80);let Cc=class extends Ch{constructor(e=64){super(128,e,16,!1),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}get(){const{Ah:e,Al:s,Bh:n,Bl:r,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:h,Gh:p,Gl:y,Hh:m,Hl:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,y,m,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,y,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=p|0,this.Gl=y|0,this.Hh=m|0,this.Hl=w|0}process(e,s){for(let k=0;k<16;k++,s+=4)Bs[k]=e.getUint32(s),Ms[k]=e.getUint32(s+=4);for(let k=16;k<80;k++){const D=Bs[k-15]|0,j=Ms[k-15]|0,f=Ws(D,j,1)^Ws(D,j,8)^Nl(D,j,7),v=zs(D,j,1)^zs(D,j,8)^_l(D,j,7),C=Bs[k-2]|0,_=Ms[k-2]|0,S=Ws(C,_,19)^$r(C,_,61)^Nl(C,_,6),U=zs(C,_,19)^Ur(C,_,61)^_l(C,_,6),O=uw(v,U,Ms[k-7],Ms[k-16]),A=hw(O,f,S,Bs[k-7],Bs[k-16]);Bs[k]=A|0,Ms[k]=O|0}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:h,Fh:p,Fl:y,Gh:m,Gl:w,Hh:E,Hl:I}=this;for(let k=0;k<80;k++){const D=Ws(u,h,14)^Ws(u,h,18)^$r(u,h,41),j=zs(u,h,14)^zs(u,h,18)^Ur(u,h,41),f=u&p^~u&m,v=h&y^~h&w,C=pw(I,j,v,Uw[k],Ms[k]),_=fw(C,E,D,f,$w[k],Bs[k]),S=C|0,U=Ws(n,r,28)^$r(n,r,34)^$r(n,r,39),O=zs(n,r,28)^Ur(n,r,34)^Ur(n,r,39),A=n&i^n&a^i&a,b=r&o^r&c^o&c;E=m|0,I=w|0,m=p|0,w=y|0,p=u|0,y=h|0,{h:u,l:h}=Vt(l|0,d|0,_|0,S|0),l=a|0,d=c|0,a=i|0,c=o|0,i=n|0,o=r|0;const N=bc(S,O,b);n=vc(N,_,U,A),r=N|0}({h:n,l:r}=Vt(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:o}=Vt(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Vt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Vt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:h}=Vt(this.Eh|0,this.El|0,u|0,h|0),{h:p,l:y}=Vt(this.Fh|0,this.Fl|0,p|0,y|0),{h:m,l:w}=Vt(this.Gh|0,this.Gl|0,m|0,w|0),{h:E,l:I}=Vt(this.Hh|0,this.Hl|0,E|0,I|0),this.set(n,r,i,o,a,c,l,d,u,h,p,y,m,w,E,I)}roundClean(){Ft(Bs,Ms)}destroy(){Ft(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class Dw extends Cc{constructor(){super(48),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}}const st=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Lw extends Cc{constructor(){super(32),this.Ah=st[0]|0,this.Al=st[1]|0,this.Bh=st[2]|0,this.Bl=st[3]|0,this.Ch=st[4]|0,this.Cl=st[5]|0,this.Dh=st[6]|0,this.Dl=st[7]|0,this.Eh=st[8]|0,this.El=st[9]|0,this.Fh=st[10]|0,this.Fl=st[11]|0,this.Gh=st[12]|0,this.Gl=st[13]|0,this.Hh=st[14]|0,this.Hl=st[15]|0}}const Co=ui(()=>new Rw),Bw=ui(()=>new Cc),Mw=ui(()=>new Dw),jw=ui(()=>new Lw),Fw=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]),Y=new Uint32Array(32);function js(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=Y[2*t],l=Y[2*t+1],d=Y[2*e],u=Y[2*e+1],h=Y[2*s],p=Y[2*s+1],y=Y[2*n],m=Y[2*n+1],w=bc(c,d,o);l=vc(w,l,u,a),c=w|0,{Dh:m,Dl:y}={Dh:m^l,Dl:y^c},{Dh:m,Dl:y}={Dh:iw(m,y),Dl:ow(m)},{h:p,l:h}=Vt(p,h,m,y),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:Ws(u,d,24),Bl:zs(u,d,24)},Y[2*t]=c,Y[2*t+1]=l,Y[2*e]=d,Y[2*e+1]=u,Y[2*s]=h,Y[2*s+1]=p,Y[2*n]=y,Y[2*n+1]=m}function Fs(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=Y[2*t],l=Y[2*t+1],d=Y[2*e],u=Y[2*e+1],h=Y[2*s],p=Y[2*s+1],y=Y[2*n],m=Y[2*n+1],w=bc(c,d,o);l=vc(w,l,u,a),c=w|0,{Dh:m,Dl:y}={Dh:m^l,Dl:y^c},{Dh:m,Dl:y}={Dh:Ws(m,y,16),Dl:zs(m,y,16)},{h:p,l:h}=Vt(p,h,m,y),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:$r(u,d,63),Bl:Ur(u,d,63)},Y[2*t]=c,Y[2*t+1]=l,Y[2*e]=d,Y[2*e+1]=u,Y[2*s]=h,Y[2*s+1]=p,Y[2*n]=y,Y[2*n+1]=m}function qw(t,e={},s,n,r){if(Ps(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)}
vendor: 57,890 bytes, lines 5-8
5class Ww extends Eo{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Ps(e),Ps(s),this.blockLen=e,this.outputLen=s,this.buffer=new Uint8Array(e),this.buffer32=Zr(this.buffer)}update(e){en(this),e=Yt(e),Xt(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&&(Hs(r),this.compress(r,0,!1),Hs(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));Hs(u);for(let h=0;c+s<i;h+=r.length,c+=s)this.length+=s,this.compress(u,h,!1);Hs(u);continue}n.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){en(this),Ec(e,this);const{pos:s,buffer32:n}=this;this.finished=!0,Ft(this.buffer.subarray(s)),Hs(n),this.compress(n,0,!0),Hs(n);const r=Zr(e);this.get().forEach((i,o)=>r[o]=ws(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 zw extends Ww{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,qw(s,e,64,16,16);let{key:n,personalization:r,salt:i}=e,o=0;if(n!==void 0&&(n=Yt(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=Yt(i);const a=Zr(i);this.v4l^=ws(a[0]),this.v4h^=ws(a[1]),this.v5l^=ws(a[2]),this.v5h^=ws(a[3])}if(r!==void 0){r=Yt(r);const a=Zr(r);this.v6l^=ws(a[0]),this.v6h^=ws(a[1]),this.v7l^=ws(a[2]),this.v7h^=ws(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:s,v1l:n,v1h:r,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:d,v5l:u,v5h:h,v6l:p,v6h:y,v7l:m,v7h:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,y,m,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,y,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=p|0,this.v6h=y|0,this.v7l=m|0,this.v7h=w|0}compress(e,s,n){this.get().forEach((c,l)=>Y[l]=c),Y.set(Fe,16);let{h:r,l:i}=uh(BigInt(this.length));Y[24]=Fe[8]^i,Y[25]=Fe[9]^r,n&&(Y[28]=~Y[28],Y[29]=~Y[29]);let o=0;const a=Fw;for(let c=0;c<12;c++)js(0,4,8,12,e,s+2*a[o++]),Fs(0,4,8,12,e,s+2*a[o++]),js(1,5,9,13,e,s+2*a[o++]),Fs(1,5,9,13,e,s+2*a[o++]),js(2,6,10,14,e,s+2*a[o++]),Fs(2,6,10,14,e,s+2*a[o++]),js(3,7,11,15,e,s+2*a[o++]),Fs(3,7,11,15,e,s+2*a[o++]),js(0,5,10,15,e,s+2*a[o++]),Fs(0,5,10,15,e,s+2*a[o++]),js(1,6,11,12,e,s+2*a[o++]),Fs(1,6,11,12,e,s+2*a[o++]),js(2,7,8,13,e,s+2*a[o++]),Fs(2,7,8,13,e,s+2*a[o++]),js(3,4,9,14,e,s+2*a[o++]),Fs(3,4,9,14,e,s+2*a[o++]);this.v0l^=Y[0]^Y[16],this.v0h^=Y[1]^Y[17],this.v1l^=Y[2]^Y[18],this.v1h^=Y[3]^Y[19],this.v2l^=Y[4]^Y[20],this.v2h^=Y[5]^Y[21],this.v3l^=Y[6]^Y[22],this.v3h^=Y[7]^Y[23],this.v4l^=Y[8]^Y[24],this.v4h^=Y[9]^Y[25],this.v5l^=Y[10]^Y[26],this.v5h^=Y[11]^Y[27],this.v6l^=Y[12]^Y[28],this.v6h^=Y[13]^Y[29],this.v7l^=Y[14]^Y[30],this.v7h^=Y[15]^Y[31],Ft(Y)}destroy(){this.destroyed=!0,Ft(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Hw=yw(t=>new zw(t)),Kw="https://rpc.walletconnect.org/v1";function Ah(t){const e=`�Ethereum Signed Message:
6${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Tw(s)).toString("hex")}async function Vw(t,e,s,n,r,i){switch(s.t){case"eip191":return await Gw(t,e,s.s);case"eip1271":return await Yw(t,e,s.s,n,r,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}async function Gw(t,e,s){return(await ky({hash:Ah(e),signature:s})).toLowerCase()===t.toLowerCase()}async function Yw(t,e,s,n,r,i){const o=Ss(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:Ah(e)).substring(2),h=a+u+c+d+l,p=await fetch(`${i||Kw}/?chainId=${n}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Jw(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:y}=await p.json();return y?y.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Jw(){return Date.now()+Math.floor(Math.random()*1e3)}function Xw(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 hr.encode(i)}function Zw(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=Hw(n,{dkLen:32});return hr.encode(r)}function kl(t){const e=new Uint8Array(Co(Qw(t)));return hr.encode(e)}function Qw(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 Pl(t){const e=Buffer.from(t,"base64"),s=mf(e).txn;if(!s)throw new Error("Invalid signed transaction: missing 'txn' field");const n=yf(s),r=Buffer.from("TX"),i=Buffer.concat([r,Buffer.from(n)]),o=jw(i);return wf.encode(o).replace(/=+$/,"")}function qo(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 eb(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(qo(e.length)),r.push(e),r.push(Buffer.from([18])),r.push(qo(s.length)),r.push(s),r.push(Buffer.from([26])),r.push(qo(n.length)),r.push(n);const i=Buffer.concat(r),o=Co(i);return Buffer.from(o).toString("hex").toUpperCase()}function tb(t){var e,s;const n=[];try{if(typeof t=="string")return n.push(t),n;if(typeof t!="object")return n;t!=null&&t.id&&n.push(t.id);const r=(s=(e=t==null?void 0:t.capabilities)==null?void 0:e.caip345)==null?void 0:s.transactionHashes;r&&n.push(...r)}catch(r){console.warn("getWalletSendCallsHashes failed: ",r)}return n}var sb=Object.defineProperty,nb=Object.defineProperties,rb=Object.getOwnPropertyDescriptors,xl=Object.getOwnPropertySymbols,ib=Object.prototype.hasOwnProperty,ob=Object.prototype.propertyIsEnumerable,Rl=(t,e,s)=>e in t?sb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ab=(t,e)=>{for(var s in e||(e={}))ib.call(e,s)&&Rl(t,s,e[s]);if(xl)for(var s of xl(e))ob.call(e,s)&&Rl(t,s,e[s]);return t},cb=(t,e)=>nb(t,rb(e));const lb="did:pkh:",Ic=t=>t==null?void 0:t.split(":"),db=t=>{const e=t&&Ic(t);if(e)return t.includes(lb)?e[3]:e[1]},Ra=t=>{const e=t&&Ic(t);if(e)return e[2]+":"+e[3]},ro=t=>{const e=t&&Ic(t);if(e)return e.pop()};async function $l(t){const{cacao:e,projectId:s}=t,{s:n,p:r}=e,i=Nh(r,r.iss),o=ro(r.iss);return await Vw(o,i,n,Ra(r.iss),s)}const Nh=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,n=ro(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: ${db(e)}`,c=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,d=t.exp?`Expiration Time: ${t.exp}`:void 0,u=t.nbf?`Not Before: ${t.nbf}`:void 0,h=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(m=>`
7- ${m}`).join("")}`:void 0,y=ji(t.resources);if(y){const m=Qr(y);r=bb(r,m)}return[s,n,"",r,"",i,o,a,c,l,d,u,h,p].filter(m=>m!=null).join(`
8`)};function ub(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function hb(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function Sn(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 pb(t,e,s,n={}){return s==null||s.sort((r,i)=>r.localeCompare(i)),{att:{[t]:fb(e,s,n)}}}function fb(t,e,s={}){e=e==null?void 0:e.sort((r,i)=>r.localeCompare(i));const n=e.map(r=>({[`${t}/${r}`]:[s]}));return Object.assign({},...n)}function _h(t){return Sn(t),`urn:recap:${ub(t).replace(/=/g,"")}`}function Qr(t){const e=hb(t.replace("urn:recap:",""));return Sn(e),e}function gb(t,e,s){const n=pb(t,e,s);return _h(n)}function mb(t){return t&&t.includes("urn:recap:")}function yb(t,e){const s=Qr(t),n=Qr(e),r=wb(s,n);return _h(r)}function wb(t,e){Sn(t),Sn(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]=cb(ab({},n.att[r]),{[a]:((c=t.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),n}function bb(t="",e){Sn(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 Ul(t){var e;const s=Qr(t);Sn(s);const n=(e=s.att)==null?void 0:e.eip155;return n?Object.keys(n).map(r=>r.split("/")[1]):[]}function Dl(t){const e=Qr(t);Sn(e);const s=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(r=>{var i;(i=r==null?void 0:r[0])!=null&&i.chains&&s.push(r[0].chains)})}),[...new Set(s.flat())]}function ji(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return mb(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Sh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function $a(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Wo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function yt(t,...e){if(!Sh(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 Ll(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 vb(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 Xs(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function ar(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Eb(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Cb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ib(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ua(t){if(typeof t=="string")t=Ib(t);else if(Sh(t))t=Da(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Ab(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Nb(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 _b=(t,e)=>{function s(n,...r){if(yt(n),!Cb)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?yt(l):yt(l,t.nonceLength)}const i=t.tagLength;i&&r[1]!==void 0&&yt(r[1]);const o=e(n,...r),a=(l,d)=>{if(d!==void 0){if(l!==2)throw new Error("cipher output not supported");yt(d)}};let c=!1;return{encrypt(l,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,yt(l),a(o.encrypt.length,d),o.encrypt(l,d)},decrypt(l,d){if(yt(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 Bl(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&&!Tb(e))throw new Error("invalid output, must be aligned");return e}function Ml(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 Sb(t,e,s){$a(s);const n=new Uint8Array(16),r=Eb(n);return Ml(r,0,BigInt(e),s),Ml(r,8,BigInt(t),s),n}function Tb(t){return t.byteOffset%4===0}function Da(t){return Uint8Array.from(t)}const Th=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),Ob=Th("expand 16-byte k"),kb=Th("expand 32-byte k"),Pb=Xs(Ob),xb=Xs(kb);function ve(t,e){return t<<e|t>>>32-e}function La(t){return t.byteOffset%4===0}const _i=64,Rb=16,Oh=2**32-1,jl=new Uint32Array;function $b(t,e,s,n,r,i,o,a){const c=r.length,l=new Uint8Array(_i),d=Xs(l),u=La(r)&&La(i),h=u?Xs(r):jl,p=u?Xs(i):jl;for(let y=0;y<c;o++){if(t(e,s,n,d,o,a),o>=Oh)throw new Error("arx: counter overflow");const m=Math.min(_i,c-y);if(u&&m===_i){const w=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let E=0,I;E<Rb;E++)I=w+E,p[I]=h[I]^d[E];y+=_i;continue}for(let w=0,E;w<m;w++)E=y+w,i[E]=r[E]^l[w];y+=m}}function Ub(t,e){const{allowShortKeys:s,extendNonceFn:n,counterLength:r,counterRight:i,rounds:o}=Ab({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Wo(r),Wo(o),$a(i),$a(s),(a,c,l,d,u=0)=>{yt(a),yt(c),yt(l);const h=l.length;if(d===void 0&&(d=new Uint8Array(h)),yt(d),Wo(u),u<0||u>=Oh)throw new Error("arx: counter overflow");if(d.length<h)throw new Error(`arx: output (${d.length}) is shorter than data (${h})`);const p=[];let y=a.length,m,w;if(y===32)p.push(m=Da(a)),w=xb;else if(y===16&&s)m=new Uint8Array(32),m.set(a),m.set(a,16),w=Pb,p.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);La(c)||p.push(c=Da(c));const E=Xs(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(w,E,Xs(c.subarray(0,16)),E),c=c.subarray(16)}const I=16-r;if(I!==c.length)throw new Error(`arx: nonce must be ${I} or 16 bytes`);if(I!==12){const D=new Uint8Array(12);D.set(c,i?0:12-c.length),c=D,p.push(c)}const k=Xs(c);return $b(t,w,E,k,l,d,u,o),ar(...p),d}}const Ke=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class Db{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=Ua(e),yt(e,32);const s=Ke(e,0),n=Ke(e,2),r=Ke(e,4),i=Ke(e,6),o=Ke(e,8),a=Ke(e,10),c=Ke(e,12),l=Ke(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]=Ke(e,16+2*d)}process(e,s,n=!1){const r=n?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],d=o[3],u=o[4],h=o[5],p=o[6],y=o[7],m=o[8],w=o[9],E=Ke(e,s+0),I=Ke(e,s+2),k=Ke(e,s+4),D=Ke(e,s+6),j=Ke(e,s+8),f=Ke(e,s+10),v=Ke(e,s+12),C=Ke(e,s+14);let _=i[0]+(E&8191),S=i[1]+((E>>>13|I<<3)&8191),U=i[2]+((I>>>10|k<<6)&8191),O=i[3]+((k>>>7|D<<9)&8191),A=i[4]+((D>>>4|j<<12)&8191),b=i[5]+(j>>>1&8191),N=i[6]+((j>>>14|f<<2)&8191),x=i[7]+((f>>>11|v<<5)&8191),L=i[8]+((v>>>8|C<<8)&8191),F=i[9]+(C>>>5|r),P=0,T=P+_*a+S*(5*w)+U*(5*m)+O*(5*y)+A*(5*p);P=T>>>13,T&=8191,T+=b*(5*h)+N*(5*u)+x*(5*d)+L*(5*l)+F*(5*c),P+=T>>>13,T&=8191;let W=P+_*c+S*a+U*(5*w)+O*(5*m)+A*(5*y);P=W>>>13,W&=8191,W+=b*(5*p)+N*(5*h)+x*(5*u)+L*(5*d)+F*(5*l),P+=W>>>13,W&=8191;let K=P+_*l+S*c+U*a+O*(5*w)+A*(5*m);P=K>>>13,K&=8191,K+=b*(5*y)+N*(5*p)+x*(5*h)+L*(5*u)+F*(5*d),P+=K>>>13,K&=8191;let ie=P+_*d+S*l+U*c+O*a+A*(5*w);P=ie>>>13,ie&=8191,ie+=b*(5*m)+N*(5*y)+x*(5*p)+L*(5*h)+F*(5*u),P+=ie>>>13,ie&=8191;let oe=P+_*u+S*d+U*l+O*c+A*a;P=oe>>>13,oe&=8191,oe+=b*(5*w)+N*(5*m)+x*(5*y)+L*(5*p)+F*(5*h),P+=oe>>>13,oe&=8191;let se=P+_*h+S*u+U*d+O*l+A*c;P=se>>>13,se&=8191,se+=b*a+N*(5*w)+x*(5*m)+L*(5*y)+F*(5*p),P+=se>>>13,se&=8191;let X=P+_*p+S*h+U*u+O*d+A*l;P=X>>>13,X&=8191,X+=b*c+N*a+x*(5*w)+L*(5*m)+F*(5*y),P+=X>>>13,X&=8191;let de=P+_*y+S*p+U*h+O*u+A*d;P=de>>>13,de&=8191,de+=b*l+N*c+x*a+L*(5*w)+F*(5*m),P+=de>>>13,de&=8191;let Te=P+_*m+S*y+U*p+O*h+A*u;P=Te>>>13,Te&=8191,Te+=b*d+N*l+x*c+L*a+F*(5*w),P+=Te>>>13,Te&=8191;let ue=P+_*w+S*m+U*y+O*p+A*h;P=ue>>>13,ue&=8191,ue+=b*u+N*d+x*l+L*c+F*a,P+=ue>>>13,ue&=8191,P=(P<<2)+P|0,P=P+T|0,T=P&8191,P=P>>>13,W+=P,i[0]=T,i[1]=W,i[2]=K,i[3]=ie,i[4]=oe,i[5]=se,i[6]=X,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;ar(n)}update(e){Ll(this),e=Ua(e),yt(e);const{buffer:s,blockLen:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(n-this.pos,r-i);if(o===n){for(;n<=r-i;i+=n)this.process(e,i);continue}s.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){ar(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ll(this),vb(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 Lb(t){const e=(n,r)=>t(r).update(Ua(n)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}const Bb=Lb(t=>new Db(t));function Mb(t,e,s,n,r,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],h=e[2],p=e[3],y=e[4],m=e[5],w=e[6],E=e[7],I=r,k=s[0],D=s[1],j=s[2],f=o,v=a,C=c,_=l,S=d,U=u,O=h,A=p,b=y,N=m,x=w,L=E,F=I,P=k,T=D,W=j;for(let ie=0;ie<i;ie+=2)f=f+S|0,F=ve(F^f,16),b=b+F|0,S=ve(S^b,12),f=f+S|0,F=ve(F^f,8),b=b+F|0,S=ve(S^b,7),v=v+U|0,P=ve(P^v,16),N=N+P|0,U=ve(U^N,12),v=v+U|0,P=ve(P^v,8),N=N+P|0,U=ve(U^N,7),C=C+O|0,T=ve(T^C,16),x=x+T|0,O=ve(O^x,12),C=C+O|0,T=ve(T^C,8),x=x+T|0,O=ve(O^x,7),_=_+A|0,W=ve(W^_,16),L=L+W|0,A=ve(A^L,12),_=_+A|0,W=ve(W^_,8),L=L+W|0,A=ve(A^L,7),f=f+U|0,W=ve(W^f,16),x=x+W|0,U=ve(U^x,12),f=f+U|0,W=ve(W^f,8),x=x+W|0,U=ve(U^x,7),v=v+O|0,F=ve(F^v,16),L=L+F|0,O=ve(O^L,12),v=v+O|0,F=ve(F^v,8),L=L+F|0,O=ve(O^L,7),C=C+A|0,P=ve(P^C,16),b=b+P|0,A=ve(A^b,12),C=C+A|0,P=ve(P^C,8),b=b+P|0,A=ve(A^b,7),_=_+S|0,T=ve(T^_,16),N=N+T|0,S=ve(S^N,12),_=_+S|0,T=ve(T^_,8),N=N+T|0,S=ve(S^N,7);let K=0;n[K++]=o+f|0,n[K++]=a+v|0,n[K++]=c+C|0,n[K++]=l+_|0,n[K++]=d+S|0,n[K++]=u+U|0,n[K++]=h+O|0,n[K++]=p+A|0,n[K++]=y+b|0,n[K++]=m+N|0,n[K++]=w+x|0,n[K++]=E+L|0,n[K++]=I+F|0,n[K++]=k+P|0,n[K++]=D+T|0,n[K++]=j+W|0}const jb=Ub(Mb,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Fb=new Uint8Array(16),Fl=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(Fb.subarray(s))},qb=new Uint8Array(32);function ql(t,e,s,n,r){const i=t(e,s,qb),o=Bb.create(i);r&&Fl(o,r),Fl(o,n);const a=Sb(n.length,r?r.length:0,!0);o.update(a);const c=o.digest();return ar(i,a),c}const Wb=t=>(e,s,n)=>({encrypt(r,i){const o=r.length;i=Bl(o+16,i,!1),i.set(r);const a=i.subarray(0,-16);t(e,s,a,a,1);const c=ql(t,e,s,a,n);return i.set(c,o),ar(c),i},decrypt(r,i){i=Bl(r.length-16,i,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=ql(t,e,s,o,n);if(!Nb(a,c))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),t(e,s,i,i,1),ar(c),i}}),kh=_b({blockSize:64,nonceLength:12,tagLength:16},Wb(jb));let Ph=class extends Eo{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,vo(e);const n=Yt(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),Ft(i)}update(e){return en(this),this.iHash.update(e),this}digestInto(e){en(this),Xt(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 Io=(t,e,s)=>new Ph(t,e).update(s).digest();Io.create=(t,e)=>new Ph(t,e);function zb(t,e,s){return vo(t),s===void 0&&(s=new Uint8Array(t.outputLen)),Io(t,Yt(s),Yt(e))}const zo=Uint8Array.from([0]),Wl=Uint8Array.of();function Hb(t,e,s,n=32){vo(t),Ps(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=Wl);const o=new Uint8Array(i*r),a=Io.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)zo[0]=d+1,c.update(d===0?Wl:l).update(s).update(zo).digestInto(l),o.set(l,r*d),a._cloneInto(c);return a.destroy(),c.destroy(),Ft(l,zo),o.slice(0,n)}const Kb=(t,e,s,n,r)=>Hb(t,zb(t,e,s),n,r),Ao=Co,Ac=BigInt(0),Ba=BigInt(1);function io(t,e=""){if(typeof t!="boolean"){const s=e&&`"${e}"`;throw new Error(s+"expected boolean, got type="+typeof t)}return t}function yn(t,e,s=""){const n=bo(t),r=t==null?void 0:t.length,i=e!==void 0;if(!n||i&&r!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=n?`length=${r}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Si(t){const e=t.toString(16);return e.length&1?"0"+e:e}function xh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ac:BigInt("0x"+t)}function No(t){return xh(er(t))}function oo(t){return Xt(t),xh(er(Uint8Array.from(t).reverse()))}function Nc(t,e){return no(t.toString(16).padStart(e*2,"0"))}function _c(t,e){return Nc(t,e).reverse()}function it(t,e,s){let n;if(typeof e=="string")try{n=no(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(bo(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 Ho=t=>typeof t=="bigint"&&Ac<=t;function Vb(t,e,s){return Ho(t)&&Ho(e)&&Ho(s)&&e<=t&&t<s}function Ma(t,e,s,n){if(!Vb(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function Rh(t){let e;for(e=0;t>Ac;t>>=Ba,e+=1);return e}const hi=t=>(Ba<<BigInt(t))-Ba;function Gb(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),r=h=>Uint8Array.of(h);let i=n(t),o=n(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...h)=>s(o,i,...h),d=(h=n(0))=>{o=l(r(0),h),i=l(),h.length!==0&&(o=l(r(1),h),i=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const p=[];for(;h<e;){i=l();const y=i.slice();p.push(y),h+=i.length}return Ks(...p)};return(h,p)=>{c(),d(h);let y;for(;!(y=p(u()));)d();return c(),y}}function _o(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 zl(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 bt=BigInt(0),at=BigInt(1),wn=BigInt(2),$h=BigInt(3),Uh=BigInt(4),Dh=BigInt(5),Yb=BigInt(7),Lh=BigInt(8),Jb=BigInt(9),Bh=BigInt(16);function St(t,e){const s=t%e;return s>=bt?s:e+s}function Kt(t,e,s){let n=t;for(;e-- >bt;)n*=n,n%=s;return n}function Hl(t,e){if(t===bt)throw new Error("invert: expected non-zero number");if(e<=bt)throw new Error("invert: expected positive modulus, got "+e);let s=St(t,e),n=e,r=bt,i=at;for(;s!==bt;){const o=n/s,a=n%s,c=r-i*o;n=s,s=a,r=i,i=c}if(n!==at)throw new Error("invert: does not exist");return St(r,e)}function Sc(t,e,s){if(!t.eql(t.sqr(e),s))throw new Error("Cannot find square root")}function Mh(t,e){const s=(t.ORDER+at)/Uh,n=t.pow(e,s);return Sc(t,n,e),n}function Xb(t,e){const s=(t.ORDER-Dh)/Lh,n=t.mul(e,wn),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,wn),r),a=t.mul(i,t.sub(o,t.ONE));return Sc(t,a,e),a}function Zb(t){const e=sn(t),s=jh(t),n=s(e,e.neg(e.ONE)),r=s(e,n),i=s(e,e.neg(n)),o=(t+Yb)/Bh;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,n);const u=a.mul(l,r),h=a.mul(l,i),p=a.eql(a.sqr(d),c),y=a.eql(a.sqr(u),c);l=a.cmov(l,d,p),d=a.cmov(h,u,y);const m=a.eql(a.sqr(d),c),w=a.cmov(l,d,m);return Sc(a,w,c),w}}function jh(t){if(t<$h)throw new Error("sqrt is not defined for small field");let e=t-at,s=0;for(;e%wn===bt;)e/=wn,s++;let n=wn;const r=sn(t);for(;Kl(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Mh;let i=r.pow(n,e);const o=(e+at)/wn;return function(a,c){if(a.is0(c))return c;if(Kl(a,c)!==1)throw new Error("Cannot find square root");let l=s,d=a.mul(a.ONE,i),u=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(u,a.ONE);){if(a.is0(u))return a.ZERO;let p=1,y=a.sqr(u);for(;!a.eql(y,a.ONE);)if(p++,y=a.sqr(y),p===l)throw new Error("Cannot find square root");const m=at<<BigInt(l-p-1),w=a.pow(d,m);l=p,d=a.sqr(w),u=a.mul(u,d),h=a.mul(h,w)}return h}}function Qb(t){return t%Uh===$h?Mh:t%Lh===Dh?Xb:t%Bh===Jb?Zb(t):jh(t)}const e0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function t0(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},s=e0.reduce((n,r)=>(n[r]="function",n),e);return _o(t,s),t}function s0(t,e,s){if(s<bt)throw new Error("invalid exponent, negatives unsupported");if(s===bt)return t.ONE;if(s===at)return e;let n=t.ONE,r=e;for(;s>bt;)s&at&&(n=t.mul(n,r)),r=t.sqr(r),s>>=at;return n}function Fh(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 Kl(t,e){const s=(t.ORDER-at)/wn,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 qh(t,e){e!==void 0&&Ps(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function sn(t,e,s=!1,n={}){if(t<=bt)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}=qh(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:hi(c),ZERO:bt,ONE:at,allowedLengths:a,create:h=>St(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return bt<=h&&h<t},is0:h=>h===bt,isValidNot0:h=>!u.is0(h)&&u.isValid(h),isOdd:h=>(h&at)===at,neg:h=>St(-h,t),eql:(h,p)=>h===p,sqr:h=>St(h*h,t),add:(h,p)=>St(h+p,t),sub:(h,p)=>St(h-p,t),mul:(h,p)=>St(h*p,t),pow:(h,p)=>s0(u,h,p),div:(h,p)=>St(h*Hl(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Hl(h,t),sqrt:i||(h=>(d||(d=Qb(t)),d(u,h))),toBytes:h=>s?_c(h,l):Nc(h,l),fromBytes:(h,p=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const m=new Uint8Array(l);m.set(h,s?0:m.length-h.length),h=m}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let y=s?oo(h):No(h);if(o&&(y=St(y,t)),!p&&!u.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:h=>Fh(u,h),cmov:(h,p,y)=>y?p:h});return Object.freeze(u)}function Wh(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 zh(t){const e=Wh(t);return e+Math.ceil(e/2)}function n0(t,e,s=!1){const n=t.length,r=Wh(e),i=zh(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?oo(t):No(t),a=St(o,e-at)+at;return s?_c(a,r):Nc(a,r)}const cr=BigInt(0),bn=BigInt(1);function ao(t,e){const s=e.negate();return t?s:e}function Ko(t,e){const s=Fh(t.Fp,e.map(n=>n.Z));return e.map((n,r)=>t.fromAffine(n.toAffine(s[r])))}function Hh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Vo(t,e){Hh(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=hi(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function Vl(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+=bn);const l=e*n,d=l+Math.abs(a)-1,u=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:l}}function r0(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 i0(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 Go=new WeakMap,Kh=new WeakMap;function Yo(t){return Kh.get(t)||1}function Gl(t){if(t!==cr)throw new Error("invalid wNAF")}class o0{constructor(e,s){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,n=this.ZERO){let r=e;for(;s>cr;)s&bn&&(n=n.add(r)),r=r.double(),s>>=bn;return n}precomputeWindow(e,s){const{windows:n,windowSize:r}=Vo(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=Vo(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:h,offsetF:p}=Vl(n,a,o);n=c,d?i=i.add(ao(h,s[p])):r=r.add(ao(u,s[l]))}return Gl(n),{p:r,f:i}}wNAFUnsafe(e,s,n,r=this.ZERO){const i=Vo(e,this.bits);for(let o=0;o<i.windows&&n!==cr;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Vl(n,o,i);if(n=a,!l){const u=s[c];r=r.add(d?u.negate():u)}}return Gl(n),r}getPrecomputes(e,s,n){let r=Go.get(s);return r||(r=this.precomputeWindow(s,e),e!==1&&(typeof n=="function"&&(r=n(r)),Go.set(s,r))),r}cached(e,s,n){const r=Yo(e);return this.wNAF(r,this.getPrecomputes(r,e,n),s)}unsafe(e,s,n,r){const i=Yo(e);return i===1?this._unsafeLadder(e,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),s,r)}createCache(e,s){Hh(s,this.bits),Kh.set(e,s),Go.delete(e)}hasCache(e){return Yo(e)!==1}}function a0(t,e,s,n){let r=e,i=t.ZERO,o=t.ZERO;for(;s>cr||n>cr;)s&bn&&(i=i.add(r)),n&bn&&(o=o.add(r)),r=r.double(),s>>=bn,n>>=bn;return{p1:i,p2:o}}function c0(t,e,s,n){r0(s,t),i0(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=Rh(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=hi(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=u;p>=0;p-=c){d.fill(o);for(let m=0;m<i;m++){const w=n[m],E=Number(w>>BigInt(p)&l);d[E]=d[E].add(s[m])}let y=o;for(let m=d.length-1,w=o;m>0;m--)w=w.add(d[m]),y=y.add(w);if(h=h.add(y),p!==0)for(let m=0;m<c;m++)h=h.double()}return h}function Yl(t,e,s){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return t0(e),e}else return sn(t,{isLE:s})}function l0(t,e,s={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>cr))throw new Error(`CURVE.${a} must be positive bigint`)}const r=Yl(e.p,s.Fp,n),i=Yl(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),mh("HashToScalar-");const Ar=BigInt(0),jn=BigInt(1),Ti=BigInt(2);function d0(t){return _o(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function u0(t){const e=d0(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||$n,l=a?255:448,d=a?32:56,u=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?Ti**BigInt(254):Ti**BigInt(447),y=a?BigInt(8)*Ti**BigInt(251)-jn:BigInt(4)*Ti**BigInt(445)-jn,m=p+y+jn,w=O=>St(O,s),E=I(u);function I(O){return _c(w(O),d)}function k(O){const A=it("u coordinate",O,d);return a&&(A[31]&=127),w(oo(A))}function D(O){return oo(r(it("scalar",O,d)))}function j(O,A){const b=C(k(A),D(O));if(b===Ar)throw new Error("invalid private or public key received");return I(b)}function f(O){return j(O,E)}function v(O,A,b){const N=w(O*(A-b));return A=w(A-N),b=w(b+N),{x_2:A,x_3:b}}function C(O,A){Ma("u",O,Ar,s),Ma("scalar",A,p,m);const b=A,N=O;let x=jn,L=Ar,F=O,P=jn,T=Ar;for(let K=BigInt(l-1);K>=Ar;K--){const ie=b>>K&jn;T^=ie,{x_2:x,x_3:F}=v(T,x,F),{x_2:L,x_3:P}=v(T,L,P),T=ie;const oe=x+L,se=w(oe*oe),X=x-L,de=w(X*X),Te=se-de,ue=F+P,Ue=F-P,Wt=w(Ue*oe),xs=w(ue*X),nn=Wt+xs,Dn=Wt-xs;F=w(nn*nn),P=w(N*w(Dn*Dn)),x=w(se*de),L=w(Te*(se+w(h*Te)))}({x_2:x,x_3:F}=v(T,x,F)),{x_2:L,x_3:P}=v(T,L,P);const W=i(L);return w(x*W)}const _={secretKey:d,publicKey:d,seed:d},S=(O=c(d))=>(Xt(O,_.seed),O);function U(O){const A=S(O);return{secretKey:A,publicKey:f(A)}}return{keygen:U,getSharedSecret:(O,A)=>j(O,A),getPublicKey:O=>f(O),scalarMult:j,scalarMultBase:f,utils:{randomSecretKey:S,randomPrivateKey:S},GuBytes:E.slice(),lengths:_}}const h0=BigInt(1),Jl=BigInt(2),p0=BigInt(3),f0=BigInt(5);BigInt(8);const Vh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),g0={p:Vh,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function m0(t){const e=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=Vh,o=t*t%i*t%i,a=Kt(o,Jl,i)*o%i,c=Kt(a,h0,i)*t%i,l=Kt(c,f0,i)*c%i,d=Kt(l,e,i)*l%i,u=Kt(d,s,i)*d%i,h=Kt(u,n,i)*u%i,p=Kt(h,r,i)*h%i,y=Kt(p,r,i)*h%i,m=Kt(y,e,i)*l%i;return{pow_p_5_8:Kt(m,Jl,i)*t%i,b2:o}}function y0(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const w0=sn(g0.p,{isLE:!0}),ja=(()=>{const t=w0.ORDER;return u0({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:s,b2:n}=m0(e);return St(Kt(s,p0,t)*n,t)},adjustScalarBytes:y0})})(),Xl=(t,e)=>(t+(t>=0?e:-e)/Gh)/e;function b0(t,e,s){const[[n,r],[i,o]]=e,a=Xl(o*t,s),c=Xl(-r*t,s);let l=t-a*n-c*i,d=-a*r-c*o;const u=l<_s,h=d<_s;u&&(l=-l),h&&(d=-d);const p=hi(Math.ceil(Rh(s)/2))+tr;if(l<_s||l>=p||d<_s||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}function Fa(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Jo(t,e){const s={};for(let n of Object.keys(e))s[n]=t[n]===void 0?e[n]:t[n];return io(s.lowS,"lowS"),io(s.prehash,"prehash"),s.format!==void 0&&Fa(s.format),s}class v0 extends Error{constructor(e=""){super(e)}}const Is={Err:v0,_tlv:{encode:(t,e)=>{const{Err:s}=Is;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const n=e.length/2,r=Si(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?Si(r.length/2|128):"";return Si(t)+i+r+e},decode(t,e){const{Err:s}=Is;let n=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new s("tlv.decode: wrong tlv");const r=e[n++],i=!!(r&128);let o=0;if(!i)o=r;else{const c=r&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(n+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=Is;if(t<_s)throw new e("integer: negative integers are not allowed");let s=Si(t);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(t){const{Err:e}=Is;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return No(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=Is,r=it("signature",t),{v:i,l:o}=n.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=Is,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}},_s=BigInt(0),tr=BigInt(1),Gh=BigInt(2),Oi=BigInt(3),E0=BigInt(4);function Jn(t,e){const{BYTES:s}=t;let n;if(typeof e=="bigint")n=e;else{let r=it("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 C0(t,e={}){const s=l0("weierstrass",t,e),{Fp:n,Fn:r}=s;let i=s.CURVE;const{h:o,n:a}=i;_o(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=Jh(n,r);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(O,A,b){const{x:N,y:x}=A.toAffine(),L=n.toBytes(N);if(io(b,"isCompressed"),b){d();const F=!n.isOdd(x);return Ks(Yh(F),L)}else return Ks(Uint8Array.of(4),L,n.toBytes(x))}function h(O){yn(O,void 0,"Point");const{publicKey:A,publicKeyUncompressed:b}=l,N=O.length,x=O[0],L=O.subarray(1);if(N===A&&(x===2||x===3)){const F=n.fromBytes(L);if(!n.isValid(F))throw new Error("bad point: is not on curve, wrong x");const P=m(F);let T;try{T=n.sqrt(P)}catch(K){const ie=K instanceof Error?": "+K.message:"";throw new Error("bad point: is not on curve, sqrt error"+ie)}d();const W=n.isOdd(T);return(x&1)===1!==W&&(T=n.neg(T)),{x:F,y:T}}else if(N===b&&x===4){const F=n.BYTES,P=n.fromBytes(L.subarray(0,F)),T=n.fromBytes(L.subarray(F,F*2));if(!w(P,T))throw new Error("bad point: is not on curve");return{x:P,y:T}}else throw new Error(`bad point: got length ${N}, expected compressed=${A} or uncompressed=${b}`)}const p=e.toBytes||u,y=e.fromBytes||h;function m(O){const A=n.sqr(O),b=n.mul(A,O);return n.add(n.add(b,n.mul(O,i.a)),i.b)}function w(O,A){const b=n.sqr(A),N=m(O);return n.eql(b,N)}if(!w(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const E=n.mul(n.pow(i.a,Oi),E0),I=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(E,I)))throw new Error("bad curve params: a or b");function k(O,A,b=!1){if(!n.isValid(A)||b&&n.is0(A))throw new Error(`bad point coordinate ${O}`);return A}function D(O){if(!(O instanceof _))throw new Error("ProjectivePoint expected")}function j(O){if(!c||!c.basises)throw new Error("no endo");return b0(O,c.basises,r.ORDER)}const f=zl((O,A)=>{const{X:b,Y:N,Z:x}=O;if(n.eql(x,n.ONE))return{x:b,y:N};const L=O.is0();A==null&&(A=L?n.ONE:n.inv(x));const F=n.mul(b,A),P=n.mul(N,A),T=n.mul(x,A);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(T,n.ONE))throw new Error("invZ was invalid");return{x:F,y:P}}),v=zl(O=>{if(O.is0()){if(e.allowInfinityPoint&&!n.is0(O.Y))return;throw new Error("bad point: ZERO")}const{x:A,y:b}=O.toAffine();if(!n.isValid(A)||!n.isValid(b))throw new Error("bad point: x or y not field elements");if(!w(A,b))throw new Error("bad point: equation left != right");if(!O.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function C(O,A,b,N,x){return b=new _(n.mul(b.X,O),b.Y,b.Z),A=ao(N,A),b=ao(x,b),A.add(b)}class _{constructor(A,b,N){this.X=k("x",A),this.Y=k("y",b,!0),this.Z=k("z",N),Object.freeze(this)}static CURVE(){return i}static fromAffine(A){const{x:b,y:N}=A||{};if(!A||!n.isValid(b)||!n.isValid(N))throw new Error("invalid affine point");if(A instanceof _)throw new Error("projective point not allowed");return n.is0(b)&&n.is0(N)?_.ZERO:new _(b,N,n.ONE)}static fromBytes(A){const b=_.fromAffine(y(yn(A,void 0,"point")));return b.assertValidity(),b}static fromHex(A){return _.fromBytes(it("pointHex",A))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(A=8,b=!0){return U.createCache(this,A),b||this.multiply(Oi),this}assertValidity(){v(this)}hasEvenY(){const{y:A}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(A)}equals(A){D(A);const{X:b,Y:N,Z:x}=this,{X:L,Y:F,Z:P}=A,T=n.eql(n.mul(b,P),n.mul(L,x)),W=n.eql(n.mul(N,P),n.mul(F,x));return T&&W}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){const{a:A,b}=i,N=n.mul(b,Oi),{X:x,Y:L,Z:F}=this;let P=n.ZERO,T=n.ZERO,W=n.ZERO,K=n.mul(x,x),ie=n.mul(L,L),oe=n.mul(F,F),se=n.mul(x,L);return se=n.add(se,se),W=n.mul(x,F),W=n.add(W,W),P=n.mul(A,W),T=n.mul(N,oe),T=n.add(P,T),P=n.sub(ie,T),T=n.add(ie,T),T=n.mul(P,T),P=n.mul(se,P),W=n.mul(N,W),oe=n.mul(A,oe),se=n.sub(K,oe),se=n.mul(A,se),se=n.add(se,W),W=n.add(K,K),K=n.add(W,K),K=n.add(K,oe),K=n.mul(K,se),T=n.add(T,K),oe=n.mul(L,F),oe=n.add(oe,oe),K=n.mul(oe,se),P=n.sub(P,K),W=n.mul(oe,ie),W=n.add(W,W),W=n.add(W,W),new _(P,T,W)}add(A){D(A);const{X:b,Y:N,Z:x}=this,{X:L,Y:F,Z:P}=A;let T=n.ZERO,W=n.ZERO,K=n.ZERO;const ie=i.a,oe=n.mul(i.b,Oi);let se=n.mul(b,L),X=n.mul(N,F),de=n.mul(x,P),Te=n.add(b,N),ue=n.add(L,F);Te=n.mul(Te,ue),ue=n.add(se,X),Te=n.sub(Te,ue),ue=n.add(b,x);let Ue=n.add(L,P);return ue=n.mul(ue,Ue),Ue=n.add(se,de),ue=n.sub(ue,Ue),Ue=n.add(N,x),T=n.add(F,P),Ue=n.mul(Ue,T),T=n.add(X,de),Ue=n.sub(Ue,T),K=n.mul(ie,ue),T=n.mul(oe,de),K=n.add(T,K),T=n.sub(X,K),K=n.add(X,K),W=n.mul(T,K),X=n.add(se,se),X=n.add(X,se),de=n.mul(ie,de),ue=n.mul(oe,ue),X=n.add(X,de),de=n.sub(se,de),de=n.mul(ie,de),ue=n.add(ue,de),se=n.mul(X,ue),W=n.add(W,se),se=n.mul(Ue,ue),T=n.mul(Te,T),T=n.sub(T,se),se=n.mul(Te,X),K=n.mul(Ue,K),K=n.add(K,se),new _(T,W,K)}subtract(A){return this.add(A.negate())}is0(){return this.equals(_.ZERO)}multiply(A){const{endo:b}=e;if(!r.isValidNot0(A))throw new Error("invalid scalar: out of range");let N,x;const L=F=>U.cached(this,F,P=>Ko(_,P));if(b){const{k1neg:F,k1:P,k2neg:T,k2:W}=j(A),{p:K,f:ie}=L(P),{p:oe,f:se}=L(W);x=ie.add(se),N=C(b.beta,K,oe,F,T)}else{const{p:F,f:P}=L(A);N=F,x=P}return Ko(_,[N,x])[0]}multiplyUnsafe(A){const{endo:b}=e,N=this;if(!r.isValid(A))throw new Error("invalid scalar: out of range");if(A===_s||N.is0())return _.ZERO;if(A===tr)return N;if(U.hasCache(this))return this.multiply(A);if(b){const{k1neg:x,k1:L,k2neg:F,k2:P}=j(A),{p1:T,p2:W}=a0(_,N,L,P);return C(b.beta,T,W,x,F)}else return U.unsafe(N,A)}multiplyAndAddUnsafe(A,b,N){const x=this.multiplyUnsafe(b).add(A.multiplyUnsafe(N));return x.is0()?void 0:x}toAffine(A){return f(this,A)}isTorsionFree(){const{isTorsionFree:A}=e;return o===tr?!0:A?A(_,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:A}=e;return o===tr?this:A?A(_,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(A=!0){return io(A,"isCompressed"),this.assertValidity(),p(_,this,A)}toHex(A=!0){return er(this.toBytes(A))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(A=!0){return this.toBytes(A)}_setWindowSize(A){this.precompute(A)}static normalizeZ(A){return Ko(_,A)}static msm(A,b){return c0(_,r,A,b)}static fromPrivateKey(A){return _.BASE.multiply(Jn(r,A))}}_.BASE=new _(i.Gx,i.Gy,n.ONE),_.ZERO=new _(n.ZERO,n.ONE,n.ZERO),_.Fp=n,_.Fn=r;const S=r.BITS,U=new o0(_,e.endo?Math.ceil(S/2):S);return _.BASE.precompute(8),_}function Yh(t){return Uint8Array.of(t?2:3)}function Jh(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function I0(t,e={}){const{Fn:s}=t,n=e.randomBytes||$n,r=Object.assign(Jh(t.Fp,s),{seed:zh(s.ORDER)});function i(h){try{return!!Jn(s,h)}catch{return!1}}function o(h,p){const{publicKey:y,publicKeyUncompressed:m}=r;try{const w=h.length;return p===!0&&w!==y||p===!1&&w!==m?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(r.seed)){return n0(yn(h,r.seed,"seed"),s.ORDER)}function c(h,p=!0){return t.BASE.multiply(Jn(s,h)).toBytes(p)}function l(h){const p=a(h);return{secretKey:p,publicKey:c(p)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:p,publicKey:y,publicKeyUncompressed:m}=r;if(s.allowedLengths||p===y)return;const w=it("key",h).length;return w===y||w===m}function u(h,p,y=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(p)===!1)throw new Error("second arg must be public key");const m=Jn(s,h);return t.fromHex(p).multiply(m).toBytes(y)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>Jn(s,h),precompute(h=8,p=t.BASE){return p.precompute(h,!1)}},lengths:r})}function A0(t,e,s={}){vo(e),_o(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=s.randomBytes||$n,r=s.hmac||((b,...N)=>Io(e,b,Ks(...N))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p}=I0(t,s),y={prehash:!1,lowS:typeof s.lowS=="boolean"?s.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function w(b){const N=a>>tr;return b>N}function E(b,N){if(!o.isValidNot0(N))throw new Error(`invalid signature ${b}: out of range 1..Point.Fn.ORDER`);return N}function I(b,N){Fa(N);const x=p.signature,L=N==="compact"?x:N==="recovered"?x+1:void 0;return yn(b,L,`${N} signature`)}class k{constructor(N,x,L){this.r=E("r",N),this.s=E("s",x),L!=null&&(this.recovery=L),Object.freeze(this)}static fromBytes(N,x=m){I(N,x);let L;if(x==="der"){const{r:W,s:K}=Is.toSig(yn(N));return new k(W,K)}x==="recovered"&&(L=N[0],x="compact",N=N.subarray(1));const F=o.BYTES,P=N.subarray(0,F),T=N.subarray(F,F*2);return new k(o.fromBytes(P),o.fromBytes(T),L)}static fromHex(N,x){return this.fromBytes(no(N),x)}addRecoveryBit(N){return new k(this.r,this.s,N)}recoverPublicKey(N){const x=i.ORDER,{r:L,s:F,recovery:P}=this;if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");if(a*Gh<x&&P>1)throw new Error("recovery id is ambiguous for h>1 curve");const T=P===2||P===3?L+a:L;if(!i.isValid(T))throw new Error("recovery id 2 or 3 invalid");const W=i.toBytes(T),K=t.fromBytes(Ks(Yh((P&1)===0),W)),ie=o.inv(T),oe=j(it("msgHash",N)),se=o.create(-oe*ie),X=o.create(F*ie),de=t.BASE.multiplyUnsafe(se).add(K.multiplyUnsafe(X));if(de.is0())throw new Error("point at infinify");return de.assertValidity(),de}hasHighS(){return w(this.s)}toBytes(N=m){if(Fa(N),N==="der")return no(Is.hexFromSig(this));const x=o.toBytes(this.r),L=o.toBytes(this.s);if(N==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ks(Uint8Array.of(this.recovery),x,L)}return Ks(x,L)}toHex(N){return er(this.toBytes(N))}assertValidity(){}static fromCompact(N){return k.fromBytes(it("sig",N),"compact")}static fromDER(N){return k.fromBytes(it("sig",N),"der")}normalizeS(){return this.hasHighS()?new k(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return er(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return er(this.toBytes("compact"))}}const D=s.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const N=No(b),x=b.length*8-c;return x>0?N>>BigInt(x):N},j=s.bits2int_modN||function(b){return o.create(D(b))},f=hi(c);function v(b){return Ma("num < 2^"+c,b,_s,f),o.toBytes(b)}function C(b,N){return yn(b,void 0,"message"),N?yn(e(b),void 0,"prehashed message"):b}function _(b,N,x){if(["recovered","canonical"].some(X=>X in x))throw new Error("sign() legacy options not supported");const{lowS:L,prehash:F,extraEntropy:P}=Jo(x,y);b=C(b,F);const T=j(b),W=Jn(o,N),K=[v(W),v(T)];if(P!=null&&P!==!1){const X=P===!0?n(p.secretKey):P;K.push(it("extraEntropy",X))}const ie=Ks(...K),oe=T;function se(X){const de=D(X);if(!o.isValidNot0(de))return;const Te=o.inv(de),ue=t.BASE.multiply(de).toAffine(),Ue=o.create(ue.x);if(Ue===_s)return;const Wt=o.create(Te*o.create(oe+Ue*W));if(Wt===_s)return;let xs=(ue.x===Ue?0:2)|Number(ue.y&tr),nn=Wt;return L&&w(Wt)&&(nn=o.neg(Wt),xs^=1),new k(Ue,nn,xs)}return{seed:ie,k2sig:se}}function S(b,N,x={}){b=it("message",b);const{seed:L,k2sig:F}=_(b,N,x);return Gb(e.outputLen,o.BYTES,r)(L,F)}function U(b){let N;const x=typeof b=="string"||bo(b),L=!x&&b!==null&&typeof b=="object"&&typeof b.r=="bigint"&&typeof b.s=="bigint";if(!x&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(L)N=new k(b.r,b.s);else if(x){try{N=k.fromBytes(it("sig",b),"der")}catch(F){if(!(F instanceof Is.Err))throw F}if(!N)try{N=k.fromBytes(it("sig",b),"compact")}catch{return!1}}return N||!1}function O(b,N,x,L={}){const{lowS:F,prehash:P,format:T}=Jo(L,y);if(x=it("publicKey",x),N=C(it("message",N),P),"strict"in L)throw new Error("options.strict was renamed to lowS");const W=T===void 0?U(b):k.fromBytes(it("sig",b),T);if(W===!1)return!1;try{const K=t.fromBytes(x);if(F&&W.hasHighS())return!1;const{r:ie,s:oe}=W,se=j(N),X=o.inv(oe),de=o.create(se*X),Te=o.create(ie*X),ue=t.BASE.multiplyUnsafe(de).add(K.multiplyUnsafe(Te));return ue.is0()?!1:o.create(ue.x)===ie}catch{return!1}}function A(b,N,x={}){const{prehash:L}=Jo(x,y);return N=C(N,L),k.fromBytes(b,"recovered").recoverPublicKey(N).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p,Point:t,sign:S,verify:O,recoverPublicKey:A,Signature:k,hash:e})}function N0(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=sn(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 _0(t){const{CURVE:e,curveOpts:s}=N0(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 S0(t,e){const s=e.Point;return Object.assign({},e,{ProjectivePoint:s,CURVE:Object.assign({},t,qh(s.Fn.ORDER,s.Fn.BITS))})}function T0(t){const{CURVE:e,curveOpts:s,hash:n,ecdsaOpts:r}=_0(t),i=C0(e,s),o=A0(i,n,r);return S0(t,o)}function qa(t,e){const s=n=>T0({...t,hash:n});return{...s(e),create:s}}const Xh={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Zh={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Qh={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},O0=sn(Xh.p),k0=sn(Zh.p),P0=sn(Qh.p),x0=qa({...Xh,Fp:O0,lowS:!1},Co);qa({...Zh,Fp:k0,lowS:!1},Mw),qa({...Qh,Fp:P0,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Bw);const R0=x0,ep="base10",ct="base16",wt="base64pad",Vs="base64url",pi="utf8",tp=0,Ts=1,fi=2,$0=0,Zl=1,qr=12,Tc=32;function U0(){const t=ja.utils.randomPrivateKey(),e=ja.getPublicKey(t);return{privateKey:vt(t,ct),publicKey:vt(e,ct)}}function Wa(){const t=$n(Tc);return vt(t,ct)}function D0(t,e){const s=ja.getSharedSecret(Mt(t,ct),Mt(e,ct)),n=Kb(Ao,s,void 0,void 0,Tc);return vt(n,ct)}function Fi(t){const e=Ao(Mt(t,ct));return vt(e,ct)}function Lt(t){const e=Ao(Mt(t,pi));return vt(e,ct)}function sp(t){return Mt(`${t}`,ep)}function Tn(t){return Number(vt(t,ep))}function np(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function rp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function L0(t){const e=sp(typeof t.type<"u"?t.type:tp);if(Tn(e)===Ts&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?Mt(t.senderPublicKey,ct):void 0,n=typeof t.iv<"u"?Mt(t.iv,ct):$n(qr),r=Mt(t.symKey,ct),i=kh(r,n).encrypt
8(Mt(t.message,pi)),o=ip({type:e,sealed:i,iv:n,senderPublicKey:s});return t.encoding===Vs?np(o):o}function B0(t){const e=Mt(t.symKey,ct),{sealed:s,iv:n}=ei({encoded:t.encoded,encoding:t.encoding}),r=kh(e,n).decrypt(s);if(r===null)throw new Error("Failed to decrypt");return vt(r,pi)}function M0(t,e){const s=sp(fi),n=$n(qr),r=Mt(t,pi),i=ip({type:s,sealed:r,iv:n});return e===Vs?np(i):i}function j0(t,e){const{sealed:s}=ei({encoded:t,encoding:e});return vt(s,pi)}function ip(t){if(Tn(t.type)===fi)return vt(Mr([t.type,t.sealed]),wt);if(Tn(t.type)===Ts){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return vt(Mr([t.type,t.senderPublicKey,t.iv,t.sealed]),wt)}return vt(Mr([t.type,t.iv,t.sealed]),wt)}function ei(t){const e=(t.encoding||wt)===Vs?rp(t.encoded):t.encoded,s=Mt(e,wt),n=s.slice($0,Zl),r=Zl;if(Tn(n)===Ts){const c=r+Tc,l=c+qr,d=s.slice(r,c),u=s.slice(c,l),h=s.slice(l);return{type:n,sealed:h,iv:u,senderPublicKey:d}}if(Tn(n)===fi){const c=s.slice(r),l=$n(qr);return{type:n,sealed:c,iv:l}}const i=r+qr,o=s.slice(r,i),a=s.slice(i);return{type:n,sealed:a,iv:o}}function F0(t,e){const s=ei({encoded:t,encoding:e==null?void 0:e.encoding});return op({type:Tn(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?vt(s.senderPublicKey,ct):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function op(t){const e=(t==null?void 0:t.type)||tp;if(e===Ts){if(typeof(t==null?void 0:t.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(t==null?void 0:t.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t==null?void 0:t.senderPublicKey,receiverPublicKey:t==null?void 0:t.receiverPublicKey}}function Ql(t){return t.type===Ts&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function ed(t){return t.type===fi}function q0(t){const e=Buffer.from(t.x,"base64"),s=Buffer.from(t.y,"base64");return Mr([new Uint8Array([4]),e,s])}function W0(t,e){const[s,n,r]=t.split("."),i=Buffer.from(rp(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=Ao(c),d=q0(e);if(!R0.verify(Mr([o,a]),l,d))throw new Error("Invalid signature");return wa(t).payload}const z0="irn";function co(t){return(t==null?void 0:t.relay)||{protocol:z0}}function Xn(t){const e=ff[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var H0=Object.defineProperty,K0=Object.defineProperties,V0=Object.getOwnPropertyDescriptors,td=Object.getOwnPropertySymbols,G0=Object.prototype.hasOwnProperty,Y0=Object.prototype.propertyIsEnumerable,sd=(t,e,s)=>e in t?H0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Xo=(t,e)=>{for(var s in e||(e={}))G0.call(e,s)&&sd(t,s,e[s]);if(td)for(var s of td(e))Y0.call(e,s)&&sd(t,s,e[s]);return t},J0=(t,e)=>K0(t,V0(e));function X0(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 nd(t){if(!t.includes("wc:")){const l=dh(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=="str
8ing"?a.methods.split(","):void 0;return{protocol:n,topic:Z0(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:X0(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Z0(t){return t.startsWith("//")?t.substring(2):t}function Q0(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 rd(t){const e=new URLSearchParams,s=Xo(Xo(J0(Xo({},Q0(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(s).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!==void 0&&e.append(n,String(r))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function ki(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var ev=Object.defineProperty,tv=Object.defineProperties,sv=Object.getOwnPropertyDescriptors,id=Object.getOwnPropertySymbols,nv=Object.prototype.hasOwnProperty,rv=Object.prototype.propertyIsEnumerable,od=(t,e,s)=>e in t?ev(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,iv=(t,e)=>{for(var s in e||(e={}))nv.call(e,s)&&od(t,s,e[s]);if(id)for(var s of id(e))rv.call(e,s)&&od(t,s,e[s]);return t},ov=(t,e)=>tv(t,sv(e));function yr(t){const e=[];return t.forEach(s=>{const[n,r]=s.split(":");e.push(`${n}:${r}`)}),e}function av(t){const e=[];return Object.values(t).forEach(s=>{e.push(...yr(s.accounts))}),e}function cv(t,e){const s=[];return Object.values(t).forEach(n=>{yr(n.accounts).includes(e)&&s.push(...n.methods)}),s}function lv(t,e){const s=[];return Object.values(t).forEach(n=>{yr(n.accounts).includes(e)&&s.push(...n.events)}),s}function So(t){return t.includes(":")}function Zn(t){return So(t)?t.split(":")[0]:t}function ad(t){var e,s,n;const r={};if(!us(t))return r;for(const[i,o]of Object.entries(t)){const a=So(i)?[i]:o.chains,c=o.methods||[],l=o.events||[],d=Zn(i);r[d]=ov(iv({},r[d]),{chains:ds(a,(e=r[d])==null?void 0:e.chains),methods:ds(c,(s=r[d])==null?void 0:s.methods),events:ds(l,(n=r[d])==null?void 0:n.events)})}return r}function dv(t){const e={};return t==null||t.forEach(s=>{var n;const[r,i]=s.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(s),(n=e[r].chains)==null||n.push(`${r}:${i}`)}),e}function cd(t,e){e=e.map(n=>n.replace("did:pkh:",""));const s=dv(e);for(const[n,r]of Object.entries(s))r.methods?r.methods=ds(r.methods,t):r.methods=t,r.events=["chainChanged","accountsChanged"];return s}function uv(t,e){var s,n,r,i,o,a;const c=ad(t),l=ad(e),d={},u=Object.keys(c).concat(Object.keys(l));for(const h of u)d[h]={chains:ds((s=c[h])==null?void 0:s.chains,(n=l[h])==null?void 0:n.chains),methods:ds((r=c[h])==null?void 0:r.methods,(i=l[h])==null?void 0:i.methods),events:ds((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return d}const hv={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}},pv={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 z(t,e){const{message:s,code:n}=pv[t];return{message:e?`${s} ${e}
8`:s,code:n}}function xe(t,e){const{message:s,code:n}=hv[t];return{message:e?`${s} ${e}`:s,code:n}}function Os(t,e){return!!Array.isArray(t)}function us(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function qe(t){return typeof t>"u"}function Me(t,e){return e&&qe(t)?!0:typeof t=="string"&&!!t.trim().length}function Oc(t,e){return e&&qe(t)?!0:typeof t=="number"&&!isNaN(t)}function fv(t,e){const{requiredNamespaces:s}=e,n=Object.keys(t.namespaces),r=Object.keys(s);let i=!0;return mn(r,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],d=yr(a),u=s[o];(!mn(ih(o,u),d)||!mn(u.methods,c)||!mn(u.events,l))&&(i=!1)}),i):!1}function lo(t){return Me(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function gv(t){if(Me(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&lo(s)}}return!1}function mv(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(Me(t,!1)){if(e(t))return!0;const s=dh(t);return e(s)}}catch{}return!1}function yv(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function wv(t){return t==null?void 0:t.topic}function bv(t,e){let s=null;return Me(t==null?void 0:t.publicKey,!1)||(s=z("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function ld(t){let e=!0;return Os(t)?t.length&&(e=t.every(s=>Me(s,!1))):e=!1,e}function vv(t,e,s){let n=null;return Os(e)&&e.length?e.forEach(r=>{n||lo(r)||(n=xe("UNSUPPORTED_CHAINS",`${s}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):lo(t)||(n=xe("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 Ev(t,e,s){let n=null;return Object.entries(t).forEach(([r,i])=>{if(n)return;const o=vv(r,ih(r,i),`${e} ${s}`);o&&(n=o)}),n}function Cv(t,e){let s=null;return Os(t)?t.forEach(n=>{s||gv(n)||(s=xe("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):s=xe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function Iv(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=Cv(n==null?void 0:n.accounts,`${e} namespace`);r&&(s=r)}),s}function Av(t,e){let s=null;return ld(t==null?void 0:t.methods)?ld(t==null?void 0:t.events)||(s=xe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=xe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function ap(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=Av(n,`${e}, namespace`);r&&(s=r)}),s}function Nv(t,e,s){let n=null;if(t&&us(t)){const r=ap(t,e);r&&(n=r);const i=Ev(t,e,s);i&&(n=i)}else n=z("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return n}function Zo(t,e){let s=null;if(t&&us(t)){const n=ap(t,e);n&&(s=n);const r=Iv(t,e);r&&(s=r)}else s=z("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function cp(t){return Me(t.protocol,!0)}function _v(t,e){let s=!1;return t?t&&Os(t)&&t.length&&t.forEach(n=>{s=cp(n)}):s=!0,s}function Sv(t){return typeof t=="number"}function mt(t){return typeof t<"u"&&typeof t!==null}function Tv(t){return!(!t||typeof t!="object"||!t.code||!Oc(t.code,!1)||!t.message||!Me(t.message,!1))}function Ov(t){return!(qe(t)||!Me(t.method,!1))}function kv(t){return!(qe(t)||qe(t.result)&&qe(t.error)||!Oc(t.id,!1)||!Me(t.jsonrpc,!1))}function Pv(t){return!(qe(t)||!Me(t.name,!1))}function dd(t,e){return!(!lo(e)||!av(t).includes(e))}function xv(t,e,s){return Me(s,!1)?cv(t,e).includes(s):!1}function Rv(t,e,s){return Me(s,!1)?lv(t,e).includes(s):!1}function ud(t,e,s){let n=null;const r=$v(t),i=Uv(e),o=Object.keys(r),a=Object.keys(i),c=hd(Object.keys(t)),l=hd(Object.keys(e)),d=c.filter(u=>!l.includes(u));return d.length&&(n=z("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
9      Required: ${d.toString()}
10      Received: ${Object.keys(e).toString()}`)),mn(o,a)||(n=z("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=yr(e[u].accounts);h.includes(u)||(n=z("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${u}
13        Required: ${u}
14        Approved: ${h.toString()}`))}),o.forEach(u=>{n||(mn(r[u].methods,i[u].methods)?mn(r[u].events,i[u].events)||(n=z("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${u}`)):n=z("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${u}`))}),n}function $v(t){const e={};return Object.keys(t).forEach(s=>{var n;
14s.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 hd(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Uv(t){const e={};return Object.keys(t).forEach(s=>{if(s.includes(":"))e[s]=t[s];else{const n=yr(t[s].accounts);n==null||n.forEach(r=>{e[r]={accounts:t[s].accounts.filter(i=>i.includes(`${r}:`)),methods:t[s].methods,events:t[s].events}})}}),e}function Dv(t,e){return Oc(t,!1)&&t<=e.max&&t>=e.min}function pd(){const t=di();return new Promise(e=>{switch(t){case Ot.browser:e(Lv());break;case Ot.reactNative:e(Bv());break;case Ot.node:e(Mv());break;default:e(!0)}})}function Lv(){return mr()&&(navigator==null?void 0:navigator.onLine)}async function Bv(){if(tn()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function Mv(){return!0}function jv(t){switch(di()){case Ot.browser:Fv(t);break;case Ot.reactNative:qv(t);break}}function Fv(t){!tn()&&mr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function qv(t){tn()&&typeof global<"u"&&global!=null&&global.NetInfo&&(global==null||global.NetInfo.addEventListener(e=>t(e==null?void 0:e.isConnected)))}function Wv(){var t;return mr()&&ks.getDocument()?((t=ks.getDocument())==null?void 0:t.visibilityState)==="visible":!0}const Qo={};class Nr{static get(e){return Qo[e]}static set(e,s){Qo[e]=s}static delete(e){delete Qo[e]}}function zv(t){const e=hr.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function Hv({publicKey:t,signature:e,payload:s}){var n;const r=za(s.method),i=128|parseInt(((n=s.version)==null?void 0:n.toString())||"4"),o=Gv(s.address),a=s.era==="00"?new Uint8Array([0]):za(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${Vv(s.tip)}`),u=Jv(d),h=new Uint8Array([0,...t,o,...e,...a,...l,...u,...r]),p=Yv(h.length+1);return new Uint8Array([...p,i,...h])}function Kv(t){const e=za(t),s=bf.blake2b(e,void 0,32);return"0x"+Buffer.from(s).toString("hex")}function za(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Vv(t){return t.startsWith("0x")?t.slice(2):t}function Gv(t){const e=hr.decode(t)[0];return e===42?0:e===60?2:1}function Yv(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 Jv(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 Xv(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),s=zv(t.transaction.address),n=Hv({publicKey:s,signature:e,payload:t.transaction}),r=Buffer.from(n).toString("hex");return Kv(r)}var Zv={};const lp="wc",dp=2,Ha="core",hs=`${lp}@2:${Ha}:`,Qv={logger:"error"},eE={database:":memory:"},tE="crypto",fd="client_ed25519_seed",sE=V.ONE_DAY,nE="keychain",rE="0.3",iE="messages",oE="0.3",aE=V.SIX_HOURS,cE="publisher",up="irn",lE="error",hp="wss://relay.walletconnect.org",dE="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"},uE="_subscription",Pt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},hE=.1,Ka="2.21.9",Oe={link_mode:"link_mode",relay:"relay"},qi={inbound:"inbound",outbound:"outbound"},pE="0.3",fE="WALLETCONNECT_CLIENT_ID",gd="WALLETCONNECT_LINK_MODE_APPS",Nt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},gE="subscription",mE="0.3",yE="pairing",wE="0.3",_r={wc_pairingDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:V.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:V.ONE_DAY,prompt:!1,tag:0},res:{ttl:V.ONE_DAY,prompt:!1,tag:0}}},hn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ht={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},bE="history",vE="0.3",EE="expirer",Dt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},CE="0.3",IE="verify-api",AE="https://verify.walletconnect.com",pp="https://verify.walletconnect.org",Wr=pp,NE=`${Wr}/v3`,_E=[AE,pp],SE="echo",TE="https://echo.walletconnect.com",ts={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"},bs={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"},qs={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"},Sr={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"},an={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"}
vendor: 6,995 bytes, line 14
14,Tr={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"},OE=.1,kE="event-client",PE=86400,xE="https://pulse.walletconnect.org/batch";function RE(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(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var m=0,w=0,E=0,I=y.length;E!==I&&y[E]===0;)E++,m++;for(var k=(I-E)*d+1>>>0,D=new Uint8Array(k);E!==I;){for(var j=y[E],f=0,v=k-1;(j!==0||f<w)&&v!==-1;v--,f++)j+=256*D[v]>>>0,D[v]=j%a>>>0,j=j/a>>>0;if(j!==0)throw new Error("Non-zero carry");w=f,E++}for(var C=k-w;C!==k&&D[C]===0;)C++;for(var _=c.repeat(m);C<k;++C)_+=t.charAt(D[C]);return _}function h(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var m=0;if(y[m]!==" "){for(var w=0,E=0;y[m]===c;)w++,m++;for(var I=(y.length-m)*l+1>>>0,k=new Uint8Array(I);y[m];){var D=s[y.charCodeAt(m)];if(D===255)return;for(var j=0,f=I-1;(D!==0||j<E)&&f!==-1;f--,j++)D+=a*k[f]>>>0,k[f]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");E=j,m++}if(y[m]!==" "){for(var v=I-E;v!==I&&k[v]===0;)v++;for(var C=new Uint8Array(w+(I-v)),_=w;v!==I;)C[_++]=k[v++];return C}}}function p(y){var m=h(y);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:p}}var $E=RE,UE=$E;const fp=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")},DE=t=>new TextEncoder().encode(t),LE=t=>new TextDecoder().decode(t);class BE{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 ME{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 gp(this,e)}}class jE{constructor(e){this.decoders=e}or(e){return gp(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 gp=(t,e)=>new jE({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class FE{constructor(e,s,n,r){this.name=e,this.prefix=s,this.baseEncode=n,this.baseDecode=r,this.encoder=new BE(e,s,n),this.decoder=new ME(e,s,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const To=({name:t,prefix:e,encode:s,decode:n})=>new FE(t,e,s,n),gi=({prefix:t,name:e,alphabet:s})=>{const{encode:n,decode:r}=UE(s,e);return To({prefix:t,name:e,encode:n,decode:i=>fp(r(i))})},qE=(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},WE=(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},Qe=({name:t,prefix:e,bitsPerChar:s,alphabet:n})=>To({prefix:e,name:t,encode(r){return WE(r,n,s)},decode(r){return qE(r,n,s,t)}}),zE=To({prefix:"\0",name:"identity",encode:t=>LE(t),decode:t=>DE(t)});var HE=Object.freeze({__proto__:null,identity:zE});const KE=Qe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var VE=Object.freeze({__proto__:null,base2:KE});const GE=Qe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var YE=Object.freeze({__proto__:null,base8:GE});const JE=gi({prefix:"9",name:"base10",alphabet:"0123456789"});var XE=Object.freeze({__proto__:null,base10:JE});const ZE=Qe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),QE=Qe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var eC=Object.freeze({__proto__:null,base16:ZE,base16upper:QE});const tC=Qe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),sC=Qe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),nC=Qe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rC=Qe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),iC=Qe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),oC=Qe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),aC=Qe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),cC=Qe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),lC=Qe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var dC=Object.freeze({__proto__:null,base32:tC,base32upper:sC,base32pad:nC,base32padupper:rC,base32hex:iC,base32hexupper:oC,base32hexpad:aC,base32hexpadupper:cC,base32z:lC});const uC=gi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hC=gi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var pC=Object.freeze({__proto__:null,base36:uC,base36upper:hC});const fC=gi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),gC=gi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var mC=Object.freeze({__proto__:null,base58btc:fC,base58flickr:gC});const yC=Qe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
14+/",bitsPerChar:6}),wC=Qe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),bC=Qe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vC=Qe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var EC=Object.freeze({__proto__:null,base64:yC,base64pad:wC,base64url:bC,base64urlpad:vC});const mp=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),CC=mp.reduce((t,e,s)=>(t[s]=e,t),[]),IC=mp.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function AC(t){return t.reduce((e,s)=>(e+=CC[s],e),"")}function NC(t){const e=[];for(const s of t){const n=IC[s.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(n)}return new Uint8Array(e)}const _C=To({prefix:"🚀",name:"base256emoji",encode:AC,decode:NC});var SC=Object.freeze({__proto__:null,base256emoji:_C}),TC=yp,md=128,OC=-128,kC=Math.pow(2,31);function yp(t,e,s){e=e||[],s=s||0;for(var n=s;t>=kC;)e[s++]=t&255|md,t/=128;for(;t&OC;)e[s++]=t&255|md,t>>>=7;return e[s]=t|0,yp.bytes=s-n+1,e}var PC=Va,xC=128,yd=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&yd)<<r:(o&yd)*Math.pow(2,r),r+=7}while(o>=xC);return Va.bytes=i-n,s}var RC=Math.pow(2,7),$C=Math.pow(2,14),UC=Math.pow(2,21),DC=Math.pow(2,28),LC=Math.pow(2,35),BC=Math.pow(2,42),MC=Math.pow(2,49),jC=Math.pow(2,56),FC=Math.pow(2,63),qC=function(t){return t<RC?1:t<$C?2:t<UC?3:t<DC?4:t<LC?5:t<BC?6:t<MC?7:t<jC?8:t<FC?9:10},WC={encode:TC,decode:PC,encodingLength:qC},wp=WC;const wd=(t,e,s=0)=>(wp.encode(t,e,s),e),bd=t=>wp.encodingLength(t),Ga=(t,e)=>{const s=e.byteLength,n=bd(t),r=n+bd(s),i=new Uint8Array(r+s);return wd(t,i,0),wd(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 bp=({name:t,code:e,encode:s})=>new HC(t,e,s);class HC{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?Ga(this.code,s):s.then(n=>Ga(this.code,n))}else throw Error("Unknown type, must be binary type")}}const vp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),KC=bp({name:"sha2-256",code:18,encode:vp("SHA-256")}),VC=bp({name:"sha2-512",code:19,encode:vp("SHA-512")});var GC=Object.freeze({__proto__:null,sha256:KC,sha512:VC});const Ep=0,YC="identity",Cp=fp,JC=t=>Ga(Ep,Cp(t)),XC={code:Ep,name:YC,encode:Cp,digest:JC};var ZC=Object.freeze({__proto__:null,identity:XC});new TextEncoder,new TextDecoder;const vd={...HE,...VE,...YE,...XE,...eC,...dC,...pC,...mC,...EC,...SC};({...GC,...ZC});function Ip(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function QC(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ip(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Ap(t,e,s,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:n}}}const Ed=Ap("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ea=Ap("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=QC(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),e1={utf8:Ed,"utf-8":Ed,hex:vd.base16,latin1:ea,ascii:ea,binary:ea,...vd};function t1(t,e="utf8"){const s=e1[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ip(globalThis.Buffer.from(t,"utf-8")):s.decoder.decode(`${s.prefix}${t}`)}var s1=Object.defineProperty,n1=(t,e,s)=>e in t?s1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qt=(t,e,s)=>n1(t,typeof e!="symbol"?e+"":e,s);class r1{constructor(e,s){this.core=e,this.logger=s,Qt(this,"keychain",new Map),Qt(this,"name",nE),Qt(this,"version",rE),Qt(this,"initialized",!1),Qt(this,"storagePrefix",hs),Qt(this,"init",async()=>
vendor: 4,649 bytes, line 14
14{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Qt(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Qt(this,"set",async(n,r)=>{this.isInitialized(),this.keychain.set(n,r),await this.persist()}),Qt(this,"get",n=>{this.isInitialized();const r=this.keychain.get(n);if(typeof r>"u"){const{message:i}=z("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(i)}return r}),Qt(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=lt(s,this.name)}get context(){return Et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Pa(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?xa(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var i1=Object.defineProperty,o1=(t,e,s)=>e in t?i1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ve=(t,e,s)=>o1(t,typeof e!="symbol"?e+"":e,s);class a1{constructor(e,s,n){this.core=e,this.logger=s,Ve(this,"name",tE),Ve(this,"keychain"),Ve(this,"randomSessionIdentifier",Wa()),Ve(this,"initialized",!1),Ve(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ve(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ve(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),i=jc(r);return Cf(i.publicKey)}),Ve(this,"generateKeyPair",()=>{this.isInitialized();const r=U0();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ve(this,"signJWT",async r=>{this.isInitialized();const i=await this.getClientSeed(),o=jc(i),a=this.randomSessionIdentifier;return await If(a,r,sE,o)}),Ve(this,"generateSharedKey",(r,i,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=D0(a,i);return this.setSymKey(c,o)}),Ve(this,"setSymKey",async(r,i)=>{this.isInitialized();const o=i||Fi(r);return await this.keychain.set(o,r),o}),Ve(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"encode",async(r,i,o)=>{this.isInitialized();const a=op(o),c=In(i);if(ed(a))return M0(c,o==null?void 0:o.encoding);if(Ql(a)){const h=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(h,p)}const l=this.getSymKey(r),{type:d,senderPublicKey:u}=a;return L0({type:d,symKey:l,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Ve(this,"decode",async(r,i,o)=>{this.isInitialized();const a=F0(i,o);if(ed(a)){const c=j0(i,o==null?void 0:o.encoding);return Gi(c)}if(Ql(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=B0({symKey:c,encoded:i,encoding:o==null?void 0:o.encoding});return Gi(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ve(this,"getPayloadType",(r,i=wt)=>{const o=ei({encoded:r,encoding:i});return Tn(o.type)}),Ve(this,"getPayloadSenderPublicKey",(r,i=wt)=>{const o=ei({encoded:r,encoding:i});return o.senderPublicKey?vt(o.senderPublicKey,ct):void 0}),this.core=e,this.logger=lt(s,this.name),this.keychain=n||new r1(this.core,this.logger)}get context(){return Et(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(fd)}catch{e=Wa(),await this.keychain.set(fd,e)}return t1(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var c1=Object.defineProperty,l1=Object.defineProperties,d1=Object.getOwnPropertyDescriptors,Cd=Object.getOwnPropertySymbols,u1=Object.prototype.hasOwnProperty,h1=Object.prototype.propertyIsEnumerable,Ya=(t,e,s)=>e in t?c1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,p1=(t,e)=>{for(var s in e||(e={}))u1.call(e,s)&&Ya(t,s,e[s]);if(Cd)for(var s of Cd(e))h1.call(e,s)&&Ya(t,s,e[s]);return t},f1=(t,e)=>l1(t,d1(e)),It=(t,e,s)=>Ya(t,typeof e!="symbol"?e+"":e,s);class g1 extends Tm{constructor(e,s){super(e,s),this.logger=e,this.core=s,It(this,"messages",new Map),It(this,"messagesWithoutClientAck",new Map),It(this,"name",iE),It(this,"version",oE),It(this,"initialized",!1),It(this,"storagePrefix",hs),It(this,"init",async()=>
14{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}}}),It(this,"set",async(n,r,i)=>{this.isInitialized();const o=Lt(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===qi.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,f1(p1({},c),{[o]:r}))}return await this.persist(),o}),It(this,"get",n=>{this.isInitialized();let r=this.messages.get(n);return typeof r>"u"&&(r={}),r}),It(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}),It(this,"has",(n,r)=>{this.isInitialized();const i=this.get(n),o=Lt(r);return typeof i[o]<"u"}),It(this,"ack",async(n,r)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(n);if(typeof i>"u")return;const o=Lt(r);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,i),await this.persist()}),It(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=lt(e,this.name),this.core=s}get context(){return Et(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,Pa(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Pa(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?xa(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?xa(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var m1=Object.defineProperty,y1=Object.defineProperties,w1=Object.getOwnPropertyDescriptors,Id=Object.getOwnPropertySymbols,b1=Object.prototype.hasOwnProperty,v1=Object.prototype.propertyIsEnumerable,Ja=(t,e,s)=>e in t?m1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Fn=(t,e)=>{for(var s in e||(e={}))b1.call(e,s)&&Ja(t,s,e[s]);if(Id)for(var s of Id(e))v1.call(e,s)&&Ja(t,s,e[s]);return t},Ad=(t,e)=>y1(t,w1(e)),xt=(t,e,s)=>Ja(t,typeof e!="symbol"?e+"":e,s);class E1 extends Om{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,xt(this,"events",new kn.EventEmitter),xt(this,"name",cE),xt(this,"queue",new Map),xt(this,"publishTimeout",V.toMiliseconds(V.ONE_MINUTE)),xt(this,"initialPublishTimeout",V.toMiliseconds(V.ONE_SECOND*15)),xt(this,"needsTransportRestart",!1),xt(this,"publish",async(n,r,i)=>{var o,a,c,l,d;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:r,opts:i}});const u=(i==null?void 0:i.ttl)||aE,h=(i==null?void 0:i.prompt)||!1,p=(i==null?void 0:i.tag)||0,y=(i==null?void 0:i.id)||gn().toString(),m=Xn(co().protocol),w={id:y,method:(i==null?void 0:i.publishMethod)||m.publish,params:Fn({topic:n,message:r,ttl:u,prompt:h,tag:p,attestation:i==null?void 0:i.attestation},i==null?void 0:i.tvf)},E=`Failed to publish payload, please try again. id:${y} tag:${p}`;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 I=new Promise(async k=>{const D=({id:f})=>{var v;((v=w.id)==null?void 0:v.toString())===f.toString()&&(this.removeRequestFromQueue(f),this.relayer.events.removeListener(
vendor: 8,940 bytes, line 14
14De.publish,D),k())};this.relayer.events.on(De.publish,D);const j=as(new Promise((f,v)=>{this.rpcPublish(w,i).then(f).catch(C=>{this.logger.warn(C,C==null?void 0:C.message),v(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${y} tag:${p}`);try{await j,this.events.removeListener(De.publish,D)}catch(f){this.queue.set(y,{request:w,opts:i,attempt:1}),this.logger.warn(f,f==null?void 0:f.message)}});this.logger.trace({type:"method",method:"publish",params:{id:y,topic:n,message:r,opts:i}}),await as(I,this.publishTimeout,E)}catch(I){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(I),(d=i==null?void 0:i.internal)!=null&&d.throwOnFailedPublish)throw I}finally{this.queue.delete(y)}}),xt(this,"publishCustom",async n=>{var r,i,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:l,opts:d={}}=n,{attestation:u,tvf:h,publishMethod:p,prompt:y,tag:m,ttl:w=V.FIVE_MINUTES}=d,E=d.id||gn().toString(),I=Xn(co().protocol),k=p||I.publish,D={id:E,method:k,params:Fn(Ad(Fn({},l),{ttl:w,prompt:y,tag:m,attestation:u}),h)},j=`Failed to publish custom payload, please try again. id:${E} tag:${m}`;try{qe((r=D.params)==null?void 0:r.prompt)&&((i=D.params)==null||delete i.prompt),qe((o=D.params)==null?void 0:o.tag)&&((a=D.params)==null||delete a.tag);const f=new Promise(async v=>{const C=({id:S})=>{var U;((U=D.id)==null?void 0:U.toString())===S.toString()&&(this.removeRequestFromQueue(S),this.relayer.events.removeListener(De.publish,C),v())};this.relayer.events.on(De.publish,C);const _=as(new Promise((S,U)=>{this.rpcPublish(D,d).then(S).catch(O=>{this.logger.warn(O,O==null?void 0:O.message),U(O)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${k} id:${E} tag:${m}`);try{await _,this.events.removeListener(De.publish,C)}catch(S){this.queue.set(E,{request:D,opts:d,attempt:1}),this.logger.warn(S,S==null?void 0:S.message)}});this.logger.trace({type:"method",method:"publish",params:{id:E,payload:l,opts:d}}),await as(f,this.publishTimeout,j)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(c=d==null?void 0:d.internal)!=null&&c.throwOnFailedPublish)throw f}finally{this.queue.delete(E)}}),xt(this,"on",(n,r)=>{this.events.on(n,r)}),xt(this,"once",(n,r)=>{this.events.once(n,r)}),xt(this,"off",(n,r)=>{this.events.off(n,r)}),xt(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.relayer=e,this.logger=lt(s,this.name),this.registerEventListeners()}get context(){return Et(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,Fn(Fn({},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,Ad(Fn({},e),{attempt:r})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${r}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(pr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(De.connection_stalled);return}this.checkQueue()}),this.relayer.on(De.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var C1=Object.defineProperty,I1=(t,e,s)=>e in t?C1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qn=(t,e,s)=>I1(t,typeof e!="symbol"?e+"":e,s);class A1{constructor(){qn(this,"map",new Map),qn(this,"set",(e,s)=>{const n=this.get(e);this.exists(e,s)||this.map.set(e,[...n,s])}),qn(this,"get",e=>this.map.get(e)||[]),qn(this,"exists",(e,s)=>this.get(e).includes(s)),qn(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,s))return;const r=n.filter(i=>i!==s);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),qn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var N1=Object.defineProperty,_1=Object.defineProperties,S1=Object.getOwnPropertyDescriptors,Nd=Object.getOwnPropertySymbols,T1=Object.prototype.hasOwnProperty,O1=Object.prototype.propertyIsEnumerable,Xa=(t,e,s)=>e in t?N1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Or=(t,e)=>{for(var s in e||(e={}))T1.call(e,s)&&Xa(t,s,e[s]);if(Nd)for(var s of Nd(e))O1.call(e,s)&&Xa(t,s,e[s]);return t},ta=(t,e)=>_1(t,S1(e)),_e=(t,e,s)=>Xa(t,typeof e!="symbol"?e+"":e,s);class k1 extends xm{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,_e(this,"subscriptions",new Map),_e(this,"topicMap",new A1),_e(this,"events",new kn.EventEmitter),_e(this,"name",gE),_e(this,"version",mE),_e(this,"pending",new Map),_e(this,"cached",[]),_e(this,"initialized",!1),_e(this,"storagePrefix",hs),_e(this,"subscribeTimeout",V.toMiliseconds(V.ONE_MINUTE)),_e(this,"initialSubscribeTimeout",V.toMiliseconds(V.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=co(r),a={topic:n,relay:o,transportType:r==null?void 0:r.transportType};(i=r==null?void 0:r.internal)!=null&&i.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,r);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),_e(this,"unsubscribe",async(n,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(n,r.id,r):await this.unsubscribeByTopic(n,r)}),_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(pr.pulse,async()=>{await this.checkPending()}),this.events.on(Nt.created,async n=>{const r=Nt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()}),this.events.on(Nt.deleted,async n=>{const r=Nt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()})}),this.relayer=e,this.logger=lt(s,this.name),this.clientId=""}get context(){return Et(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=co(n);await this.restartToComplete({topic:e,id:s,relay:r}),await this.rpcUnsubscribe(e,s,r);const i=xe("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;
14const o=await this.getSubscriptionId(e);if((r=n==null?void 0:n.internal)!=null&&r.skipSubscribe)return o;(!n||(n==null?void 0:n.transportType)===Oe.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const a={method:Xn(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(i=n==null?void 0:n.internal)==null?void 0:i.throwOnFailedPublish;try{if((n==null?void 0:n.transportType)===Oe.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(u=>this.logger.warn(u))},V.toMiliseconds(V.ONE_SECOND)),o;const l=new Promise(async u=>{const h=p=>{p.topic===e&&(this.events.removeListener(Nt.created,h),u(p.id))};this.events.on(Nt.created,h);try{const p=await as(new Promise((y,m)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),m(w)}).then(y)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Nt.created,h),u(p)}catch{}}),d=await as(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:Xn(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 as(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:Xn(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 as(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:Xn(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,ta(Or({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,Or({},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,Or({},s)),this.topicMap.set(s.topic,e),this.events.emit(Nt.created,s)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const s=this.subscriptions.get(e);if(!s){const{message:n}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Nt.deleted,ta(Or({},n),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Nt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<s;n++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(Nt.resubscribed)}
14async 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}=z("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=>ta(Or({},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 nw(V.toMiliseconds(V.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}=z("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 Lt(e+await this.getClientId())}}var P1=Object.defineProperty,_d=Object.getOwnPropertySymbols,x1=Object.prototype.hasOwnProperty,R1=Object.prototype.propertyIsEnumerable,Za=(t,e,s)=>e in t?P1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Sd=(t,e)=>{for(var s in e||(e={}))x1.call(e,s)&&Za(t,s,e[s]);if(_d)for(var s of _d(e))R1.call(e,s)&&Za(t,s,e[s]);return t},Ee=(t,e,s)=>Za(t,typeof e!="symbol"?e+"":e,s);class $1 extends km{constructor(e){super(e),Ee(this,"protocol","wc"),Ee(this,"version",2),Ee(this,"core"),Ee(this,"logger"),Ee(this,"events",new kn.EventEmitter),Ee(this,"provider"),Ee(this,"messages"),Ee(this,"subscriber"),Ee(this,"publisher"),Ee(this,"name",dE),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",V.toMiliseconds(V.THIRTY_SECONDS+V.FIVE_SECONDS)),Ee(this,"reconnectTimeout"),Ee(this,"connectPromise"),Ee(this,"reconnectInProgress",!1),Ee(this,"requestsInFlight",[]),Ee(this,"connectTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Ee(this,"request",async s=>{var n,r;this.logger.debug("Publishing Request Payload");const i=s.id||gn().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",()=>{so()&&(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==null?void 0: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(Pt.payload,this.onPayloadHandler),this.provider.on(Pt.connect,this.onConnectHandler),this.provider.on(Pt.disconnect,this.onDisconnectHandler),this.provider.on(Pt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?lt(e.logger,this.name):ci(wo({level:e.logger||lE})),this.messages=new g1(this.logger,e.core),this.subscriber=new k1(this,this.logger),this.publisher=new E1(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||hp,Fy()?this.packageName=El():qy()&&(this.bundleId=El()
14),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e==null?void 0:e.message))}get context(){return Et(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:Oe.relay},qi.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,s){var n,r,i;this.isInitialized(),(!(s!=null&&s.transportType)||(s==null?void 0:s.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((n=s==null?void 0:s.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(r=s==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",c;const l=d=>{d.topic===e&&(this.subscriber.off(Nt.created,l),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(Nt.created,l)}),new Promise(async(d,u)=>{a=await this.subscriber.subscribe(e,Sd({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 as(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 pd())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const s=e.sort((n,r)=>n.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const n of s)try{await this.onMessageEvent(n)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:n}=e;if(!s.sessionExists){const r=Be(V.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,qi.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=()=>
vendor: 20,880 bytes, line 14
14{r(new Error("Connection interrupted while trying to connect"))};this.provider.once(Pt.disconnect,i),await as(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(Pt.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(Pt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Pt.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,V.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,n,r,i;if(so())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null||i.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new dc(new Ef(Vy({sdkVersion:Ka,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}),uc(e)){if(!e.method.endsWith(uE))return;const s=e.params,{topic:n,message:r,publishedAt:i,attestation:o}=s.data,a={topic:n,message:r,publishedAt:i,transportType:Oe.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Sd({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else hc(e)&&this.events.emit(De.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,qi.inbound),this.events.emit(De.message,e))}async acknowledgePayload(e){const s=Gr(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Pt.payload,this.onPayloadHandler),this.provider.off(Pt.connect,this.onConnectHandler),this.provider.off(Pt.disconnect,this.onDisconnectHandler),this.provider.off(Pt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await pd();jv(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(n=>this.logger.error(n,n==null?void 0:n.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(pr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Wv())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s==null?void 0:s.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(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==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},V.toMiliseconds(hE)))))}isInitialized(){if(!this.initialized){const{message:e}=z("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 U1(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Td(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Od(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const D1="[object RegExp]",L1="[object String]",B1="[object Number]",M1="[object Boolean]",kd="[object Arguments]",j1="[object Symbol]",F1="[object Date]",q1="[object Map]",W1="[object Set]",z1="[object Array]",H1="[object Function]",K1="[object ArrayBuffer]",sa="[object Object]",V1="[object Error]",G1="[object DataView]",Y1="[object Uint8Array]",J1="[object Uint8ClampedArray]",X1="[object Uint16Array]",Z1="[object Uint32Array]",Q1="[object BigUint64Array]",eI="[object Int8Array]",tI="[object Int16Array]",sI="[object Int32Array]",nI="[object BigInt64Array]",rI="[object Float32Array]",iI="[object Float64Array]";function oI(){}function Pd(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 aI(t,e,s){return Dr(t,e,void 0,void 0,void 0,void 0,s)}function Dr(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 zr(t,e,i,o)}return zr(t,e,i,o)}function zr(t,e,s,n){if(Object.is(t,e))return!0;let r=Od(t),i=Od(e);if(r===kd&&(r=sa),i===kd&&(i=sa),r!==i)return!1;switch(r){case L1:return t.toString()===e.toString();case B1:{const c=t.valueOf(),l=e.valueOf();return U1(c,l)}case M1:case F1:case j1:return Object.is(t.valueOf(),e.valueOf());case D1:return t.source===e.source&&t.flags===e.flags;case H1: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 q1:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Dr(l,e.get(c),c,t,e,s,n))return!1;return!0}case W1:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let d=0;d<c.length;d++){const u=c[d],h=l.findIndex(p=>Dr(u,p,void 0,t,e,s,n));if(h===-1)return!1;l.splice(h,1)}return!0}case z1:case Y1:case J1:case X1:case Z1:case Q1:case eI:case tI:case sI:case nI:case rI:case iI:{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(!Dr(t[c],e[c],c,t,e,s,n))return!1;return!0}case K1:return t.byteLength!==e.byteLength?!1:zr(new Uint8Array(t),new Uint8Array(e),s,n);case G1:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:zr(new Uint8Array(t),new Uint8Array(e),s,n);case V1:return t.name===e.name&&t.message===e.message;case sa:{if(!(zr(t.constructor,e.constructor,s,n)||Pd(t)&&Pd(e)))return!1;const c=[...Object.keys(t),...Td(t)],l=[...Object.keys(e),...Td(e)];if(c.length!==l.length)return!1;for(let d=0;d<c.length;d++){const u=c[d],h=t[u];if(!Object.hasOwn(e,u))return!1;const p=e[u];if(!Dr(h,p,u,t,e,s,n))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function cI(t,e){return aI(t,e,oI)}var lI=Object.defineProperty,xd=Object.getOwnPropertySymbols,dI=Object.prototype.hasOwnProperty,uI=Object.prototype.propertyIsEnumerable,Qa=(t,e,s)=>e in t?lI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Rd=(t,e)=>{for(var s in e||(e={}))dI.call(e,s)&&Qa(t,s,e[s]);if(xd)for(var s of xd(e))uI.call(e,s)&&Qa(t,s,e[s]);return t},ft=(t,e,s)=>Qa(t,typeof e!="symbol"?e+"":e,s);class Un extends Pm{constructor(e,s,n,r=hs,i=void 0){super(e,s,n,r),this.core=e,this.logger=s,this.name=n,ft(this,"map",new Map),ft(this,"version",pE),ft(this,"cached",[]),ft(this,"initialized",!1),ft(this,"getKey"),ft(this,"storagePrefix",hs),ft(this,"recentlyDeleted",[]),ft(this,"recentlyDeletedLimit",200),ft(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):yv(o)?this.map.set(o.id,o):wv(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ft(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())}),ft(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ft(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>cI(a[c],o[c]))):this.values)),ft(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=Rd(Rd({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ft(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=lt(s,this.name),this.storagePrefix=r,this.getKey=i}get context(){return Et(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}=z("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:n}=z("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}=z("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}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var hI=Object.defineProperty,pI=(t,e,s)=>e in t?hI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pe=(t,e,s)=>pI(t,typeof e!="symbol"?e+"":e,s);class fI{constructor(e,s){this.core=e,this.logger=s,pe(this,"name",yE),pe(this,"version",wE),pe(this,"events",new pc),pe(this,"pairings"),pe(this,"initialized",!1),pe(this,"storagePrefix",hs),pe(this,"ignoredPayloadTypes",[Ts]),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=Wa(),i=await this.core.crypto.setSymKey(r),o=Be(V.FIVE_MINUTES),a={protocol:up},c={topic:i,expiry:o,relay:a,active:!1,methods:n==null?void 0:n.methods},l=rd({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:r,relay:a,expiryTimestamp:o,methods:n==null?void 0:n.methods});return this.events.emit(hn.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:n==null?void 0:n.transportType,internal:n==null?void 0:n.internal}),{topic:i,uri:l}}),pe(this,"pair",async n=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:n==null?void 0:n.uri,trace:[ts.pairing_started]}});this.isValidPair(n,r);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=nd(n.uri);r.props.properties.topic=i,r.addTrace(ts.pairing_uri_validation_success),r.addTrace(ts.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(i)){if(d=this.pairings.get(i),r.addTrace(ts.existing_pairing),d.active)throw r.setError(bs.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);r.addTrace(ts.pairing_not_expired)}const u=c||Be(V.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(ts.store_new_pairing),n.activatePairing&&await this.activate({topic:i}),this.events.emit(hn.create,h),r.addTrace(ts.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),r.addTrace(ts.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(bs.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(p){throw r.setError(bs.subscribe_pairing_topic_failure),p}return r.addTrace(ts.subscribe_pairing_topic_success),h}),pe(this,"activate",async({topic:n})=>{this.isInitialized();const r=Be(V.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}=un();this.events.once(Ie("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",xe("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 rd({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=ns(r,i),a=await this.core.crypto.encode(n,o),c=_r[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=Gr(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=_r[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=Ou(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=_r[c]?_r[c].res:_r.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,xe("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=>is(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(hn.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(()=>{ys(r)?this.events.emit(Ie("pairing_ping",i),{}):ss(r)&&this.events.emit(Ie("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(hn.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=xe("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(xe("WC_METHOD_UNSUPPORTED",n))}),pe(this,"isValidPair",(n,r)=>{var i;if(!mt(n)){const{message:a}=z("MISSING_OR_INVALID",`pair() params: ${n}`);throw r.setError(bs.malformed_pairing_uri),new Error(a)}if(!mv(n.uri)){const{message:a}=z("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw r.setError(bs.malformed_pairing_uri),new Error(a)}const o=nd(n==null?void 0:n.uri);if(!((i=o==null?void 0:o.relay)!=null&&i.protocol)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(bs.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(bs.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&V.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(bs.pairing_expired);const{message:a}=z("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),pe(this,"isValidPing",async n=>{if(!mt(n)){const{message:i}=z("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),pe(this,"isValidDisconnect",async n=>{if(!mt(n)){const{message:i}=z("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),pe(this,"isValidPairingTopic",async n=>{if(!Me(n,!1)){const{message:r}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(r)}if(!this.pairings.keys.includes(n)){const{message:r}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(r)}if(is(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:r}=z("EXPIRED",`pairing topic: ${n}`);throw new Error(r)}}),this.core=e,this.logger=lt(s,this.name),this.pairings=new Un(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Et(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=z("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!==Oe.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const i=await this.core.crypto.decode(s,n);uc(i)?(this.core.history.set(s,i),await this.onRelayEventRequest({topic:s,payload:i})):hc(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(Dt.expired,async e=>{const{topic:s}=lh(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(hn.expire,{topic:s}))})}}var gI=Object.defineProperty,mI=(t,e,s)=>e in t?gI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ge=(t,e,s)=>mI(t,typeof e!="symbol"?e+"":e,s);class yI extends Sm{constructor(e,s){super(e,s),this.core=e,this.logger=s,Ge(this,"records",new Map),Ge(this,"events",new kn.EventEmitter),Ge(this,"name",bE),Ge(this,"version",vE),Ge(this,"cac
14hed",[]),Ge(this,"initialized",!1),Ge(this,"storagePrefix",hs),Ge(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)}),Ge(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:Be(V.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ht.created,o)}),Ge(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=ss(n)?{error:n.error}:{result:n.result},this.records.set(r.id,r),this.persist(),this.events.emit(Ht.updated,r))}),Ge(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))),Ge(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(Ht.deleted,i)}}),this.persist()}),Ge(this,"exists",async(n,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===n:!1)),Ge(this,"on",(n,r)=>{this.events.on(n,r)}),Ge(this,"once",(n,r)=>{this.events.once(n,r)}),Ge(this,"off",(n,r)=>{this.events.off(n,r)}),Ge(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=lt(s,this.name)}get context(){return Et(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:ns(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}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ht.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=z("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(Ht.created,e=>{const s=Ht.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Ht.updated,e=>{const s=Ht.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Ht.deleted,e=>{const s=Ht.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(pr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{V.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(Ht.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var wI=Object.defineProperty,bI=(t,e,s)=>e in t?wI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,nt=(t,e,s)=>bI(t,typeof e!="symbol"?e+"":e,s);class vI extends Rm{constructor(e,s){super(e,s),this.core=e,this.logger=s,nt(this,"expirations",new Map),nt(this,"events",new kn.EventEmitter),nt(this,"name",EE),nt(this,"version",CE),nt(this,"cac
14hed",[]),nt(this,"initialized",!1),nt(this,"storagePrefix",hs),nt(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)}),nt(this,"has",n=>{try{const r=this.formatTarget(n);return typeof this.getExpiration(r)<"u"}catch{return!1}}),nt(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(Dt.created,{target:i,expiration:o})}),nt(this,"get",n=>{this.isInitialized();const r=this.formatTarget(n);return this.getExpiration(r)}),nt(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(Dt.deleted,{target:r,expiration:i})}}),nt(this,"on",(n,r)=>{this.events.on(n,r)}),nt(this,"once",(n,r)=>{this.events.once(n,r)}),nt(this,"off",(n,r)=>{this.events.off(n,r)}),nt(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=lt(s,this.name)}get context(){return Et(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 Gy(e);if(typeof e=="number")return Yy(e);const{message:s}=z("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(Dt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=z("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}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return s}checkExpiry(e,s){const{expiry:n}=s;V.toMiliseconds(n)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(Dt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(pr.pulse,()=>this.checkExpirations()),this.events.on(Dt.created,e=>{const s=Dt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Dt.expired,e=>{const s=Dt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Dt.deleted,e=>{const s=Dt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var EI=Object.defineProperty,CI=(t,e,s)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Le=(t,e,s)=>CI(t,typeof e!="symbol"?e+"":e,s);class II extends $m{constructor(e,s,n){super(e,s,n),this.core=e,this.logger=s,this.store=n,Le(this,"name",IE),Le(this,"abortController"),Le(this,"isDevEnv"),Le(this,"verifyUrlV3",NE),Le(this,"storagePrefix",hs),Le(this,"version",dp),Le(this,"publicKey"),Le(this,"fetchPromise"),Le(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&V.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(!mr()||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=ks.getDocument(),d=this.startAbortTimer(V.ONE_SECOND*5),u=await new Promise((h,p)=>{const y=()=>{window.removeEventListener("message",w),l.body.removeChild(m),p("attestation aborted")};this.abortController.signal.addEventListener("abort",y);const m=l.createElement("iframe");m.src=c,m.style.display="none",m.addEventListener("error",y,{signal:this.abortController.signal});const w=E=>
vendor: 55,735 bytes, line 14
14{if(E.data&&typeof E.data=="string")try{const I=JSON.parse(E.data);if(I.type==="verify_attestation"){if(wa(I.attestation).payload.id!==o)return;clearInterval(d),l.body.removeChild(m),this.abortController.signal.removeEventListener("abort",y),window.removeEventListener("message",w),h(I.attestation===null?"":I.attestation)}}catch(I){this.logger.warn(I)}};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(wa(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),Le(this,"fetchAttestation",async(r,i)=>{this.logger.debug(`resolving attestation: ${r} from url: ${i}`);const o=this.startAbortTimer(V.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||Wr;return _E.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Wr}`),i=Wr),i}),Le(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(V.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=W0(r,i.publicKey),a={hasExpired:V.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=lt(s,this.name),this.abortController=new AbortController,this.isDevEnv=wc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Et(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),V.toMiliseconds(e))}}var AI=Object.defineProperty,NI=(t,e,s)=>e in t?AI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$d=(t,e,s)=>NI(t,typeof e!="symbol"?e+"":e,s);class _I extends Um{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,$d(this,"context",SE),$d(this,"registerDeviceToken",async n=>{const{clientId:r,token:i,notificationType:o,enableEncrypted:a=!1}=n,c=`${TE}/${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=lt(s,this.context)}}var SI=Object.defineProperty,Ud=Object.getOwnPropertySymbols,TI=Object.prototype.hasOwnProperty,OI=Object.prototype.propertyIsEnumerable,ec=(t,e,s)=>e in t?SI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,kr=(t,e)=>{for(var s in e||(e={}))TI.call(e,s)&&ec(t,s,e[s]);if(Ud)for(var s of Ud(e))OI.call(e,s)&&ec(t,s,e[s]);return t},We=(t,e,s)=>ec(t,typeof e!="symbol"?e+"":e,s);class kI extends Dm{constructor(e,s,n=!0){super(e,s,n),this.core=e,this.logger=s,We(this,"context",kE),We(this,"storagePrefix",hs),We(this,"storageVersion",OE),We(this,"events",new Map),We(this,"shouldPersist",!1),We(this,"init",async()=>{if(!wc())try{const r={eventId:Il(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:ah(this.core.relayer.protocol,this.core.relayer.version,Ka)}}};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=Il(),d=this.core.projectId||"",u=Date.now(),h=kr({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 kr(kr({},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(pr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{V.fromMiliseconds(Date.now())-V.fromMiliseconds(r.timestamp)>PE&&(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,kr(kr({},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(`${xE}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ka}${i}`,{method:"POST",body:JSON.stringify(r)})}),We(this,"getAppDomain",()=>oh().url),this.logger=lt(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 PI=Object.defineProperty,Dd=Object.getOwnPropertySymbols,xI=Object.prototype.hasOwnProperty,RI=Object.prototype.propertyIsEnumerable,tc=(t,e,s)=>e in t?PI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ld=(t,e)=>{for(var s in e||(e={}))xI.call(e,s)&&tc(t,s,e[s]);if(Dd)for(var s of Dd(e))RI.call(e,s)&&tc(t,s,e[s]);return t},Se=(t,e,s)=>tc(t,typeof e!="symbol"?e+"":e,s);let $I=class Np extends Im{constructor(e){var s;super(e),Se(this,"protocol",lp),Se(this,"version",dp),Se(this,"name",Ha),Se(this,"relayUrl"),Se(this,"projectId"),Se(this,"customStoragePrefix"),Se(this,"events",new kn.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:Oe.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:l})});const n=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||hp,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=wo({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:Qv.logger,name:Ha}),{logger:i,chunkLoggerController:o}=vm({opts:r,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(s=this.logChunkController)!=null&&s.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=lt(i,this.name),this.heartbeat=new vf,this.crypto=new a1(this,this.logger,e==null?void 0:e.keychain),this.history=new yI(this,this.logger),this.expirer=new vI(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new rm(Ld(Ld({},eE),e==null?void 0:e.storageOptions)),this.relayer=new $1({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new fI(this,this.logger),this.verify=new II(this,this.logger,this.storage),this.echoClient=new _I(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new kI(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new Np(e);await s.initialize();const n=await s.crypto.getClientId();return await s.storage.setItem(fE,n),s}get context(){return Et(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(gd,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(gd)||[],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"&&Zv.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const UI=$I,_p="wc",Sp=2,Tp="client",kc=`${_p}@${Sp}:${Tp}:`,na={name:Tp,logger:"error"},Bd="WALLETCONNECT_DEEPLINK_CHOICE",DI="proposal",Md="Proposal expired",LI="session",Wn=V.SEVEN_DAYS,BI="engine",Ye={wc_sessionPropose:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1104},res:{ttl:V.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1106},res:{ttl:V.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1112},res:{ttl:V.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1114},res:{ttl:V.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:V.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:V.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1119}}},ra={min:V.FIVE_MINUTES,max:V.SEVEN_DAYS},es={idle:"IDLE",active:"ACTIVE"},MI={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:""}},jI="request",FI=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],qI="wc",WI="auth",zI="authKeys",HI="pairingTopics",KI="requests",Oo=`${qI}@${1.5}:${WI}:`,Wi=`${Oo}:PUB_KEY`;var VI=Object.defineProperty,GI=Object.defineProperties,YI=Object.getOwnPropertyDescriptors,jd=Object.getOwnPropertySymbols,JI=Object.prototype.hasOwnProperty,XI=Object.prototype.propertyIsEnumerable,sc=(t,e,s)=>e in t?VI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ae=(t,e)=>{for(var s in e||(e={}))JI.call(e,s)&&sc(t,s,e[s]);if(jd)for(var s of jd(e))XI.call(e,s)&&sc(t,s,e[s]);return t},rt=(t,e)=>GI(t,YI(e)),B=(t,e,s)=>sc(t,typeof e!="symbol"?e+"":e,s);class ZI extends jm{constructor(e){super(e),B(this,"name",BI),B(this,"events",new pc),B(this,"initialized",!1),B(this,"requestQueue",{state:es.idle,queue:[]}),B(this,"sessionRequestQueue",{state:es.idle,queue:[]}),B(this,"emittedSessionRequests",new rw({limit:500})),B(this,"requestQueueDelay",V.ONE_SECOND),B(this,"expectedPairingMethodMap",new Map),B(this,"recentlyDeletedMap",new Map),B(this,"recentlyDeletedLimit",200),B(this,"relayMessageCache",[]),B(this,"pendingSessions",new Map),B(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(Ye)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay)))}),B(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=rt(Ae({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=uv(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 f=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=f.active}}catch(f){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),f}if(!d||!h){const{topic:f,uri:v}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});d=f,u=v}if(!d){const{message:f}=z("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(f)}const p=await this.client.core.crypto.generateKeyPair(),y=Ye.wc_sessionPropose.req.ttl||V.FIVE_MINUTES,m=Be(y),w=rt(Ae(Ae({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:up}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:d},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Rs()}),E=Ie("session_connect",w.id),{reject:I,resolve:k,done:D}=un(y,Md),j=({id:f})=>{f===w.id&&(this.client.events.off("proposal_expire",j),this.pendingSessions.delete(w.id),this.events.emit(E,{error:{message:Md,code:0}}))};return this.client.events.on("proposal_expire",j),this.events.once(E,({error:f,session:v})=>{this.client.events.off("proposal_expire",j),f?I(f):v&&k(v)}),await this.sendProposeSession({proposal:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:w.id}}}),await this.setProposal(w.id,w),{uri:u,approval:D}}),B(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}}),B(this,"approve",async s=>{var n,r,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=s==null?void 0:s.id)==null?void 0:n.toString(),trace:[qs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(_){throw o.setError(Sr.no_internet_connection),_}try{await this.isValidProposalId(s==null?void 0:s.id)}catch(_){throw this.client.logger.error(`approve() -> proposal.get(${s==null?void 0:s.id}) failed`),o.setError(Sr.proposal_not_found),_}try{await this.isValidApprove(s)}catch(_){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Sr.session_approve_namespace_validation_failure),_}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=s,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:y,proposer:m,requiredNamespaces:w,optionalNamespaces:E}=p;let I=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:y});I||(I=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:qs.session_approve_started,properties:{topic:y,trace:[qs.session_approve_started,qs.session_namespaces_validation_success]}}));const k=await this.client.core.crypto.generateKeyPair(),D=m.publicKey,j=await this.client.core.crypto.generateSharedKey(k,D),f=Ae(Ae(Ae({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:k,metadata:this.client.metadata},expiry:Be(Wn)},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),v=Oe.relay;I.addTrace(qs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(j,{transportType:v,internal:{skipSubscribe:!0}})}catch(_){throw I.setError(Sr.subscribe_session_topic_failure),_}I.addTrace(qs.subscribe_session_topic_success);const C=rt(Ae({},f),{topic:j,requiredNamespaces:w,optionalNamespaces:E,pairingTopic:y,acknowledged:!1,self:f.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:k,transportType:Oe.relay});await this.client.session.set(j,C),I.addTrace(qs.store_session);try{await this.sendApproveSession({sessionTopic:j,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:k},sessionSettleRequest:f,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),I.addTrace(qs.session_approve_publish_success)}catch(_){throw this.client.logger.error(_),this.client.session.delete(j,xe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(j),_}return this.client.core.eventClient.deleteEvent({eventId:I.eventId}),await this.client.core.pairing.updateMetadata({topic:y,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:y}),await this.setExpiry(j,Be(Wn)),{topic:j,acknowledged:()=>Promise.resolve(this.client.session.get(j))}}),B(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:Ye.wc_sessionPropose.reject}),await this.deleteProposal(n)}),B(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}=un(),c=Rs(),l=gn().toString(),d=this.client.session.get(n).namespaces;return this.events.once(Ie("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}}),B(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=Rs(),{done:i,resolve:o,reject:a}=un();return this.events.once(Ie("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,Be(Wn)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),B(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=Ye.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(i);(a==null?void 0:a.transportType)===Oe.relay&&await this.confirmOnlineStateOrThrow();const c=Rs(),l=gn().toString(),{done:d,resolve:u,reject:h}=un(o,"Request expired. Please try again.");this.events.once(Ie("session_request",c),({error:w,result:E})=>{w?h(w):u(E)});const p="wc_sessionRequest",y=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(y)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:{request:rt(Ae({},r),{expiryTimestamp:Be(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:y}).catch(w=>h(w)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),await d();const m={request:rt(Ae({},r),{expiryTimestamp:Be(o)}),chainId:n};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:m,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,m)}).catch(E=>h(E)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),w()}),new Promise(async w=>{var E;if(!((E=a.sessionConfig)!=null&&E.disableDeepLink)){const I=await Qy(this.client.core.storage,Bd);await Jy({id:c,topic:i,wcDeepLink:I})}w()}),d()]).then(w=>w[2])}),B(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===Oe.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);ys(r)?await this.sendResult({id:i,topic:n,result:r.result,throwOnFailedPublish:!0,appLink:a}):ss(r)&&await this.sendError({id:i,topic:n,error:r.error,appLink:a}),this.cleanupAfterResponse(s)}),B(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=Rs(),i=gn().toString(),{done:o,resolve:a,reject:c}=un();this.events.once(Ie("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}))}),B(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:n,event:r,chainId:i}=s,o=gn().toString(),a=Rs();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:r,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),B(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:xe("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}=z("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(r)}}),B(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(n=>fv(n,s)))),B(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),B(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?Oe.link_mode:Oe.relay;o===Oe.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:d,nonce:u,type:h,exp:p,nbf:y,methods:m=[],expiry:w}=s,E=[...s.resources||[]],{topic:I,uri:k}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:I,uri:k}});const D=await this.client.core.crypto.generateKeyPair(),j=Fi(D);if(await Promise.all([this.client.auth.authKeys.set(Wi,{responseTopic:j,publicKey:D}),this.client.auth.pairingTopics.set(j,{topic:j,pairingTopic:I})]),await this.client.core.relayer.subscribe(j,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${I}`),m.length>0){const{namespace:P}=Ss(a[0]);let T=gb(P,"request",m);ji(E)&&(T=yb(T,E.pop())),E.push(T)}const f=w&&w>Ye.wc_sessionAuthenticate.req.ttl?w:Ye.wc_sessionAuthenticate.req.ttl,v={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:d,version:"1",nonce:u,iat:new Date().toISOString(),exp:p,nbf:y,resources:E},requester:{publicKey:D,metadata:this.client.metadata},expiryTimestamp:Be(f)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},_={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:I,proposer:{publicKey:D,metadata:this.client.metadata},expiryTimestamp:Be(Ye.wc_sessionPropose.req.ttl),id:Rs()},{done:S,resolve:U,reject:O}=un(f,"Request expired"),A=Rs(),b=Ie("session_connect",_.id),N=Ie("session_request",A),x=async({error:P,session:T})=>{this.events.off(N,L),P?O(P):T&&U({session:T})},L=async P=>{var T,W,K;if(await this.deletePendingAuthRequest(A,{message:"fulfilled",code:0}),P.error){const ue=xe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===ue.code?void 0:(this.events.off(b,x),O(P.error.message))}await this.deleteProposal(_.id),this.events.off(b,x);const{cacaos:ie,responder:oe}=P.result,se=[],X=[];for(const ue of ie){await $l({cacao:ue,projectId:this.client.core.projectId})||(this.client.logger.error(ue,"Signature verification failed"),O(xe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ue}=ue,Wt=ji(Ue.resources),xs=[Ra(Ue.iss)],nn=ro(Ue.iss);if(Wt){const Dn=Ul(Wt),ef=Dl(Wt);se.push(...Dn),xs.push(...ef)}for(const Dn of xs)X.push(`${Dn}:${nn}`)}const de=await this.client.core.crypto.generateSharedKey(D,oe.publicKey);let Te;se.length>0&&(Te={topic:de,acknowledged:!0,self:{publicKey:D,metadata:this.client.metadata},peer:oe,controller:oe.publicKey,expiry:Be(Wn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:I,namespaces:cd([...new Set(se)],[...new Set(X)]),transportType:o},await this.client.core.relayer.subscribe(de,{transportType:o}),await this.client.session.set(de,Te),I&&await this.client.core.pairing.updateMetadata({topic:I,metadata:oe.metadata}),Te=this.client.session.get(de)),(T=this.client.metadata.redirect)!=null&&T.linkMode&&(W=oe.metadata.redirect)!=null&&W.linkMode&&(K=oe.metadata.redirect)!=null&&K.universal&&n&&(this.client.core.addLinkModeSupportedApp(oe.metadata.redirect.universal),this.client.session.update(de,{transportType:Oe.link_mode})),U({auths:ie,session:Te})};this.events.once(b,x),this.events.once(N,L);let F;try{if(i){const P=ns("wc_sessionAuthenticate",v,A);this.client.core.history.set(I,P);const T=await this.client.core.crypto.encode("",P,{type:fi,encoding:Vs});F=ki(n,I,T)}else await Promise.all([this.sendRequest({topic:I,method:"wc_sessionAuthenticate",params:v,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:A}),this.sendRequest({topic:I,method:"wc_sessionPropose",params:_,expiry:Ye.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:_.id})])}catch(P){throw this.events.off(b,x),this.events.off(N,L),P}return await this.setProposal(_.id,_),await this.setAuthRequest(A,{request:rt(Ae({},v),{verifyContext:{}}),pairingTopic:I,transportType:o}),{uri:F??k,response:S}}),B(this,"approveSessionAuthenticate",async s=>{const{id:n,auths:r}=s,i=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[an.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw i.setError(Tr.no_internet_connection),w}const o=this.getPendingAuthRequest(n);if(!o)throw i.setError(Tr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||Oe.relay;a===Oe.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=Fi(c),u={type:Ts,receiverPublicKey:c,senderPublicKey:l},h=[],p=[];for(const w of r){if(!await $l({cacao:w,projectId:this.client.core.projectId})){i.setError(Tr.invalid_cacao);const j=xe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:j,encodeOpts:u}),new Error(j.message)}i.addTrace(an.cacaos_verified);const{p:E}=w,I=ji(E.resources),k=[Ra(E.iss)],D=ro(E.iss);if(I){const j=Ul(I),f=Dl(I);h.push(...j),k.push(...f)}for(const j of k)p.push(`${j}:${D}`)}const y=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(an.create_authenticated_session_topic);let m;if((h==null?void 0:h.length)>0){m={topic:y,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Be(Wn),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:cd([...new Set(h)],[...new Set(p)]),transportType:a},i.addTrace(an.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(y,{transportType:a})}catch(w){throw i.setError(Tr.subscribe_authenticated_session_topic_failure),w}i.addTrace(an.subscribe_authenticated_session_topic_success),await this.client.session.set(y,m),i.addTrace(an.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(an.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(Tr.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}}),B(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===Oe.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Fi(o),l={type:Ts,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:r,encodeOpts:l,rpcOpts:Ye.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)}),B(this,"formatAuthMessage",s=>{this.isInitialized();const{request:n,iss:r}=s;return Nh(n,r)}),B(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)}),B(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)}}),B(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,xe("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(Bd).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,xe("USER_DISCONNECTED"))}),r===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=es.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),B(this,"deleteProposal",async(s,n)=>{if(n)try{const r=this.client.proposal.get(s),i=this.client.core.eventClient.getEvent({topic:r.pairingTopic});i==null||i.setError(Sr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,xe("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),B(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=es.idle,this.client.events.emit("session_request_expire",{id:s}))}),B(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)])}),B(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}))}),B(this,"setProposal",async(s,n)=>{this.client.core.expirer.set(s,Be(Ye.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,n)}),B(this,"setAuthRequest",async(s,n)=>{const{request:r,pairingTopic:i,transportType:o=Oe.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})}),B(this,"setPendingSessionRequest",async s=>{const{id:n,topic:r,params:i,verifyContext:o}=s,a=i.request.expiryTimestamp||Be(Ye.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})}),B(this,"sendRequest",async s=>{const{topic:n,method:r,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:d,tvf:u,publishOpts:h={}}=s,p=ns(r,i,c);let y;const m=!!d;try{const I=m?Vs:wt;y=await this.client.core.crypto.encode(n,p,{encoding:I})}catch(I){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),I}let w;if(FI.includes(r)){const I=Lt(JSON.stringify(p)),k=Lt(y);w=await this.client.core.verify.register({id:k,decryptedId:I})}const E=Ae(Ae({},Ye[r].req),h);if(E.attestation=w,o&&(E.ttl=o),a&&(E.id=a),this.client.core.history.set(n,p),m){const I=ki(d,n,y);await global.Linking.openURL(I,this.client.name)}else E.tvf=rt(Ae({},u),{correlationId:p.id}),l?(E.internal=rt(Ae({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,y,E)):this.client.core.relayer.publish(n,y,E).catch(I=>this.client.logger.error(I));return p.id}),B(this,"sendProposeSession",async s=>{const{proposal:n,publishOpts:r}=s,i=ns("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:wt}),a=Lt(JSON.stringify(i)),c=Lt(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:rt(Ae({},r),{publishMethod:"wc_proposeSession",attestation:l})})}),B(this,"sendApproveSession",async s=>{const{sessionTopic:n,pairingProposalResponse:r,proposal:i,sessionSettleRequest:o,publishOpts:a}=s,c=Gr(i.id,r),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:wt}),d=ns("wc_sessionSettle",o,a==null?void 0:a.id),u=await this.client.core.crypto.encode(n,d,{encoding:wt});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:u},opts:rt(Ae({},a),{publishMethod:"wc_approveSession"})})}),B(this,"sendResult",async s=>{const{id:n,topic:r,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=Gr(n,i);let d;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const y=u?Vs:wt;d=await this.client.core.crypto.encode(r,l,rt(Ae({},a||{}),{encoding:y}))}catch(y){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),y}let h,p;try{h=await this.client.core.history.get(r,n);const y=h.request;try{p=this.getTVFParams(n,y.params,i)}catch(m){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${m==null?void 0:m.message}`)}}catch(y){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${n}) failed`),y}if(u){const y=ki(c,r,d);await global.Linking.openURL(y,this.client.name)}else{const y=h.request.method,m=Ye[y].res;m.tvf=rt(Ae({},p),{correlationId:n}),o?(m.internal=rt(Ae({},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)}),B(this,"sendError",async s=>{const{id:n,topic:r,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=Ou(n,i);let d;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=u?Vs:wt;d=await this.client.core.crypto.encode(r,l,rt(Ae({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),p}let h;try{h=await this.client.core.history.get(r,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${r}, ${n}) failed`),p}if(u){const p=ki(c,r,d);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,y=a||Ye[p].res;this.client.core.relayer.publish(r,d,y)}await this.client.core.history.resolve(l)}),B(this,"cleanup",async()=>{const s=[],n=[];this.client.session.getAll().forEach(r=>{let i=!1;is(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=>{is(r.expiryTimestamp)&&n.push(r.id)}),await Promise.all([...s.map(r=>this.deleteSession({topic:r})),...n.map(r=>this.deleteProposal(r))])}),B(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),B(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),B(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===es.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=es.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=es.idle}),B(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}`)}}),B(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}`)}}),B(this,"onRelayEventUnknownPayload",s=>{const{topic:n}=s,{message:r}=z("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),B(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)}),B(this,"onSessionProposeRequest",async s=>{const{topic:n,payload:r,attestation:i,encryptedId:o}=s,{params:a,id:c}=r;try{const l=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(bs.proposal_listener_not_found)),this.isValidConnect(Ae({},r.params));const d=a.expiryTimestamp||Be(Ye.wc_sessionPropose.req.ttl),u=Ae({id:c,pairingTopic:n,expiryTimestamp:d,attestation:i,encryptedId:o},a);await this.setProposal(c,u);const h=await this.getVerifyContext({attestationId:i,hash:Lt(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});l==null||l.addTrace(ts.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:Ye.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),B(this,"onSessionProposeResponse",async(s,n,r)=>{const{id:i}=n;if(ys(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(ss(n)){await this.deleteProposal(i);const o=Ie("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})}}),B(this,"onSessionSettleRequest",async(s,n)=>{const{id:r,params:i}=n;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=n.params,p=[...this.pendingSessions.values()].find(w=>w.sessionTopic===s);if(!p)return this.client.logger.error(`Pending session not found for topic ${s}`);const y=this.client.proposal.get(p.proposalId),m=rt(Ae(Ae(Ae({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:y.requiredNamespaces,optionalNamespaces:y.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),{transportType:Oe.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(Ie("session_connect",p.proposalId),{session:m}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:n.id,topic:s,result:!0})}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),B(this,"onSessionSettleResponse",async(s,n)=>{const{id:r}=n;ys(n)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(Ie("session_approve",r),{})):ss(n)&&(await this.client.session.delete(s,xe("USER_DISCONNECTED")),this.events.emit(Ie("session_approve",r),{error:n.error}))}),B(this,"onSessionUpdateRequest",async(s,n)=>{const{params:r,id:i}=n;try{const o=`${s}_session_update`,a=Nr.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:xe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ae({topic:s},r));try{Nr.set(o,i),await this.client.session.update(s,{namespaces:r.namespaces}),await this.sendResult({id:i,topic:s,result:!0})}catch(c){throw Nr.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)}}),B(this,"isRequestOutOfSync",(s,n)=>n.toString().slice(0,-3)<s.toString().slice(0,-3)),B(this,"onSessionUpdateResponse",(s,n)=>{const{id:r}=n,i=Ie("session_update",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);ys(n)?this.events.emit(Ie("session_update",r),{}):ss(n)&&this.events.emit(Ie("session_update",r),{error:n.error})}),B(this,"onSessionExtendRequest",async(s,n)=>{const{id:r}=n;try{this.isValidExtend({topic:s}),await this.setExpiry(s,Be(Wn)),await this.sendResult({id:r,topic:s,result:!0}),this.client.events.emit("session_extend",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),B(this,"onSessionExtendResponse",(s,n)=>{const{id:r}=n,i=Ie("session_extend",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);ys(n)?this.events.emit(Ie("session_extend",r),{}):ss(n)&&this.events.emit(Ie("session_extend",r),{error:n.error})}),B(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)}}),B(this,"onSessionPingResponse",(s,n)=>{const{id:r}=n,i=Ie("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);ys(n)?this.events.emit(Ie("session_ping",r),{}):ss(n)&&this.events.emit(Ie("session_ping",r),{error:n.error})},500)}),B(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:xe("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),B(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(Ae({topic:o},h));const p=this.client.session.get(o),y=await this.getVerifyContext({attestationId:c,hash:Lt(JSON.stringify(ns("wc_sessionRequest",h,u))),encryptedId:l,metadata:p.peer.metadata,transportType:d}),m={id:u,topic:o,params:h,verifyContext:y};await this.setPendingSessionRequest(m),d===Oe.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((r=p.peer.metadata.redirect)==null?void 0:r.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(p){await this.sendError({id:u,topic:o,error:p}),this.client.logger.error(p)}}),B(this,"onSessionRequestResponse",(s,n)=>{const{id:r}=n,i=Ie("session_request",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);ys(n)?this.events.emit(Ie("session_request",r),{result:n.result}):ss(n)&&this.events.emit(Ie("session_request",r),{error:n.error})}),B(this,"onSessionEventRequest",async(s,n)=>{const{id:r,params:i}=n;try{const o=`${s}_session_event_${i.event.name}`,a=Nr.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Ae({topic:s},i)),this.client.events.emit("session_event",{id:r,topic:s,params:i}),Nr.set(o,r)}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),B(this,"onSessionAuthenticateResponse",(s,n)=>{const{id:r}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:n}),ys(n)?this.events.emit(Ie("session_request",r),{result:n.result}):ss(n)&&this.events.emit(Ie("session_request",r),{error:n.error})}),B(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:Lt(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:r,id:i.id,authPayload:d,verifyContext:h,expiryTimestamp:u};await this.setAuthRequest(i.id,{request:p,pairingTopic:r,transportType:c}),c===Oe.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:i.params,id:i.id,verifyContext:h})}catch(l){this.client.logger.error(l);const d=i.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(i.params.requester.metadata,c),p={type:Ts,receiverPublicKey:d,senderPublicKey:u};await this.sendError({id:i.id,topic:r,error:l,encodeOpts:p,rpcOpts:Ye.wc_sessionAuthenticate.autoReject,appLink:h})}}),B(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),B(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=es.idle,this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay))}),B(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=Ie("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ie("session_request",i.request.id),{error:n})})}),B(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===es.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)}}),B(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=es.active,this.emittedSessionRequests.add(s.id),this.client.events.emit("session_request",s)}),B(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:ns("wc_sessionPropose",rt(Ae({},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})}),B(this,"isValidConnect",async s=>{if(!mt(s)){const{message:l}=z("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),!_v(c)){const{message:l}=z("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!qe(r)&&us(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)&&us(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)}`)}}),B(this,"validateNamespaces",(s,n)=>{const r=Nv(s,"connect()",n);if(r)throw new Error(r.message)}),B(this,"isValidApprove",async s=>{if(!mt(s))throw new Error(z("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=Zo(r,"approve()");if(l)throw new Error(l.message);const d=ud(c.requiredNamespaces,r,"approve()");if(d)throw new Error(d.message);if(!Me(i,!0)){const{message:u}=z("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(", ")}`)}}),B(this,"isValidReject",async s=>{if(!mt(s)){const{message:i}=z("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(i)}const{id:n,reason:r}=s;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!Tv(r)){const{message:i}=z("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(i)}}),B(this,"isValidSessionSettleRequest",s=>{if(!mt(s)){const{message:l}=z("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}
vendor: 13,509 bytes, line 14
14const{relay:n,controller:r,namespaces:i,expiry:o}=s;if(!cp(n)){const{message:l}=z("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=bv(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Zo(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(is(o)){const{message:l}=z("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),B(this,"isValidUpdate",async s=>{if(!mt(s)){const{message:c}=z("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=Zo(r,"update()");if(o)throw new Error(o.message);const a=ud(i.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),B(this,"isValidExtend",async s=>{if(!mt(s)){const{message:r}=z("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(r)}const{topic:n}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),B(this,"isValidRequest",async s=>{if(!mt(s)){const{message:c}=z("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(!dd(a,i)){const{message:c}=z("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!Ov(r)){const{message:c}=z("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!xv(a,i,r.method)){const{message:c}=z("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Dv(o,ra)){const{message:c}=z("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${ra.min} and ${ra.max}`);throw new Error(c)}}),B(this,"isValidRespond",async s=>{var n;if(!mt(s)){const{message:o}=z("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==null?void 0:s.response)!=null&&n.id&&this.cleanupAfterResponse(s),o}if(!kv(i)){const{message:o}=z("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(o)}}),B(this,"isValidPing",async s=>{if(!mt(s)){const{message:r}=z("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),B(this,"isValidEmit",async s=>{if(!mt(s)){const{message:a}=z("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(!dd(o,i)){const{message:a}=z("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!Pv(r)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Rv(o,i,r.name)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),B(this,"isValidDisconnect",async s=>{if(!mt(s)){const{message:r}=z("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),B(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(!Me(r,!1))throw new Error("uri is required parameter");if(!Me(i,!1))throw new Error("domain is required parameter");if(!Me(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Ss(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Ss(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),B(this,"getVerifyContext",async s=>{const{attestationId:n,hash:r,encryptedId:i,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||Wr,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Oe.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}),B(this,"validateSessionProps",(s,n)=>{Object.values(s).forEach((r,i)=>{if(r==null){const{message:o}=z("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${r} for key ${Object.keys(s)[i]}`);throw new Error(o)}})}),B(this,"getPendingAuthRequest",s=>{const n=this.client.auth.requests.get(s);return typeof n=="object"?n:void 0}),B(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)}}}),B(this,"checkRecentlyDeleted",s=>{const n=this.recentlyDeletedMap.get(s);if(n){const{message:r}=z("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${s}`);throw new Error(r)}}),B(this,"isLinkModeEnabled",(s,n)=>{var r,i,o,a,c,l,d,u,h;return!s||n!==Oe.link_mode?!1:((i=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:i.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((d=s==null?void 0:s.redirect)==null?void 0:d.universal)!==void 0&&((u=s==null?void 0:s.redirect)==null?void 0:u.universal)!==""&&((h=s==null?void 0:s.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),B(this,"getAppLinkIfEnabled",(s,n)=>{var r;return this.isLinkModeEnabled(s,n)?(r=s==null?void 0:s.redirect)==null?void 0:r.universal:void 0}),B(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const n=Cl(s,"topic")||"",r=decodeURIComponent(Cl(s,"wc_ev")||""),i=this.client.session.keys.includes(n);i&&this.client.session.update(n,{transportType:Oe.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:r,sessionExists:i})}),B(this,"registerLinkModeListeners",async()=>{var s;if(wc()||tn()&&(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)}}}),B(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}),B(this,"isValidContractData",s=>{var n;if(!s)return!1;try{const r=(s==null?void 0:s.data)||((n=s==null?void 0:s[0])==null?void 0:n.data);if(!r.startsWith("0x"))return!1;const i=r.slice(2);return/^[0-9a-fA-F]*$/.test(i)?i.length%2===0:!1}catch{}return!1}),B(this,"extractTxHashesFromResult",(s,n)=>{var r;try{if(!n)return[];const i=s.method,o=MI[i];if(i==="sui_signTransaction")return[Zw(n.transactionBytes)];if(i==="near_signTransaction")return[kl(n)];if(i==="near_signTransactions")return n.map(c=>kl(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(r=n.tx_json)==null?void 0:r.hash];if(i==="polkadot_signTransaction")return[Xv({transaction:s.params.transactionPayload,signature:n.signature})];if(i==="algo_signTxn")return Os(n)?n.map(c=>Pl(c)):[Pl(n)];if(i==="cosmos_signDirect")return[eb(n)];if(i==="wallet_sendCalls")return tb(n);if(typeof n=="string")return[n];const a=n[o.key];if(Os(a))return i==="solana_signAllTransactions"?a.map(c=>Xw(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}=z("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(Wi)?this.client.auth.authKeys.get(Wi):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,n,{receiverPublicKey:o,encoding:i===Oe.link_mode?Vs:wt});uc(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:r,transportType:i,encryptedId:Lt(n)})):hc(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(Dt.expired,async e=>{const{topic:s,id:n}=lh(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,z("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,z("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(hn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(hn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Me(e,!1)){const{message:s}=z("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}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(is(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=z("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!Me(e,!1)){const{message:s}=z("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}=z("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(is(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=z("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=z("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(Me(e,!1)){const{message:s}=z("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=z("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!Sv(e)){const{message:s}=z("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=z("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(is(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=z("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class QI extends Un{constructor(e,s){super(e,s,DI,kc),this.core=e,this.logger=s}}let eA=class extends Un{constructor(e,s){super(e,s,LI,kc),this.core=e,this.logger=s}};class tA extends Un{constructor(e,s){super(e,s,jI,kc,n=>n.id),this.core=e,this.logger=s}}class sA extends Un{constructor(e,s){super(e,s,zI,Oo,()=>Wi),this.core=e,this.logger=s}}class nA extends Un{constructor(e,s){super(e,s,HI,Oo),this.core=e,this.logger=s}}class rA extends Un{constructor(e,s){super(e,s,KI,Oo,n=>n.id),this.core=e,this.logger=s}}var iA=Object.defineProperty,oA=(t,e,s)=>e in t?iA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ia=(t,e,s)=>oA(t,typeof e!="symbol"?e+"":e,s);class aA{constructor(e,s){this.core=e,this.logger=s,ia(this,"authKeys"),ia(this,"pairingTopics"),ia(this,"requests"),this.authKeys=new sA(this.core,this.logger),this.pairingTopics=new nA(this.core,this.logger),this.requests=new rA(this.core,this.logger)}
14async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}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,fe=(t,e,s)=>lA(t,typeof e!="symbol"?e+"":e,s);let dA=class Op extends Mm{constructor(e){super(e),fe(this,"protocol",_p),fe(this,"version",Sp),fe(this,"name",na.name),fe(this,"metadata"),fe(this,"core"),fe(this,"logger"),fe(this,"events",new kn.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==null?void 0:e.name)||na.name,this.metadata=zy(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const s=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:ci(wo({level:(e==null?void 0:e.logger)||na.logger}));this.core=(e==null?void 0:e.core)||new UI(e),this.logger=lt(s,this.name),this.session=new eA(this.core,this.logger),this.proposal=new QI(this.core,this.logger),this.pendingRequest=new tA(this.core,this.logger),this.engine=new ZI(this),this.auth=new aA(this.core,this.logger)}static async init(e){const s=new Op(e);return await s.initialize(),s}get context(){return Et(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 Fd="error",uA="wss://relay.walletconnect.org",hA="wc",pA="universal_provider",Pi=`${hA}@2:${pA}:`,kp="https://rpc.walletconnect.org/v1/",Pp="generic",fA=`${kp}bundler`,sr="call_status",gA=86400,Pc={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function xc(t){return t==null||typeof t!="object"&&typeof t!="function"}function xp(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}
14function Rp(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const mA="[object RegExp]",$p="[object String]",Up="[object Number]",Dp="[object Boolean]",Lp="[object Arguments]",yA="[object Symbol]",wA="[object Date]",bA="[object Map]",vA="[object Set]",EA="[object Array]",CA="[object ArrayBuffer]",IA="[object Object]",AA="[object DataView]",NA="[object Uint8Array]",_A="[object Uint8ClampedArray]",SA="[object Uint16Array]",TA="[object Uint32Array]",OA="[object Int8Array]",kA="[object Int16Array]",PA="[object Int32Array]",xA="[object Float32Array]",RA="[object Float64Array]";function Rc(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function $A(t,e){return Qn(t,void 0,t,new Map,e)}function Qn(t,e,s,n=new Map,r=void 0){const i=r==null?void 0:r(t,e,s,n);if(i!=null)return i;if(xc(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]=Qn(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,Qn(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(Qn(a,void 0,s,n,r));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(Rc(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=Qn(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),pn(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),pn(o,t,s,n,r),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),pn(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,pn(o,t,s,n,r),o}if(typeof t=="object"&&UA(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),pn(o,t,s,n,r),o}return t}function pn(t,e,s=t,n,r){const i=[...Object.keys(e),...xp(e)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Qn(e[a],a,s,n,r))}}function UA(t){switch(Rp(t)){case Lp:case EA:case CA:case AA:case Dp:case wA:case xA:case RA:case OA:case kA:case PA:case bA:case Up:case IA:case mA:case vA:case $p:case yA:case NA:case _A:case SA:case TA:return!0;default:return!1}}function DA(t,e){return $A(t,(s,n,r,i)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Up:case $p:case Dp:{const o=new t.constructor(t==null?void 0:t.valueOf());return pn(o,t),o}case Lp:{const o={};return pn(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function qd(t){return DA(t)}function Wd(t){return t!==null&&typeof t=="object"&&Rp(t)==="[object Arguments]"}function zd(t){return typeof t=="object"&&t!==null}function LA(){}function BA(t){return Rc(t)}function MA(t){var s;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const n=t[Symbol.toStringTag];return n==null||!((s=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&s.writable)?!1:t.toString()===`[object ${n}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function jA(t){if(xc(t))return t;if(Array.isArray(t)||Rc(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);
vendor: 4,213 bytes, line 14
14return 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 FA(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=nc(r,o,n,new Map)}return r}function nc(t,e,s,n){if(xc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return jA(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),...xp(e)];for(let i=0;i<r.length;i++){const o=r[i];let a=e[o],c=t[o];if(Wd(a)&&(a={...a}),Wd(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=qd(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const d=[],u=Reflect.ownKeys(c);for(let h=0;h<u.length;h++){const p=u[h];d[p]=c[p]}c=d}else c=[];const l=s(c,a,o,t,e,n);l!=null?t[o]=l:Array.isArray(a)||zd(c)&&zd(a)?t[o]=nc(c,a,s,n):c==null&&MA(a)?t[o]=nc({},a,s,n):c==null&&BA(a)?t[o]=qd(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function qA(t,...e){return FA(t,...e,LA)}var WA=Object.defineProperty,zA=Object.defineProperties,HA=Object.getOwnPropertyDescriptors,Hd=Object.getOwnPropertySymbols,KA=Object.prototype.hasOwnProperty,VA=Object.prototype.propertyIsEnumerable,Kd=(t,e,s)=>e in t?WA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xi=(t,e)=>{for(var s in e||(e={}))KA.call(e,s)&&Kd(t,s,e[s]);if(Hd)for(var s of Hd(e))VA.call(e,s)&&Kd(t,s,e[s]);return t},GA=(t,e)=>zA(t,HA(e));function Bp(t,e,s){var n;const r=Ss(t);return((n=e.rpcMap)==null?void 0:n[r.reference])||`${kp}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function YA(t){return t.includes(":")?t.split(":")[1]:t}function Mp(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function JA(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 Vd(t){return Object.fromEntries(Object.entries(t).filter(([e,s])=>{var n,r;return((n=s==null?void 0:s.chains)==null?void 0:n.length)&&((r=s==null?void 0:s.chains)==null?void 0:r.length)>0}))}function Ri(t={},e={}){const s=Vd(Gd(t)),n=Vd(Gd(e));return qA(s,n)}function Gd(t){var e,s,n,r,i;const o={};if(!us(t))return o;for(const[a,c]of Object.entries(t)){const l=So(a)?[a]:c.chains,d=c.methods||[],u=c.events||[],h=c.rpcMap||{},p=Zn(a);o[p]=GA(xi(xi({},o[p]),c),{chains:ds(l,(e=o[p])==null?void 0:e.chains),methods:ds(d,(s=o[p])==null?void 0:s.methods),events:ds(u,(n=o[p])==null?void 0:n.events)}),(us(h)||us(((r=o[p])==null?void 0:r.rpcMap)||{}))&&(o[p].rpcMap=xi(xi({},h),(i=o[p])==null?void 0:i.rpcMap))}return o}function Yd(t){return t.includes(":")?t.split(":")[2]:t}function Jd(t){const e={};for(const[s,n]of Object.entries(t)){const r=n.methods||[],i=n.events||[],o=n.accounts||[],a=So(s)?[s]:n.chains?n.chains:Mp(n.accounts);e[s]={chains:a,methods:r,events:i,accounts:o}}return e}function oa(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 XA(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const jp={},nr=t=>jp[t],aa=(t,e)=>{jp[t]=e};var ZA=Object.defineProperty,Xd=Object.getOwnPropertySymbols,QA=Object.prototype.hasOwnProperty,eN=Object.prototype.propertyIsEnumerable,Zd=(t,e,s)=>e in t?ZA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qd=(t,e)=>{for(var s in e||(e={}))QA.call(e,s)&&Zd(t,s,e[s]);if(Xd)for(var s of Xd(e))eN.call(e,s)&&Zd(t,s,e[s]);return t};const eu="eip155",tN=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],sN=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,ca=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,tu=t=>Object.keys(t).filter(e=>tN.includes(e)).reduce((e,s)=>(e[s]=nN(t[s]),e),{}),nN=t=>typeof t=="string"&&XA(t)?JSON.parse(t):t,rN=(t,e,s)=>{const{sessionProperties:n={},scopedProperties:r={}}=t,i={};if(!us(r)&&!us(n))return;const o=tu(n);for(const a of s){const c=sN(a);if(!c)continue;i[ca(c)]=o;const l=r==null?void 0:r[`${eu}
14:${c}`];if(l){const d=l==null?void 0:l[`${eu}:${c}:${e}`];i[ca(c)]=Qd(Qd({},i[ca(c)]),tu(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 iN=Object.defineProperty,oN=(t,e,s)=>e in t?iN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,aN=(t,e,s)=>oN(t,e+"",s);let la;class $c{constructor(e){aN(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 la||(la=new $c(e)),la}}var cN=Object.defineProperty,lN=Object.defineProperties,dN=Object.getOwnPropertyDescriptors,su=Object.getOwnPropertySymbols,uN=Object.prototype.hasOwnProperty,hN=Object.prototype.propertyIsEnumerable,nu=(t,e,s)=>e in t?cN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pN=(t,e)=>{for(var s in e||(e={}))uN.call(e,s)&&nu(t,s,e[s]);if(su)for(var s of su(e))hN.call(e,s)&&nu(t,s,e[s]);return t},fN=(t,e)=>lN(t,dN(e));async function gN(t,e){const s=Ss(t.result.capabilities.caip345.caip2),n=t.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(n.map(u=>mN(s.reference,u,e))),i=r.filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u);r.filter(u=>u.status==="rejected").forEach(u=>console.warn("Failed to fetch transaction receipt:",u.reason));const o=!i.length||i.some(u=>!u),a=i.every(u=>(u==null?void 0:u.status)==="0x1"),c=i.every(u=>(u==null?void 0:u.status)==="0x0"),l=i.some(u=>(u==null?void 0:u.status)==="0x0");let d;return o?d=100:a?d=200:c?d=500:l&&(d=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:i,status:d}}async function mN(t,e,s){return await s(parseInt(t)).request(ns("eth_getTransactionReceipt",[e]))}async function yN({sendCalls:t,storage:e}){const s=await e.getItem(sr);await e.setItem(sr,fN(pN({},s),{[t.result.id]:{request:t.request,result:t.result,expiry:Be(gA)}}))}async function wN({resultId:t,storage:e}){const s=await e.getItem(sr);if(s){delete s[t],await e.setItem(sr,s);for(const n in s)is(s[n].expiry)&&delete s[n];await e.setItem(sr,s)}}async function bN({resultId:t,storage:e}){const s=await e.getItem(sr),n=s==null?void 0:s[t];if(n&&!is(n.expiry))return n;await wN({resultId:t,storage:e})}var vN=Object.defineProperty,EN=Object.defineProperties,CN=Object.getOwnPropertyDescriptors,ru=Object.getOwnPropertySymbols,IN=Object.prototype.hasOwnProperty,AN=Object.prototype.propertyIsEnumerable,rc=(t,e,s)=>e in t?vN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,da=(t,e)=>{for(var s in e||(e={}))IN.call(e,s)&&rc(t,s,e[s]);if(ru)for(var s of ru(e))AN.call(e,s)&&rc(t,s,e[s]);return t},ua=(t,e)=>EN(t,CN(e)),cn=(t,e,s)=>rc(t,typeof e!="symbol"?e+"":e,s);class NN{constructor(e){cn(this,"name","eip155"),cn(this,"client"),cn(this,"chainId"),cn(this,"namespace"),cn(this,"httpProviders"),cn(this,"events"),cn(this,"storage"),this.namespace=e.namespace,this.events=nr("events"),this.client=nr("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=$c.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(Pc.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||Bp(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dc(new ku(n,nr("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(YA(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=ua(da({},this.httpProviders),{[s]:this.createHttpProvider(s)}),this.httpProviders[s])}async handleSwitchChain(e){var s,n;let r=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const i=parseInt(r,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${i}`);else throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,n,r,i,o;const a=(n=(s=e.request)==null?void 0:s.params)==null?void 0:n[0],c=((i=(r=e.request)==null?void 0:r.params)==null?void 0:i[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),d=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{},u=`${a}${c.join(",")}`,h=d==null?void 0:d[u];if(h)return h;let p;try{p=rN(l,a,c)}catch(m){console.warn("Failed to extract capabilities from session",m)}if(p)return p;const y=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ua(da({},l.sessionProperties||{}),{capabilities:ua(da({},d||{}),{[u]:y})})})}catch(m){console.warn("Failed to update session with capabilities",m)}return y}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 bN({resultId:(r=e.request.params)==null?void 0:r[0],storage:this.storage});if(c)try{return await gN(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;
14const r=new URL(e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ns("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`${fA}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}async sendCalls(e){var s,n,r;const i=await this.client.request(e),o=(s=e.request.params)==null?void 0:s[0],a=i==null?void 0:i.id,c=(i==null?void 0:i.capabilities)||{},l=(n=c==null?void 0:c.caip345)==null?void 0:n.caip2,d=(r=c==null?void 0:c.caip345)==null?void 0:r.transactionHashes;return!a||!l||!(d!=null&&d.length)||await yN({sendCalls:{request:o,result:i},storage:this.storage}),i}}var _N=Object.defineProperty,SN=(t,e,s)=>e in t?_N(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,zn=(t,e,s)=>SN(t,typeof e!="symbol"?e+"":e,s);class TN{constructor(e){zn(this,"name",Pp),zn(this,"client"),zn(this,"httpProviders"),zn(this,"events"),zn(this,"namespace"),zn(this,"chainId"),this.namespace=e.namespace,this.events=nr("events"),this.client=nr("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(Pc.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 Ss(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=Ss(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=Ss(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||Bp(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new dc(new ku(n,nr("disableProviderPing")))}}var ON=Object.defineProperty,kN=Object.defineProperties,PN=Object.getOwnPropertyDescriptors,iu=Object.getOwnPropertySymbols,xN=Object.prototype.hasOwnProperty,RN=Object.prototype.propertyIsEnumerable,ic=(t,e,s)=>e in t?ON(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Pr=(t,e)=>{for(var s in e||(e={}))xN.call(e,s)&&ic(t,s,e[s]);if(iu)for(var s of iu(e))RN.call(e,s)&&ic(t,s,e[s]);return t},$i=(t,e)=>kN(t,PN(e)),Rt=(t,e,s)=>ic(t,typeof e!="symbol"?e+"":e,s);let $N=class Fp{constructor(e){Rt(this,"client"),Rt(this,"namespaces"),Rt(this,"optionalNamespaces"),Rt(this,"sessionProperties"),Rt(this,"scopedProperties"),Rt(this,"events",new pc),Rt(this,"rpcProviders",{}),Rt(this,"session"),Rt(this,"providerOpts"),Rt(this,"logger"),Rt(this,"uri"),Rt(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:ci(wo({level:(e==null?void 0:e.logger)||Fd})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const s=new Fp(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:Pr({},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,Gr(i,o))).catch(o=>s(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");
vendor: 11,201 bytes, line 14
14return 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:xe("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=Jd(this.session.namespaces);this.namespaces=Ri(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=Jd(r.namespaces);return this.namespaces=Ri(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(!Os(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 dA.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Fd,relayUrl:this.providerOpts.relayUrl||uA,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=>Zn(s)))];aa("client",this.client),aa("events",this.events),aa("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const n=JA(s,this.session);if((n==null?void 0:n.length)===0)return;const r=Mp(n),i=Ri(this.namespaces,this.optionalNamespaces),o=$i(Pr({},i[s]),{accounts:n,chains:r});switch(s){case"eip155":this.rpcProviders[s]=new NN({namespace:o});break;default:this.rpcProviders[s]=new TN({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&&Os(o)&&this.events.emit("accountsChanged",o.map(Yd))}else if(i.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Zn(o),l=oa(o)!==oa(a)?`${c}:${oa(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=$i(Pr({},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",$i(Pr({},xe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Pc.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged($i(Pr({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Pp]}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=Ri(s,n),this.sessionProperties=r,this.scopedProperties=i}validateChain(e){const[s,n]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,n];if(s&&!Object.keys(this.namespaces||{}).map(o=>Zn(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=Zn(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(Yd);if(!Os(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(`${Pi}/${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(`${Pi}/${e}${n}`)}async deleteFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${Pi}/${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(Pi)&&await this.client.core.storage.removeItem(n)}catch(s){this.logger.warn("Failed to cleanup storage",s)}}};const vs={EIP155:$.CHAIN.EVM,CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH"},ti={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:{[$.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[$.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[$.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[$.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[$.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[$.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-454
140-9e6a2b9cae00"},ConnectorNamesMap:{[$.CONNECTOR_ID.INJECTED]:"Browser Wallet",[$.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[$.CONNECTOR_ID.COINBASE]:"Coinbase",[$.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[$.CONNECTOR_ID.LEDGER]:"Ledger",[$.CONNECTOR_ID.SAFE]:"Safe"}},Je={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,n])=>{e[`${vs.EIP155}:${s}`]=n}),e},isLowerCaseMatch(t,e){return(t==null?void 0:t.toLowerCase())===(e==null?void 0:e.toLowerCase())},getActiveNamespaceConnectedToAuth(){const t=g.state.activeChain;return $.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(e=>q.getConnectorId(e)===$.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 $.CHAIN.EVM;const[e]=t.split(":");return e},getOtherAuthNamespaces(t){return t?$.AUTH_CONNECTOR_SUPPORTED_CHAINS.filter(n=>n!==t):[]},getConnectorStorageInfo(t,e){const n=M.getConnections()[e]??[];return{hasDisconnected:M.isConnectorDisconnected(t,e),hasConnected:n.some(r=>Je.isLowerCaseMatch(r.connectorId,t))}}},UN={extractVersion(t){var n;if(!t||typeof t!="string")return null;const e=/(?:[~^>=<]+\s*)?(?<version>\d+(?:\.\d+){0,2})(?:-[a-zA-Z]+\.\d+)?/u,s=t.match(e);return((n=s==null?void 0:s.groups)==null?void 0:n.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}},DN=new AbortController,$t={EmbeddedWalletAbortController:DN,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 ${Rr()?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"}}},qp={TOKEN_ADDRESSES_BY_SYMBOL:{USDC:{8453:xg.asset,84532:Rg.asset}},getTokenSymbolByAddress(t){if(!t)return;const[e]=Object.entries(qp.TOKEN_ADDRESSES_BY_SYMBOL).find(([s,n])=>Object.values(n).includes(t))??[];return e}};var ha,ou;function LN(){if(ou)return ha;ou=1;const t=lc();ha=r;const e=j().console||{},s={mapHttpRequest:y,mapHttpResponse:y,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:y,res:y,err:h};function n(f,v){return Array.isArray(f)?f.filter(function(_){return _!=="!stdSerializers.err"}):f===!0?Object.keys(v):!1}function r(f){f=f||{},f.browser=f.browser||{};const v=f.browser.transmit;if(v&&typeof v.send!="function")throw Error("pino: transmit option must have a send function");const C=f.browser.write||e;f.browser.write&&(f.browser.asObject=!0);const _=f.serializers||{},S=n(f.browser.serialize,_);let U=f.browser.serialize;Array.isArray(f.browser.serialize)&&f.browser.serialize.indexOf("!stdSerializers.err")>-1&&(U=!1);const O=["error","fatal","warn","info","debug","trace"];typeof C=="function"&&(C.error=C.fatal=C.warn=C.info=C.debug=C.trace=C),f.enabled===!1&&(f.level="silent");const A=f.level||"info",b=Object.create(C);b.log||(b.log=w),Object.defineProperty(b,"levelVal",{get:x}),Object.defineProperty(b,"level",{get:L,set:F});const N={transmit:v,serialize:S,asObject:f.browser.asObject,levels:O,timestamp:p(f)};b.levels=r.levels,b.level=A,b.setMaxListeners=b.getMaxListeners=b.emit=b.addListener=b.on=b.prependListener=b.once=b.prependOnceListener=b.removeListener=b.removeAllListeners=b.listeners=b.listenerCount=b.eventNames=b.write=b.flush=w,b.serializers=_,b._serialize=S,b._stdErrSerialize=U,b.child=P,v&&(b._logEvent=u());function x(){return this.level==="silent"?1/0:this.levels.values[this.level]}function L(){return this._level}function F(T){if(T!=="silent"&&!this.levels.values[T])throw Error("unknown level "+T);this._level=T,i(N,b,"error","log"),i(N,b,"fatal","error"),i(N,b,"warn","error"),i(N,b,"info","log"),i(N,b,"debug","log"),i(N,b,"trace","log")}function P(T,W){if(!T)throw new Error("missing bindings for child Pino");W=W||{},S&&T.serializers&&(W.serializers=T.serializers);const K=W.serializers;if(S&&K){var ie=Object.assign({},_,K),oe=f.browser.serialize===!0?Object.keys(ie):S;delete T.serializers,c([T],oe,ie,this._stdErrSerialize)}function se(X){this._childLevel=(X._childLevel|0)+1,this.error=l(X,T,"error"),this.fatal=l(X,T,"fatal"),this.warn=l(X,T,"warn"),this.info=l(X,T,"info"),this.debug=l(X,T,"debug"),this.trace=l(X,T,"trace"),ie&&(this.serializers=ie,this._serialize=oe),v&&(this._logEvent=u([].concat(X._logEvent.bindings,T)))}return se.prototype=this,new se(this)}return b}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:E,epochTime:I,unixTime:k,isoTime:D});function i(f,v,C,_){const S=Object.getPrototypeOf(v);v[C]=v.levelVal>
14v.levels.values[C]?w:S[C]?S[C]:e[C]||e[_]||w,o(f,v,C)}function o(f,v,C){!f.transmit&&v[C]===w||(v[C]=(function(_){return function(){const U=f.timestamp(),O=new Array(arguments.length),A=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var b=0;b<O.length;b++)O[b]=arguments[b];if(f.serialize&&!f.asObject&&c(O,this._serialize,this.serializers,this._stdErrSerialize),f.asObject?_.call(A,a(this,C,O,U)):_.apply(A,O),f.transmit){const N=f.transmit.level||v.level,x=r.levels.values[N],L=r.levels.values[C];if(L<x)return;d(this,{ts:U,methodLevel:C,methodValue:L,transmitValue:r.levels.values[f.transmit.level||v.level],send:f.transmit.send,val:v.levelVal},O)}}})(v[C]))}function a(f,v,C,_){f._serialize&&c(C,f._serialize,f.serializers,f._stdErrSerialize);const S=C.slice();let U=S[0];const O={};_&&(O.time=_),O.level=r.levels.values[v];let A=(f._childLevel|0)+1;if(A<1&&(A=1),U!==null&&typeof U=="object"){for(;A--&&typeof S[0]=="object";)Object.assign(O,S.shift());U=S.length?t(S.shift(),S):void 0}else typeof U=="string"&&(U=t(S.shift(),S));return U!==void 0&&(O.msg=U),O}function c(f,v,C,_){for(const S in f)if(_&&f[S]instanceof Error)f[S]=r.stdSerializers.err(f[S]);else if(typeof f[S]=="object"&&!Array.isArray(f[S]))for(const U in f[S])v&&v.indexOf(U)>-1&&U in C&&(f[S][U]=C[U](f[S][U]))}function l(f,v,C){return function(){const _=new Array(1+arguments.length);_[0]=v;for(var S=1;S<_.length;S++)_[S]=arguments[S-1];return f[C].apply(this,_)}}function d(f,v,C){const _=v.send,S=v.ts,U=v.methodLevel,O=v.methodValue,A=v.val,b=f._logEvent.bindings;c(C,f._serialize||Object.keys(f.serializers),f.serializers,f._stdErrSerialize===void 0?!0:f._stdErrSerialize),f._logEvent.ts=S,f._logEvent.messages=C.filter(function(N){return b.indexOf(N)===-1}),f._logEvent.level.label=U,f._logEvent.level.value=O,_(U,f._logEvent,A),f._logEvent=u(b)}function u(f){return{ts:0,messages:[],bindings:f||[],level:{label:"",value:0}}}function h(f){const v={type:f.constructor.name,msg:f.message,stack:f.stack};for(const C in f)v[C]===void 0&&(v[C]=f[C]);return v}function p(f){return typeof f.timestamp=="function"?f.timestamp:f.timestamp===!1?E:I}function y(){return{}}function m(f){return f}function w(){}function E(){return!1}function I(){return Date.now()}function k(){return Math.round(Date.now()/1e3)}function D(){return new Date(Date.now()).toISOString()}function j(){function f(v){return typeof v<"u"&&v}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 f(self)||f(window)||f(this)||{}}}return ha}var Vn=LN();const Wp=Tu(Vn),BN={level:"info"},Uc=1e3*1024;class MN{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}}let au=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const s=new MN(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}}}}},zp=class{constructor(e,s=Uc){this.level=e??"error",this.levelValue=Vn.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=s,this.logs=new au(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,s){s===Vn.levels.values.error?console.error(e):s===Vn.levels.values.warn?console.warn(e):s===Vn.levels.values.debug?console.debug(e):s===Vn.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(In({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 au(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const s=this.getLogArray();return s.push(In({extraMetadata:e})),new Blob(s,{type:"application/json"})}},jN=class{constructor(e,s=Uc){this.baseChunkLogger=new zp(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)}},FN=class{constructor(e,s=Uc){this.baseChunkLogger=new zp(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 qN=Object.defineProperty,WN=Object.defineProperties,zN=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,HN=Object.prototype.hasOwnProperty,KN=Object.prototype.propertyIsEnumerable,lu=(t,e,s)=>e in t?qN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,uo=(t,e)=>{for(var s in e||(e={}))HN.call(e,s)&&lu(t,s,e[s]);if(cu)for(var s of cu(e))KN.call(e,s)&&lu(t,s,e[s]);return t},ho=(t,e)=>WN(t,zN(e));function VN(t){return ho(uo({},t),{level:(t==null?void 0:t.level)||BN.level})}function GN(t){var e,s;const n=new jN((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Wp(ho(uo({},t.opts),{level:"trace",browser:ho(uo({},(s=t.opts)==null?void 0:s.browser),{write:r=>n.write(r)})}
14)),chunkLoggerController:n}}function YN(t){var e;const s=new FN((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Wp(ho(uo({},t.opts),{level:"trace"}),s),chunkLoggerController:s}}function JN(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?GN(t):YN(t)}const XN={createLogger(t,e="error"){const s=VN({level:e}),{logger:n}=JN({opts:s});return n.error=(...r)=>{for(const i of r)if(i instanceof Error){t(i,...r);return}t(void 0,...r)},n}},ZN="rpc.walletconnect.org";function du(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 pa=["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"],Gn={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===ZN}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:$.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${$.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){var r,i,o;const n=(o=(i=(r=t.rpcUrls)==null?void 0:r.default)==null?void 0:i.http)==null?void 0:o[0];return pa.includes(e)?du(e,s):n||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){var h,p,y,m,w,E,I;const r=this.getChainNamespace(t),i=this.getCaipNetworkId(t),o=(y=(p=(h=t.rpcUrls)==null?void 0:h.default)==null?void 0:p.http)==null?void 0:y[0],a=this.getDefaultRpcUrl(t,i,s),c=((E=(w=(m=t==null?void 0:t.rpcUrls)==null?void 0:m.chainDefault)==null?void 0:w.http)==null?void 0:E[0])||o,l=((I=n==null?void 0:n[i])==null?void 0:I.map(k=>k.url))||[],d=[...l,...a?[a]:[]],u=[...l];return c&&!u.includes(c)&&u.push(c),{...t,chainNamespace:r,caipNetworkId:i,assets:{imageId:ti.NetworkImageIds[t.id],imageUrl:e==null?void 0:e[t.id]},rpcUrls:{...t.rpcUrls,default:{http:d},chainDefault:{http:u}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){return t.map(r=>Gn.extendCaipNetwork(r,{customNetworkImageUrls:e,customRpcUrls:n,projectId:s}))},getViemTransport(t,e,s){var r,i,o;const n=[];return s==null||s.forEach(a=>{n.push(bi(a.url,a.config))}),pa.includes(t.caipNetworkId)&&n.push(bi(du(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),(o=(i=(r=t==null?void 0:t.rpcUrls)==null?void 0:r.default)==null?void 0:i.http)==null||o.forEach(a=>{n.push(bi(a))}),qc(n)},extendWagmiTransports(t,e,s){if(pa.includes(t.caipNetworkId)){const n=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return qc([s,bi(n)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:$.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){var c;const e=M.getActiveCaipNetworkId(),s=g.getAllRequestedCaipNetworks(),n=Array.from(((c=g.state.chains)==null?void 0:c.keys())||[]),r=e==null?void 0:e.split(":")[0],i=r?n.includes(r):!1,o=s==null?void 0:s.find(l=>l.caipNetworkId===e);return i&&!o&&e?this.getUnsupportedNetwork(e):o||t||(s==null?void 0:s[0])}},QN={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"]},Lr={filterOutDuplicatesByRDNS(t){const e=R.state.enableEIP6963?q.state.connectors:[],s=M.getRecentWallets(),n=e.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}
14).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!=null&&a.rdns&&i.includes(String(a.rdns))||!(a!=null&&a.rdns)&&e.some(l=>l.name===a.name)))},filterOutDuplicatesByIds(t){const e=q.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=M.getRecentWallets(),n=e.map(a=>a.explorerId),r=s.map(a=>a.id),i=n.concat(r);return t.filter(a=>!i.includes(a==null?void 0:a.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=q.state,{featuredWalletIds:s}=R.state,n=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>{var c;return(c=a.info)!=null&&c.rdns&&(o[a.info.rdns]=!0),o},{});return t.map(o=>({...o,installed:!!o.rdns&&!!n[o.rdns??""]})).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(s!=null&&s.length){const l=s.indexOf(o.id),d=s.indexOf(a.id);if(l!==-1&&d!==-1)return l-d;if(l!==-1)return-1;if(d!==-1)return 1}return 0})},getConnectOrderMethod(t,e){var c;const s=(t==null?void 0:t.connectMethodsOrder)||((c=R.state.features)==null?void 0:c.connectMethodsOrder),n=e||q.state.connectors;if(s)return s;const{injected:r,announced:i}=zi.getConnectorsByType(n,te.state.recommended,te.state.featured),o=r.filter(zi.showConnector),a=i.filter(zi.showConnector);return o.length||a.length?["wallet","email","social"]:QN.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&te.state.excludedWallets.some(n=>n.rdns===t.rdns),s=!!t.name&&te.state.excludedWallets.some(n=>Je.isLowerCaseMatch(n.name,t.name));return e||s},markWalletsWithDisplayIndex(t){return t.map((e,s)=>({...e,display_index:s}))}},zi={getConnectorsByType(t,e,s){const{customWallets:n}=R.state,r=M.getRecentWallets(),i=Lr.filterOutDuplicateWallets(e),o=Lr.filterOutDuplicateWallets(s),a=t.filter(u=>u.type==="MULTI_CHAIN"),c=t.filter(u=>u.type==="ANNOUNCED"),l=t.filter(u=>u.type==="INJECTED"),d=t.filter(u=>u.type==="EXTERNAL");return{custom:n,recent:r,external:d,multiChain:a,announced:c,injected:l,recommended:i,featured:o}},showConnector(t){var r;const e=(r=t.info)==null?void 0:r.rdns,s=!!e&&te.state.excludedWallets.some(i=>!!i.rdns&&i.rdns===e),n=!!t.name&&te.state.excludedWallets.some(i=>Je.isLowerCaseMatch(i.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!J.isMobile()||J.isMobile()&&!e&&!H.checkInstalled())||s||n)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||n))},getIsConnectedWithWC(){return Array.from(g.state.chains.values()).some(s=>q.getConnectorId(s.namespace)===$.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:n,announced:r,injected:i,multiChain:o,external:a,overriddenConnectors:c=(l=>(l=R.state.features)==null?void 0:l.connectorTypeOrder)()??[]}){const u=[{type:"walletConnect",isEnabled:!0},{type:"recent",isEnabled:n.length>0},{type:"injected",isEnabled:[...i,...r,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(m=>m.isEnabled),h=new Set(u.map(m=>m.type)),p=c.filter(m=>h.has(m)).map(m=>({type:m,isEnabled:!0})),y=u.filter(({type:m})=>!p.some(({type:E})=>E===m));return Array.from(new Set([...p,...y].map(({type:m})=>m)))},sortConnectorsByExplorerWallet(t){return[...t].sort((e,s)=>e.explorerWallet&&s.explorerWallet?(e.explorerWallet.order??0)-(s.explorerWallet.order??0):e.explorerWallet?-1:s.explorerWallet?1:0)},getAuthName({email:t,socialUsername:e,socialProvider:s}){return e?s&&s==="discord"&&e.endsWith("0")?e.slice(0,-1):e:t.length>30?`${t.slice(0,-3)}...`:t},async fetchProviderData(t){var e,s;try{if(t.name==="Browser Wallet"&&!J.isMobile())return{accounts:[],chainId:void 0};if(t.id===$.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};const[n,r]=await Promise.all([(e=t.provider)==null?void 0:e.request({method:"eth_accounts"}),(s=t.provider)==null?void 0:s.request({method:"eth_chainId"}).then(i=>Number(i))]);return{accounts:n,chainId:r}}catch(n){return console.warn(`Failed to fetch provider data for ${t.name}`,n),{accounts:[],chainId:void 0}}},getFilteredCustomWallets(t){const e=M.getRecentWallets(),s=q.state.connectors.map(o=>{var a;return(a=o.info)==null?void 0:a.rdns}
14).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==null?void 0:o.rdns)))},hasWalletConnector(t){return q.state.connectors.some(e=>e.id===t.id||e.name===t.name)},isWalletCompatibleWithCurrentChain(t){const e=g.state.activeChain;return e&&t.chains?t.chains.some(s=>{const n=s.split(":")[0];return e===n}):!0},getFilteredRecentWallets(){return M.getRecentWallets().filter(s=>!Lr.isExcluded(s)).filter(s=>!this.hasWalletConnector(s)).filter(s=>this.isWalletCompatibleWithCurrentChain(s))},getCappedRecommendedWallets(t){const{connectors:e}=q.state,{customWallets:s,featuredWalletIds:n}=R.state,r=e.find(I=>I.id==="walletConnect"),i=e.filter(I=>I.type==="INJECTED"||I.type==="ANNOUNCED"||I.type==="MULTI_CHAIN");if(!r&&!i.length&&!(s!=null&&s.length))return[];const o=Ea.isEmailEnabled(),a=Ea.isSocialsEnabled(),c=i.filter(I=>I.name!=="Browser Wallet"),l=(n==null?void 0:n.length)||0,d=(s==null?void 0:s.length)||0,u=c.length||0,h=o?1:0,p=a?1:0,y=l+d+u+h+p,w=Math.max(0,4-y);return w<=0?[]:Lr.filterOutDuplicateWallets(t).slice(0,w)}};/**
15 * @license
16 * Copyright 2019 Google LLC
17 * SPDX-License-Identifier: BSD-3-Clause
18 */const Hi=globalThis,Dc=Hi.ShadowRoot&&(Hi.ShadyCSS===void 0||Hi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Lc=Symbol(),uu=new WeakMap;let Hp=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(Dc&&e===void 0){const n=s!==void 0&&s.length===1;n&&(e=uu.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&uu.set(s,e))}return e}toString(){return this.cssText}};const Gt=t=>new Hp(typeof t=="string"?t:t+"",void 0,Lc),Gs=(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 Hp(s,t,Lc)},e_=(t,e)=>{if(Dc)t.adoptedStyleSheets=e.map(s=>s instanceof CSSStyleSheet?s:s.styleSheet);else for(const s of e){const n=document.createElement("style"),r=Hi.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=s.cssText,t.appendChild(n)}},hu=Dc?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const n of e.cssRules)s+=n.cssText;return Gt(s)})(t):t;/**
19 * @license
20 * Copyright 2017 Google LLC
21 * SPDX-License-Identifier: BSD-3-Clause
22 */const{is:t_,defineProperty:s_,getOwnPropertyDescriptor:n_,getOwnPropertyNames:r_,getOwnPropertySymbols:i_,getPrototypeOf:o_}=Object,Zs=globalThis,pu=Zs.trustedTypes,a_=pu?pu.emptyScript:"",fa=Zs.reactiveElementPolyfillSupport,Hr=(t,e)=>t,oc={toAttribute(t,e){switch(e){case Boolean:t=t?a_: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}},Kp=(t,e)=>!t_(t,e),fu={attribute:!0,type:String,converter:oc,reflect:!1,useDefault:!1,hasChanged:Kp};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Zs.litPropertyMetadata??(Zs.litPropertyMetadata=new WeakMap);let Yn=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,s=fu){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&&s_(this.prototype,e,r)}}static getPropertyDescriptor(e,s,n){const{get:r,set:i}=n_(this.prototype,e)??{get(){return this[s]},set(o){this[s]=o}};return{get:r,set(o){const a=r==null?void 0:r.call(this);i==null||i.call(this,o),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??fu}static _$Ei(){if(this.hasOwnProperty(Hr("elementProperties")))return;const e=o_(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Hr("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Hr("properties"))){const s=this.properties,n=[...r_(s),...i_(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(hu(r))}else e!==void 0&&s.push(hu(e));return s}static _$Eu(e,s){const n=s.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(s=>this.enableUpdating=s),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(s=>s(this))}addController(e){var s;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((s=e.hostConnected)==null||s.call(e))}
vendor: 18,757 bytes, lines 22-32
22removeController(e){var s;(s=this._$EO)==null||s.delete(e)}_$E_(){const e=new Map,s=this.constructor.elementProperties;for(const n of s.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return e_(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(s=>{var n;return(n=s.hostConnected)==null?void 0:n.call(s)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(s=>{var n;return(n=s.hostDisconnected)==null?void 0:n.call(s)})}attributeChangedCallback(e,s,n){this._$AK(e,n)}_$ET(e,s){var i;const n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&n.reflect===!0){const o=(((i=n.converter)==null?void 0:i.toAttribute)!==void 0?n.converter:oc).toAttribute(s,n.type);this._$Em=e,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(e,s){var i,o;const n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const a=n.getPropertyOptions(r),c=typeof a.converter=="function"?{fromAttribute:a.converter}:((i=a.converter)==null?void 0:i.fromAttribute)!==void 0?a.converter:oc;this._$Em=r;const l=c.fromAttribute(s,a.type);this[r]=l??((o=this._$Ej)==null?void 0:o.get(r))??l,this._$Em=null}}requestUpdate(e,s,n,r=!1,i){var o;if(e!==void 0){const a=this.constructor;if(r===!1&&(i=this[e]),n??(n=a.getPropertyOptions(e)),!((n.hasChanged??Kp)(i,s)||n.useDefault&&n.reflect&&i===((o=this._$Ej)==null?void 0:o.get(e))&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,s,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,s,{useDefault:n,reflect:r,wrapped:i},o){n&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,o??s??this[e]),i!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(s=void 0),this._$AL.set(e,s)),r===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(s){Promise.reject(s)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var n;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[i,o]of this._$Ep)this[i]=o;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[i,o]of r){const{wrapped:a}=o,c=this[i];a!==!0||this._$AL.has(i)||c===void 0||this.C(i,void 0,o,c)}}let e=!1;const s=this._$AL;try{e=this.shouldUpdate(s),e?(this.willUpdate(s),(n=this._$EO)==null||n.forEach(r=>{var i;return(i=r.hostUpdate)==null?void 0:i.call(r)}),this.update(s)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(s)}willUpdate(e){}_$AE(e){var s;(s=this._$EO)==null||s.forEach(n=>{var r;return(r=n.hostUpdated)==null?void 0:r.call(n)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(s=>this._$ET(s,this[s]))),this._$EM()}updated(e){}firstUpdated(e){}};Yn.elementStyles=[],Yn.shadowRootOptions={mode:"open"},Yn[Hr("elementProperties")]=new Map,Yn[Hr("finalized")]=new Map,fa==null||fa({ReactiveElement:Yn}),(Zs.reactiveElementVersions??(Zs.reactiveElementVersions=[])).push("2.1.2");/**
23 * @license
24 * Copyright 2017 Google LLC
25 * SPDX-License-Identifier: BSD-3-Clause
26 */const Kr=globalThis,gu=t=>t,po=Kr.trustedTypes,mu=po?po.createPolicy("lit-html",{createHTML:t=>t}):void 0,Vp="$lit$",Ys=`lit$${Math.random().toFixed(9).slice(2)}$`,Gp="?"+Ys,c_=`<${Gp}>`,On=document,si=()=>On.createComment(""),ni=t=>t===null||typeof t!="object"&&typeof t!="function",Bc=Array.isArray,l_=t=>Bc(t)||typeof(t==null?void 0:t[Symbol.iterator])=="function",ga=`[ 	
27\f\r]`,xr=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,yu=/-->/g,wu=/>/g,ln=RegExp(`>|${ga}(?:([^\\s"'>=/]+)(${ga}*=${ga}*(?:[^ 	
28\f\r"'\`<>=]|("|')|))|$)`,"g"),bu=/'/g,vu=/"/g,Yp=/^(?:script|style|textarea|title)$/i,Jp=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),NS=Jp(1),_S=Jp(2),lr=Symbol.for("lit-noChange"),He=Symbol.for("lit-nothing"),Eu=new WeakMap,vn=On.createTreeWalker(On,129);function Xp(t,e){if(!Bc(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return mu!==void 0?mu.createHTML(e):e}const d_=(t,e)=>{const s=t.length-1,n=[];let r,i=e===2?"<svg>":e===3?"<math>":"",o=xr;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===xr?d[1]==="!--"?o=yu:d[1]!==void 0?o=wu:d[2]!==void 0?(Yp.test(d[2])&&(r=RegExp("</"+d[2],"g")),o=ln):d[3]!==void 0&&(o=ln):o===ln?d[0]===">"?(o=r??xr,u=-1):d[1]===void 0?u=-2:(u=o.lastIndex-d[2].length,l=d[1],o=d[3]===void 0?ln:d[3]==='"'?vu:bu):o===vu||o===bu?o=ln:o===yu||o===wu?o=xr:(o=ln,r=void 0);const p=o===ln&&t[a+1].startsWith("/>")?" ":"";i+=o===xr?c+c_:u>=0?(n.push(l),c.slice(0,u)+Vp+c.slice(u)+Ys+p):c+Ys+(u===-2?a:p)}return[Xp(t,i+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class ri{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]=d_(e,s);if(this.el=ri.createElement(l,n),vn.currentNode=this.el.content,s===2||s===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(r=vn.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const u of r.getAttributeNames())if(u.endsWith(Vp)){const h=d[o++],p=r.getAttribute(u).split(Ys),y=/([.?@])?(.*)/.exec(h);c.push({type:1,index:i,name:y[2],strings:p,ctor:y[1]==="."?h_:y[1]==="?"?p_:y[1]==="@"?f_:ko}),r.removeAttribute(u)}else u.startsWith(Ys)&&(c.push({type:6,index:i}),r.removeAttribute(u));if(Yp.test(r.tagName)){const u=r.textContent.split(Ys),h=u.length-1;if(h>0){r.textContent=po?po.emptyScript:"";for(let p=0;p<h;p++)r.append(u[p],si()),vn.nextNode(),c.push({type:2,index:++i});r.append(u[h],si())}}}else if(r.nodeType===8)if(r.data===Gp)c.push({type:2,index:i});else{let u=-1;for(;(u=r.data.indexOf(Ys,u+1))!==-1;)c.push({type:7,index:i}),u+=Ys.length-1}i++}}static createElement(e,s){const n=On.createElement("template");return n.innerHTML=e,n}}function dr(t,e,s=t,n){var o,a;if(e===lr)return e;let r=n!==void 0?(o=s._$Co)==null?void 0:o[n]:s._$Cl;const i=ni(e)?void 0:e._$litDirective$;return(r==null?void 0:r.constructor)!==i&&((a=r==null?void 0:r._$AO)==null||a.call(r,!1),i===void 0?r=void 0:(r=new i(t),r._$AT(t,s,n)),n!==void 0?(s._$Co??(s._$Co=[]))[n]=r:s._$Cl=r),r!==void 0&&(e=dr(t,r._$AS(t,e.values),r,n)),e}class u_{constructor(e,s){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=s}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:s},parts:n}=this._$AD,r=((e==null?void 0:e.creationScope)??On).importNode(s,!0);vn.currentNode=r;let i=vn.nextNode(),o=0,a=0,c=n[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new mi(i,i.nextSibling,this,e):c.type===1?l=new c.ctor(i,c.name,c.strings,this,e):c.type===6&&(l=new g_(i,this,e)),this._$AV.push(l),c=n[++a]}o!==(c==null?void 0:c.index)&&(i=vn.nextNode(),o++)}return vn.currentNode=On,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 mi{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,s,n,r){this.type=2,this._$AH=He,this._$AN=void 0,this._$AA=e,this._$AB=s,this._$AM=n,this.options=r,this._$Cv=(r==null?void 0:r.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const s=this._$AM;return s!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=s.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,s=this){e=dr(this,e,s),ni(e)?e===He||e==null||e===""?(this._$AH!==He&&this._$AR(),this._$AH=He):e!==this._$AH&&e!==lr&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):l_(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&&ni(this._$AH)?this._$AA.nextSibling.data=e:this.T(On.createTextNode(e)),this._$AH=e}$(e){var i;const{values:s,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=ri.createElement(Xp(n.h,n.h[0]),this.options)),n);if(((i=this._$AH)==null?void 0:i._$AD)===r)this._$AH.p(s);else{const o=new u_(r,this),a=o.u(this.options);o.p(s),this.T(a),this._$AH=o}}_$AC(e){let s=Eu.get(e.strings);return s===void 0&&Eu.set(e.strings,s=new ri(e)),s}k(e){Bc(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 mi(this.O(si()),this.O(si()),this,this.options)):n=s[r],n._$AI(i),r++;r<s.length&&(this._$AR(n&&n._$AB.nextSibling,r),s.length=r)}_$AR(e=this._$AA.nextSibling,s){var n;for((n=this._$AP)==null?void 0:n.call(this,!1,!0,s);e!==this._$AB;){const r=gu(e).nextSibling;gu(e).remove(),e=r}}setConnected(e){var s;this._$AM===void 0&&(this._$Cv=e,(s=this._$AP)==null||s.call(this,e))}}class ko{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=dr(this,e,s,0),o=!ni(e)||e!==this._$AH&&e!==lr,o&&(this._$AH=e);else{const a=e;let c,l;for(e=i[0],c=0;c<i.length-1;c++)l=dr(this,a[n+c],s,c),l===lr&&(l=this._$AH[c]),o||(o=!ni(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 h_ extends ko{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===He?void 0:e}}class p_ extends ko{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==He)}}class f_ extends ko{constructor(e,s,n,r,i){super(e,s,n,r,i),this.type=5}_$AI(e,s=this){if((e=dr(this,e,s,0)??He)===lr)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){var s;typeof this._$AH=="function"?this._$AH.call(((s=this.options)==null?void 0:s.host)??this.element,e):this._$AH.handleEvent(e)}}class g_{constructor(e,s,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=s,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){dr(this,e)}}const ma=Kr.litHtmlPolyfillSupport;ma==null||ma(ri,mi),(Kr.litHtmlVersions??(Kr.litHtmlVersions=[])).push("3.3.2");const m_=(t,e,s)=>{const n=(s==null?void 0:s.renderBefore)??e;let r=n._$litPart$;if(r===void 0){const i=(s==null?void 0:s.renderBefore)??null;n._$litPart$=r=new mi(e.insertBefore(si(),i),i,void 0,s??{})}return r._$AI(t),r};/**
29 * @license
30 * Copyright 2017 Google LLC
31 * SPDX-License-Identifier: BSD-3-Clause
32 */const Cn=globalThis;class Ki extends Yn{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var s;const e=super.createRenderRoot();return(s=this.renderOptions).renderBefore??(s.renderBefore=e.firstChild),e}update(e){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=m_(s,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return lr}}var _u;Ki._$litElement$=!0,Ki.finalized=!0,(_u=Cn.litElementHydrateSupport)==null||_u.call(Cn,{LitElement:Ki});const ya=Cn.litElementPolyfillSupport;ya==null||ya({LitElement:Ki});(Cn.litElementVersions??(Cn.litElementVersions=[])).push("4.2.2");const y_={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)"},fo={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"}},w_={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"},b_={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"},v_={regular:"KHTeka",mono:"KHTekaMono"},E_={regular:"400",medium:"500"},C_={h1:"50px",h2:"44px",h3:"38px",h4:"32px",h5:"26px",h6:"20px",large:"16px",medium:"14px",small:"12px"},I_={"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"}}
32,A_={"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)"},N_={xl:"400ms",lg:"200ms",md:"125ms",sm:"75ms"},ac={colors:y_,fontFamily:v_,fontWeight:E_,textSize:C_,typography:I_,tokens:{core:fo.core,theme:fo.dark},borderRadius:w_,spacing:b_,durations:N_,easings:A_},Cu="--apkt",Cs={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]=`${Cu}-${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[`${Cu}-${l}`]=d)}}return n(t,e),s},createRootStyles(t,e){const s={...ac,tokens:{...ac.tokens,theme:t==="light"?fo.light:fo.dark}},{cssVariables:n}=Cs.createCSSVariables(s),r=Cs.assignCSSVariables(n,s),i=Cs.generateW3MVariables(e),o=Cs.generateW3MOverrides(e),a=Cs.generateScaledVariables(e),c=Cs.generateBaseVariables(r),l={...r,...c,...i,...o,...a},d=Cs.applyColorMixToVariables(e,l),u={...l,...d};return`:root {${Object.entries(u).map(([p,y])=>`${p}:${y.replace("/[:;{}</>]/g","")};`).join("")}}`},generateW3MVariables(t){if(!t)return{};const e={};return e["--w3m-font-family"]=t["--w3m-font-family"]||"KHTeka",e["--w3m-accent"]=t["--w3m-accent"]||"#0988F0",e["--w3m-color-mix"]=t["--w3m-color-mix"]||"#000",e["--w3m-color-mix-strength"]=`${t["--w3m-color-mix-strength"]||0}%`,e["--w3m-font-size-master"]=t["--w3m-font-size-master"]||"10px",e["--w3m-border-radius-master"]=t["--w3m-border-radius-master"]||"4px",e},generateW3MOverrides(t){if(!t)return{};const e={};if(t["--w3m-accent"]){const s=t["--w3m-accent"];e["--apkt-tokens-core-iconAccentPrimary"]=s,e["--apkt-tokens-core-borderAccentPrimary"]=s,e["--apkt-tokens-core-textAccentPrimary"]=s,e["--apkt-tokens-core-backgroundAccentPrimary"]=s}return t["--w3m-font-family"]&&(e["--apkt-fontFamily-regular"]=t["--w3m-font-family"]),t["--w3m-z-index"]&&(e["--apkt-tokens-core-zIndex"]=`${t["--w3m-z-index"]}`),e},generateScaledVariables(t){if(!t)return{};const e={};if(t["--w3m-font-size-master"]){const s=parseFloat(t["--w3m-font-size-master"].replace("px",""));e["--apkt-textSize-h1"]=`${Number(s)*5}px`,e["--apkt-textSize-h2"]=`${Number(s)*4.4}px`,e["--apkt-textSize-h3"]=`${Number(s)*3.8}px`,e["--apkt-textSize-h4"]=`${Number(s)*3.2}px`,e["--apkt-textSize-h5"]=`${Number(s)*2.6}px`,e["--apkt-textSize-h6"]=`${Number(s)*2}px`,e["--apkt-textSize-large"]=`${Number(s)*1.6}px`,e["--apkt-textSize-medium"]=`${Number(s)*1.4}px`,e["--apkt-textSize-small"]=`${Number(s)*1.2}px`}if(t["--w3m-border-radius-master"]){const s=parseFloat(t["--w3m-border-radius-master"].replace("px",""));e["--apkt-borderRadius-1"]=`${Number(s)}px`,e["--apkt-borderRadius-2"]=`${Number(s)*2}px`,e["--apkt-borderRadius-3"]=`${Number(s)*3}px`,e["--apkt-borderRadius-4"]=`${Number(s)*4}px`,e["--apkt-borderRadius-5"]=`${Number(s)*5}px`,e["--apkt-borderRadius-6"]=`${Number(s)*6}px`,e["--apkt-borderRadius-8"]=`${Number(s)*8}px`,e["--apkt-borderRadius-16"]=`${Number(s)*16}px`,e["--apkt-borderRadius-20"]=`${Number(s)*20}px`,e["--apkt-borderRadius-32"]=`${Number(s)*32}px`,e["--apkt-borderRadius-64"]=`${Number(s)*64}px`,e["--apkt-borderRadius-128"]=`${Number(s)*128}px`}return e},generateColorMixCSS(t,e){if(!(t!=null&&t["--w3m-color-mix"])||!t["--w3m-color-mix-strength"])return"";const s=t["--w3m-color-mix"],n=t["--w3m-color-mix-strength"];if(!n||n===0)return"";const r=Object.keys(e||{}).filter(o=>{const a=o.includes("-tokens-core-background")||o.includes("-tokens-core-text")||o.includes("-tokens-core-border")||o.includes("-tokens-core-foreground")||o.includes("-tokens-core-icon")||o.includes("-tokens-theme-background")||o.includes("-tokens-theme-text")||o.includes("-tokens-theme-border")||o.includes("-tokens-theme-foreground")||o.includes("-tokens-theme-icon"),c=o.includes("-borderRadius-")||o.includes("-spacing-")||o.includes("-textSize-")||o.includes("-fontFamily-")||o.includes("-fontWeight-")||o.includes("-typography-")||o.includes("-duration-")||o.includes("-ease-")||o.includes("-path-")||o.includes("-width-")||o.includes("-height-")||o.includes("-visual-size-")||o.includes("-modal-width")||o.includes("-cover");return a&&!c});return r.length===0?"":` @supports (background: color-mix(in srgb, white 50%, black)) {
33      :root {
34        ${r.map(o=>{const a=(e==null?void 0:e[o])||"";return a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?`${o}: color-mix(in srgb, ${s} ${n}%, ${a});`:`${o}: color-mix(in srgb, ${s} ${n}%, var(${o}-base, ${a}));`}).join("")}
35      }
36    }`},generateBaseVariables(t){const e={},s=t["--apkt-tokens-theme-backgroundPrimary"];s&&(e["--apkt-tokens-theme-backgroundPrimary-base"]=s);const n=t["--apkt-tokens-core-backgroundAccentPrimary"];return n&&(e["--apkt-tokens-core-backgroundAccentPrimary-base"]=n),e},applyColorMixToVariables(t,e){const s={};if(e!=null&&e["--apkt-tokens-theme-backgroundPrimary"]&&(s["--apkt-tokens-theme-backgroundPrimary"]="var(--apkt-tokens-theme-backgroundPrimary-base)"),e!=null&&e["--apkt-tokens-core-backgroundAccentPrimary"]&&(s["--apkt-tokens-core-backgroundAccentPrimary"]="var(--apkt-tokens-core-backgroundAccentPrimary-base)"),!(t!=null&&t["--w3m-color-mix"])||!t["--w3m-color-mix-strength"])return s;const n=t["--w3m-color-mix"],r=t["--w3m-color-mix-strength"];if(!r||r===0)return s;const i=Object.keys(e||{}).filter(o=>{const a=o.includes("-tokens-core-background")||o.includes("-tokens-core-text")||o.includes("-tokens-core-border")||o.includes("-tokens-core-foreground")||o.includes("-tokens-core-icon")||o.includes("-tokens-theme-background")||o.includes("-tokens-theme-text")||o.includes("-tokens-theme-border")||o.includes("-tokens-theme-foreground")||o.includes("-tokens-theme-icon")||o.includes("-tokens-theme-overlay"),c=o.includes("-borderRadius-")||o.includes("-spacing-")||o.includes("-textSize-")||o.includes("-fontFamily-")||o.includes("-fontWeight-")||o.includes("-typography-")||o.includes("-duration-")||o.includes("-ease-")||o.includes("-path-")||o.includes("-width-")||o.includes("-height-")||o.includes("-visual-size-")||o.includes("-modal-width")||o.includes("-cover");return a&&!c});
36return i.length===0||i.forEach(o=>{const a=(e==null?void 0:e[o])||"";o.endsWith("-base")||(o==="--apkt-tokens-theme-backgroundPrimary"||o==="--apkt-tokens-core-backgroundAccentPrimary"?s[o]=`color-mix(in srgb, ${n} ${r}%, var(${o}-base))`:a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?s[o]=`color-mix(in srgb, ${n} ${r}%, ${a})`:s[o]=`color-mix(in srgb, ${n} ${r}%, var(${o}-base, ${a}))`)}),s}},{cssVariablesVarPrefix:__}=Cs.createCSSVariables(ac);function SS(t,...e){return Gs(t,...e.map(s=>Gt(typeof s=="function"?s(__):s)))}let fn,En,cs,Tt,go;const Es={"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 mo(t,e="dark"){fn&&document.head.removeChild(fn),fn=document.createElement("style"),fn.textContent=Cs.createRootStyles(e,t),document.head.appendChild(fn)}function TS(t,e="dark"){if(go=t,En=document.createElement("style"),cs=document.createElement("style"),Tt=document.createElement("style"),En.textContent=rr(t).core.cssText,cs.textContent=rr(t).dark.cssText,Tt.textContent=rr(t).light.cssText,document.head.appendChild(En),document.head.appendChild(cs),document.head.appendChild(Tt),mo(t,e),cc(e),!(t!=null&&t["--w3m-font-family"]))for(const[s,n]of Object.entries(Es)){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)}cc(e)}function cc(t="dark"){cs&&Tt&&fn&&(t==="light"?(mo(go,t),cs.removeAttribute("media"),Tt.media="enabled"):(mo(go,t),Tt.removeAttribute("media"),cs.media="enabled"))}function S_(t){var e,s,n;if(go=t,En&&cs&&Tt&&(En.textContent=rr(t).core.cssText,cs.textContent=rr(t).dark.cssText,Tt.textContent=rr(t).light.cssText,t!=null&&t["--w3m-font-family"])){const r=t["--w3m-font-family"];En.textContent=(e=En.textContent)==null?void 0:e.replace("font-family: KHTeka",`font-family: ${r}`),cs.textContent=(s=cs.textContent)==null?void 0:s.replace("font-family: KHTeka",`font-family: ${r}`),Tt.textContent=(n=Tt.textContent)==null?void 0:n.replace("font-family: KHTeka",`font-family: ${r}`)}if(fn){const r=(Tt==null?void 0:Tt.media)==="enabled"?"light":"dark";mo(t,r)}}function rr(t){const e=!!(t!=null&&t["--w3m-font-family"]);return{core:Gs`
37      ${e?Gs``:Gs`
38            @font-face {
39              font-family: 'KHTeka';
40              src:
41                url(${Gt(Es["KHTeka-400-woff2"])}) format('woff2'),
42                url(${Gt(Es["KHTeka-400-woff"])}) format('woff');
43              font-weight: 400;
44              font-style: normal;
45              font-display: swap;
46            }
47
48            @font-face {
49              font-family: 'KHTeka';
50              src:
51                url(${Gt(Es["KHTeka-300-woff2"])}) format('woff2'),
52                url(${Gt(Es["KHTeka-300-woff"])}) format('woff');
53              font-weight: 300;
54              font-style: normal;
55            }
56
57            @font-face {
58              font-family: 'KHTekaMono';
59              src:
60                url(${Gt(Es["KHTekaMono-400-woff2"])}) format('woff2'),
61                url(${Gt(Es["KHTekaMono-400-woff"])}) format('woff');
62              font-weight: 400;
63              font-style: normal;
64            }
65
66            @font-face {
67              font-family: 'KHTeka';
68              src:
69                url(${Gt(Es["KHTeka-400-woff2"])}) format('woff2'),
70                url(${Gt(Es["KHTeka-400-woff"])}) format('woff');
71              font-weight: 400;
72              font-style: normal;
73            }
74          `}
75
76      @keyframes w3m-shake {
77        0% {
78          transform: scale(1) rotate(0deg);
79        }
80        20% {
81          transform: scale(1) rotate(-1deg);
82        }
83        40% {
84          transform: scale(1) rotate(1.5deg);
85        }
86        60% {
87          transform: scale(1) rotate(-1.5deg);
88        }
89        80% {
90          transform: scale(1) rotate(1deg);
91        }
92        100% {
93          transform: scale(1) rotate(0deg);
94        }
95      }
96      @keyframes w3m-iframe-fade-out {
97        0% {
98          opacity: 1;
99        }
100        100% {
101          opacity: 0;
102        }
103      }
104      @keyframes w3m-iframe-zoom-in {
105        0% {
106          transform: translateY(50px);
107          opacity: 0;
108        }
109        100% {
110          transform: translateY(0px);
111          opacity: 1;
112        }
113      }
114      @keyframes w3m-iframe-zoom-in-mobile {
115        0% {
116          transform: scale(0.95);
117          opacity: 0;
118        }
119        100% {
120          transform: scale(1);
121          opacity: 1;
122        }
123      }
124      :root {
125        --apkt-modal-width: 370px;
126
127        --apkt-visual-size-inherit: inherit;
128        --apkt-visual-size-sm: 40px;
129        --apkt-visual-size-md: 55px;
130        --apkt-visual-size-lg: 80px;
131
132        --apkt-path-network-sm: path(
133          '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.
13361 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'
134        );
135
136        --apkt-path-network-md: path(
137          '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'
138        );
139
140        --apkt-path-network-lg: path(
141          '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'
142        );
143
144        --apkt-width-network-sm: 36px;
145        --apkt-width-network-md: 48px;
146        --apkt-width-network-lg: 86px;
147
148        --apkt-duration-dynamic: 0ms;
149        --apkt-height-network-sm: 40px;
150        --apkt-height-network-md: 54px;
151        --apkt-height-network-lg: 96px;
152      }
153    `,dark:Gs`
154      :root {
155      }
156    `,light:Gs`
157      :root {
158      }
159    `}}const OS=Gs`
160  div,
161  span,
162  iframe,
163  a,
164  img,
165  form,
166  button,
167  label,
168  *::after,
169  *::before {
170    margin: 0;
171    padding: 0;
172    box-sizing: border-box;
173    font-style: normal;
174    text-rendering: optimizeSpeed;
175    -webkit-font-smoothing: antialiased;
176    -moz-osx-font-smoothing: grayscale;
177    -webkit-tap-highlight-color: transparent;
178    backface-visibility: hidden;
179  }
180
181  :host {
182    font-family: var(--apkt-fontFamily-regular);
183  }
184`,kS=Gs`
185  button,
186  a {
187    cursor: pointer;
188    display: flex;
189    justify-content: center;
190    align-items: center;
191    position: relative;
192
193    will-change: background-color, color, border, box-shadow, width, height, transform, opacity;
194    outline: none;
195    border: none;
196    text-decoration: none;
197    transition:
198      background-color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
199      color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
200      border var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
201      box-shadow var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
202      width var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
203      height var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
204      transform var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
205      opacity var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
206      scale var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
207      border-radius var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2);
208    will-change:
209      background-color, color, border, box-shadow, width, height, transform, opacity, scale,
210      border-radius;
211  }
212
213  a:active:not([disabled]),
214  button:active:not([disabled]) {
215    scale: 0.975;
216    transform-origin: center;
217  }
218
219  button:disabled {
220    cursor: default;
221  }
222
223  input {
224    border: none;
225    outline: none;
226    appearance: none;
227  }
228`,Vi={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([Vi.getAddresses(t),Vi.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){var n,r;const s=((n=e.rpcUrls.chainDefault)==null?void 0:n.http)||[];await t.request({method:"wallet_addEthereumChain",params:[{chainId:Vi.numberToHexString(e.id),rpcUrls:[...s],chainName:e.name,nativeCurrency:{name:e.nativeCurrency.name,decimals:e.nativeCurrency.decimals,symbol:e.nativeCurrency.symbol},blockExplorerUrls:[(r=e.blockExplorers)==null?void 0:r.default.url],iconUrls:[ti.NetworkImageIds[e.id]]}]})}},Hn={ACCOUNT_INDEXES:{PAYMENT:0,ORDINAL:1}};function wr(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const Iu=wr({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"}
228),Au=wr({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"});wr({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"});wr({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});wr({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});wr({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 T_={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"]},Jt={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace(t){return T_[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 Iu.caipNetworkId:d.chains.push(Iu.deprecatedCaipNetworkId);break;case Au.caipNetworkId:d.chains.push(Au.deprecatedCaipNetworkId);break}return d!=null&&d.rpcMap&&c&&(d.rpcMap[i]=c),n},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{var n;const e=await Fr.resolveName(t);return((n=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:n.address)||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],n=e.accounts.map(r=>{const[i,o]=r.split(":");return`${i}:${o}`});return Array.from(new Set([...s,...n]))})}
228,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===Jt.RPC_ERROR_CODE.USER_REJECTED_METHODS,r=s&&e.code===Jt.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=Jt.getWalletConnectAccounts(t,e);s(a)}),n&&t.on("disconnect",()=>{n()}),r&&t.on("accountsChanged",a=>{var c,l,d,u,h;try{const p=((d=(l=(c=t.session)==null?void 0:c.namespaces)==null?void 0:l[e])==null?void 0:d.accounts)||[],y=(h=(u=t.rpcProviders)==null?void 0:u[e])==null?void 0:h.getDefaultChain(),m=a.map(w=>{const E=p.find(D=>D.includes(`${e}:${y}:${w}`));if(!E)return;const{chainId:I,chainNamespace:k}=ot.parseCaipAddress(E);return{address:w,chainId:I,chainNamespace:k}}).filter(w=>w!==void 0);m.length>0&&r(m)}catch(p){console.warn("Failed to parse accounts for namespace on accountsChanged event",e,a,p)}}),i&&t.on("chainChanged",a=>{i(a)}),o&&t.on("display_uri",a=>{o(a)})},getWalletConnectAccounts(t,e){var r,i,o,a;const s=new Set,n=(a=(o=(i=(r=t==null?void 0:t.session)==null?void 0:r.namespaces)==null?void 0:i[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>ot.parseCaipAddress(c)).filter(({address:c})=>s.has(c.toLowerCase())?!1:(s.add(c.toLowerCase()),!0));return n&&n.length>0?n:[]}};class O_{constructor(e){this.namespace=e.namespace}async syncConnections(e){switch(this.namespace){case $.CHAIN.EVM:await this.syncEVMConnections(e);break;case $.CHAIN.SOLANA:await this.syncSolanaConnections(e);break;case $.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}=Je.getConnectorStorageInfo(o.id,this.namespace);return!a&&c}).map(async o=>{if(o.id===$.CONNECTOR_ID.WALLET_CONNECT){const a=Jt.getWalletConnectAccounts(n,this.namespace),c=s.find(l=>{var d,u;return l.chainNamespace===this.namespace&&l.id.toString()===((u=(d=a[0])==null?void 0:d.chainId)==null?void 0:u.toString())});a.length>0&&r({connectorId:o.id,accounts:a.map(l=>({address:l.address})),caipNetwork:c})}else{const{accounts:a,chainId:c}=await zi.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!==$.CONNECTOR_ID.AUTH&&o.id!==$.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}=Je.getConnectorStorageInfo(o.id,this.namespace);return!a&&c}).map(async o=>{if(o.id===$.CONNECTOR_ID.WALLET_CONNECT){const a=Jt.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==null?void 0: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}=Je.getConnectorStorageInfo(o.id,this.namespace);return!a&&c}).map(async o=>{var u,h,p,y,m,w;if(o.id===$.CONNECTOR_ID.WALLET_CONNECT){const E=Jt.getWalletConnectAccounts(n,this.namespace);E.length>0&&r({connectorId:o.id,accounts:E.map(I=>({address:I.address})),caipNetwork:s});return}const a=await o.connect(),c=await o.getAccountAddresses();let l=c==null?void 0:c.map(E=>J.createAccount($.CHAIN.BITCOIN,E.address,E.purpose||"payment",E.publicKey,E.path));if(l&&l.length>1&&(l=[{namespace:$.CHAIN.BITCOIN,publicKey:((u=l[Hn.ACCOUNT_INDEXES.PAYMENT])==null?void 0:u.publicKey)??"",path:((h=l[Hn.ACCOUNT_INDEXES.PAYMENT])==null?void 0:h.path)??"",address:((p=l[Hn.ACCOUNT_INDEXES.PAYMENT])==null?void 0:p.address)??"",type:"payment"},{namespace:$.CHAIN.BITCOIN,publicKey:((y=l[Hn.ACCOUNT_INDEXES.ORDINAL])==null?void 0:y.publicKey)??"",path:((m=l[Hn.ACCOUNT_INDEXES.ORDINAL])==null?void 0:m.path)??"",address:((w=l[Hn.ACCOUNT_INDEXES.ORDINAL])==null?void 0:w.address)??"",type:"ordinal"}
228]),!(o.chains.find(E=>E.id===(s==null?void 0: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(E=>({address:E.address,type:E.type,publicKey:E.publicKey,path:E.path})),caipNetwork:s}))}))}getConnection({address:e,connectorId:s,connections:n,connectors:r}){if(s){const o=n.find(l=>Je.isLowerCaseMatch(l.connectorId,s));if(!o)return null;const a=r.find(l=>Je.isLowerCaseMatch(l.id,o.connectorId)),c=e?o.accounts.find(l=>Je.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=>Je.isLowerCaseMatch(a.id,o.connectorId)));if(i){const[o]=i.accounts,a=r.find(c=>Je.isLowerCaseMatch(c.id,i.connectorId));return{...i,account:o,connector:a}}return null}}const Br={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 Zp{constructor({provider:e,namespace:s}){this.id=$.CONNECTOR_ID.WALLET_CONNECT,this.name=ti.ConnectorNamesMap[$.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=ti.ConnectorImageIds[$.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=g.getCaipNetworks.bind(g),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=s}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const s=this.getCaipNetworks(),n=R.state.universalProviderConfigOverride,r=Jt.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 rs.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:k_})}}const k_=["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"],P_=[$.CONNECTOR_ID.AUTH,$.CONNECTOR_ID.WALLET_CONNECT];class x_{constructor(e){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=s=>g.getCaipNetworks(s),this.getConnectorId=s=>q.getConnectorId(s),e&&this.construct(e),e!=null&&e.namespace&&(this.connectionManager=new O_({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==null?void 0:s.toString()));e&&n&&this.addConnection({connectorId:$.CONNECTOR_ID.AUTH,accounts:e,caipNetwork:n})}setAuthProvider(e){e.onConnect(this.onAuthConnected.bind(this)),e.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:$.CONNECTOR_ID.AUTH,type:"AUTH",name:$.CONNECTOR_NAMES.AUTH,provider:e,imageId:ti.ConnectorImageIds[$.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
228("connections",this.availableConnections)}deleteConnection(e){this.availableConnections=this.availableConnections.filter(s=>!Je.isLowerCaseMatch(s.connectorId,e)),this.emit("connections",this.availableConnections)}clearConnections(e=!1){this.availableConnections=[],e&&this.emit("connections",this.availableConnections)}setStatus(e,s){g.setAccountProp("status",e,s)}on(e,s){var n;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(n=this.eventListeners.get(e))==null||n.add(s)}off(e,s){const n=this.eventListeners.get(e);n&&n.delete(s)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const n=this.eventListeners.get(e);n&&n.forEach(r=>r(s))}async connectWalletConnect(e){try{return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}catch(s){throw Jt.isUserRejectedRequestError(s)?new Uu(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=jt(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 Zp);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==null?void 0:r.toString())),o=this.connectors.find(a=>a.id===s);n&&(this.emit("accountChanged",{address:n,chainId:r,connector:o}),this.addConnection({connectorId:s,accounts:e.map(a=>{const{address:c}=J.getAccount(a);return{address:c}}),caipNetwork:i}))}}onAccountsChanged(e,s,n=!0){var r,i;if(e.length>0){const{address:o}=J.getAccount(e[0]),a=(r=this.connectionManager)==null?void 0:r.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors});o&&Je.isLowerCaseMatch(this.getConnectorId($.CHAIN.EVM),s)&&this.emit("accountChanged",{address:o,chainId:(i=a==null?void 0:a.caipNetwork)==null?void 0:i.id,connector:a==null?void 0:a.connector}),this.addConnection({connectorId:s,accounts:e.map(c=>{const{address:l}=J.getAccount(c);return{address:l}}),caipNetwork:a==null?void 0:a.caipNetwork})}else n&&this.onDisconnect(s)}onDisconnect(e){this.removeProviderListeners(e),this.deleteConnection(e),Je.isLowerCaseMatch(this.getConnectorId($.CHAIN.EVM),e)&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(e,s){var o;const n=typeof e=="string"&&e.startsWith("0x")?Vi.hexStringToNumber(e).toString():e.toString(),r=(o=this.connectionManager)==null?void 0:o.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors}),i=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===n);r&&this.addConnection({connectorId:s,accounts:r.accounts,caipNetwork:i}),Je.isLowerCaseMatch(this.getConnectorId($.CHAIN.EVM),s)&&this.emit("switchNetwork",{chainId:n})}listenProviderEvents(e,s){if(P_.includes(e))return;const n=o=>this.onAccountsChanged(o,e),r=o=>this.onChainChanged(o,e),i=()=>this.onDisconnect(e);this.providerHandlers[e]||(s.on("disconnect",i),s.on("accountsChanged",n),s.on("chainChanged",r),this.providerHandlers[e]={provider:s,disconnect:i,accountsChanged:n,chainChanged:r})}removeProviderListeners(e){if(this.providerHandlers[e]){const{provider:s,disconnect:n,accountsChanged:r,chainChanged:i}=this.providerHandlers[e];s.removeListener("disconnect",n),s.removeListener("accountsChanged",r),s.removeListener("chainChanged",i),this.providerHandlers[e]=null}}emitFirstAvailableConnection(){var s,n;const e=(s=this.connectionManager)==null?void 0:s.getConnection({connections:this.connections,connectors:this.connectors});if(e){const[r]=e.accounts;this.emit("accountChanged",{address:r==null?void 0:r.address,chainId:(n=e.caipNetwork)==null?void 0:n.id,connector:e.connector})}}}class R_ extends x_{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter
228:setUniversalProvider - namespace is required");return this.addConnector(new Zp({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit("disconnect")}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}return{connections:[]}}syncConnections(){return Promise.resolve()}async getAccounts({namespace:e}){var r,i,o,a;const s=this.provider,n=((a=(o=(i=(r=s==null?void 0:s.session)==null?void 0:r.namespaces)==null?void 0:i[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const[,,l]=c.split(":");return l}).filter((c,l,d)=>d.indexOf(c)===l))||[];return Promise.resolve({accounts:n.map(c=>J.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var o,a,c,l,d;if(!(e.caipNetwork&&ye.BALANCE_SUPPORTED_CHAINS.includes((o=e.caipNetwork)==null?void 0:o.chainNamespace))||(a=e.caipNetwork)!=null&&a.testnet)return{balance:"0.00",symbol:((c=e.caipNetwork)==null?void 0:c.nativeCurrency.symbol)||""};const n=g.getAccountData();if(n!=null&&n.balanceLoading&&e.chainId===((l=g.state.activeCaipNetwork)==null?void 0:l.id))return{balance:(n==null?void 0:n.balance)||"0.00",symbol:(n==null?void 0:n.balanceSymbol)||""};const i=(await g.fetchTokenBalance()).find(u=>{var h,p;return u.chainId===`${(h=e.caipNetwork)==null?void 0:h.chainNamespace}:${e.chainId}`&&u.symbol===((p=e.caipNetwork)==null?void 0:p.nativeCurrency.symbol)});return{balance:(i==null?void 0:i.quantity.numeric)||"0.00",symbol:(i==null?void 0:i.symbol)||((d=e.caipNetwork)==null?void 0:d.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:s,message:n,address:r}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let i="";return((o=g.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===$.CHAIN.SOLANA?i=(await s.request({method:"solana_signMessage",params:{message:hr.encode(ne
228w TextEncoder().encode(n)),pubkey:r}},(a=g.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:i=await s.request({method:"personal_sign",params:[n,r]},(c=g.state.activeCaipNetwork)==null?void 0:c.caipNetworkId),{signature:i}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var r,i,o,a,c,l;const{caipNetwork:s}=e,n=this.getWalletConnectConnector();if(s.chainNamespace===$.CHAIN.EVM)try{await((r=n.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:Fc(s.id)}]}))}catch(d){if(d.code===Br.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||d.code===Br.ERROR_INVALID_CHAIN_ID||d.code===Br.ERROR_CODE_DEFAULT||((o=(i=d==null?void 0:d.data)==null?void 0:i.originalError)==null?void 0:o.code)===Br.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=n.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:Fc(s.id),rpcUrls:[(a=s==null?void 0:s.rpcUrls.chainDefault)==null?void 0:a.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[(c=s.blockExplorers)==null?void 0:c.default.url]}]}))}catch{throw new Error("Chain is not supported")}}n.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(n=>n.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}const $_=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication"],Ui={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(s=>s!=="email"):!1},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?ye.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?ye.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?ye.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?ye.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?ye.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:()=>ye.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>ye.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>ye.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"?ye.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!t}},U_={localSettingsOverridden:new Set,getApiConfig(t,e){return e==null?void 0:e.find(s=>
228s.id===t)},addWarning(t,e){if(t!==void 0){const s=Ui[e],n=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(n)}},processFeature(t,e,s,n,r){const i=Ui[t],o=e[i.localFeatureName];if(r&&!i.isAvailableOnBasic)return!1;if(n){const a=this.getApiConfig(i.apiFeatureName,s);return(a==null?void 0:a.config)===null?this.processFallbackFeature(t,o):a!=null&&a.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return Ui[t].processApi(e)},processFallbackFeature(t,e){return Ui[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 te.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?ye.DEFAULT_REMOTE_FEATURES:ye.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of $_){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),ye.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.`;At.open({debugMessage:$t.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(o)},"warning")}return i}};class D_{constructor(e){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,n)=>{var r,i,o;if(s){const a=(r=g.getCaipNetworks(s))==null?void 0:r.find(d=>d.id===n);if(a)return a;const c=(i=g.getNetworkData(s))==null?void 0:i.caipNetwork;return c||((o=g.getRequestedCaipNetworks(s).filter(d=>d.chainNamespace===s))==null?void 0:o[0])}return g.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>g.getCaipNetworks(s),this.getActiveChainNamespace=()=>g.state.activeChain,this.setRequestedCaipNetworks=(s,n)=>{g.setRequestedCaipNetworks(s,n)},this.getApprovedCaipNetworkIds=()=>g.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>{var n,r;return g.state.activeChain===s||!s?g.state.activeCaipAddress:(r=(n=g.state.chains.get(s))==null?void 0:n.accountState)==null?void 0:r.caipAddress},this.setClientId=s=>{re.setClientId(s)},this.getProvider=s=>Re.getProvider(s),this.getProviderType=s=>Re.getProviderId(s),this.getPreferredAccountType=s=>jt(s),this.setCaipAddress=(s,n,r=!1)=>{g.setAccountProp("caipAddress",s,n,r),g.setAccountProp("address",J.getPlainAddress(s),n,r)},this.setBalance=(s,n,r)=>{g.setAccountProp("balance",s,r),g.setAccountProp("balanceSymbol",n,r)},this.setProfileName=(s,n)=>{g.setAccountProp("profileName",s,n)},this.setProfileImage=(s,n)=>{g.setAccountProp("profileImage",s,n)},this.setUser=(s,n)=>{g.setAccountProp("user",s,n)},this.resetAccount=s=>{g.resetAccount(s)},this.setCaipNetwork=s=>{g.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,n)=>{g.setChainNetworkData(n,{caipNetwork:s})},this.setStatus=(s,n)=>{g.setAccountProp("status",s,n),q.isConnected()?M.setConnectionStatus("connected"):M.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>{var n;return(n=g.getAccountData(s))==null?void 0:n.address},this.setConnectors=s=>{const n=[...q.state.allConnectors,...s];q.setConnectors(n)},this.setConnections=(s,n)=>{M.setConnections(s,n),H.setConnections(s,n)},this.fetchIdentity=s=>re.fetchIdentity(s),this.getReownName=s=>Fr.getNamesForAddress(s),this.getConnectors=()=>q.getConnectors(),this.getConnectorImage=s=>Mu.getConnectorImage(s),this.getConnections=s=>this.remoteFeatures.multiWallet?Xi.getConnectionsData(s).connections:(At.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=s=>this.remoteFeatures.multiWallet?Xi.getConnectionsData(s).recentConnections:(At.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async s=>{if(!this.remoteFeatures.multiWallet){At.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await H.switchConnection(s)},this.deleteConnection=s=>{if(!this.remoteFeatures.multiWallet){At.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}M.deleteAddressFromConnection(s),H.syncStorageConnections()},this.setConnectedWalletInfo=(s,n)=>{const r=Re.getProviderId(n),i=s?{...s,type:r}:void 0;g.setAccountProp("connectedWalletInfo",i,n)},this.getIsConnectedState=()=>!!g.state.activeCaipAddress,this.addAddressLabel=(s,n,r)=>
228{var o;const i=((o=g.getAccountData(r))==null?void 0:o.addressLabels)||{};g.setAccountProp("addressLabels",{...i,[s]:n},r)},this.removeAddressLabel=(s,n)=>{var i;const r=((i=g.getAccountData(n))==null?void 0:i.addressLabels)||{};g.setAccountProp("addressLabels",{...r,[s]:void 0},n)},this.getAddress=s=>{var r;const n=s||g.state.activeChain;return(r=g.getAccountData(n))==null?void 0:r.address},this.setApprovedCaipNetworksData=s=>g.setApprovedCaipNetworksData(s),this.resetNetwork=s=>{g.resetNetwork(s)},this.addConnector=s=>{q.addConnector(s)},this.resetWcConnection=()=>{H.resetWcConnection()},this.setAddressExplorerUrl=(s,n)=>{g.setAccountProp("addressExplorerUrl",s,n)},this.setSmartAccountDeployed=(s,n)=>{g.setAccountProp("smartAccountDeployed",s,n)},this.setPreferredAccountType=(s,n)=>{g.setAccountProp("preferredAccountType",s,n)},this.setEIP6963Enabled=s=>{R.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),UN.checkSDKVersion(e.sdkVersion)}getChainNamespacesSet(e,s){const n=e==null?void 0:e.map(i=>i.namespace).filter(i=>!!i);if(n!=null&&n.length)return[...new Set(n)];const r=s==null?void 0:s.map(i=>i.chainNamespace);return[...new Set(r)]}async initialize(e){var s,n,r,i,o;if(this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),R.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),this.remoteFeatures=await U_.fetchRemoteFeatures(e),R.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&Na.setOnrampProviders(this.remoteFeatures.onramp),((s=R.state.remoteFeatures)!=null&&s.email||Array.isArray((n=R.state.remoteFeatures)==null?void 0:n.socials)&&((r=R.state.remoteFeatures)==null?void 0:r.socials.length)>0)&&await this.checkAllowedOrigins(),(i=R.state.features)!=null&&i.reownAuthentication||(o=R.state.remoteFeatures)!=null&&o.reownAuthentication){const{ReownAuthentication:a}=await Vr(async()=>{const{ReownAuthentication:l}=await import("./features-BkQdjCPz.js");return{ReownAuthentication:l}},__vite__mapDeps([9,1,2])),c=R.state.siwx;c instanceof a||(c&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),R.setSIWX(new a))}}async openSend(e){var i;const s=e.namespace||g.state.activeChain,n=this.getCaipAddress(s),r=(i=this.getCaipNetwork(s))==null?void 0:i.id;if(!n)throw new Error("openSend: caipAddress not found");if((r==null?void 0:r.toString())!==e.chainId.toString()){const o=g.getCaipNetworkById(e.chainId,s);if(!o)throw new Error(`openSend: caipNetwork with chainId ${e.chainId} not found`);await this.switchNetwork(o,{throwOnFailure:!0})}try{const o=qp.getTokenSymbolByAddress(e.assetAddress);o&&await te.fetchTokenImages([o])}catch{}return await he.open({view:"WalletSend",data:{send:e}}),new Promise((o,a)=>{const c=ce.subscribeKey("hash",u=>{u&&(d(),o({hash:u}))}),l=he.subscribe(u=>{u.open||(d(),a(new Error("Modal closed")))}),d=this.createCleanupHandler([c,l])})}toModalOptions(){function e(n){return(n==null?void 0:n.view)==="Swap"}function s(n){return(n==null?void 0:n.view)==="WalletSend"}return{isSwap:e,isSend:s}}async checkAllowedOrigins(){try{const e=await te.fetchAllowedOrigins();if(!J.isClient())return;const s=window.location.origin;Jt.isOriginAllowed(s,e,Br.DEFAULT_ALLOWED_ANCESTORS)||At.open($t.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error))return;switch(e.message){case"RATE_LIMITED":At.open($t.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const s=e.cause instanceof Error?e.cause:e;At.open({displayMessage:$t.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:$t.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(s.message)},"error");break}}}}createCleanupHandler(e){return()=>{e.forEach(s=>{try{s()}catch{}})}}sendInitializeEvent(e){var n;const{...s}=e;delete s.adapters,delete s.universalProvider,le.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(r=>r.id),siweConfig:{options:((n=e.siweConfig)==null?void 0:n.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&_t.setThemeMode(e.themeMode),e.themeVariables&&_t.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");g.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const s=this.getDefaultNetwork();s&&g.setActiveCaipNetwork(s)}initializeConnectionController(e){H.initialize(e.adapters??[]),H.setWcBasic(e.basic??!1)}initializeConnectorController(){q.initialize(this.chainNamespaces)}initializeProjectSettings(e){R.setProjectId(e.projectId),R.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var r;R.setDebug(e.debug!==!1),R.setEnableWalletGuide(e.enableWalletGuide!==!1),R.setEnableWallets(e.enableWallets!==!1),R.setEIP6963Enabled(e.enableEIP6963!==!1),R.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),R.setEnableReconnect(e.enableReconnect!==!1),R.setEnableMobileFullScreen(e.enableMobileFullScreen===!0),R.setEnableAuthLogger(e.enableAuthLogger!==!1),R.setCustomRpcUrls(e.customRpcUrls),R.setEnableEmbedded(e.enableEmbedded),R.setAllWallets(e.allWallets),R.setIncludeWalletIds(e.includeWalletIds),R.setExcludeWalletIds(e.excludeWalletIds),R.setFeaturedWalletIds(e.featuredWalletIds),R.setTokens(e.tokens),R.setTermsConditionsUrl(e.termsConditionsUrl),R.setPrivacyPolicyUrl(e.privacyPolicyUrl),R.setCustomWallets(e.customWallets),R.setFeatures(e.features),R.setAllowUnsupportedChain(e.allowUnsupportedChain),R.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),R.setPreferUniversalLinks(e.experimental_preferUniversalLinks),R.setDefaultAccountTypes(e.defaultAccountTypes);const s=this.getDefaultMetaData();if(!e.metadata&&s&&(e.metadata=s),R.setMetadata(e.metadata),R.setDisableAppend(e.disableAppend),R.setEnableEmbedded(e.enableEmbedded),R.setSIWX(e.siwx),this.features=R.state.features??{},!e.projectId){At.open($t.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(i=>i.namespace===$.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");R.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,s,n,r;return J.isClient()?{name:((s=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:s.textContent)||"",description:((n=document.querySelector('meta[property="og:description"]'))==null?void 0:n.content)||"",url:window.location.origin,icons:[((r=document.querySelector('link[rel~="icon"]'))==null?void 0:r.href)||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const n=Gn.getUnsupportedNetwork(`${s}:${e}`);g.setActiveCaipNetwork(n)}}getDefaultNetwork(){return Gn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}
228extendCaipNetwork(e,s){return Gn.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return Gn.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(r=>{var i;return r.id===((i=e.defaultNetwork)==null?void 0:i.id)});return s?Gn.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectConnector(e,s){var n,r;try{this.setLoading(!0,e);let i={connections:[]};const o=this.getAdapter(e);return(((r=(n=g.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.caipAddress)||!R.state.enableReconnect)&&(o!=null&&o.disconnect)&&(i=await o.disconnect({id:s})),this.setLoading(!1,e),i}catch(i){throw this.setLoading(!1,e),new Error(`Failed to disconnect chains: ${i.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var l;const e=g.state.activeChain,s=this.getAdapter(e),n=(l=this.getCaipNetwork(e))==null?void 0:l.id,r=H.getConnections(e),i=this.remoteFeatures.multiWallet,o=r.length>0;if(!s)throw new Error("Adapter not found");const a=await s.connectWalletConnect(n);(!o||!i)&&this.close(),this.setClientId((a==null?void 0:a.clientId)||null),M.setConnectedNamespaces([...g.state.chains.keys()]),await this.syncWalletConnectAccount(),await rs.initializeIfEnabled()},connectExternal:async e=>{const s=await this.onConnectExternal(e);return await this.connectInactiveNamespaces(e,s),s?{address:s.address}:void 0},reconnectExternal:async({id:e,info:s,type:n,provider:r})=>{var a;const i=g.state.activeChain,o=this.getAdapter(i);if(!i)throw new Error("reconnectExternal: namespace not found");if(!o)throw new Error("reconnectExternal: adapter not found");o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:s,type:n,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),M.addConnectedNamespace(i),this.syncConnectedWalletInfo(i))},disconnectConnector:async e=>{await this.disconnectConnector(e.namespace,e.id)},disconnect:async e=>{var l;const{id:s,chainNamespace:n,initialDisconnect:r}=e||{},i=n||g.state.activeChain,o=q.getConnectorId(i),a=s===$.CONNECTOR_ID.AUTH||o===$.CONNECTOR_ID.AUTH,c=s===$.CONNECTOR_ID.WALLET_CONNECT||o===$.CONNECTOR_ID.WALLET_CONNECT;try{const d=Array.from(g.state.chains.keys());let u=n?[n]:d;(c||a)&&(u=d);const h=u.map(async m=>{const w=q.getConnectorId(m),E=s||w,I=await this.disconnectConnector(m,E);I&&(a&&M.deleteConnectedSocialProvider(),I.connections.forEach(k=>{M.addDisconnectedConnectorId(k.connectorId,m)})),r&&this.onDisconnectNamespace({chainNamespace:m,closeModal:!1})}),p=await Promise.allSettled(h);ce.resetSend(),H.resetWcConnection(),(l=rs.getSIWX())!=null&&l.signOutOnDisconnect&&await rs.clearSessions(),q.setFilterByNamespace(void 0),H.syncStorageConnections();const y=p.filter(m=>m.status==="rejected");if(y.length>0)throw new Error(y.map(m=>m.reason.message).join(", "));le.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:n||"all"}})}catch(d){throw new Error(`Failed to disconnect chains: ${d.message}`)}},checkInstalled:e=>e?e.some(s=>{var n;return!!((n=window.ethereum)!=null&&n[String(s)])}):!!window.ethereum,signMessage:async e=>{const s=g.state.activeChain,n=this.getAdapter(g.state.activeChain);if(!s)throw new Error("signMessage: namespace not found");if(!n)throw new Error("signMessage: adapter not found");const r=this.getAddress(s);if(!r)throw new Error("signMessage: address not found");const i=await(n==null?void 0:n.signMessage({message:e,address:r,provider:Re.getProvider(s)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{const s=e.chainNamespace;if(!s)throw new Error("sendTransaction: namespace not found");if(ye.SEND_SUPPORTED_NAMESPACES.includes(s)){const n=this.getAdapter(s);if(!n)throw new Error("sendTransaction: adapter not found");const r=Re.getProvider(s),i=await(n==null?void 0:n.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:r}));return(i==null?void 0:i.hash)||""}return""},estimateGas:async e=>{const s=e.chainNamespace;if(s===$.CHAIN.EVM){const n=this.getAdapter(s);if(!n)throw new Error("estimateGas: adapter is required but got undefined");const r=Re.getProvider(s),i=this.getCaipNetwork();if(!i)throw new Error("estimateGas: caipNetwork is required but got undefined");const o=await(n==null?void 0:n.estimateGas({...e,provider:r,caipNetwork:i}));return(o==null?void 0:o.gas)||0n}return 0n},getEnsAvatar:async()=>{var r;const e=g.state.activeChain;if(!e)throw new Error("getEnsAvatar: namespace is required but got undefined");const s=this.getAddress(e);if(!s)throw new Error("getEnsAvatar: address not found");await this.syncIdentity({address:s,chainId:Number((r=this.getCaipNetwork())==null?void 0:r.id),chainNamespace:e});const n=g.getAccountData();return(n==null?void 0:n.profileImage)||!1},getEnsAddress:async e=>await Jt.resolveReownName(e),writeContract:async e=>{const s=g.state.activeChain,n=this.getAdapter(s);if(!s)throw new Error("writeContract: namespace is required but got undefined");if(!n)throw new Error("writeContract: adapter is required but got undefined");const r=this.getCaipNetwork(),i=this.getCaipAddress(),o=Re.getProvider(s);if(!r||!i)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");const a=await(n==null?void 0:n.writeContract({...e,caipNetwork:r,provider:o,caipAddress:i}));return a==null?void 0:a.hash},parseUnits:(e,s)=>{const n=this.getAdapter(g.state.activeChain);if(!n)throw new Error("parseUnits: adapter is required but got undefined");return(n==null?void 0:n.parseUnits({value:e,decimals:s}))??0n},formatUnits:(e,s)=>{const n=this.getAdapter(g.state.activeChain);if(!n)throw new Error("formatUnits: adapter is required but got undefined");return(n==null?void 0:n.formatUnits({value:e,decimals:s}))??"0"},getCapabilities:async e=>{const s=this.getAdapter(g.state.activeChain);if(!s)throw new Error("getCapabilities: adapter is required but got undefined");return await(s==null?void 0:s.getCapabilities(e))},grantPermissions:async e=>{const s=this.getAdapter(g.state.activeChain);if(!s)throw new Error("grantPermissions: adapter is required but got undefined");return await(s==null?void 0:s.grantPermissions(e))},revokePermissions:async e=>{const s=this.getAdapter(g.state.activeChain);if(!s)throw new Error("revokePermissions: adapter is required but got undefined");return s!=null&&s.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(g.state.activeChain);if(!s)throw new Error("walletGetAssets: adapter is required but got undefined");return await(s==null?void 0:s.walletGetAssets(e))??{}},updateBalance:e=>{const s=this.getAddress(e),n=this.getCaipNetwork(e);!n||!s||this.updateNativeBalance(s,n==null?void 0:n.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},H.setClient(this.connectionControllerClient)}async onConnectExternal(e){var l,d,u,h,p,y,m,w;const s=g.state.activeChain,n=e.chain||s,r=this.getAdapter(n);let i=!0;if(e.type===vs.CONNECTOR_TYPE_AUTH&&$.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(k=>q.getConnectorId(k)===$.CONNECTOR_ID.AUTH)&&e.chain!==s&&(i=!1),e.chain&&e.chain!==s&&!e.caipNetwork){const E=this.getCaipNetworks().find(I=>I.chainNamespace===e.chain);E&&i&&this.setCaipNetwork(E)}if(!n)throw new Error("connectExternal: namespace not found");if(!r)throw new Error("connectExternal: adapter not found");const o=this.getCaipNetwork(n),a=e.caipNetwork||o,c=await r.connect({id:e.id,address:e.address,info:e.info,type:e.type,provider:e.provider,socialUri:e.socialUri,chainId:((l=e.caipNetwork)==null?void 0:l.id)||(o==null?void 0:o.id),rpcUrl:((p=(h=(u=(d=e.caipNetwork)==null?void 0:d.rpcUrls)==null?void 0:u.default)==null?void 0:h.http)==null?void 0:p[0])||((w=(m=(y=o==null?void 0:o.rpcUrls)==null?void 0:y.default)==null?void 0:m.http)==null?void 0:w[0])});if(c)return M.addConnectedNamespace(n),this.syncProvider({...c,chainNamespace:n}),this.setStatus("connected",n),this.syncConnectedWalletInfo(n),M.removeDisconnectedConnectorId(e.id,n),{address:c.address,connectedCaipNetwork:a}}async connectInactiveNamespaces(e,s){var c;const n=e.type===vs.CONNECTOR_TYPE_AUTH,r=Je.getOtherAuthNamespaces((c=s==null?void 0:s.connectedCaipNetwork)==null?void 0:c.chainNamespace),i=g.state.activeCaipNetwork,o=this.getAdapter(i==null?void 0:i.chainNamespace),a=Re.getProvider(i==null?void 0:i.chainNamespace);n&&(await Promise.all(r.map(async l=>{var d,u,h;try{const p=Re.getProvider(l),y=this.getCaipNetwork(l),m=this.getAdapter(l);await(m==null?void 0:m.connect({...e,provider:p,socialUri:void 0,chainId:y==null?void 0:y.id,rpcUrl:(h=(u=(d=y==null?void 0:y.rpcUrls)==null?void 0:d.default)==null?void 0:u.http)==null?void 0:h[0]}))&&(M.addConnectedNamespace(l),M.removeDisconnectedConnectorId(e.id,l),this.setStatus("connected",l),this.syncConnectedWalletInfo(l))}catch(p){At.warn($t.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,$t.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(l,p instanceof Error?p.message:void 0),$t.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),i&&await(o==null?void 0:o.switchNetwork({caipNetwork:i,provider:a,providerType:e.type})))}getApprovedCaipNetworksData(){var s,n,r,i,o;if(Re.getProviderId(g.state.activeChain)===vs.CONNECTOR_TYPE_WALLET_CONNECT){const a=(n=(s=this.universalProvider)==null?void 0:s.session)==null?void 0:n.namespaces;return{supportsAllNetworks:((o=(i=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:i.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=Re.getProvider(s),i=Re.getProviderId(s);if(e.chainNamespace===g.state.activeChain){const o=this.getAdapter(s);
228await(o==null?void 0:o.switchNetwork({caipNetwork:e,provider:r,providerType:i}))}else if(this.setCaipNetwork(e),i===vs.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}=ot.parseCaipAddress(i);return`${a}:${o}`});return Array.from(new Set([...n,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,n)=>{var i,o;const r=e==null?void 0:e.find(a=>a.namespace===n);return r?(r.construct({namespace:n,projectId:(i=this.options)==null?void 0:i.projectId,networks:(o=this.caipNetworks)==null?void 0:o.filter(({chainNamespace:a})=>a===n)}),s[n]=r):s[n]=new R_({namespace:n,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){var s;this.onConnectors(e),this.listenAdapter(e),await((s=this.chainAdapters)==null?void 0:s[e].syncConnectors(this.options,this)),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){const s=this.getAdapter(e);s==null||s.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const n=M.getConnectionStatus();R.state.enableReconnect===!1?this.setStatus("disconnected",e):n==="connected"?this.setStatus("connecting",e):n==="disconnected"?(M.clearAddressCache(),this.setStatus(n,e)):this.setStatus(n,e),s.on("switchNetwork",({address:r,chainId:i})=>{var l,d;const o=this.getCaipNetworks().find(u=>u.id.toString()===i.toString()||u.caipNetworkId.toString()===i.toString()),a=g.state.activeChain===e,c=(d=(l=g.state.chains.get(e))==null?void 0:l.accountState)==null?void 0:d.address;if(o){const u=a&&r?r:c;u&&this.syncAccount({address:u,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(i)}),s.on("disconnect",()=>{const r=this.remoteFeatures.multiWallet,i=Array.from(H.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:e,closeModal:!r||i.length===0})}),s.on("connections",r=>{this.setConnections(r,e)}),s.on("pendingTransactions",()=>{const r=this.getAddress(e),i=g.state.activeCaipNetwork;!r||!(i!=null&&i.id)||this.updateNativeBalance(r,i.id,i.chainNamespace)}),s.on("accountChanged",({address:r,chainId:i,connector:o})=>{var d,u;this.handlePreviousConnectorConnection(o);const a=g.state.activeChain===e;o!=null&&o.provider&&(this.syncProvider({id:o.id,type:o.type,provider:o==null?void 0:o.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e));const c=(u=(d=g.getNetworkData(e))==null?void 0:d.caipNetwork)==null?void 0:u.id,l=i||c;a&&l?this.syncAccount({address:r,chainId:l,chainNamespace:e}):!a&&l?(this.syncAccountInfo(r,l,e),this.syncBalance({address:r,chainId:l,chainNamespace:e})):this.syncAccountInfo(r,i,e),M.addConnectedNamespace(e)})}async handlePreviousConnectorConnection(e){var c;const s=e==null?void 0:e.chain,n=e==null?void 0:e.id,r=q.getConnectorId(s),i=(c=R.state.remoteFeatures)==null?void 0:c.multiWallet,a=s&&n&&r&&r!==n&&!i;try{a&&await H.disconnect({id:r,namespace:s})}catch(l){console.warn("Error disconnecting previous connector",l)}}async createUniversalProviderForAdapter(e){var s,n,r;await this.getUniversalProvider(),this.universalProvider&&await((r=(n=(s=this.chainAdapters)==null?void 0:s[e])==null?void 0:n.setUniversalProvider)==null?void 0:r.call(n,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(e=>H.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()||M.deleteRecentWallet();const s=M.getRecentWallet();le.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:J.isMobile()?"mobile":"qrcode",name:(s==null?void 0:s.name)||"Unknown",re
228connect:!0,view:ne.state.view,walletRank:s==null?void 0:s.order}})}async syncNamespaceConnection(e){try{e===$.CHAIN.EVM&&J.isSafeApp()&&q.setConnectorId($.CONNECTOR_ID.SAFE,e);const s=q.getConnectorId(e);switch(this.setStatus("connecting",e),s){case $.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case $.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}onDisconnectNamespace(e){const{chainNamespace:s,closeModal:n}=e||{};g.resetAccount(s),g.resetNetwork(s),M.removeConnectedNamespace(s);const r=Array.from(g.state.chains.keys());(s?[s]:r).forEach(o=>M.addDisconnectedConnectorId(q.getConnectorId(o)||"",o)),q.removeConnectorId(s),Re.resetChain(s),this.setUser(null,s),this.setStatus("disconnected",s),this.setConnectedWalletInfo(null,s),n!==!1&&he.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(e=>{const s=this.getAdapter(e),n=this.getCaipAddress(e),r=this.getCaipNetwork(e);return s==null?void 0:s.syncConnections({connectToFirstConnector:!n,caipNetwork:r})}))}async syncAdapterConnection(e){var a,c,l,d;const s=this.getAdapter(e),n=this.getCaipNetwork(e),r=q.getConnectorId(e),o=q.getConnectors(e).find(u=>u.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(n!=null&&n.id))throw new Error("CaipNetwork not found");const u=await(s==null?void 0:s.syncConnection({namespace:e,id:o.id,chainId:n.id,rpcUrl:(l=(c=(a=n==null?void 0:n.rpcUrls)==null?void 0:a.default)==null?void 0:c.http)==null?void 0:l[0]}));u?(this.syncProvider({...u,chainNamespace:e}),await this.syncAccount({...u,chainNamespace:e}),this.setStatus("connected",e),le.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:u.address,properties:{method:"browser",name:((d=o.info)==null?void 0:d.name)||o.name||"Unknown",reconnect:!0,view:ne.state.view,walletRank:void 0}})):this.setStatus("disconnected",e)}catch{this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})}}async syncWalletConnectAccount(){var n,r;const e=Object.keys(((r=(n=this.universalProvider)==null?void 0:n.session)==null?void 0:r.namespaces)||{}),s=this.chainNamespaces.map(async i=>{var d,u,h,p,y;const o=this.getAdapter(i);if(!o)return;const a=((p=(h=(u=(d=this.universalProvider)==null?void 0:d.session)==null?void 0:u.namespaces)==null?void 0:h[i])==null?void 0:p.accounts)||[],c=(y=g.state.activeCaipNetwork)==null?void 0:y.id,l=a.find(m=>{const{chainId:w}=ot.parseCaipAddress(m);return w===(c==null?void 0:c.toString())})||a[0];if(l){const m=ot.validateCaipAddress(l),{chainId:w,address:E}=ot.parseCaipAddress(m);if(Re.setProviderId(i,vs.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&g.state.activeCaipNetwork&&o.namespace!==$.CHAIN.EVM){const I=o.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:g.state.activeCaipNetwork});Re.setProvider(i,I)}else Re.setProvider(i,this.universalProvider);q.setConnectorId($.CONNECTOR_ID.WALLET_CONNECT,i),M.addConnectedNamespace(i),await this.syncAccount({address:E,chainId:w,chainNamespace:i})}else e.includes(i)&&this.setStatus("disconnected",i);this.syncConnectedWalletInfo(i),await g.setApprovedCaipNetworksData(i)});await Promise.all(s)}syncProvider({type:e,provider:s,id:n,chainNamespace:r}){Re.setProviderId(r,e),Re.setProvider(r,s),q.setConnectorId(n,r)}async syncAccount(e){var u,h;const s=e.chainNamespace===g.state.activeChain,n=g.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:i,chainNamespace:o}=e,{chainId:a}=M.getActiveNetworkProps(),c=i||a,l=((u=g.state.activeCaipNetwork)==null?void 0:u.name)===$.UNSUPPORTED_NETWORK_NAME,d=g.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!d)&&c){let p=this.getCaipNetworks().find(E=>E.id.toString()===c.toString()),y=this.getCaipNetworks().find(E=>E.chainNamespace===o);if(!d&&!p&&!y){const E=this.getApprovedCaipNetworkIds()||[],I=E.find(D=>{var j;return((j=ot.parseCaipNetworkId(D))==null?void 0:j.chainId)===c.toString()}),k=E.find(D=>{var j;return((j=ot.parseCaipNetworkId(D))==null?void 0:j.chainNamespace)===o});p=this.getCaipNetworks().find(D=>D.caipNetworkId===I),y=this.getCaipNetworks().find(D=>D.caipNetworkId===k||"deprecatedCaipNetworkId"in D&&D.deprecatedCaipNetworkId===k)}const m=p||y;(m==null?void 0:m.chainNamespace)===g.state.activeChain?R.state.enableNetworkSwitch&&!R.state.allowUnsupportedChain&&((h=g.state.activeCaipNetwork)==null?void 0:h.name)===$.UNSUPPORTED_NETWORK_NAME?g.showUnsupportedChainUI():this.setCaipNetwork(m):s||n&&this.setCaipNetworkOfNamespace(n,o),this.syncConnectedWalletInfo(o);const w=this.getAddress(o);Je.isLowerCaseMatch(r,w)||this.syncAccountInfo(r,m==null?void 0:m.id,o),s?await this.syncBalance({address:r,chainId:m==null?void 0:m.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:n==null?void 0:n.id,chainNamespace:o}),this.syncIdentity({address:r,chainId:i,chainNamespace:o})}}async syncAccountInfo(e,s,n){const r=this.getCaipAddress(n),i=s||(r==null?void 0:r.split(":")[1]);if(!i)return;const o=`${n}:${i}:${e}`;this.setCaipAddress(o,n,!0),await this.syncIdentity({address:e,chainId:i,chainNamespace:n})}async syncReownName(e,s){try{const n=await this.getReownName(e);
228if(n[0]){const r=n[0];this.setProfileName(r.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){var r;const s=q.getConnectorId(e),n=Re.getProviderId(e);if(n===vs.CONNECTOR_TYPE_ANNOUNCED||n===vs.CONNECTOR_TYPE_INJECTED){if(s){const o=this.getConnectors().find(a=>{var u,h;const c=a.id===s,l=((u=a.info)==null?void 0:u.rdns)===s,d=(h=a.connectors)==null?void 0:h.some(p=>{var y;return p.id===s||((y=p.info)==null?void 0:y.rdns)===s});return c||l||!!d});if(o){const{info:a,name:c,imageUrl:l}=o,d=l||this.getConnectorImage(o);this.setConnectedWalletInfo({name:c,icon:d,...a},e)}}}else if(n===vs.CONNECTOR_TYPE_WALLET_CONNECT){const i=Re.getProvider(e);i!=null&&i.session&&this.setConnectedWalletInfo({...i.session.peer.metadata,name:i.session.peer.metadata.name,icon:(r=i.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(s&&(s===$.CONNECTOR_ID.COINBASE_SDK||s===$.CONNECTOR_ID.COINBASE)){const i=this.getConnectors().find(l=>l.id===s),o=(i==null?void 0:i.name)||"Coinbase Wallet",a=(i==null?void 0:i.imageUrl)||this.getConnectorImage(i),c=i==null?void 0:i.info;this.setConnectedWalletInfo({...c,name:o,icon:a},e)}}async syncBalance(e){!Pu.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(n=>{var r;return n.id.toString()===((r=e.chainId)==null?void 0:r.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,n){const r=this.getAdapter(n),i=g.getCaipNetworkByNamespace(n,s);if(r){const o=await r.getBalance({address:e,chainId:s,caipNetwork:i,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,n),o}}async initializeUniversalAdapter(){var n,r,i,o,a,c,l,d,u,h;const e=XN.createLogger((p,...y)=>{p&&this.handleAlertError(p),console.error(...y)}),s={projectId:(n=this.options)==null?void 0:n.projectId,metadata:{name:(r=this.options)!=null&&r.metadata?(i=this.options)==null?void 0:i.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(c=this.options)!=null&&c.metadata?(l=this.options)==null?void 0:l.metadata.url:"",icons:(d=this.options)!=null&&d.metadata?(u=this.options)==null?void 0:u.metadata.icons:[""]},logger:e};R.setManualWCControl(!!((h=this.options)!=null&&h.manualWCControl)),this.universalProvider=this.options.universalProvider??await $N.init(s),R.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(e=>{Jt.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:s=>{H.setUri(s)},onConnect:s=>{const{address:n}=J.getAccount(s[0]);H.finalizeWcConnection(n)},onDisconnect:()=>{g.state.noAdapters&&this.resetAccount(e),H.resetWcConnection()},onChainChanged:s=>{const n=g.state.activeChain,r=n&&q.state.activeConnectorIds[n]===$.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(g.state.noAdapters||r)){const i=this.getCaipNetworks().find(a=>a.id.toString()===s.toString()||a.caipNetworkId.toString()===s.toString()),o=this.getCaipNetwork();if(!i){this.setUnsupportedNetwork(s);return}(o==null?void 0:o.id.toString())!==(i==null?void 0:i.id.toString())&&(o==null?void 0:o.chainNamespace)===(i==null?void 0:i.chainNamespace)&&this.setCaipNetwork(i)}},onAccountsChanged:s=>{const n=g.state.activeChain,r=n&&q.state.activeConnectorIds[n]===$.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(g.state.noAdapters||r)){const i=s==null?void 0:s[0];i&&this.syncAccount({address:i.address,chainId:i.chainId,chainNamespace:i.chainNamespace})}}})})}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&J.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}
228async 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=g.getAllApprovedCaipNetworkIds(),s=g.getAllRequestedCaipNetworks();return J.sortRequestedNetworks(e,s).filter(r=>g.isCaipNetworkDisabled(r))}handleAlertError(e){const s=Object.entries($t.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[n,r]=s??[],{message:i,alertErrorKey:o}=r??{};if(n&&i&&!this.reportedAlertErrors[n]){const a=$t.ALERT_ERRORS[o];a&&(At.open(a,"error"),this.reportedAlertErrors[n]=!0)}}getAdapter(e){var s;if(e)return(s=this.chainAdapters)==null?void 0:s[e]}createAdapter(e){var r,i;if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const n=e;n.namespace=s,n.construct({namespace:s,projectId:(r=this.options)==null?void 0:r.projectId,networks:(i=this.caipNetworks)==null?void 0:i.filter(({chainNamespace:o})=>o===s)}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=n)}async open(e){await this.injectModalUi(),e!=null&&e.uri&&H.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 H.disconnect({namespace:e})}getSIWX(){return R.state.siwx}getError(){return""}getChainId(){var e;return(e=g.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e,{throwOnFailure:s=!1}={}){const n=this.getCaipNetworks().find(r=>r.id===e.id);if(!n){At.open($t.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await g.switchActiveNetwork(n,{throwOnFailure:s})}getWalletProvider(){return g.state.activeChain?Re.state.providers[g.state.activeChain]:null}getWalletProviderType(){return Re.getProviderId(g.state.activeChain)}subscribeProviders(e){return Re.subscribeProviders(e)}getThemeMode(){return _t.state.themeMode}getThemeVariables(){return _t.state.themeVariables}setThemeMode(e){_t.setThemeMode(e),cc(_t.state.themeMode)}setTermsConditionsUrl(e){R.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){R.setPrivacyPolicyUrl(e)}setThemeVariables(e){_t.setThemeVariables(e),S_(_t.state.themeVariables)}subscribeTheme(e){return _t.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?H.subscribe(e):(At.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){var n,r;if(e)return(r=(n=g.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.connectedWalletInfo;const s=g.getAccountData();return s==null?void 0:s.connectedWalletInfo}getAccount(e){const s=e||g.state.activeChain,n=q.getAuthConnector(s),r=g.getAccountData(s),i=M.getConnectedConnectorId(g.state.activeChain),o=H.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===$.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:M.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:jt(s),isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const n=()=>{const r=this.getAccount(s);r&&e(r)};s?g.subscribeChainProp("accountState",n,s):g.subscribe(n),q.subscribe(n)}subscribeNetwork(e){return g.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s==null?void 0:s.id,caipNetworkId:s==null?void 0:s.caipNetworkId})})}subscribeWalletInfo(e,s){return s?g.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo),s):g.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo))}subscribeShouldUpdateToAddress(e){g.subscribeChainProp("accountState",s=>e(s==null?void 0:s.shouldUpdateToAddress))}subscribeCaipNetworkChange(e){g.subscribeKey("activeCaipNetwork",e)}getState(){return Ns.state}getRemoteFeatures(){return R.state.remoteFeatures}subscribeState(e){return Ns.subscribe(e)}subscribeRemoteFeatures(e){return R.subscribeKey("remoteFeatures",e)}showErrorMessage(e){os.showError(e)}showSuccessMessage(e){os.showSuccess(e)}getEvent(){return{...le.state}}subscribeEvents(e){return le.subscribe(e)}replace(e){ne.replace(e)}redirect(e){ne.push(e)}popTransactionStack(e){ne.popTransactionStack(e)}isOpen(){return he.state.open}isTransactionStackEmpty(){return ne.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){R.setFeatures(e)}updateRemoteFeatures(e){R.setRemoteFeatures(e)}updateOptions(e){const n={...R.state||{},...e};R.setOptions(n)}setConnectMethodsOrder(e){R.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){R.setWalletFeaturesOrder(e)}setCollapseWallets(e){R.setCollapseWallets(e)}setSocialsOrder(e){R.setSocialsOrder(e)}getConnectMethodsOrder(){return Lr.getConnectOrderMethod(R.state.features,q.getConnectors())}
228addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const n=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(r=>r.id===n.id)||g.addNetwork(n)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(r=>r.id===s)&&g.removeNetwork(e,s)}}let Nu=!1;class Qp extends D_{async open(e){q.isConnected()||await super.open(e)}async close(){var e;if(await super.close(),this.options.manualWCControl){const s=(e=g.getAccountData(this.activeChainNamespace))==null?void 0:e.address;H.finalizeWcConnection(s)}}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!Nu&&J.isClient()){if(await Vr(()=>import("./basic-B1jP2ajb.js"),__vite__mapDeps([10,11,1,2,12])),await Vr(()=>import("./w3m-modal-CLBw97XS.js"),__vite__mapDeps([13,11,1,2])),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!R.state.disableAppend&&!R.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}Nu=!0}}}const L_="1.8.7";function B_(t){return new Qp({...t,basic:!0,sdkVersion:`html-core-${L_}`})}const PS=Object.freeze(Object.defineProperty({__proto__:null,AppKit:Qp,createAppKit:B_},Symbol.toStringTag,{value:"Module"}));export{Bt as $,te as A,re as B,g as C,Ig as D,le as E,At as F,gc as G,fy as H,ye as I,Fu as J,q as K,Ze as L,Xe as M,Pu as N,ke as O,he as P,rs as Q,ne as R,ee as S,SS as T,OS as U,Ki as V,As as W,NS as X,kS as Y,__ as Z,Mu as _,$ as a,QN as a0,R as a1,Gs as a2,_t as a3,TS as a4,ot as a5,Kp as a6,oc as a7,He as a8,_S as a9,lr as aa,zi as ab,Je as ac,Nn as ad,Js as ae,Gn as af,M as ag,Lr as ah,PS as ai,Z as b,cS as c,hl as d,or as e,qc as f,Ei as g,ay as h,Xu as i,gy as j,aS as k,dS as l,oy as m,uS as n,hS as o,to as p,pS as q,lS as r,Af as s,Qu as t,$f as u,os as v,qt as w,H as x,jt as y,J 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.