PageSourceSearch

https://xbubble.ai/xbubble/assets/core-BOzHcyJ6.js

js xbubble.ai collected 2026-10-05 13:28:43 UTC 511,492 bytes, 911 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CRPZpX17.js","assets/index-BRLcHRdH.css","assets/basic-Dt_HnegP.js","assets/index-gc4GJOkJ.js","assets/browser-DAGd5jmX.js","assets/to-string-CqV7wPRW.js","assets/w3m-modal-rktXCkeb.js"])))=>i.map(i=>d[i]);
2import{dC as Zr,dD as fh,_ as Go,dE as gh,dF as M,dG as ds,dH as mh,dI as wh,dJ as Jo,dK as gu,dL as nr,dM as dn,dN as mu,dO as st,dP as yh,dQ as bh,dR as vt,dS as Ws,dT as Xr,dU as ka,dV as Tt,dW as vh,dX as Ra,dY as Ua,dZ as so,d_ as Da,d$ as tc,e0 as Eh,e1 as Ch,e2 as Ih,e3 as sc,e4 as $r,e5 as wu,e6 as ns,e7 as Ht,e8 as hs,e9 as jt}from"./index-CRPZpX17.js";import{f as Ot,t as ut,c as Ci}from"./to-string-CqV7wPRW.js";var rc={};const H={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"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof rc<"u"?rc.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},yu={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 i;if(!e)return;const s=t.find(n=>n.caipNetworkId===e);if(s)return s.name;const[r]=e.split(":");return((i=H.CHAIN_NAME_MAP)==null?void 0:i[r])||void 0}};var Ah=20,Nh=1,Xs=1e6,ic=1e6,_h=-7,Sh=21,Ph=!1,hn="[big.js] ",or=hn+"Invalid ",ro=or+"decimal places",Oh=or+"rounding mode",bu=hn+"Division by zero",ge={},Gt=void 0,Th=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function vu(){function t(e){var s=this;if(!(s instanceof t))return e===Gt?vu():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(or+"value");e=e===0&&1/e<0?"-0":String(e)}$h(s,e)}s.constructor=t}return t.prototype=ge,t.DP=Ah,t.RM=Nh,t.NE=_h,t.PE=Sh,t.strict=Ph,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function $h(t,e){var s,r,i;if(!Th.test(e))throw Error(or+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(s=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(s<0&&(s=r),s+=+e.slice(r+1),e=e.substring(0,r)):s<0&&(s=e.length),i=e.length,r=0;r<i&&e.charAt(r)=="0";)++r;if(r==i)t.c=[t.e=0];else{for(;i>0&&e.charAt(--i)=="0";);for(t.e=s-r-1,t.c=[],s=0;r<=i;)t.c[s++]=+e.charAt(r++)}return t}function ar(t,e,s,r){var i=t.c;if(s===Gt&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(Oh);if(e<1)r=s===3&&(r||!!i[0])||e===0&&(s===1&&i[0]>=5||s===2&&(i[0]>5||i[0]===5&&(r||i[1]!==Gt))),i.length=1,r?(t.e=t.e-e+1,i[0]=1):i[0]=t.e=0;else if(e<i.length){if(r=s===1&&i[e]>=5||s===2&&(i[e]>5||i[e]===5&&(r||i[e+1]!==Gt||i[e-1]&1))||s===3&&(r||!!i[0]),i.length=e,r){for(;++i[--e]>9;)if(i[e]=0,e===0){++t.e,i.unshift(1);break}}for(e=i.length;!i[--e];)i.pop()}return t}function cr(t,e,s){var r=t.e,i=t.c.join(""),n=i.length;if(e)i=i.charAt(0)+(n>1?"."+i.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)i="0"+i;i="0."+i}else if(r>0)if(++r>n)for(r-=n;r--;)i+="0";else r<n&&(i=i.slice(0,r)+"."+i.slice(r));else n>1&&(i=i.charAt(0)+"."+i.slice(1));return t.s<0&&s?"-"+i:i}ge.abs=function(){var t=new this.constructor(this);return t.s=1,t};ge.cmp=function(t){var e,s=this,r=s.c,i=(t=new s.constructor(t)).c,n=s.s,o=t.s,a=s.e,c=t.e;if(!r[0]||!i[0])return r[0]?n:i[0]?-o:0;if(n!=o)return n;if(e=n<0,a!=c)return a>c^e?1:-1;for(o=(a=r.length)<(c=i.length)?a:c,n=-1;++n<o;)if(r[n]!=i[n])return r[n]>i[n]^e?1:-1;return a==c?0:a>c^e?1:-1};ge.div=function(t){var e=this,s=e.constructor,r=e.c,i=(t=new s(t)).c,n=e.s==t.s?1:-1,o=s.DP;if(o!==~~o||o<0||o>Xs)throw Error(ro);if(!i[0])throw Error(bu);if(!r[0])return t.s=n,t.c=[t.e=0],t;var a,c,l,u,d,h=i.slice(),p=a=i.length,w=r.length,f=r.slice(0,a),m=f.length,y=t,b=y.c=[],v=0,C=o+(y.e=e.e-t.e)+1;for(y.s=n,n=C<0?0:C,h.unshift(0);m++<a;)f.push(0);do{for(l=0;l<10;l++){if(a!=(m=f.length))u=a>m?1:-1;else for(d=-1,u=0;++d<a;)if(i[d]!=f[d]){u=i[d]>f[d]?1:-1;break}if(u<0){for(c=m==a?i:h;m;){if(f[--m]<c[m]){for(d=m;d&&!f[--d];)f[d]=9;--f[d],f[m]+=10}f[m]-=c[m]}for(;!f[0];)f.shift()}else break}b[v++]=u?l:++l,f[0]&&u?f[m]=r[p]||0:f=[r[p]]}while((p++<w||f[0]!==Gt)&&n--);return!b[0]&&v!=1&&(b.shift(),y.e--,C--),v>C&&ar(y,C,s.RM,f[0]!==Gt),y};ge.eq=function(t){return this.cmp(t)===0};ge.gt=function(t){return this.cmp(t)>0};ge.gte=function(t){return this.cmp(t)>-1};ge.lt=function(t){return this.cmp(t)<0};ge.lte=function(t){return this.cmp(t)<1};ge.minus=ge.sub=function(t){var e,s,r,i,n=this,o=n.constructor,a=n.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,n.plus(t);var l=n.c.slice(),u=n.e,d=t.c,h=t.e;if(!l[0]||!d[0])return d[0]?t.s=-c:l[0]?t=new o(n):t.s=1,t;if(a=u-h){for((i=a<0)?(a=-a,r=l):(h=u,r=d),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(s=((i=l.length<d.length)?l:d).length,a=c=0;c<s;c++)if(l[c]!=d[c]){i=l[c]<d[c];break}if(i&&(r=l,l=d,d=r,t.s=-t.s),(c=(s=d.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;s>a;){if(l[--s]<d[s]){for(e=s;e&&!l[--e];)l[e]=9;--l[e],l[s]+=10}
2l[s]-=d[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};ge.mod=function(t){var e,s=this,r=s.constructor,i=s.s,n=(t=new r(t)).s;if(!t.c[0])throw Error(bu);return s.s=t.s=1,e=t.cmp(s)==1,s.s=i,t.s=n,e?new r(s):(i=r.DP,n=r.RM,r.DP=r.RM=0,s=s.div(t),r.DP=i,r.RM=n,this.minus(s.times(t)))};ge.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};ge.plus=ge.add=function(t){var e,s,r,i=this,n=i.constructor;if(t=new n(t),i.s!=t.s)return t.s=-t.s,i.minus(t);var o=i.e,a=i.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new n(i):t.s=i.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,r=l):(e=-e,r=a),r.reverse();e--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),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};ge.pow=function(t){var e=this,s=new e.constructor("1"),r=s,i=t<0;if(t!==~~t||t<-ic||t>ic)throw Error(or+"exponent");for(i&&(t=-t);t&1&&(r=r.times(e)),t>>=1,!!t;)e=e.times(e);return i?s.div(r):r};ge.prec=function(t,e){if(t!==~~t||t<1||t>Xs)throw Error(or+"precision");return ar(new this.constructor(this),t,e)};ge.round=function(t,e){if(t===Gt)t=0;else if(t!==~~t||t<-Xs||t>Xs)throw Error(ro);return ar(new this.constructor(this),t+this.e+1,e)};ge.sqrt=function(){var t,e,s,r=this,i=r.constructor,n=r.s,o=r.e,a=new i("0.5");if(!r.c[0])return new i(r);if(n<0)throw Error(hn+"No square root");n=Math.sqrt(+cr(r,!0,!0)),n===0||n===1/0?(e=r.c.join(""),e.length+o&1||(e+="0"),n=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new i((n==1/0?"5e":(n=n.toExponential()).slice(0,n.indexOf("e")+1))+o)):t=new i(n+""),o=t.e+(i.DP+=4);do s=t,t=a.times(s.plus(r.div(s)));while(s.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return ar(t,(i.DP-=4)+t.e+1,i.RM)};ge.times=ge.mul=function(t){var e,s=this,r=s.constructor,i=s.c,n=(t=new r(t)).c,o=i.length,a=n.length,c=s.e,l=t.e;if(t.s=s.s==t.s?1:-1,!i[0]||!n[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=i,i=n,n=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]+n[c]*i[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};ge.toExponential=function(t,e){var s=this,r=s.c[0];if(t!==Gt){if(t!==~~t||t<0||t>Xs)throw Error(ro);for(s=ar(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return cr(s,!0,!!r)};ge.toFixed=function(t,e){var s=this,r=s.c[0];if(t!==Gt){if(t!==~~t||t<0||t>Xs)throw Error(ro);for(s=ar(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return cr(s,!1,!!r)};ge[Symbol.for("nodejs.util.inspect.custom")]=ge.toJSON=ge.toString=function(){var t=this,e=t.constructor;return cr(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};ge.toNumber=function(){var t=+cr(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(hn+"Imprecise conversion");return t};ge.toPrecision=function(t,e){var s=this,r=s.constructor,i=s.c[0];if(t!==Gt){if(t!==~~t||t<1||t>Xs)throw Error(or+"precision");for(s=ar(new r(s),t,e);s.c.length<t;)s.c.push(0)}return cr(s,t<=s.e||s.e<=r.NE||s.e>=r.PE,!!i)};ge.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(hn+"valueOf disallowed");return cr(t,t.e<=e.NE||t.e>=e.PE,!0)};var ni=vu();const xh={bigNumber(t){return t?new ni(t):new ni(0)},multiply(t,e){if(t===void 0||e===void 0)return new ni(0);const s=new ni(t),r=new ni(e);return s.times(r)},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(t){return t===void 0?0:parseFloat(t.replace(/,/gu,""))}},kh=[{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"}]}
2],Rh=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Uh=[{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"}]}],Dh={getERC20Abi:t=>H.USDT_CONTRACT_ADDRESSES.includes(t)?Uh:kh,getSwapAbi:()=>Rh},ps={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,r,i]=e;if(!s||!r||!i)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:r,address:i}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,r]=e;if(!s||!r)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:r}}},ee={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections"};function fo(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const X={setItem(t,e){mi()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(mi())return localStorage.getItem(t)||void 0},removeItem(t){mi()&&localStorage.removeItem(t)},clear(){mi()&&localStorage.clear()}};function mi(){return typeof window<"u"&&typeof localStorage<"u"}function Is(t,e){return e==="light"?{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const Mh=Symbol(),nc=Object.getPrototypeOf,Yo=new WeakMap,Lh=t=>t&&(Yo.has(t)?Yo.get(t):nc(t)===Object.prototype||nc(t)===Array.prototype),jh=t=>Lh(t)&&t[Mh]||null,oc=(t,e=!0)=>{Yo.set(t,e)},Gn={},go=t=>typeof t=="object"&&t!==null,bs=new WeakMap,wi=new WeakSet,Bh=(t=Object.is,e=(l,u)=>new Proxy(l,u),s=l=>go(l)&&!wi.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),r=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,n=(l,u,d=r)=>{const h=i.get(l);if((h==null?void 0:h[0])===u)return h[1];const p=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return oc(p,!0),i.set(l,[u,p]),Reflect.ownKeys(l).forEach(w=>{if(Object.getOwnPropertyDescriptor(p,w))return;const f=Reflect.get(l,w),{enumerable:m}=Reflect.getOwnPropertyDescriptor(l,w),y={value:f,enumerable:m,configurable:!0};if(wi.has(f))oc(f,!1);else if(f instanceof Promise)delete y.value,y.get=()=>d(f);else if(bs.has(f)){const[b,v]=bs.get(f);y.value=n(b,v(),d)}Object.defineProperty(p,w,y)}),Object.preventExtensions(p)},o=new WeakMap,a=[1,1],c=l=>{if(!go(l))throw new Error("object required");const u=o.get(l);if(u)return u;let d=a[0];const h=new Set,p=(E,k=++a[0])=>{d!==k&&(d=k,h.forEach(A=>A(E,k)))};let w=a[1];const f=(E=++a[1])=>
2(w!==E&&!h.size&&(w=E,y.forEach(([k])=>{const A=k[1](E);A>d&&(d=A)})),d),m=E=>(k,A)=>{const R=[...k];R[1]=[E,...R[1]],p(R,A)},y=new Map,b=(E,k)=>{if((Gn?"production":void 0)!=="production"&&y.has(E))throw new Error("prop listener already exists");if(h.size){const A=k[3](m(E));y.set(E,[k,A])}else y.set(E,[k])},v=E=>{var k;const A=y.get(E);A&&(y.delete(E),(k=A[1])==null||k.call(A))},C=E=>(h.add(E),h.size===1&&y.forEach(([A,R],W)=>{if((Gn?"production":void 0)!=="production"&&R)throw new Error("remove already exists");const _=A[3](m(W));y.set(W,[A,_])}),()=>{h.delete(E),h.size===0&&y.forEach(([A,R],W)=>{R&&(R(),y.set(W,[A]))})}),S=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),N=e(S,{deleteProperty(E,k){const A=Reflect.get(E,k);v(k);const R=Reflect.deleteProperty(E,k);return R&&p(["delete",[k],A]),R},set(E,k,A,R){const W=Reflect.has(E,k),_=Reflect.get(E,k,R);if(W&&(t(_,A)||o.has(A)&&t(_,o.get(A))))return!0;v(k),go(A)&&(A=jh(A)||A);let $=A;if(A instanceof Promise)A.then(O=>{A.status="fulfilled",A.value=O,p(["resolve",[k],O])}).catch(O=>{A.status="rejected",A.reason=O,p(["reject",[k],O])});else{!bs.has(A)&&s(A)&&($=c(A));const O=!wi.has($)&&bs.get($);O&&b(k,O)}return Reflect.set(E,k,$,R),p(["set",[k],A,_]),!0}});o.set(l,N);const U=[S,f,n,C];return bs.set(N,U),Reflect.ownKeys(l).forEach(E=>{const k=Object.getOwnPropertyDescriptor(l,E);"value"in k&&(N[E]=l[E],delete k.value,delete k.writable),Object.defineProperty(S,E,k)}),N})=>[c,bs,wi,t,e,s,r,i,n,o,a],[qh]=Bh();function _e(t={}){return qh(t)}function Xe(t,e,s){const r=bs.get(t);(Gn?"production":void 0)!=="production"&&!r&&console.warn("Please use proxy object");let i;const n=[],o=r[3];let a=!1;const l=o(u=>{n.push(u),i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(n.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Ri(t,e){const s=bs.get(t);(Gn?"production":void 0)!=="production"&&!s&&console.warn("Please use proxy object");const[r,i,n]=s;return n(r,i(),e)}function Qs(t){return wi.add(t),t}function Qe(t,e,s,r){let i=t[e];return Xe(t,()=>{const n=t[e];Object.is(i,n)||s(i=n)})}function Fh(t){const e=_e({data:Array.from([]),has(s){return this.data.some(r=>r[0]===s)},set(s,r){const i=this.data.find(n=>n[0]===s);return i?i[1]=r:this.data.push([s,r]),this},get(s){var r;return(r=this.data.find(i=>i[0]===s))==null?void 0:r[1]},delete(s){const r=this.data.findIndex(i=>i[0]===s);return r===-1?!1:(this.data.splice(r,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)},forEach(s){this.data.forEach(r=>{s(r[1],r[0],this)})},keys(){return this.data.map(s=>s[0]).values()},values(){return this.data.map(s=>s[1]).values()},entries(){return new Map(this.data).entries()},get[Symbol.toStringTag](){return"Map"},[Symbol.iterator](){return this.entries()}});return Object.defineProperties(e,{data:{enumerable:!1},size:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(e),e}const Eu=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],zh="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",Ee={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,ONE_SEC_MS:1e3,BALANCE_SUPPORTED_CHAINS:["eip155","solana"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:["eip155","solana"],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["coinbase","meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1}
vendor: 6,110 bytes, line 2
2,DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal"}},F={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=F.getActiveNamespace(),e=F.getActiveCaipNetworkId(),s=e?e.split(":")[1]:void 0,r=s?isNaN(Number(s))?s:Number(s):void 0;return{namespace:t,caipNetworkId:e,chainId:r}},setWalletConnectDeepLink({name:t,href:e}){try{X.setItem(ee.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=X.getItem(ee.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{X.removeItem(ee.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{X.setItem(ee.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{X.setItem(ee.ACTIVE_CAIP_NETWORK_ID,t),F.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return X.getItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{X.removeItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=fo(t);X.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=F.getRecentWallets();e.find(r=>r.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),X.setItem(ee.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=X.getItem(ee.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const s=fo(t);X.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return X.getItem(ee.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=fo(t);return X.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",t)}},setConnectedSocialProvider(t){try{X.setItem(ee.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return X.getItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{X.removeItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return X.getItem(ee.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var s;const t=X.getItem(ee.ACTIVE_CAIP_NETWORK_ID);return(s=t==null?void 0:t.split(":"))==null?void 0:s[1]},setConnectionStatus(t){try{X.setItem(ee.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return X.getItem(ee.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=X.getItem(ee.CONNECTED_NAMESPACES);return t!=null&&t.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));X.setItem(ee.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=F.getConnectedNamespaces();e.includes(t)||(e.push(t),F.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=F.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),F.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return X.getItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{X.setItem(ee.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{X.removeItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=X.getItem(ee.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=F.getBalanceCache();X.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=F.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;F.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=F.getBalanceCache();e[t.caipAddress]=t,X.setItem(ee.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=X.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=F.getBalanceCache();X.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=F.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),F.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=F.getNativeBalanceCache();e[t.caipAddress]=t,X.setItem(ee.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=X.getItem(ee.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t}
2,getEnsFromCacheForAddress(t){try{const s=F.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;F.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=F.getEnsCache();e[t.address]=t,X.setItem(ee.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=F.getEnsCache();X.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=X.getItem(ee.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=F.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;F.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=F.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},X.setItem(ee.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=F.getIdentityCache();X.setItem(ee.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{X.removeItem(ee.PORTFOLIO_CACHE),X.removeItem(ee.NATIVE_BALANCE_CACHE),X.removeItem(ee.ENS_CACHE),X.removeItem(ee.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{X.setItem(ee.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=X.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={...F.getConnections(),[e]:t};X.setItem(ee.CONNECTIONS,JSON.stringify(s))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=X.getItem(ee.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}}},Z={isMobile(){var t;return this.isClient()?!!(typeof(window==null?void 0:window.matchMedia)=="function"&&((t=window==null?void 0:window.matchMedia("(pointer:coarse)"))!=null&&t.matches)||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t==null?void 0:t.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return Z.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window==null?void 0:window.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=Ee.TEN_SEC_MS:!0},isAllowedRetry(t,e=Ee.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return(window==null?void 0:window.self)!==(window==null?void 0:window.top)}catch{return!1}},isSafeApp(){var t,e;if(Z.isClient()&&window.self!==window.top)try{const s=(e=(t=window==null?void 0:window.location)==null?void 0:t.ancestorOrigins)==null?void 0:e[0],r="https://app.safe.global";if(s){const i=new URL(s),n=new URL(r);return i.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Ee.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(...r)=>{function i(){t(...r)}s&&clearTimeout(s),s=setTimeout(i,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(Z.isHttpUrl(t))return this.formatUniversalUrl(t,e);let r=t,i=s;r.includes("://")||(r=t.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),i&&!(i!=null&&i.endsWith("/"))&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const n=encodeURIComponent(e);return{redirect:`${r}wc?uri=${n}`,redirectUniversalLink:i?`${i}wc?uri=${n}`:void 0,href:r}},formatUniversalUrl(t,e){if(!Z.isHttpUrl(t))return this.formatNativeUrl(t,e);let s=t;s.endsWith("/")||(s=`${s}/`);const r=encodeURIComponent(e);return{redirect:`${s}wc?uri=${r}`,href:s}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?F.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,r,i;if(typeof window>"u")return!1;const t=(r=(s=window.matchMedia)==null?void 0:s.call(window,"(display-mode: standalone)"))==null?void 0:r.matches,e=(i=window==null?void 0:window.navigator)==null?void 0:i.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,r)=>{const i=new Image;i.onload=s,i.onerror=r,i.crossOrigin="anonymous",i.src=t});return Promise.race([e,Z.wait(2e3)])},formatBalance(t,e){let s="0.000";if(typeof t=="string"){const r=Number(t);if(r){const i=Math.floor(r*1e3)/1e3;i&&(s=i.toString())}}return`${s}${e?` ${e}`:""}`},formatBalance2(t,e){var r;let s;if(t==="0")s="0";else if(typeof t=="string"){const i=Number(t);i&&(s=(r=i.toString().match(/^-?\d+(?:\.\d{0,3})?/u))==null?void 0:r[0])}
2return{value:s??"0",rest:s==="0"?"000":"",symbol:e}},getApiUrl(){return H.W3M_API_URL},getBlockchainApiUrl(){return H.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return H.PULSE_API_URL},getUUID(){return crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){var e,s;return typeof t=="string"?t:typeof((s=(e=t==null?void 0:t.issues)==null?void 0:e[0])==null?void 0:s.message)=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const s={};return e&&t&&(t.forEach((r,i)=>{s[r]=i}),e.sort((r,i)=>{const n=s[r.id],o=s[i.id];return n!==void 0&&o!==void 0?n-o:n!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const s of t)e+=s.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[s,r]=e.split(".");return{dollars:s,pennies:r}},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(r=>{const i=r[e];return s.has(i)?!1:(s.add(i),!0)})},generateSdkVersion(t,e,s){const i=t.length===0?Ee.ADAPTER_TYPES.UNIVERSAL:t.map(n=>n.adapterType).join(",");return`${e}-${i}-${s}`},createAccount(t,e,s,r,i){return{namespace:t,address:e,type:s,publicKey:r,path:i}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),s=e[0];return e.filter(Boolean).length===3&&s in H.CHAIN_NAME_MAP},isMac(){const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window==null?void 0:window.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const i="provider_authorization_url=",n=t.substring(t.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(n),s,e);return t.replace(n,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const r=t.indexOf(e);if(r===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const i=t.indexOf("&",r),n=e.length,o=i!==-1?i:t.length,a=t.substring(0,r+n),c=t.substring(r+n,o),l=t.substring(i),u=c+s;return a+u+l}};async function oi(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class pn{constructor({baseUrl:e,clientId:s}){this.baseUrl=e,this.clientId=s}async get({headers:e,signal:s,cache:r,...i}){const n=this.createUrl(i);return(await oi(n,{method:"GET",headers:e,signal:s,cache:r})).json()}async getBlob({headers:e,signal:s,...r}){const i=this.createUrl(r);return(await oi(i,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await oi(n,{method:"POST",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}async put({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await oi(n,{method:"PUT",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}async delete({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await oi(n,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}createUrl({path:e,params:s}){const r=new URL(e,this.baseUrl);return s&&Object.entries(s).forEach(([i,n])=>{n&&r.searchParams.append(i,n)}),this.clientId&&r.searchParams.append("clientId",this.clientId),r}}const Wh={getFeatureValue(t,e){const s=e==null?void 0:e[t];return s===void 0?Ee.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(Z.isTelegram()){if(Z.isIos())return t.filter(e=>e!=="google");if(Z.isMac())return t.filter(e=>e!=="x");if(Z.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},K=_e({features:Ee.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Ee.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),T={state:K,subscribeKey(t,e){return Qe(K,t,e)},setOptions(t){Object.assign(K,t)},setRemoteFeatures(t){var s;if(!t)return;const e={...K.remoteFeatures,...t};K.remoteFeatures=e,(s=K.remoteFeatures)!=null&&s.socials&&(K.remoteFeatures.socials=Wh.filterS
2ocialsByPlatform(K.remoteFeatures.socials))},setFeatures(t){if(!t)return;K.features||(K.features=Ee.DEFAULT_FEATURES);const e={...K.features,...t};K.features=e},setProjectId(t){K.projectId=t},setCustomRpcUrls(t){K.customRpcUrls=t},setAllWallets(t){K.allWallets=t},setIncludeWalletIds(t){K.includeWalletIds=t},setExcludeWalletIds(t){K.excludeWalletIds=t},setFeaturedWalletIds(t){K.featuredWalletIds=t},setTokens(t){K.tokens=t},setTermsConditionsUrl(t){K.termsConditionsUrl=t},setPrivacyPolicyUrl(t){K.privacyPolicyUrl=t},setCustomWallets(t){K.customWallets=t},setIsSiweEnabled(t){K.isSiweEnabled=t},setIsUniversalProvider(t){K.isUniversalProvider=t},setSdkVersion(t){K.sdkVersion=t},setMetadata(t){K.metadata=t},setDisableAppend(t){K.disableAppend=t},setEIP6963Enabled(t){K.enableEIP6963=t},setDebug(t){K.debug=t},setEnableWalletConnect(t){K.enableWalletConnect=t},setEnableWalletGuide(t){K.enableWalletGuide=t},setEnableAuthLogger(t){K.enableAuthLogger=t},setEnableWallets(t){K.enableWallets=t},setPreferUniversalLinks(t){K.experimental_preferUniversalLinks=t},setHasMultipleAddresses(t){K.hasMultipleAddresses=t},setSIWX(t){K.siwx=t},setConnectMethodsOrder(t){K.features={...K.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){K.features={...K.features,walletFeaturesOrder:t}},setSocialsOrder(t){K.remoteFeatures={...K.remoteFeatures,socials:t}},setCollapseWallets(t){K.features={...K.features,collapseWallets:t}},setEnableEmbedded(t){K.enableEmbedded=t},setAllowUnsupportedChain(t){K.allowUnsupportedChain=t},setManualWCControl(t){K.manualWCControl=t},setEnableNetworkSwitch(t){K.enableNetworkSwitch=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(K.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){K.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return K.universalProviderConfigOverride},getSnapshot(){return Ri(K)}},Hh=Object.freeze({enabled:!0,events:[]}),Vh=new pn({baseUrl:Z.getAnalyticsUrl(),clientId:null}),Kh=5,Gh=60*1e3,fs=_e({...Hh}),Jh={state:fs,subscribeKey(t,e){return Qe(fs,t,e)},async sendError(t,e){if(!fs.enabled)return;const s=Date.now();if(fs.events.filter(n=>{const o=new Date(n.properties.timestamp||"").getTime();return s-o<Gh}).length>=Kh)return;const i={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};fs.events.push(i);try{if(typeof window>"u")return;const{projectId:n,sdkType:o,sdkVersion:a}=T.state;await Vh.post({path:"/e",params:{projectId:n,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:Z.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){fs.enabled=!0},disable(){fs.enabled=!1},clearEvents(){fs.events=[]}};class Lr extends Error{constructor(e,s,r){super(e),this.name="AppKitError",this.category=s,this.originalError=r,Object.setPrototypeOf(this,Lr.prototype);let i=!1;if(r instanceof Error&&typeof r.stack=="string"&&r.stack){const n=r.stack,o=n.indexOf(`
3`);if(o>-1){const a=n.substring(o+1);this.stack=`${this.name}: ${this.message}
4${a}`,i=!0}}i||(Error.captureStackTrace?Error.captureStackTrace(this,Lr):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function ac(t,e){const s=t instanceof Lr?t:new Lr(t instanceof Error?t.message:String(t),e,t);throw Jh.sendError(s,s.category),s}function Et(t,e="INTERNAL_SDK_ERROR"){const s={};return Object.keys(t).forEach(r=>{const i=t[r];if(typeof i=="function"){let n=i;i.constructor.name==="AsyncFunction"?n=async(...o)=>{try{return await i(...o)}catch(a){return ac(a,e)}}:n=(...o)=>{try{return i(...o)}catch(a){return ac(a,e)}},s[r]=n}else s[r]=i}),s}const Vt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},Yh={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,r=encodeURIComponent(s);if(t===Vt.PHANTOM.id&&!("phantom"in window)){const i=s.startsWith("https")?"https":"http",n=s.split("/")[2],o=encodeURIComponent(`${i}://${n}`);window.location.href=`${Vt.PHANTOM.url}/ul/browse/${r}?ref=${o}`}t===Vt.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Vt.SOLFLARE.url}/ul/v1/browse/${r}?ref=${r}`),e===H.CHAIN.SOLANA&&t===Vt.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Vt.COINBASE.url}/dapp?cb_url=${r}`)}},ht=_e({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Zh={state:ht,subscribeNetworkImages(t){return Xe(ht.networkImages,()=>t(ht.networkImages))},subscribeKey(t,e){return Qe(ht,t,e)},subscribe(t){return Xe(ht,()=>t(ht))},setWalletImage(t,e){ht.walletImages[t]=e},setNetworkImage(t,e){ht.networkImages[t]=e},setChainImage(t,e){ht.chainImages[t]=e},setConnectorImage(t,e){ht.connectorImages={...ht.connectorImages,[t]:e}},setTokenImage(t,e){ht.tokenImages[t]=e},setCurrencyImage(t,e){ht.currencyImages[t]=e}},Dt=Et(Zh),Xh={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},mo=_e({networkImagePromises:{}}),Cu={async fetchWalletImage(t){if(t)return await V._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(mo.networkImagePromises[t]||(mo.networkImagePromises[t]=V._fetchNetworkImage(t)),await mo.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return Dt.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 Dt.state.walletImages[t.image_id]},getNetworkImage(t){var e,s,r;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((r=t==null?void 0:t.assets)!=null&&r.imageId)return Dt.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return Dt.state.networkImages[t]},getConnectorImage(t){if(t!=null&&t.imageUrl)return t.imageUrl;if(t!=null&&t.imageId)return Dt.state.connectorImages[t.imageId]},getChainImage(t){return Dt.state.networkImages[Xh[t]]}},gs=_e({message:"",variant:"info",open:!1}),Qh={state:gs,subscribeKey(t,e){return Qe(gs,t,e)},open(t,e){const{debug:s}=T.state,{shortMessage:r,longMessage:i}=t;s&&(gs.message=r,gs.variant=e,gs.open=!0),i&&console.error(typeof i=="function"?i():i)},close(){gs.open=!1,gs.message="",gs.variant="info"}},Bs=Et(Qh),ep=Z.getAnalyticsUrl(),tp=new pn({baseUrl:ep,clientId:null}),sp=["MODAL_CREATED"],ts=_e({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Pe={state:ts,subscribe(t){return Xe(ts,()=>t(ts))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=T.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(t){try{const e=z.state.address;if(sp.includes(t.data.event)||typeof window>"u")return;await tp.post({path:"/e",params:Pe.getSdkProperties(),body:{eventId:Z.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e}}}),ts.reportedErrors.FORBIDDEN=!1}
4catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===H.HTTP_STATUS_CODES.FORBIDDEN&&!ts.reportedErrors.FORBIDDEN&&(Bs.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${mi()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),ts.reportedErrors.FORBIDDEN=!0)}},sendEvent(t){var e;ts.timestamp=Date.now(),ts.data=t,(e=T.state.features)!=null&&e.analytics&&Pe._sendAnalyticsEvent(ts)}},rp=Z.getApiUrl(),rt=new pn({baseUrl:rp,clientId:null}),ip=40,cc=4,np=20,te=_e({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),V={state:te,subscribeKey(t,e){return Qe(te,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=T.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return T.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${rt.baseUrl}/getWalletImage/${t}`,s=await rt.getBlob({path:e,params:V._getSdkProperties()});Dt.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${rt.baseUrl}/public/getAssetImage/${t}`,s=await rt.getBlob({path:e,params:V._getSdkProperties()});Dt.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${rt.baseUrl}/public/getAssetImage/${t}`,s=await rt.getBlob({path:e,params:V._getSdkProperties()});Dt.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${rt.baseUrl}/public/getCurrencyImage/${t}`,s=await rt.getBlob({path:e,params:V._getSdkProperties()});Dt.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${rt.baseUrl}/public/getTokenImage/${t}`,s=await rt.getBlob({path:e,params:V._getSdkProperties()});Dt.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){return Z.isMobile()?t==null?void 0:t.filter(s=>s.mobile_link||s.id===Vt.COINBASE.id?!0:g.state.activeChain==="solana"&&(s.id===Vt.SOLFLARE.id||s.id===Vt.PHANTOM.id)):t},async fetchProjectConfig(){return(await rt.get({path:"/appkit/v1/config",params:V._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await rt.get({path:"/projects/v1/origins",params:V._getSdkProperties()});return t}catch{return[]}},async fetchNetworkImages(){const t=g.getAllRequestedCaipNetworks(),e=t==null?void 0:t.map(({assets:s})=>s==null?void 0:s.imageId).filter(Boolean).filter(s=>!Cu.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>V._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=B.state,e=t.map(({imageId:s}
4)=>s).filter(Boolean);await Promise.allSettled(e.map(s=>V._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>V._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>V._fetchTokenImage(e)))},async fetchWallets(t){var n;const e=t.exclude??[];V._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Vt).map(o=>o.id));const r=await rt.get({path:"/getWallets",params:{...V._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:(n=t.include)==null?void 0:n.join(","),exclude:e.join(",")}});return{data:V._filterWalletsByPlatform(r==null?void 0:r.data)||[],count:r==null?void 0:r.count}},async fetchFeaturedWallets(){const{featuredWalletIds:t}=T.state;if(t!=null&&t.length){const e={...V._getSdkProperties(),page:1,entries:(t==null?void 0:t.length)??cc,include:t},{data:s}=await V.fetchWallets(e),r=[...s].sort((n,o)=>t.indexOf(n.id)-t.indexOf(o.id)),i=r.map(n=>n.image_id).filter(Boolean);await Promise.allSettled(i.map(n=>V._fetchWalletImage(n))),te.featured=r,te.allFeatured=r}},async fetchRecommendedWallets(){try{te.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=T.state,r=[...e??[],...s??[]].filter(Boolean),i=g.getRequestedCaipNetworkIds().join(","),n={page:1,entries:cc,include:t,exclude:r,chains:i},{data:o,count:a}=await V.fetchWallets(n),c=F.getRecentWallets(),l=o.map(d=>d.image_id).filter(Boolean),u=c.map(d=>d.image_id).filter(Boolean);await Promise.allSettled([...l,...u].map(d=>V._fetchWalletImage(d))),te.recommended=o,te.allRecommended=o,te.count=a??0}catch{}finally{te.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:r}=T.state,i=g.getRequestedCaipNetworkIds().join(","),n=[...te.recommended.map(({id:u})=>u),...s??[],...r??[]].filter(Boolean),o={page:t,entries:ip,include:e,exclude:n,chains:i},{data:a,count:c}=await V.fetchWallets(o),l=a.slice(0,np).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(l.map(u=>V._fetchWalletImage(u))),te.wallets=Z.uniqueBy([...te.wallets,...V._filterOutExtensions(a)],"id").filter(u=>{var d;return(d=u.chains)==null?void 0:d.some(h=>i.includes(h))}),te.count=c>te.count?c:te.count,te.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await V.fetchWallets(e);s&&s.forEach(r=>{te.excludedWallets.push({rdns:r.rdns,name:r.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:r}=T.state,i=g.getRequestedCaipNetworkIds().join(",");te.search=[];const n={page:1,entries:100,search:t==null?void 0:t.trim(),badge_type:e,include:s,exclude:r,chains:i},{data:o}=await V.fetchWallets(n);Pe.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=>V._fetchWalletImage(c)),Z.wait(300)]),te.search=V._filterOutExtensions(o)},initPromise(t,e){const s=te.promises[t];return s||(te.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:r=!0}={}){const i=[t&&V.initPromise("connectorImages",V.fetchConnectorImages),e&&V.initPromise("featuredWallets",V.fetchFeaturedWallets),s&&V.initPromise("recommendedWallets",V.fetchRecommendedWallets),r&&V.initPromise("networkImages",V.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){var t;(t=T.state.features)!=null&&t.analytics&&V.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await rt.get({path:"/getAnalyticsConfig",params:V._getSdkProperties()});T.setFeatures({analytics:t})}catch{T.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!(t!=null&&t.length)){te.featured=te.allFeatured,te.recommended=te.allRecommended;return}const e=g.getRequestedCaipNetworkIds().join(",");te.featured=te.allFeatured.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))}),te.recommended=te.allRecommended.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))}),te.filteredWallets=te.wallets.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))})},clearFilterByNamespaces(){te.filteredWallets=[]},setFilterByNamespace(t){if(!t){te.featured=te.allFeatured,te.recommended=te.allRecommended;return}const e=g.getRequestedCaipNetworkIds().join(",");te.featured=te.allFeatured.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))}),te.recommended=te.allRecommended.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))}),te.filteredWallets=te.wallets.filter(s=>{var r;return(r=s.chains)==null?void 0:r.some(i=>e.includes(i))})}},me=_e({view:"Connect",history:["Connect"],transactionStack:[]}),op={state:me,subscribeKey(t,e){return Qe(me,t,e)},pushTransactionStack(t){me.transactionStack.push(t)},popTransactionStack(t){const e=me.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:r,onCancel:i}=e;switch(t){case"success":s==null||s();break;case"error":r==null||r(),re.goBack();break;case"cancel":i==null||i(),re.goBack();break}},push(t,e){t!==me.view&&(me.view=t,me.history.push(t),me.data=e)},reset(t,e){me.view=t,me.history=[t],me.data=e},replace(t,e){me.history.at(-1)===t||(me.view=t,me.history[me.history.length-1]=t,me.data=e)},goBack(){var r;const t=g.state.activeCaipAddress,e=re.state.view==="ConnectingFarcaster",s=!t&&e;if(me.history.length>1){me.history.pop();const[i]=me.history.slice(-1);i&&(t&&i==="Connect"?me.view="Account":me.view=i)}else ze.close();(r=me.data)!=null&&r.wallet&&(me.data.wallet=void 0),setTimeout(()=>{var i,n,o;if(s){z.setFarcasterUrl(void 0,g.state.activeChain);const a=B.getAuthConnector();(i=a==null?void 0:a.provider)==null||i.reload();const c=Ri(T.state);(o=(n=a==null?void 0:a.provider)==null?void 0:n.syncDappData)==null||o.call(n,{metadata:c.metadata,sdkVersion:c.sdkVersion,projectId:c.projectId,sdkType:c.sdkType})}},100)},goBackToIndex(t){if(me.history.length>1){me.history=me.history.slice(0,t+1);const[e]=me.history.slice(-1);e&&(me.view=e)}},goBackOrCloseModal(){re.state.history.length>1?re.goBack():ze.close()}},re=Et(op),ss=_e({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Zo={state:ss,subscribe(t){return Xe(ss,()=>t(ss))},setThemeMode(t){ss.themeMode=t;try{const e=B.getAuthConnector();if(e){const s=Zo.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:Is(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){ss.themeVariables={...ss.themeVariables,...t};try{const e=B.getAuthConnector();if(e){const s=Zo.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:Is(ss.themeVariables,ss.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Ri(ss)}},gt=Et(Zo),Iu={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},ae=_e({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...Iu},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),ap={state:ae,subscribe(t){return Xe(ae,()=>{t(ae)})},subscribeKey(t,e){return Qe(ae,t,e)}
4,initialize(t){t.forEach(e=>{const s=F.getConnectedConnectorId(e);s&&B.setConnectorId(s,e)})},setActiveConnector(t){t&&(ae.activeConnector=Qs(t))},setConnectors(t){t.filter(i=>!ae.allConnectors.some(n=>n.id===i.id&&B.getConnectorName(n.name)===B.getConnectorName(i.name)&&n.chain===i.chain)).forEach(i=>{i.type!=="MULTI_CHAIN"&&ae.allConnectors.push(Qs(i))});const s=B.getEnabledNamespaces(),r=B.getEnabledConnectors(s);ae.connectors=B.mergeMultiChainConnectors(r)},filterByNamespaces(t){Object.keys(ae.filterByNamespaceMap).forEach(e=>{ae.filterByNamespaceMap[e]=!1}),t.forEach(e=>{ae.filterByNamespaceMap[e]=!0}),B.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){ae.filterByNamespaceMap[t]=e,B.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=B.getEnabledNamespaces(),e=B.getEnabledConnectors(t),s=B.areAllNamespacesEnabled();ae.connectors=B.mergeMultiChainConnectors(e),s?V.clearFilterByNamespaces():V.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(ae.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return ae.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(ae.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=B.generateConnectorMapByName(t),s=[];return e.forEach(r=>{const i=r[0],n=(i==null?void 0:i.id)===H.CONNECTOR_ID.AUTH;r.length>1&&i?s.push({name:i.name,imageUrl:i.imageUrl,imageId:i.imageId,connectors:[...r],type:n?"AUTH":"MULTI_CHAIN",chain:"eip155",id:(i==null?void 0:i.id)||""}):i&&s.push(i)}),s},generateConnectorMapByName(t){const e=new Map;return t.forEach(s=>{const{name:r}=s,i=B.getConnectorName(r);if(!i)return;const n=e.get(i)||[];n.find(a=>a.chain===s.chain)||n.push(s),e.set(i,n)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(s=>{e.find(r=>r.chain===s.chain)||e.push(s)}),e},addConnector(t){var e,s,r;if(t.id===H.CONNECTOR_ID.AUTH){const i=t,n=Ri(T.state),o=gt.getSnapshot().themeMode,a=gt.getSnapshot().themeVariables;(s=(e=i==null?void 0:i.provider)==null?void 0:e.syncDappData)==null||s.call(e,{metadata:n.metadata,sdkVersion:n.sdkVersion,projectId:n.projectId,sdkType:n.sdkType}),(r=i==null?void 0:i.provider)==null||r.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:Is(a,o)}),B.setConnectors([t])}else B.setConnectors([t])},getAuthConnector(t){var r;const e=t||g.state.activeChain,s=ae.connectors.find(i=>i.id===H.CONNECTOR_ID.AUTH);if(s)return(r=s==null?void 0:s.connectors)!=null&&r.length?s.connectors.find(n=>n.chain===e):s},getAnnouncedConnectorRdns(){return ae.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>{var e;return(e=t.info)==null?void 0:e.rdns})},getConnectorById(t){return ae.allConnectors.find(e=>e.id===t)},getConnector(t,e){return ae.allConnectors.filter(r=>r.chain===g.state.activeChain).find(r=>{var i;return r.explorerId===t||((i=r.info)==null?void 0:i.rdns)===e})},syncIfAuthConnector(t){var n,o;if(t.id!=="ID_AUTH")return;const e=t,s=Ri(T.state),r=gt.getSnapshot().themeMode,i=gt.getSnapshot().themeVariables;(o=(n=e==null?void 0:e.provider)==null?void 0:n.syncDappData)==null||o.call(n,{metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:r,themeVariables:i,w3mThemeVariables:Is(i,r)})},getConnectorsByNamespace(t){const e=ae.allConnectors.filter(s=>s.chain===t);return B.mergeMultiChainConnectors(e)},selectWalletConnector(t){const e=B.getConnector(t.id,t.rdns),s=g.state.activeChain;Yh.handleMobileDeeplinkRedirect((e==null?void 0:e.explorerId)||t.id,s),e?re.push("ConnectingExternal",{connector:e}):re.push("ConnectingWalletConnect",{wallet:t})},getConnectors(t){return t?B.getConnectorsByNamespace(t):B.mergeMultiChainConnectors(ae.allConnectors)},setFilterByNamespace(t){ae.filterByNamespace=t,ae.connectors=B.getConnectors(t),V.setFilterByNamespace(t)},setConnectorId(t,e){t&&(ae.activeConnectorIds={...ae.activeConnectorIds,[e]:t},F.setConnectedConnectorId(e,t))},removeConnectorId(t){ae.activeConnectorIds={...ae.activeConnectorIds,[t]:void 0},F.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return ae.activeConnectorIds[t]},isConnected(t){return t?!!ae.activeConnectorIds[t]:Object.values(ae.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){ae.activeConnectorIds={...Iu}}},B=Et(ap),Ii={ACCOUNT_TYPES:{SMART_ACCOUNT:"smartAccount"}},Ls=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),Ue=_e({...Ls}),cp={state:Ue,subscribeKey(t,e){return Qe(Ue,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=Z.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){Ue.message=Ls.message,Ue.variant=Ls.variant,Ue.svg=Ls.svg,Ue.open=Ls.open,Ue.autoClose=Ls.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:r=Ls.autoClose}){Ue.open?(Ue.open=!1,setTimeout(()=>{Ue.message=t,Ue.variant=s,Ue.svg=e,Ue.open=!0,Ue.autoClose=r},150)):(Ue.message=t,Ue.variant=s,Ue.svg=e,Ue.open=!0,Ue.autoClose=r)}},Mt=cp,Ie=_e({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),lp={state:Ie,subscribe(t){return Xe(Ie,()=>t(Ie))},setLastNetworkInView(t){Ie.lastNetworkInView=t},async fetchTransactions(t,e){var s,r;if(!t)throw new Error("Transactions can't be fetched without an accountAddress");Ie.loading=!0;
4try{const i=await J.fetchTransactions({account:t,cursor:Ie.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:(s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId}),n=yi.filterSpamTransactions(i.data),o=yi.filterByConnectedChain(n),a=[...Ie.transactions,...o];Ie.loading=!1,e==="coinbase"?Ie.coinbaseTransactions=yi.groupTransactionsByYearAndMonth(Ie.coinbaseTransactions,i.data):(Ie.transactions=a,Ie.transactionsByYear=yi.groupTransactionsByYearAndMonth(Ie.transactionsByYear,o)),Ie.empty=a.length===0,Ie.next=i.next?i.next:void 0}catch{const n=g.state.activeChain;Pe.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:T.state.projectId,cursor:Ie.next,isSmartAccount:((r=z.state.preferredAccountTypes)==null?void 0:r[n])===Ii.ACCOUNT_TYPES.SMART_ACCOUNT}}),Mt.showError("Failed to fetch transactions"),Ie.loading=!1,Ie.empty=!0,Ie.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const s=t;return e.forEach(r=>{const i=new Date(r.metadata.minedAt).getFullYear(),n=new Date(r.metadata.minedAt).getMonth(),o=s[i]??{},c=(o[n]??[]).filter(l=>l.id!==r.id);s[i]={...o,[n]:[...c,r].sort((l,u)=>new Date(u.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),s},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(r=>{var i;return((i=r.nft_info)==null?void 0:i.flags.is_spam)===!0}))},filterByConnectedChain(t){var r;const e=(r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId;return t.filter(i=>i.metadata.chain===e)},clearCursor(){Ie.next=void 0},resetTransactions(){Ie.transactions=[],Ie.transactionsByYear={},Ie.lastNetworkInView=void 0,Ie.loading=!1,Ie.empty=!1,Ie.next=void 0}},yi=Et(lp,"API_ERROR"),ye=_e({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let Rs;const up={state:ye,subscribeKey(t,e){return Qe(ye,t,e)},_getClient(){return ye._client},setClient(t){ye._client=Qs(t)},async connectWalletConnect(){var t,e,s,r;if(Z.isTelegram()||Z.isSafari()&&Z.isIos()){if(Rs){await Rs,Rs=void 0;return}if(!Z.isPairingExpired(ye==null?void 0:ye.wcPairingExpiry)){const i=ye.wcUri;ye.wcUri=i;return}Rs=(e=(t=Y._getClient())==null?void 0:t.connectWalletConnect)==null?void 0:e.call(t).catch(()=>{}),Y.state.status="connecting",await Rs,Rs=void 0,ye.wcPairingExpiry=void 0,Y.state.status="connected"}else await((r=(s=Y._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:r.call(s))},async connectExternal(t,e,s=!0){var r,i;await((i=(r=Y._getClient())==null?void 0:r.connectExternal)==null?void 0:i.call(r,t)),s&&g.setActiveNamespace(e)},async reconnectExternal(t){var s,r;await((r=(s=Y._getClient())==null?void 0:s.reconnectExternal)==null?void 0:r.call(s,t));const e=t.chain||g.state.activeChain;e&&B.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){var r;ze.setLoading(!0,g.state.activeChain);const s=B.getAuthConnector();s&&(z.setPreferredAccountType(t,e),await s.provider.setPreferredAccount(t),F.setPreferredAccountTypes(z.state.preferredAccountTypes??{[e]:t}),await Y.reconnectExternal(s),ze.setLoading(!1,g.state.activeChain),Pe.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}}))},async signMessage(t){var e;return(e=Y._getClient())==null?void 0:e.signMessage(t)},parseUnits(t,e){var s;return(s=Y._getClient())==null?void 0:s.parseUnits(t,e)},formatUnits(t,e){var s;return(s=Y._getClient())==null?void 0:s.formatUnits(t,e)},async sendTransaction(t){var e;return(e=Y._getClient())==null?void 0:e.sendTransaction(t)},async getCapabilities(t){var e;return(e=Y._getClient())==null?void 0:e.getCapabilities(t)},async grantPermissions(t){var e;return(e=Y._getClient())==null?void 0:e.grantPermissions(t)},async walletGetAssets(t){var e;return((e=Y._getClient())==null?void 0:e.walletGetAssets(t))??{}},async estimateGas(t){var e;return(e=Y._getClient())==null?void 0:e.estimateGas(t)},async writeContract(t){var e;return(e=Y._getClient())==null?void 0:e.writeContract(t)},async getEnsAddress(t){var e;return(e=Y._getClient())==null?void 0:e.getEnsAddress(t)},async getEnsAvatar(t){var e;return(e=Y._getClient())==null?void 0:e.getEnsAvatar(t)},checkInstalled(t){var e,s;return((s=(e=Y._getClient())==null?void 0:e.checkInstalled)==null?void 0:s.call(e,t))||!1},resetWcConnection(){ye.wcUri=void 0,ye.wcPairingExpiry=void 0,ye.wcLinking=void 0,ye.recentWallet=void 0,ye.status="disconnected",yi.resetTransactions(),F.deleteWalletConnectDeepLink()},resetUri(){ye.wcUri=void 0,ye.wcPairingExpiry=void 0,Rs=void 0},finalizeWcConnection(){var s,r;const{wcLinking:t,recentWallet:e}=Y.state;t&&F.setWalletConnectDeepLink(t),e&&F.setAppKitRecent(e),Pe.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:t?"mobile":"qrcode",name:((r=(s=re.state.data)==null?void 0:s.wallet)==null?void 0:r.name)||"Unknown"}})},setWcBasic(t){ye.wcBasic=t},setUri(t){ye.wcUri=t,ye.wcPairingExpiry=Z.getPairingExpiry()},setWcLinking(t){ye.wcLinking=t},setWcError(t){ye.wcError=t,ye.buffering=!1},setRecentWallet(t){ye.recentWallet=t},setBuffering(t){ye.buffering=t},setStatus(t){ye.status=t},async disconnect(t){var e;try{await((e=Y._getClient())==null?void 0:e.disconnect(t))}catch(s){throw new Lr("Failed to disconnect","INTERNAL_SDK_ERROR",s)}},setConnections(t,e){ye.connections.set(e,t)},switchAccount({connection:t,address:e,namespace:s}){if(B.state.activeConnectorIds[s]===t.connectorId){const n=g.state.activeCaipNetwork;if(n){const o=`${s}:${n.id}:${e}`;z.setCaipAddress(o,s)}else console.warn(`No current network found for namespace "${s}"`)}else{const n=B.getConnector(t.connectorId);n?Y.connectExternal(n,s):console.warn(`No connector found for namespace "${s}"`)}}},Y=Et(up),dr=_e({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),Ns={state:dr,subscribe(t){return Xe(dr,()=>t(dr))},subscribeOpen(t){return Qe(dr,"open",t)},set(t){Object.assign(dr,{...dr,...t})}};
4function dp(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function lc(t){return dp(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Au="2.37.9";let ai={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${Au}`},Zt=class Xo extends Error{constructor(e,s={}){var a;const r=(()=>{var c;return s.cause instanceof Xo?s.cause.details:(c=s.cause)!=null&&c.message?s.cause.message:s.details})(),i=s.cause instanceof Xo&&s.cause.docsPath||s.docsPath,n=(a=ai.getDocsUrl)==null?void 0:a.call(ai,{...s,docsPath:i}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...ai.version?[`Version: ${ai.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=r,this.docsPath=i,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=Au}walk(e){return Nu(this,e)}};function Nu(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Nu(t.cause,e):e?null:t}let _u=class extends Zt{constructor({size:e,targetSize:s,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}};function Ma(t,{dir:e,size:s=32}={}){return typeof t=="string"?hp(t,{dir:e,size:s}):pp(t,{dir:e,size:s})}function hp(t,{dir:e,size:s=32}={}){if(s===null)return t;const r=t.replace("0x","");if(r.length>s*2)throw new _u({size:Math.ceil(r.length/2),targetSize:s,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function pp(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new _u({size:t.length,targetSize:s,type:"bytes"});const r=new Uint8Array(s);for(let i=0;i<s;i++){const n=e==="right";r[n?i:s-i-1]=t[n?i:t.length-i-1]}return r}let fp=class extends Zt{constructor({max:e,min:s,signed:r,size:i,value:n}){super(`Number "${n}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${s} to ${e})`:`(above ${s})`}`,{name:"IntegerOutOfRangeError"})}},gp=class extends Zt{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function Su(t,{size:e}){if(lc(t)>e)throw new gp({givenSize:lc(t),maxSize:e})}const mp=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function uc(t,e={}){return typeof t=="number"||typeof t=="bigint"?yp(t,e):typeof t=="string"?Ou(t,e):typeof t=="boolean"?wp(t,e):Pu(t,e)}function wp(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(Su(s,{size:e.size}),Ma(s,{size:e.size})):s}function Pu(t,e={}){let s="";for(let i=0;i<t.length;i++)s+=mp[t[i]];const r=`0x${s}`;return typeof e.size=="number"?(Su(r,{size:e.size}),Ma(r,{dir:"right",size:e.size})):r}function yp(t,e={}){const{signed:s,size:r}=e,i=BigInt(t);let n;r?s?n=(1n<<BigInt(r)*8n-1n)-1n:n=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&s?-n-1n:0;if(n&&i>n||i<o){const c=typeof t=="bigint"?"n":"";throw new fp({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:s,size:r,value:`${t}${c}`})}const a=`0x${(s&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Ma(a,{size:r}):a}const bp=new TextEncoder;function Ou(t,e={}){const s=bp.encode(t);return Pu(s,e)}let vp=class 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 r=this.keys().next().value;r&&this.delete(r)}return this}};const Gs=(t,e,s)=>JSON.stringify(t,(r,i)=>typeof i=="bigint"?i.toString():i,s);function Ep(t,e){let s=t.toString();const r=s.startsWith("-");r&&(s=s.slice(1)),s=s.padStart(e,"0");let[i,n]=[s.slice(0,s.length-e),s.slice(s.length-e)];return n=n.replace(/(0+)$/,""),`${r?"-":""}${i||"0"}${n?`.${n}`:""}`}const La=t=>t;class Ai extends Zt{constructor({body:e,cause:s,details:r,headers:i,status:n,url:o}){super("HTTP request failed.",{cause:s,details:r,metaMessages:[n&&`Status: ${n}`,`URL: ${La(o)}`,e&&`Request body: ${Gs(e)}
5`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=i,this.status=n,this.url=o}}class Tu extends Zt{constructor({body:e,error:s,url:r}){super("RPC Request failed.",{cause:s,details:s.message,metaMessages:[`URL: ${La(r)}`,`Request body: ${Gs(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=s.code,this.data=s.data}}class dc extends Zt{constructor({body:e,url:s}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${La(s)}`,`Request body: ${Gs(e)}`],name:"TimeoutError"})}}const Cp=-1;class dt extends Zt{constructor(e,{code:s,docsPath:r,metaMessages:i,name:n,shortMessage:o}){super(o,{cause:e,docsPath:r,metaMessages:i||(e==null?void 0:e.metaMessages),name:n||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=n||e.name,this.code=e instanceof Tu?e.code:s??Cp}}class Ct extends dt{constructor(e,s){super(e,s),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=s.data}}class Ui extends dt{constructor(e){super(e,{code:Ui.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Ui,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Di extends dt{constructor(e){super(e,{code:Di.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Di,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Mi extends dt{constructor(e,{method:s}={}){super(e,{code:Mi.code,name:"MethodNotFoundRpcError",shortMessage:`The method${s?` "${s}"`:""} does not exist / is not available.`})}}Object.defineProperty(Mi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Li extends dt{constructor(e){super(e,{code:Li.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
6`)})}}Object.defineProperty(Li,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class jr extends dt{constructor(e){super(e,{code:jr.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(jr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class ji extends dt{constructor(e){super(e,{code:ji.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
7`)})}}Object.defineProperty(ji,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Bi extends dt{constructor(e){super(e,{code:Bi.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class qi extends dt{constructor(e){super(e,{code:qi.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(qi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Br extends dt{constructor(e){super(e,{code:Br.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Br,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Hs extends dt{constructor(e,{method:s}={}){super(e,{code:Hs.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${s?` "${s}"`:""} is not supported.`})}}Object.defineProperty(Hs,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class qr extends dt{constructor(e){super(e,{code:qr.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(qr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Fi extends dt{constructor(e){super(e,{code:Fi.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Fi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Js extends Ct{constructor(e){super(e,{code:Js.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Js,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class zi extends Ct{constructor(e){super(e,{code:zi.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(zi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Wi extends Ct{constructor(e,{method:s}={}){super(e,{code:Wi.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${s?` " ${s}"`:""}.`})}}Object.defineProperty(Wi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Hi extends Ct{constructor(e){super(e,{code:Hi.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Hi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});
7class Vi extends Ct{constructor(e){super(e,{code:Vi.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Vi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Ki extends Ct{constructor(e){super(e,{code:Ki.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Ki,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class Gi extends Ct{constructor(e){super(e,{code:Gi.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(Gi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Ji extends Ct{constructor(e){super(e,{code:Ji.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Ji,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class Yi extends Ct{constructor(e){super(e,{code:Yi.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(Yi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Zi extends Ct{constructor(e){super(e,{code:Zi.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Zi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class Xi extends Ct{constructor(e){super(e,{code:Xi.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(Xi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Qi extends Ct{constructor(e){super(e,{code:Qi.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Qi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class en extends Ct{constructor(e){super(e,{code:en.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(en,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class Ip extends dt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}class ja extends Zt{constructor({cause:e,message:s}={}){var i;const r=(i=s==null?void 0:s.replace("execution reverted: ",""))==null?void 0:i.replace("execution reverted","");super(`Execution reverted ${r?`with reason: ${r}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(ja,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(ja,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});function Ap(){let t=()=>{},e=()=>{};return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}}const wo=new Map;function Np({fn:t,id:e,shouldSplitBatch:s,wait:r=0,sort:i}){const n=async()=>{const u=c();o();const d=u.map(({args:h})=>h);d.length!==0&&t(d).then(h=>{i&&Array.isArray(h)&&h.sort(i);for(let p=0;p<u.length;p++){const{resolve:w}=u[p];w==null||w([h[p],h])}}).catch(h=>{for(let p=0;p<u.length;p++){const{reject:w}=u[p];w==null||w(h)}})},o=()=>wo.delete(e),a=()=>c().map(({args:u})=>u),c=()=>wo.get(e)||[],l=u=>wo.set(e,[...c(),u]);return{flush:o,async schedule(u){const{promise:d,resolve:h,reject:p}=Ap();return(s==null?void 0:s([...a(),u]))&&n(),c().length>0?(l({args:u,resolve:h,reject:p}),d):(l({args:u,resolve:h,reject:p}),setTimeout(n,r),d)}}}async function $u(t){return new Promise(e=>setTimeout(e,t))}function _p(t,{delay:e=100,retryCount:s=2,shouldRetry:r=()=>!0}={}){return new Promise((i,n)=>{const o=async({count:a=0}={})=>{const c=async({error:l})=>{const u=typeof e=="function"?e({count:a,error:l}):e;u&&await $u(u),o({count:a+1})};try{const l=await t();i(l)}catch(l){if(a<s&&await r({count:a,error:l}))return c({error:l});n(l)}};o()})}const Qo=256;let An=Qo,Nn;function Sp(t=11){if(!Nn||An+t>Qo*2){Nn="",An=0;for(let e=0;e<Qo;e++)Nn+=(256+Math.random()*256|0).toString(16).substring(1)}return Nn.substring(An,An+++t)}const _n=new vp(8192);function Pp(t,{enabled:e=!0,id:s}){if(!e||!s)return t();if(_n.get(s))return _n.get(s);const r=t().finally(()=>_n.delete(s));return _n.set(s,r),r}function Op(t,e={}){return async(s,r={})=>{var d;const{dedupe:i=!1,methods:n,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...r},{method:l}=s;if((d=n==null?void 0:n.exclude)!=null&&d.includes(l))throw new Hs(new Error("method not supported"),{method:l});if(n!=null&&n.include&&!n.include.includes(l))throw new Hs(new Error("method not supported"),{method:l});const u=i?Ou(`${c}.${Gs(s)}`):void 0;return Pp(()=>_p(async()=>{try{return await t(s)}catch(h){const p=h;switch(p.code){case Ui.code:throw new Ui(p);
7case Di.code:throw new Di(p);case Mi.code:throw new Mi(p,{method:s.method});case Li.code:throw new Li(p);case jr.code:throw new jr(p);case ji.code:throw new ji(p);case Bi.code:throw new Bi(p);case qi.code:throw new qi(p);case Br.code:throw new Br(p);case Hs.code:throw new Hs(p,{method:s.method});case qr.code:throw new qr(p);case Fi.code:throw new Fi(p);case Js.code:throw new Js(p);case zi.code:throw new zi(p);case Wi.code:throw new Wi(p);case Hi.code:throw new Hi(p);case Vi.code:throw new Vi(p);case Ki.code:throw new Ki(p);case Gi.code:throw new Gi(p);case Ji.code:throw new Ji(p);case Yi.code:throw new Yi(p);case Zi.code:throw new Zi(p);case Xi.code:throw new Xi(p);case Qi.code:throw new Qi(p);case en.code:throw new en(p);case 5e3:throw new Js(p);default:throw h instanceof Zt?h:new Ip(p)}}},{delay:({count:h,error:p})=>{var w;if(p&&p instanceof Ai){const f=(w=p==null?void 0:p.headers)==null?void 0:w.get("Retry-After");if(f!=null&&f.match(/\d/))return Number.parseInt(f,10)*1e3}return~~(1<<h)*o},retryCount:a,shouldRetry:({error:h})=>Tp(h)}),{enabled:i,id:u})}}function Tp(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===qr.code||t.code===jr.code:t instanceof Ai&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function $p(t,{errorInstance:e=new Error("timed out"),timeout:s,signal:r}){return new Promise((i,n)=>{(async()=>{let o;try{const a=new AbortController;s>0&&(o=setTimeout(()=>{r&&a.abort()},s)),i(await t({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&n(e),n(a)}finally{clearTimeout(o)}})()})}function xp(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const hc=xp();function kp(t,e={}){return{async request(s){var h;const{body:r,fetchFn:i=e.fetchFn??fetch,onRequest:n=e.onRequest,onResponse:o=e.onResponse,timeout:a=e.timeout??1e4}=s,c={...e.fetchOptions??{},...s.fetchOptions??{}},{headers:l,method:u,signal:d}=c;try{const p=await $p(async({signal:f})=>{const m={...c,body:Array.isArray(r)?Gs(r.map(C=>({jsonrpc:"2.0",id:C.id??hc.take(),...C}))):Gs({jsonrpc:"2.0",id:r.id??hc.take(),...r}),headers:{"Content-Type":"application/json",...l},method:u||"POST",signal:d||(a>0?f:null)},y=new Request(t,m),b=await(n==null?void 0:n(y,m))??{...m,url:t};return await i(b.url??t,b)},{errorInstance:new dc({body:r,url:t}),timeout:a,signal:!0});o&&await o(p);let w;if((h=p.headers.get("Content-Type"))!=null&&h.startsWith("application/json"))w=await p.json();else{w=await p.text();try{w=JSON.parse(w||"{}")}catch(f){if(p.ok)throw f;w={error:w}}}if(!p.ok)throw new Ai({body:r,details:Gs(w.error)||p.statusText,headers:p.headers,status:p.status,url:t});return w}catch(p){throw p instanceof Ai||p instanceof dc?p:new Ai({body:r,cause:p,url:t})}}}}function xu({key:t,methods:e,name:s,request:r,retryCount:i=3,retryDelay:n=150,timeout:o,type:a},c){const l=Sp();return{config:{key:t,methods:e,name:s,request:r,retryCount:i,retryDelay:n,timeout:o,type:a},request:Op(r,{methods:e,retryCount:i,retryDelay:n,uid:l}),value:c}}function pc(t,e={}){const{key:s="fallback",name:r="Fallback",rank:i=!1,shouldThrow:n=Rp,retryCount:o,retryDelay:a}=e;return({chain:c,pollingInterval:l=4e3,timeout:u,...d})=>{let h=t,p=()=>{};const w=xu({key:s,name:r,async request({method:f,params:m}){let y;const b=async(v=0)=>{const C=h[v]({...d,chain:c,retryCount:0,timeout:u});try{const S=await C.request({method:f,params:m});return p({method:f,params:m,response:S,transport:C,status:"success"}),S}catch(S){if(p({error:S,method:f,params:m,transport:C,status:"error"}),n(S)||v===h.length-1||(y??(y=h.slice(v+1).some(I=>{const{include:N,exclude:U}=I({chain:c}).config.methods||{};return N?N.includes(f):U?!U.includes(f):!0})),!y))throw S;return b(v+1)}};return b()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:f=>p=f,transports:h.map(f=>f({chain:c,retryCount:0}))});if(i){const f=typeof i=="object"?i:{};Up({chain:c,interval:f.interval??l,onTransports:m=>h=m,ping:f.ping,sampleCount:f.sampleCount,timeout:f.timeout,transports:h,weights:f.weights})}return w}}function Rp(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===Br.code||t.code===Js.code||ja.nodeMessage.test(t.message)||t.code===5e3))}function Up({chain:t,interval:e=4e3,onTransports:s,ping:r,sampleC
7ount:i=10,timeout:n=1e3,transports:o,weights:a={}}){const{stability:c=.7,latency:l=.3}=a,u=[],d=async()=>{const h=await Promise.all(o.map(async f=>{const m=f({chain:t,retryCount:0,timeout:n}),y=Date.now();let b,v;try{await(r?r({transport:m}):m.request({method:"net_listening"})),v=1}catch{v=0}finally{b=Date.now()}return{latency:b-y,success:v}}));u.push(h),u.length>i&&u.shift();const p=Math.max(...u.map(f=>Math.max(...f.map(({latency:m})=>m)))),w=o.map((f,m)=>{const y=u.map(I=>I[m].latency),v=1-y.reduce((I,N)=>I+N,0)/y.length/p,C=u.map(I=>I[m].success),S=C.reduce((I,N)=>I+N,0)/C.length;return S===0?[0,m]:[l*v+c*S,m]}).sort((f,m)=>m[0]-f[0]);s(w.map(([,f])=>o[f])),await $u(e),d()};d()}class Dp extends Zt{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function Sn(t,e={}){const{batch:s,fetchFn:r,fetchOptions:i,key:n="http",methods:o,name:a="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:l,retryDelay:u,raw:d}=e;return({chain:h,retryCount:p,timeout:w})=>{const{batchSize:f=1e3,wait:m=0}=typeof s=="object"?s:{},y=e.retryCount??p,b=w??e.timeout??1e4,v=t||(h==null?void 0:h.rpcUrls.default.http[0]);if(!v)throw new Dp;const C=kp(v,{fetchFn:r,fetchOptions:i,onRequest:c,onResponse:l,timeout:b});return xu({key:n,methods:o,name:a,async request({method:S,params:I}){const N={method:S,params:I},{schedule:U}=Np({id:v,wait:m,shouldSplitBatch(R){return R.length>f},fn:R=>C.request({body:R}),sort:(R,W)=>R.id-W.id}),E=async R=>s?U(R):[await C.request({body:R})],[{error:k,result:A}]=await E(N);if(d)return{error:k,result:A};if(k)throw new Tu({body:N,error:k,url:v});return A},retryCount:y,retryDelay:u,timeout:b,type:"http"},{fetchOptions:i,url:v})}}const yo={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 Ep(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],r=parseInt(s,10);return isNaN(r)?"0x0":`0x${r.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"}},fc={async getMyTokensWithBalance(t){const e=z.state.address,s=g.state.activeCaipNetwork;if(!e||!s)return[];if(s.chainNamespace==="eip155"){const i=await this.getEIP155Balances(e,s);if(i)return this.filterLowQualityTokens(i)}const r=await J.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(r.balances)},async getEIP155Balances(t,e){var s,r;try{const i=yo.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),n=await Y.getCapabilities(t);if(!((r=(s=n==null?void 0:n[i])==null?void 0:s.assetDiscovery)!=null&&r.supported))return null;const o=await Y.walletGetAssets({account:t,chainFilter:[i]});return yo.isWalletGetAssetsResponse(o)?(o[i]||[]).map(c=>yo.createBalance(c,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(t){return(t==null?void 0:t.map(e=>({...e,address:e!=null&&e.address?e.address:g.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]}},fe=_e({tokenBalances:[],loading:!1}),Mp={state:fe,subscribe(t){return Xe(fe,()=>t(fe))},subscribeKey(t,e){return Qe(fe,t,e)},setToken(t){t&&(fe.token=Qs(t))},setTokenAmount(t){fe.sendTokenAmount=t},setReceiverAddress(t){fe.receiverAddress=t},setReceiverProfileImageUrl(t){fe.receiverProfileImageUrl=t},setReceiverProfileName(t){fe.receiverProfileName=t},setNetworkBalanceInUsd(t){fe.networkBalanceInUSD=t},setLoading(t){fe.loading=t},async sendToken(){var t;try{switch(de.setLoading(!0),(t=g.state.activeCaipNetwork)==null?void 0:t.chainNamespace){case"eip155":await de.sendEvmToken();return;case"solana":await de.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}finally{de.setLoading(!1)}},async sendEvmToken(){var s,r,i,n;const t=g.state.activeChain,e=(s=z.state.preferredAccountTypes)==null?void 0:s[t];if(!de.state.sendTokenAmount||!de.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!de.state.token)throw new Error("A token is required");(r=de.state.token)!=null&&r.address?(Pe.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Ii.ACCOUNT_TYPES.SMART_ACCOUNT,token:de.state.token.address,amount:de.state.sendTokenAmount,network:((i=g.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||""}}),await de.sendERC20Token({receiverAddress:de.state.receiverAddress,tokenAddress:de.state.token.address,sendTokenAmount:de.state.sendTokenAmount,decimals:de.state.token.quantity.decimals})):(Pe.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Ii.ACCOUNT_TYPES.SMART_ACCOUNT,token:de.state.token.symbol||"",amount:de.state.sendTokenAmount,network:((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}}),await de.sendNativeToken({receiverAddress:de.state.receiverAddress,sendTokenAmount:de.state.sendTokenAmount,decimals:de.state.token.quantity.decimals}))},async fetchTokenBalance(t){var n,o;fe.loading=!0;const e=(n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,s=(o=g.state.activeCaipNetwork)==null?void 0:o.chainNamespace,r=g.state.activeCaipAddress,i=r?Z.getPlainAddress(r):void 0;if(fe.lastRetry&&!Z.isAllowedRetry(fe.lastRetry,30*Ee.ONE_SEC_MS))return fe.loading=!1,[];try{if(i&&e&&s){const a=await fc.getMyTokensWithBalance();return fe.tokenBalances=a,fe.lastRetry=void 0,a}}catch(a){fe.lastRetry=Date.now(),t==null||t(a),Mt.showError("Token Balance Unavailable")}finally{fe.loading=!1}return[]},fetchNetworkBalance(){if(fe.tokenBalances.length===0)return;const t=fc.mapBalancesToSwapTokens(fe.tokenBalances);if(!t)return;const e=t.find(s=>
7s.address===g.getActiveNetworkTokenAddress());e&&(fe.networkBalanceInUSD=e?xh.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){var n,o,a,c;re.pushTransactionStack({});const e=t.receiverAddress,s=z.state.address,r=Y.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));await Y.sendTransaction({chainNamespace:"eip155",to:e,address:s,data:"0x",value:r??BigInt(0)}),Pe.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:((n=z.state.preferredAccountTypes)==null?void 0:n.eip155)===Ii.ACCOUNT_TYPES.SMART_ACCOUNT,token:((o=de.state.token)==null?void 0:o.symbol)||"",amount:t.sendTokenAmount,network:((a=g.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)||""}}),(c=Y._getClient())==null||c.updateBalance("eip155"),de.resetSend()},async sendERC20Token(t){re.pushTransactionStack({onSuccess(){re.replace("Account")}});const e=Y.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));if(z.state.address&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const s=Z.getPlainAddress(t.tokenAddress);await Y.writeContract({fromAddress:z.state.address,tokenAddress:s,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:Dh.getERC20Abi(s),chainNamespace:"eip155"}),de.resetSend()}},async sendSolanaToken(){var t;if(!de.state.sendTokenAmount||!de.state.receiverAddress)throw new Error("An amount and receiver address are required");re.pushTransactionStack({onSuccess(){re.replace("Account")}}),await Y.sendTransaction({chainNamespace:"solana",to:de.state.receiverAddress,value:de.state.sendTokenAmount}),(t=Y._getClient())==null||t.updateBalance("solana"),de.resetSend()},resetSend(){fe.token=void 0,fe.sendTokenAmount=void 0,fe.receiverAddress=void 0,fe.receiverProfileImageUrl=void 0,fe.receiverProfileName=void 0,fe.loading=!1,fe.tokenBalances=[]}},de=Et(Mp),bo={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},Pn={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},L=_e({chains:Fh(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),Lp={state:L,subscribe(t){return Xe(L,()=>{t(L)})},subscribeKey(t,e){return Qe(L,t,e)},subscribeChainProp(t,e,s){let r;return Xe(L.chains,()=>{var n;const i=s||L.activeChain;if(i){const o=(n=L.chains.get(i))==null?void 0:n[t];r!==o&&(r=o,e(o))}})},initialize(t,e,s){const{chainId:r,namespace:i}=F.getActiveNetworkProps(),n=e==null?void 0:e.find(u=>u.id.toString()===(r==null?void 0:r.toString())),a=t.find(u=>(u==null?void 0:u.namespace)===i)||(t==null?void 0:t[0]),c=t.map(u=>u.namespace).filter(u=>u!==void 0),l=T.state.enableEmbedded?new Set([...c]):new Set([...(e==null?void 0:e.map(u=>u.chainNamespace))??[]]);((t==null?void 0:t.length)===0||!a)&&(L.noAdapters=!0),L.noAdapters||(L.activeChain=a==null?void 0:a.namespace,L.activeCaipNetwork=n,g.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:n}),L.activeChain&&Ns.set({activeChain:a==null?void 0:a.namespace})),l.forEach(u=>{const d=e==null?void 0:e.filter(h=>h.chainNamespace===u);g.state.chains.set(u,{namespace:u,networkState:_e({...Pn,caipNetwork:d==null?void 0:d[0]}),accountState:_e(bo),caipNetworks:d??[],...s}),g.setRequestedCaipNetworks(d??[],u)})},removeAdapter(t){var e,s;if(L.activeChain===t){const r=Array.from(L.chains.entries()).find(([i])=>i!==t);if(r){const i=(s=(e=r[1])==null?void 0:e.caipNetworks)==null?void 0:s[0];i&&g.setActiveCaipNetwork(i)}}L.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:s},r){L.chains.set(t.namespace,{namespace:t.namespace,networkState:{...Pn,caipNetwork:r[0]},accountState:bo,caipNetworks:r,connectionControllerClient:s,networkControllerClient:e}),g.setRequestedCaipNetworks((r==null?void 0:r.filter(i=>i.chainNamespace===t.namespace))??[],t.namespace)},addNetwork(t){var s;const e=L.chains.get(t.chainNamespace);if(e){const r=[...e.caipNetworks||[]];(s=e.caipNetworks)!=null&&s.find(i=>i.id===t.id)||r.push(t),L.chains.set(t.chainNamespace,{...e,caipNetworks:r}),g.setRequestedCaipNetworks(r,t.chainNamespace),B.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){var r,i,n;const s=L.chains.get(t);if(s){const o=((r=L.activeCaipNetwork)==null?void 0:r.id)===e,a=[...((i=s.caipNetworks)==null?void 0:i.filter(c=>c.id!==e))||[]];o&&((n=s==null?void 0:s.caipNetworks)!=null&&n[0])&&g.setActiveCaipNetwork(s.caipNetworks[0]),L.chains.set(t,{...s,caipNetworks:a}),g.setRequestedCaipNetworks(a||[],t),a.length===0&&B.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=L.chains.get(t);s&&(s.networkState={...s.networkState||Pn,...e},L.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const r=L.chains.get(t);if(r){const i={...r.accountState||bo,...e};L.chains.set(t,{...r,accountState:i}),(L.chains.size===1||L.activeChain===t)&&(e.caipAddress&&(L.activeCaipAddress=e.caipAddress),z.replaceState(i))}},setChainNetworkData(t,e){if(!t)return;const s=L.chains.get(t);if(s){const r={...s.networkState||Pn,...e};L.chains.set(t,{...s,networkState:r})}}
7,setAccountProp(t,e,s,r=!0){g.setChainAccountData(s,{[t]:e},r),t==="status"&&e==="disconnected"&&s&&B.removeConnectorId(s)},setActiveNamespace(t){var r,i;L.activeChain=t;const e=t?L.chains.get(t):void 0,s=(r=e==null?void 0:e.networkState)==null?void 0:r.caipNetwork;s!=null&&s.id&&t&&(L.activeCaipAddress=(i=e==null?void 0:e.accountState)==null?void 0:i.caipAddress,L.activeCaipNetwork=s,g.setChainNetworkData(t,{caipNetwork:s}),F.setActiveCaipNetworkId(s==null?void 0:s.caipNetworkId),Ns.set({activeChain:t,selectedNetworkId:s==null?void 0:s.caipNetworkId}))},setActiveCaipNetwork(t){var r,i,n;if(!t)return;L.activeChain!==t.chainNamespace&&g.setIsSwitchingNamespace(!0);const e=L.chains.get(t.chainNamespace);L.activeChain=t.chainNamespace,L.activeCaipNetwork=t,g.setChainNetworkData(t.chainNamespace,{caipNetwork:t}),(r=e==null?void 0:e.accountState)!=null&&r.address?L.activeCaipAddress=`${t.chainNamespace}:${t.id}:${(i=e==null?void 0:e.accountState)==null?void 0:i.address}`:L.activeCaipAddress=void 0,g.setAccountProp("caipAddress",L.activeCaipAddress,t.chainNamespace),e&&z.replaceState(e.accountState),de.resetSend(),Ns.set({activeChain:L.activeChain,selectedNetworkId:(n=L.activeCaipNetwork)==null?void 0:n.caipNetworkId}),F.setActiveCaipNetworkId(t.caipNetworkId),!g.checkIfSupportedNetwork(t.chainNamespace)&&T.state.enableNetworkSwitch&&!T.state.allowUnsupportedChain&&!Y.state.wcBasic&&g.showUnsupportedChainUI()},addCaipNetwork(t){var s;if(!t)return;const e=L.chains.get(t.chainNamespace);e&&((s=e==null?void 0:e.caipNetworks)==null||s.push(t))},async switchActiveNamespace(t){var i;if(!t)return;const e=t!==g.state.activeChain,s=(i=g.getNetworkData(t))==null?void 0:i.caipNetwork,r=g.getCaipNetworkByNamespace(t,s==null?void 0:s.id);e&&r&&await g.switchActiveNetwork(r)},async switchActiveNetwork(t){var i;const e=g.state.chains.get(g.state.activeChain),s=!((i=e==null?void 0:e.caipNetworks)!=null&&i.some(n=>{var o;return n.id===((o=L.activeCaipNetwork)==null?void 0:o.id)})),r=g.getNetworkControllerClient(t.chainNamespace);if(r){try{await r.switchCaipNetwork(t),s&&ze.close()}catch{re.goBack()}Pe.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})}},getNetworkControllerClient(t){const e=t||L.activeChain,s=L.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||L.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=L.chains.get(e);if(!(s!=null&&s.connectionControllerClient))throw new Error("ConnectionController client not set");return s.connectionControllerClient},getAccountProp(t,e){var i;let s=L.activeChain;if(e&&(s=e),!s)return;const r=(i=L.chains.get(s))==null?void 0:i.accountState;if(r)return r[t]},getNetworkProp(t,e){var r;const s=(r=L.chains.get(e))==null?void 0:r.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=L.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:r=[]}=(e==null?void 0:e.networkState)||{};return Z.sortRequestedNetworks(s,r)},getAllRequestedCaipNetworks(){const t=[];return L.chains.forEach(e=>{const s=g.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){g.setAdapterNetworkState(e,{requestedCaipNetworks:t});const r=g.getAllRequestedCaipNetworks().map(n=>n.chainNamespace),i=Array.from(new Set(r));B.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const t=[];return L.chains.forEach(e=>{const s=g.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(){return L.activeCaipNetwork},getActiveCaipAddress(){return L.activeCaipAddress},getApprovedCaipNetworkIds(t){var r;const e=L.chains.get(t);return((r=e==null?void 0:e.networkState)==null?void 0:r.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){const s=e||L.activeCaipNetwork,r=g.getRequestedCaipNetworks(t);return r.length?r==null?void 0:r.some(i=>i.id===(s==null?void 0:s.id)):!0},checkIfSupportedChainId(t){if(!L.activeChain)return!0;const e=g.getRequestedCaipNetworks(L.activeChain);return e==null?void 0:e.some(s=>s.id===t)},setSmartAccountEnabledNetworks(t,e){g.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){var r;const t=yu.caipNetworkIdToNumber((r=L.activeCaipNetwork)==null?void 0:r.caipNetworkId),e=L.activeChain;if(!e||!t)return!1;const s=g.getNetworkProp("smartAccountEnabledNetworks",e);return!!(s!=null&&s.includes(Number(t)))},getActiveNetworkTokenAddress(){var r,i;const t=((r=L.activeCaipNetwork)==null?void 0:r.chainNamespace)||"eip155",e=((i=L.activeCaipNetwork)==null?void 0:i.id)||1,s=Ee.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`},showUnsupportedChainUI(){ze.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=L.activeCaipNetwork;return!!(t!=null&&t.chainNamespace&&Ee.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){g.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(t){const e=t;if(!e)throw new Error("Chain is required to set account prop");L.activeCaipAddress=void 0,g.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol
7:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountTypes:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),B.removeConnectorId(e)},setIsSwitchingNamespace(t){L.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){var s,r;const t=[];let e;if(L.chains.forEach(i=>{H.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===i.namespace)&&i.namespace&&t.push(i.namespace)}),t.length>0){const i=t[0];return e=i?(r=(s=L.chains.get(i))==null?void 0:s.caipNetworks)==null?void 0:r[0]:void 0,e}},getAccountData(t){var e;return t?(e=g.state.chains.get(t))==null?void 0:e.accountState:z.state},getNetworkData(t){var s;const e=t||L.activeChain;if(e)return(s=g.state.chains.get(e))==null?void 0:s.networkState},getCaipNetworkByNamespace(t,e){var i,n,o;if(!t)return;const s=g.state.chains.get(t),r=(i=s==null?void 0:s.caipNetworks)==null?void 0:i.find(a=>a.id===e);return r||((n=s==null?void 0:s.networkState)==null?void 0:n.caipNetwork)||((o=s==null?void 0:s.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const t=B.state.filterByNamespace;return(t?[L.chains.get(t)]:Array.from(L.chains.values())).flatMap(s=>(s==null?void 0:s.caipNetworks)||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?g.getRequestedCaipNetworks(t):g.getAllRequestedCaipNetworks()}},g=Et(Lp),jp={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"}]}]},ku=Z.getBlockchainApiUrl(),it=_e({clientId:null,api:new pn({baseUrl:ku,clientId:null}),supportedChains:{http:[],ws:[]}}),J={state:it,async get(t){const{st:e,sv:s}=J.getSdkProperties(),r=T.state.projectId,i={...t.params||{},st:e,sv:s,projectId:r};return it.api.get({...t,params:i})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=T.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{it.supportedChains.http.length||await J.getSupportedNetworks()}catch{return!1}return it.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await J.get({path:"v1/supported-chains"});return it.supportedChains=t,t}catch{return it.supportedChains}},async fetchIdentity({address:t,caipNetworkId:e}){if(!await J.isNetworkSupported(e))return{avatar:"",name:""};const r=F.getIdentityFromCacheForAddress(t);if(r)return r;const i=await J.get({path:`/v1/identity/${t}`,params:{sender:g.state.activeCaipAddress?Z.getPlainAddress(g.state.activeCaipAddress):void 0}});return F.updateIdentityCache({address:t,identity:i,timestamp:Date.now()}),i},async fetchTransactions({account:t,cursor:e,onramp:s,signal:r,cache:i,chainId:n}){var a;return await J.isNetworkSupported((a=g.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?J.get({path:`/v1/account/${t}/history`,params:{cursor:e,onramp:s,chainId:n},signal:r,cache:i}):{data:[],next:void 0}},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:r,gasPrice:i}){var o;return await J.isNetworkSupported((o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?J.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:s,to:r,gasPrice:i}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){var s;return await J.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){var s;return await J.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?it.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:T.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){var r;return await J.isNetworkSupported((r=g.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?J.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){var i;const{st:e,sv:s}=J.getSdkProperties();if(!await J.isNetworkSupported((i=g.state.activeCaipNetwork)==null?void 0:i.caipNetworkId))throw new Error("Network not supported for Gas Price");return J.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:s}})},async generateSwapCalldata({amount:t,from:e,to:s,userAddress:r,disableEstimate:i}){var o;if(!await J.isNetworkSupported((o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return it.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:Ee.CONVERT_SLIPPAGE_TOLERANCE},projectId:T.state.projectId,from:e,to:s,userAddress:r,disableEstimate:i}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){var o;const{st:r,sv:i}=J.getSdkProperties();if(!await J.isNetworkSupported((o=g.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return J.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:t,to:e,st:r,sv:i}})},async getBalance(t,e,s){var l;const{st:r,sv:i}=J.getSdkProperties();if(!await J.isNetworkSupported((l=g.state.activeCaipNetwork)==null?void 0:l.caipNetworkId))return Mt.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=F.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await J.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:r,sv:i}});return F.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){var s;return await J.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){var s;return await J.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:`/v1/profile/reverse/${t}`,params:{sender:z.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(t){var s;return await J.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:r}){var n;return await J.isNetworkSupported((n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?it.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:s,signature:r},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:s,purchaseAmount:r,paymentAmount:i}){var a;return await J.isNetworkSupported((a=g.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await it.api.post({path:"/v1/generators/onrampurl",params:{projectId:T.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:r,presetFiatAmount:i}})).url:""},async getOnrampOptions(){var e;if(!await J.isNetworkSupported((e=g.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await J.get({path:"/v1/onramp/options"})}catch{return jp}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:r}){var i;try{return await J.isNetworkSupported((i=g.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?await it.api.post({path:"/v1/onramp/quote",params:{projectId:T.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:s,network:r}}):null}catch{return{coinbaseFee:{amount:s,currency:e.id},networkFee:{amount:s,currency:e.id},paymentSubtotal:{amount:s,currency:e.id},paymentTotal:{amount:s,currency:e.id},purchaseAmount:{amount:s,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){var s;return await J.isNetworkSupported((s=g.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?J.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){var i;return await J.isNetworkSupported((i=g.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?it.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:T.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){it.clientId=t,it.api=new pn({baseUrl:ku,clientId:t})}},It=_e({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),Bp={state:It,replaceState(t){t&&Object.assign(It,Qs(t))},subscribe(t){return g.subscribeChainProp("accountState",e=>
7{if(e)return t(e)})},subscribeKey(t,e,s){let r;return g.subscribeChainProp("accountState",i=>{if(i){const n=i[t];r!==n&&(r=n,e(n))}},s)},setStatus(t,e){g.setAccountProp("status",t,e)},getCaipAddress(t){return g.getAccountProp("caipAddress",t)},setCaipAddress(t,e){const s=t?Z.getPlainAddress(t):void 0;e===g.state.activeChain&&(g.state.activeCaipAddress=t),g.setAccountProp("caipAddress",t,e),g.setAccountProp("address",s,e)},setBalance(t,e,s){g.setAccountProp("balance",t,s),g.setAccountProp("balanceSymbol",e,s)},setProfileName(t,e){g.setAccountProp("profileName",t,e)},setProfileImage(t,e){g.setAccountProp("profileImage",t,e)},setUser(t,e){g.setAccountProp("user",t,e)},setAddressExplorerUrl(t,e){g.setAccountProp("addressExplorerUrl",t,e)},setSmartAccountDeployed(t,e){g.setAccountProp("smartAccountDeployed",t,e)},setCurrentTab(t){g.setAccountProp("currentTab",t,g.state.activeChain)},setTokenBalance(t,e){t&&g.setAccountProp("tokenBalance",t,e)},setShouldUpdateToAddress(t,e){g.setAccountProp("shouldUpdateToAddress",t,e)},setAllAccounts(t,e){g.setAccountProp("allAccounts",t,e)},addAddressLabel(t,e,s){const r=g.getAccountProp("addressLabels",s)||new Map;r.set(t,e),g.setAccountProp("addressLabels",r,s)},removeAddressLabel(t,e){const s=g.getAccountProp("addressLabels",e)||new Map;s.delete(t),g.setAccountProp("addressLabels",s,e)},setConnectedWalletInfo(t,e){g.setAccountProp("connectedWalletInfo",t,e,!1)},setPreferredAccountType(t,e){g.setAccountProp("preferredAccountTypes",{...It.preferredAccountTypes,[e]:t},e)},setPreferredAccountTypes(t){It.preferredAccountTypes=t},setSocialProvider(t,e){t&&g.setAccountProp("socialProvider",t,e)},setSocialWindow(t,e){g.setAccountProp("socialWindow",t?Qs(t):void 0,e)},setFarcasterUrl(t,e){g.setAccountProp("farcasterUrl",t,e)},async fetchTokenBalance(t){var n,o;It.balanceLoading=!0;const e=(n=g.state.activeCaipNetwork)==null?void 0:n.caipNetworkId,s=(o=g.state.activeCaipNetwork)==null?void 0:o.chainNamespace,r=g.state.activeCaipAddress,i=r?Z.getPlainAddress(r):void 0;if(It.lastRetry&&!Z.isAllowedRetry(It.lastRetry,30*Ee.ONE_SEC_MS))return It.balanceLoading=!1,[];try{if(i&&e&&s){const c=(await J.getBalance(i,e)).balances.filter(l=>l.quantity.decimals!=="0");return z.setTokenBalance(c,s),It.lastRetry=void 0,It.balanceLoading=!1,c}}catch(a){It.lastRetry=Date.now(),t==null||t(a),Mt.showError("Token Balance Unavailable")}finally{It.balanceLoading=!1}return[]},resetAccount(t){g.resetAccount(t)}},z=Et(Bp),qp={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const s=g.state.activeCaipNetwork,r=re.state.data;if(t.id===(s==null?void 0:s.id))return;const n=z.getCaipAddress(g.state.activeChain),o=t.chainNamespace!==g.state.activeChain,a=z.getCaipAddress(t.chainNamespace),l=B.getConnectorId(g.state.activeChain)===H.CONNECTOR_ID.AUTH,u=H.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(d=>d===t.chainNamespace);e||l&&u?re.push("SwitchNetwork",{...r,network:t}):n&&o&&!a?re.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):re.push("SwitchNetwork",{...r,network:t})}},nt=_e({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),Fp={state:nt,subscribe(t){return Xe(nt,()=>t(nt))},subscribeKey(t,e){return Qe(nt,t,e)},async open(t){var o,a;const e=z.state.status==="connected",s=t==null?void 0:t.namespace,r=g.state.activeChain,i=s&&s!==r,n=(o=g.getAccountData(t==null?void 0:t.namespace))==null?void 0:o.caipAddress;if(Y.state.wcBasic?V.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await V.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),B.setFilterByNamespace(t==null?void 0:t.namespace),ze.setLoading(!0,s),s&&i){const c=((a=g.getNetworkData(s))==null?void 0:a.caipNetwork)||g.getRequestedCaipNetworks(s)[0];c&&qp.onSwitchNetwork({network:c,ignoreSwitchConfirmation:!0})}else{const c=g.state.noAdapters;T.state.manualWCControl||c&&!n?Z.isMobile()?re.reset("AllWallets"):re.reset("ConnectingWalletConnectBasic"):t!=null&&t.view?re.reset(t.view,t.data):n?re.reset("Account"):re.reset("Connect")}nt.open=!0,Ns.set({open:!0}),Pe.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!n}})},close(){const t=T.state.enableEmbedded,e=!!g.state.activeCaipAddress;nt.open&&Pe.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),nt.open=!1,re.reset("Connect"),ze.clearLoading(),t?e?re.replace("Account"):re.push("Connect"):Ns.set({open:!1}),Y.resetUri()}
7,setLoading(t,e){e&&nt.loadingNamespaceMap.set(e,t),nt.loading=t,Ns.set({loading:t})},clearLoading(){nt.loadingNamespaceMap.clear(),nt.loading=!1},shake(){nt.shake||(nt.shake=!0,setTimeout(()=>{nt.shake=!1},500))}},ze=Et(Fp),Ni={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},ea={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},zp={providers:Eu,selectedProvider:null,error:null,purchaseCurrency:Ni,paymentCurrency:ea,purchaseCurrencies:[Ni],paymentCurrencies:[],quotesLoading:!1},oe=_e(zp),Wp={state:oe,subscribe(t){return Xe(oe,()=>t(oe))},subscribeKey(t,e){return Qe(oe,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=g.state.activeChain===H.CHAIN.SOLANA?"SOL":"USDC",s=z.state.address??"",r=new URL(t.url);r.searchParams.append("publicKey",zh),r.searchParams.append("destinationCurrencyCode",e),r.searchParams.append("walletAddress",s),r.searchParams.append("externalCustomerId",T.state.projectId),oe.selectedProvider={...t,url:r.toString()}}else oe.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=Eu.filter(r=>e.includes(r.name));oe.providers=s}else oe.providers=[]},setPurchaseCurrency(t){oe.purchaseCurrency=t},setPaymentCurrency(t){oe.paymentCurrency=t},setPurchaseAmount(t){ta.state.purchaseAmount=t},setPaymentAmount(t){ta.state.paymentAmount=t},async getAvailableCurrencies(){const t=await J.getOnrampOptions();oe.purchaseCurrencies=t.purchaseCurrencies,oe.paymentCurrencies=t.paymentCurrencies,oe.paymentCurrency=t.paymentCurrencies[0]||ea,oe.purchaseCurrency=t.purchaseCurrencies[0]||Ni,await V.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await V.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){var t,e;oe.quotesLoading=!0;try{const s=await J.getOnrampQuote({purchaseCurrency:oe.purchaseCurrency,paymentCurrency:oe.paymentCurrency,amount:((t=oe.paymentAmount)==null?void 0:t.toString())||"0",network:(e=oe.purchaseCurrency)==null?void 0:e.symbol});return oe.quotesLoading=!1,oe.purchaseAmount=Number(s==null?void 0:s.purchaseAmount.amount),s}catch(s){return oe.error=s.message,oe.quotesLoading=!1,null}finally{oe.quotesLoading=!1}},resetState(){oe.selectedProvider=null,oe.error=null,oe.purchaseCurrency=Ni,oe.paymentCurrency=ea,oe.purchaseCurrencies=[Ni],oe.paymentCurrencies=[],oe.paymentAmount=void 0,oe.purchaseAmount=void 0,oe.quotesLoading=!1}},ta=Et(Wp),gc=2147483648,Hp={convertEVMChainIdToCoinType(t){if(t>=gc)throw new Error("Invalid chainId");return(gc|t)>>>0}},At=_e({suggestions:[],loading:!1}),Vp={state:At,subscribe(t){return Xe(At,()=>t(At))},subscribeKey(t,e){return Qe(At,t,e)},async resolveName(t){var e,s;try{return await J.lookupEnsName(t)}catch(r){const i=r;throw new Error(((s=(e=i==null?void 0:i.reasons)==null?void 0:e[0])==null?void 0:s.description)||"Error resolving name")}},async isNameRegistered(t){try{return await J.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{At.loading=!0,At.suggestions=[];const e=await J.getEnsNameSuggestions(t);return At.suggestions=e.suggestions.map(s=>({...s,name:s.name}))||[],At.suggestions}catch(e){const s=_i.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{At.loading=!1}},async getNamesForAddress(t){try{if(!g.state.activeCaipNetwork)return[];const s=F.getEnsFromCacheForAddress(t);if(s)return s;const r=await J.reverseLookupEnsName({address:t});return F.updateEnsCache({address:t,ens:r,timestamp:Date.now()}),r}catch(e){const s=_i.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){const e=g.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const s=z.state.address,r=B.getAuthConnector();if(!s||!r)throw new Error("Address or auth connector not found");At.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});re.pushTransactionStack({onCancel(){re.replace("RegisterAccountName")}});const n=await Y.signMessage(i);At.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=Hp.convertEVMChainIdToCoinType(Number(o));await J.registerEnsName({coinType:a,address:s,signature:n,message:i}),z.setProfileName(t,e.chainNamespace),re.replace("RegisterAccountNameSuccess")}catch(i){const n=_i.parseEnsApiError(i,`Error registering name ${t}`);throw re.replace("RegisterAccountName"),new Error(n)}finally{At.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){var r,i;const s=t;return((i=(r=s==null?void 0:s.reasons)==null?void 0:r[0])==null?void 0:i.description)||e}},_i=Et(Vp);var Kp=Object.defineProperty,Gp=(t,e,s)=>e in t?Kp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mc=(t,e,s)=>Gp(t,typeof e!="symbol"?e+"":e,s);let Jp=class extends Zr{constructor(e){super(),this.opts=e,mc(this,"protocol","wc"),mc(this,"version",2)}};var Yp=Object.defineProperty,Zp=(t,e,s)=>e in t?Yp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Xp=(t,e,s)=>Zp(t,e+"",s);let Qp=class extends Zr{constructor(e,s){super(),this.core=e,this.logger=s,Xp(this,"records",new Map)}},ef=class{constructor(e,s){this.logger=e,this.core=s}},tf=class extends Zr{constructor(e,s){super(),this.relayer=e,this.logger=s}},sf=class extends Zr{constructor(e){super()}},rf=class{constructor(e,s,r,i){this.core=e,this.logger=s,this.name=r}},nf=class extends Zr{constructor(e,s){super(),this.relayer=e,this.logger=s}},of=class extends Zr{constructor(e,s){super(),this.core=e,this.logger=s}},af=class{constructor(e,s,r){this.core=e,this.logger=s,this.store=r}},cf=class{constructor(e,s){this.projectId=e,this.logger=s}},lf=class{constructor(e,s,r){this.core=e,this.logger=s,this.telemetryEnabled=r}};var uf=Object.defineProperty,df=(t,e,s)=>e in t?uf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,wc=(t,e,s)=>df(t,typeof e!="symbol"?e+"":e,s);let hf=class{constructor(e){this.opts=e,wc(this,"protocol","wc"),wc(this,"version",2)}},pf=class{constructor(e){this.client=e}};
7function tn(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function yc(t){return tn(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Ru="2.23.2";let ci={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${Ru}`};class er extends Error{constructor(e,s={}){var a;const r=(()=>{var c;return s.cause instanceof er?s.cause.details:(c=s.cause)!=null&&c.message?s.cause.message:s.details})(),i=s.cause instanceof er&&s.cause.docsPath||s.docsPath,n=(a=ci.getDocsUrl)==null?void 0:a.call(ci,{...s,docsPath:i}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...ci.version?[`Version: ${ci.version}`]:[]].join(`
8`);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=r,this.docsPath=i,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=Ru}walk(e){return Uu(this,e)}}function Uu(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Uu(t.cause,e):e?null:t}class Du extends er{constructor({size:e,targetSize:s,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}}function Qr(t,{dir:e,size:s=32}={}){return typeof t=="string"?ff(t,{dir:e,size:s}):gf(t,{dir:e,size:s})}function ff(t,{dir:e,size:s=32}={}){if(s===null)return t;const r=t.replace("0x","");if(r.length>s*2)throw new Du({size:Math.ceil(r.length/2),targetSize:s,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function gf(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new Du({size:t.length,targetSize:s,type:"bytes"});const r=new Uint8Array(s);for(let i=0;i<s;i++){const n=e==="right";r[n?i:s-i-1]=t[n?i:t.length-i-1]}return r}class mf extends er{constructor({max:e,min:s,signed:r,size:i,value:n}){super(`Number "${n}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${s} to ${e})`:`(above ${s})`}`,{name:"IntegerOutOfRangeError"})}}class wf extends er{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ei(t,{size:e}){if(yc(t)>e)throw new wf({givenSize:yc(t),maxSize:e})}function sa(t,e={}){const{signed:s}=e;e.size&&ei(t,{size:e.size});const r=BigInt(t);if(!s)return r;const i=(t.length-2)/2,n=(1n<<BigInt(i)*8n-1n)-1n;return r<=n?r:r-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function yf(t,e={}){return Number(sa(t,e))}const bf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ra(t,e={}){return typeof t=="number"||typeof t=="bigint"?Lu(t,e):typeof t=="string"?Cf(t,e):typeof t=="boolean"?vf(t,e):Mu(t,e)}function vf(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(ei(s,{size:e.size}),Qr(s,{size:e.size})):s}function Mu(t,e={}){let s="";for(let i=0;i<t.length;i++)s+=bf[t[i]];const r=`0x${s}`;return typeof e.size=="number"?(ei(r,{size:e.size}),Qr(r,{dir:"right",size:e.size})):r}function Lu(t,e={}){const{signed:s,size:r}=e,i=BigInt(t);let n;r?s?n=(1n<<BigInt(r)*8n-1n)-1n:n=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&s?-n-1n:0;if(n&&i>n||i<o){const c=typeof t=="bigint"?"n":"";throw new mf({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:s,size:r,value:`${t}${c}`})}const a=`0x${(s&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Qr(a,{size:r}):a}const Ef=new TextEncoder;function Cf(t,e={}){const s=Ef.encode(t);return Mu(s,e)}const If=new TextEncoder;function Af(t,e={}){return typeof t=="number"||typeof t=="bigint"?_f(t,e):typeof t=="boolean"?Nf(t,e):tn(t)?ju(t,e):Bu(t,e)}function Nf(t,e={}){const s=new Uint8Array(1);return s[0]=Number(t),typeof e.size=="number"?(ei(s,{size:e.size}),Qr(s,{size:e.size})):s}const rs={zero:48,nine:57,A:65,F:70,a:97,f:102};function bc(t){if(t>=rs.zero&&t<=rs.nine)return t-rs.zero;if(t>=rs.A&&t<=rs.F)return t-(rs.A-10);if(t>=rs.a&&t<=rs.f)return t-(rs.a-10)}function ju(t,e={}){let s=t;e.size&&(ei(s,{size:e.size}),s=Qr(s,{dir:"right",size:e.size}));let r=s.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,n=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=bc(r.charCodeAt(a++)),l=bc(r.charCodeAt(a++));if(c===void 0||l===void 0)throw new er(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);n[o]=c*16+l}return n}function _f(t,e){const s=Lu(t,e);return ju(s)}function Bu(t,e={}){const s=If.encode(t);return typeof e.size=="number"?(ei(s,{size:e.size}),Qr(s,{dir:"right",size:e.size})):s}
8function qu(t,e){const s=e||"hex",r=fh(tn(t,{strict:!1})?Af(t):t);return s==="bytes"?r:ra(r)}class Sf 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 r=this.keys().next().value;r&&this.delete(r)}return this}}const vo=new Sf(8192);function Pf(t,e){if(vo.has(`${t}.${e}`))return vo.get(`${t}.${e}`);const s=t.substring(2).toLowerCase(),r=qu(Bu(s),"bytes"),i=s.split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(r[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const n=`0x${i.join("")}`;return vo.set(`${t}.${e}`,n),n}function Of(t){const e=qu(`0x${t.substring(4)}`).substring(26);return Pf(`0x${e}`)}async function Tf({hash:t,signature:e}){const s=tn(t)?t:ra(t),{secp256k1:r}=await Go(async()=>{const{secp256k1:o}=await import("./index-CRPZpX17.js").then(a=>a.eB);return{secp256k1:o}},__vite__mapDeps([0,1]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:d,yParity:h}=e,p=Number(h??d),w=vc(p);return new r.Signature(sa(l),sa(u)).addRecoveryBit(w)}const o=tn(e)?e:ra(e),a=yf(`0x${o.slice(130)}`),c=vc(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(s.substring(2)).toHex(!1)}`}function vc(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 $f({hash:t,signature:e}){return Of(await Tf({hash:t,signature:e}))}var xf={};const kf=":";function Ur(t){const[e,s]=t.split(kf);return{namespace:e,reference:s}}function Fu(t,e){return t.includes(":")?[t]:e.chains||[]}var Rf=Object.defineProperty,Uf=Object.defineProperties,Df=Object.getOwnPropertyDescriptors,Ec=Object.getOwnPropertySymbols,Mf=Object.prototype.hasOwnProperty,Lf=Object.prototype.propertyIsEnumerable,Cc=(t,e,s)=>e in t?Rf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ic=(t,e)=>{for(var s in e||(e={}))Mf.call(e,s)&&Cc(t,s,e[s]);if(Ec)for(var s of Ec(e))Lf.call(e,s)&&Cc(t,s,e[s]);return t},jf=(t,e)=>Uf(t,Df(e));const Bf="ReactNative",yt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},qf="js";function Jn(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function xs(){return!ds.getDocument()&&!!ds.getNavigator()&&navigator.product===Bf}function Ff(){return xs()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function zf(){return xs()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function ti(){return!Jn()&&!!ds.getNavigator()&&!!ds.getDocument()}
8function fn(){return xs()?yt.reactNative:Jn()?yt.node:ti()?yt.browser:yt.unknown}function Ac(){var t;try{return xs()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Wf(t,e){const s=new URLSearchParams(t);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const i=e[r];i!==void 0&&s.set(r,i)}return s.toString()}function Hf(t){var e,s;const r=zu();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),jf(Ic(Ic({},r),t),{url:(t==null?void 0:t.url)||r.url,name:(t==null?void 0:t.name)||r.name,description:(t==null?void 0:t.description)||r.description,icons:(s=t==null?void 0:t.icons)!=null&&s.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function zu(){return gh.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Vf(){if(fn()===yt.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:s,Version:r}=global.Platform;return[s,r].join("-")}const t=wh();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 Kf(){var t;const e=fn();return e===yt.browser?[e,((t=ds.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function Wu(t,e,s){const r=Vf(),i=Kf();return[[t,e].join("-"),[qf,s].join("-"),r,i].join("/")}function Gf({protocol:t,version:e,relayUrl:s,sdkVersion:r,auth:i,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),u=Wu(t,e,r),d={auth:i,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=Wf(l[1]||"",d);return l[0]+"?"+h}function Vs(t,e){return t.filter(s=>e.includes(s)).length===t.length}function ia(t){return Object.fromEntries(t.entries())}function na(t){return new Map(Object.entries(t))}function js(t=M.FIVE_MINUTES,e){const s=M.toMiliseconds(t||M.FIVE_MINUTES);let r,i,n,o;return{resolve:a=>{n&&r&&(clearTimeout(n),r(a),o=Promise.resolve(a))},reject:a=>{n&&i&&(clearTimeout(n),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),r=a,i=c})}}function As(t,e,s){return new Promise(async(r,i)=>{const n=setTimeout(()=>i(new Error(s)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(n)})}function Hu(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 Jf(t){return Hu("topic",t)}function Yf(t){return Hu("id",t)}function Vu(t){const[e,s]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")r.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))r.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return r}function De(t,e){return M.fromMiliseconds(Date.now()+M.toMiliseconds(t))}function vs(t){return Date.now()>=M.toMiliseconds(t)}function pe(t,e){return`${t}${e?`:${e}`:""}`}function Jt(t=[],e=[]){return[...new Set([...t,...e])]}async function Zf({id:t,topic:e,wcDeepLink:s}){var r;try{if(!s)return;const i=typeof s=="string"?JSON.parse(s):s,n=i==null?void 0:i.href;if(typeof n!="string")return;const o=Xf(n,t,e),a=fn();if(a===yt.browser){if(!((r=ds.getDocument())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Qf(o)}else a===yt.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function Xf(t,e,s){const r=`requestId=${e}&sessionTopic=${s}`;
vendor: 38,779 bytes, lines 8-11
8t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${n}${rg(r,!0)}`}else i=`${i}/wc?${r}`;return i}function Qf(t){let e="_self";sg()?e="_top":(tg()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function eg(t,e){let s="";try{if(ti()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(r){console.error(r)}return s}function Nc(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),r=s.indexOf(e);return s[r+2]}function _c(){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 Ba(){return typeof process<"u"&&xf.IS_VITEST==="true"}function tg(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function sg(){try{return window.self!==window.top}catch{return!1}}function rg(t,e=!1){const s=Buffer.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function Ku(t){return Buffer.from(t,"base64").toString("utf-8")}function ig(t){return new Promise(e=>setTimeout(e,t))}function sn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ng(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function gn(t,...e){if(!ng(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 qa(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");sn(t.outputLen),sn(t.blockLen)}function Fr(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 Gu(t,e){gn(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const On=BigInt(2**32-1),Sc=BigInt(32);function og(t,e=!1){return e?{h:Number(t&On),l:Number(t>>Sc&On)}:{h:Number(t>>Sc&On)|0,l:Number(t&On)|0}}function ag(t,e=!1){let s=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:n,l:o}=og(t[i],e);[s[i],r[i]]=[n,o]}return[s,r]}const cg=(t,e,s)=>t<<s|e>>>32-s,lg=(t,e,s)=>e<<s|t>>>32-s,ug=(t,e,s)=>e<<s-32|t>>>64-s,dg=(t,e,s)=>t<<s-32|e>>>64-s,hr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function hg(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Eo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function qt(t,e){return t<<32-e|t>>>e}const Pc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function pg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Oc(t){for(let e=0;e<t.length;e++)t[e]=pg(t[e])}function fg(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function zr(t){return typeof t=="string"&&(t=fg(t)),gn(t),t}function gg(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];gn(i),e+=i.length}const s=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const n=t[r];s.set(n,i),i+=n.length}return s}let Fa=class{clone(){return this._cloneInto()}};function Ju(t){const e=r=>t().update(zr(r)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function si(t=32){if(hr&&typeof hr.getRandomValues=="function")return hr.getRandomValues(new Uint8Array(t));if(hr&&typeof hr.randomBytes=="function")return hr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Yu=[],Zu=[],Xu=[],mg=BigInt(0),li=BigInt(1),wg=BigInt(2),yg=BigInt(7),bg=BigInt(256),vg=BigInt(113);for(let t=0,e=li,s=1,r=0;t<24;t++){[s,r]=[r,(2*s+3*r)%5],Yu.push(2*(5*r+s)),Zu.push((t+1)*(t+2)/2%64);let i=mg;for(let n=0;n<7;n++)e=(e<<li^(e>>yg)*vg)%bg,e&wg&&(i^=li<<(li<<BigInt(n))-li);Xu.push(i)}const[Eg,Cg]=ag(Xu,!0),Tc=(t,e,s)=>s>32?ug(t,e,s):cg(t,e,s),$c=(t,e,s)=>s>32?dg(t,e,s):lg(t,e,s);function Ig(t,e=24){const s=new Uint32Array(10);for(let r=24-e;r<24;r++){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],u=s[c+1],d=Tc(l,u,1)^s[a],h=$c(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=d,t[o+p+1]^=h}let i=t[2],n=t[3];for(let o=0;o<24;o++){const a=Zu[o],c=Tc(i,n,a),l=$c(i,n,a),u=Yu[o];i=t[u],n=t[u+1],t[u]=c,t[u+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]^=Eg[r],t[1]^=Cg[r]}s.fill(0)}let Ag=class Qu extends Fa{constructor(e,s,r,i=!1,n=24){if(super(),this.blockLen=e,this.suffix=s,this.outputLen=r,this.enableXOF=i,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,sn(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=hg(this.state)}keccak(){Pc||Oc(this.state32),Ig(this.state32,this.rounds),Pc||Oc(this.state32),this.posOut=0,this.pos=0}update(e){Fr(this);const{blockLen:s,state:r}=this;e=zr(e);const i=e.length;for(let n=0;n<i;){const o=Math.min(s-this.pos,i-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:r,blockLen:i}=this;e[r]^=s,(s&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Fr(this,!1),gn(e),this.finish();const s=this.state,{blockLen:r}=this;for(let i=0,n=e.length;i<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-i);e.set(s.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=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 sn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Gu(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:s,suffix:r,outputLen:i,rounds:n,enableXOF:o}=this;return e||(e=new Qu(s,r,i,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Ng=(t,e,s)=>Ju(()=>new Ag(e,t,s)),_g=Ng(1,136,256/8),Sg="https://rpc.walletconnect.org/v1";function ed(t){const e=`�Ethereum Signed Message:
9${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Buffer.from(_g(s)).toString("hex")}async function Pg(t,e,s,r,i,n){switch(s.t){case"eip191":return await Og(t,e,s.s);case"eip1271":return await Tg(t,e,s.s,r,i,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}async function Og(t,e,s){return(await $f({hash:ed(e),signature:s})).toLowerCase()===t.toLowerCase()}async function Tg(t,e,s,r,i,n){const o=Ur(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l="0000000000000000000000000000000000000000000000000000000000000041",u=s.substring(2),d=ed(e).substring(2),h=a+d+c+l+u,p=await fetch(`${n||Sg}/?chainId=${r}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:$g(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:w}=await p.json();return w?w.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function $g(){return Date.now()+Math.floor(Math.random()*1e3)}function xg(t){const e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);const r=s[0];if(r===0)throw new Error("No signatures found");const i=1+r*64;if(s.length<i)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const n=Buffer.from(t,"base64").slice(1,65);return gu.encode(n)}var kg=Object.defineProperty,Rg=Object.defineProperties,Ug=Object.getOwnPropertyDescriptors,xc=Object.getOwnPropertySymbols,Dg=Object.prototype.hasOwnProperty,Mg=Object.prototype.propertyIsEnumerable,kc=(t,e,s)=>e in t?kg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Lg=(t,e)=>{for(var s in e||(e={}))Dg.call(e,s)&&kc(t,s,e[s]);if(xc)for(var s of xc(e))Mg.call(e,s)&&kc(t,s,e[s]);return t},jg=(t,e)=>Rg(t,Ug(e));const Bg="did:pkh:",za=t=>t==null?void 0:t.split(":"),qg=t=>{const e=t&&za(t);if(e)return t.includes(Bg)?e[3]:e[1]},oa=t=>{const e=t&&za(t);if(e)return e[2]+":"+e[3]},Yn=t=>{const e=t&&za(t);if(e)return e.pop()};async function Rc(t){const{cacao:e,projectId:s}=t,{s:r,p:i}=e,n=td(i,i.iss),o=Yn(i.iss);return await Pg(o,n,r,oa(i.iss),s)}const td=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,r=Yn(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0;const n=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${qg(e)}`,c=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,u=t.exp?`Expiration Time: ${t.exp}`:void 0,d=t.nbf?`Not Before: ${t.nbf}`:void 0,h=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(f=>`
10- ${f}`).join("")}`:void 0,w=Bn(t.resources);if(w){const f=rn(w);i=Yg(i,f)}return[s,r,"",i,"",n,o,a,c,l,u,d,h,p].filter(f=>f!=null).join(`
11`)};function Fg(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function zg(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function tr(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 r=t.att[s];if(Array.isArray(r))throw new Error(`Resource must be an object: ${s}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${s}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${s}`);Object.keys(r).forEach(i=>{const n=r[i];if(!Array.isArray(n))throw new Error(`Ability limits ${i} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function Wg(t,e,s,r={}){return s==null||s.sort((i,n)=>i.localeCompare(n)),{att:{[t]:Hg(e,s,r)}}}function Hg(t,e,s={}){e=e==null?void 0:e.sort((i,n)=>i.localeCompare(n));const r=e.map(i=>({[`${t}/${i}`]:[s]}));return Object.assign({},...r)}function sd(t){return tr(t),`urn:recap:${Fg(t).replace(/=/g,"")}`}function rn(t){const e=zg(t.replace("urn:recap:",""));return tr(e),e}function Vg(t,e,s){const r=Wg(t,e,s);return sd(r)}function Kg(t){return t&&t.includes("urn:recap:")}function Gg(t,e){const s=rn(t),r=rn(e),i=Jg(s,r);return sd(i)}function Jg(t,e){tr(t),tr(e);const s=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,n)=>i.localeCompare(n)),r={att:{}};return s.forEach(i=>{var n,o;Object.keys(((n=t.att)==null?void 0:n[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;r.att[i]=jg(Lg({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((l=e.att[i])==null?void 0:l[a])})})}),r}function Yg(t="",e){tr(e);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(s))return t;const r=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,h)=>d.action.localeCompare(h.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const u=Object.keys(l).map(d=>(i++,`(${i}) '${d}': '${l[d].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const n=r.join(" "),o=`${s}${n}`;return`${t?t+" ":""}${o}`}function Uc(t){var e;const s=rn(t);tr(s);const r=(e=s.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function Dc(t){const e=rn(t);tr(e);const s=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(i=>{var n;(n=i==null?void 0:i[0])!=null&&n.chains&&s.push(i[0].chains)})}),[...new Set(s.flat())]}function Bn(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return Kg(e)?e:void 0}function Co(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function rd(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wt(t,...e){if(!rd(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 Mc(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 Zg(t,e){wt(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Lc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const _s=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),Xg=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Qg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Qg)throw new Error("Non little-endian hardware is not supported");function em(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function aa(t){if(typeof t=="string")t=em(t);else if(rd(t))t=ca(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function tm(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function sm(t,e){if(t.length!==e.length)return!1;let s=0;for(let r=0;r<t.length;r++)s|=t[r]^e[r];return s===0}const rm=(t,e)=>{function s(r,...i){if(wt(r),t.nonceLength!==void 0){const l=i[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?wt(l):wt(l,t.nonceLength)}const n=t.tagLength;n&&i[1]!==void 0&&wt(i[1]);const o=e(r,...i),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");wt(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,wt(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(wt(l),n&&l.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(s,t),s};function jc(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&&!im(e))throw new Error("invalid output, must be aligned");return e}function Bc(t,e,s,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,r);const i=BigInt(32),n=BigInt(4294967295),o=Number(s>>i&n),a=Number(s&n);t.setUint32(e+4,o,r),t.setUint32(e+0,a,r)}function im(t){return t.byteOffset%4===0}function ca(t){return Uint8Array.from(t)}function Wr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const id=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),nm=id("expand 16-byte k"),om=id("expand 32-byte k"),am=_s(nm),cm=_s(om);function ce(t,e){return t<<e|t>>>32-e}function la(t){return t.byteOffset%4===0}const Tn=64,lm=16,nd=2**32-1,qc=new Uint32Array;function um(t,e,s,r,i,n,o,a){const c=i.length,l=new Uint8Array(Tn),u=_s(l),d=la(i)&&la(n),h=d?_s(i):qc,p=d?_s(n):qc;for(let w=0;w<c;o++){if(t(e,s,r,u,o,a),o>=nd)throw new Error("arx: counter overflow");const f=Math.min(Tn,c-w);if(d&&f===Tn){const m=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<lm;y++)b=m+y,p[b]=h[b]^u[y];w+=Tn;continue}for(let m=0,y;m<f;m++)y=w+m,n[y]=i[y]^l[m];w+=f}}function dm(t,e){const{allowShortKeys:s,extendNonceFn:r,counterLength:i,counterRight:n,rounds:o}=tm({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Co(i),Co(o),Lc(n),Lc(s),(a,c,l,u,d=0)=>{wt(a),wt(c),wt(l);const h=l.length;if(u===void 0&&(u=new Uint8Array(h)),wt(u),Co(d),d<0||d>=nd)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);const p=[];let w=a.length,f,m;if(w===32)p.push(f=ca(a)),m=cm;else if(w===16&&s)f=new Uint8Array(32),f.set(a),f.set(a,16),m=am,p.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);la(c)||p.push(c=ca(c));const y=_s(f);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(m,y,_s(c.subarray(0,16)),y),c=c.subarray(16)}const b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){const C=new Uint8Array(12);C.set(c,n?0:12-c.length),c=C,p.push(c)}const v=_s(c);return um(t,m,y,v,l,u,d,o),Wr(...p),u}}const He=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class hm{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=aa(e),wt(e,32);const s=He(e,0),r=He(e,2),i=He(e,4),n=He(e,6),o=He(e,8),a=He(e,10),c=He(e,12),l=He(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=He(e,16+2*u)}process(e,s,r=!1){const i=r?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],h=o[5],p=o[6],w=o[7],f=o[8],m=o[9],y=He(e,s+0),b=He(e,s+2),v=He(e,s+4),C=He(e,s+6),S=He(e,s+8),I=He(e,s+10),N=He(e,s+12),U=He(e,s+14);let E=n[0]+(y&8191),k=n[1]+((y>>>13|b<<3)&8191),A=n[2]+((b>>>10|v<<6)&8191),R=n[3]+((v>>>7|C<<9)&8191),W=n[4]+((C>>>4|S<<12)&8191),_=n[5]+(S>>>1&8191),$=n[6]+((S>>>14|I<<2)&8191),O=n[7]+((I>>>11|N<<5)&8191),j=n[8]+((N>>>8|U<<8)&8191),q=n[9]+(U>>>5|i),x=0,G=x+E*a+k*(5*m)+A*(5*f)+R*(5*w)+W*(5*p);x=G>>>13,G&=8191,G+=_*(5*h)+$*(5*d)+O*(5*u)+j*(5*l)+q*(5*c),x+=G>>>13,G&=8191;let Q=x+E*c+k*a+A*(5*m)+R*(5*f)+W*(5*w);x=Q>>>13,Q&=8191,Q+=_*(5*p)+$*(5*h)+O*(5*d)+j*(5*u)+q*(5*l),x+=Q>>>13,Q&=8191;let se=x+E*l+k*c+A*a+R*(5*m)+W*(5*f);x=se>>>13,se&=8191,se+=_*(5*w)+$*(5*p)+O*(5*h)+j*(5*d)+q*(5*u),x+=se>>>13,se&=8191;let Ce=x+E*u+k*l+A*c+R*a+W*(5*m);x=Ce>>>13,Ce&=8191,Ce+=_*(5*f)+$*(5*w)+O*(5*p)+j*(5*h)+q*(5*d),x+=Ce>>>13,Ce&=8191;let he=x+E*d+k*u+A*l+R*c+W*a;x=he>>>13,he&=8191,he+=_*(5*m)+$*(5*f)+O*(5*w)+j*(5*p)+q*(5*h),x+=he>>>13,he&=8191;let Te=x+E*h+k*d+A*u+R*l+W*c;x=Te>>>13,Te&=8191,Te+=_*a+$*(5*m)+O*(5*f)+j*(5*w)+q*(5*p),x+=Te>>>13,Te&=8191;let Me=x+E*p+k*h+A*d+R*u+W*l;x=Me>>>13,Me&=8191,Me+=_*c+$*a+O*(5*m)+j*(5*f)+q*(5*w),x+=Me>>>13,Me&=8191;let Ye=x+E*w+k*p+A*h+R*d+W*u;x=Ye>>>13,Ye&=8191,Ye+=_*l+$*c+O*a+j*(5*m)+q*(5*f),x+=Ye>>>13,Ye&=8191;let ke=x+E*f+k*w+A*p+R*h+W*d;x=ke>>>13,ke&=8191,ke+=_*u+$*l+O*c+j*a+q*(5*m),x+=ke>>>13,ke&=8191;let Re=x+E*m+k*f+A*w+R*p+W*h;x=Re>>>13,Re&=8191,Re+=_*d+$*u+O*l+j*c+q*a,x+=Re>>>13,Re&=8191,x=(x<<2)+x|0,x=x+G|0,G=x&8191,x=x>>>13,Q+=x,n[0]=G,n[1]=Q,n[2]=se,n[3]=Ce,n[4]=he,n[5]=Te,n[6]=Me,n[7]=Ye,n[8]=ke,n[9]=Re}finalize(){const{h:e,pad:s}=this,r=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let n=(i^1)-1;for(let a=0;a<10;a++)r[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|r[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;Wr(r)}update(e){Mc(this);const{buffer:s,blockLen:r}=this;e=aa(e);const i=e.length;for(let n=0;n<i;){const o=Math.min(r-this.pos,i-n);if(o===r){for(;r<=i-n;n+=r)this.process(e,n);continue}s.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===r&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){Wr(this.h,this.r,this.buffer,this.pad)}digestInto(e){Mc(this),Zg(e,this),this.finished=!0;const{buffer:s,h:r}=this;let{pos:i}=this;if(i){for(s[i++]=1;i<16;i++)s[i]=0;this.process(s,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=r[o]>>>0,e[n++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const r=e.slice(0,s);return this.destroy(),r}}function pm(t){const e=(r,i)=>t(i).update(aa(r)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=r=>t(r),e}const fm=pm(t=>new hm(t));function gm(t,e,s,r,i,n=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],h=e[2],p=e[3],w=e[4],f=e[5],m=e[6],y=e[7],b=i,v=s[0],C=s[1],S=s[2],I=o,N=a,U=c,E=l,k=u,A=d,R=h,W=p,_=w,$=f,O=m,j=y,q=b,x=v,G=C,Q=S;for(let Ce=0;Ce<n;Ce+=2)I=I+k|0,q=ce(q^I,16),_=_+q|0,k=ce(k^_,12),I=I+k|0,q=ce(q^I,8),_=_+q|0,k=ce(k^_,7),N=N+A|0,x=ce(x^N,16),$=$+x|0,A=ce(A^$,12),N=N+A|0,x=ce(x^N,8),$=$+x|0,A=ce(A^$,7),U=U+R|0,G=ce(G^U,16),O=O+G|0,R=ce(R^O,12),U=U+R|0,G=ce(G^U,8),O=O+G|0,R=ce(R^O,7),E=E+W|0,Q=ce(Q^E,16),j=j+Q|0,W=ce(W^j,12),E=E+W|0,Q=ce(Q^E,8),j=j+Q|0,W=ce(W^j,7),I=I+A|0,Q=ce(Q^I,16),O=O+Q|0,A=ce(A^O,12),I=I+A|0,Q=ce(Q^I,8),O=O+Q|0,A=ce(A^O,7),N=N+R|0,q=ce(q^N,16),j=j+q|0,R=ce(R^j,12),N=N+R|0,q=ce(q^N,8),j=j+q|0,R=ce(R^j,7),U=U+W|0,x=ce(x^U,16),_=_+x|0,W=ce(W^_,12),U=U+W|0,x=ce(x^U,8),_=_+x|0,W=ce(W^_,7),E=E+k|0,G=ce(G^E,16),$=$+G|0,k=ce(k^$,12),E=E+k|0,G=ce(G^E,8),$=$+G|0,k=ce(k^$,7);let se=0;r[se++]=o+I|0,r[se++]=a+N|0,r[se++]=c+U|0,r[se++]=l+E|0,r[se++]=u+k|0,r[se++]=d+A|0,r[se++]=h+R|0,r[se++]=p+W|0,r[se++]=w+_|0,r[se++]=f+$|0,r[se++]=m+O|0,r[se++]=y+j|0,r[se++]=b+q|0,r[se++]=v+x|0,r[se++]=C+G|0,r[se++]=S+Q|0}const mm=dm(gm,{counterRight:!1,counterLength:4,allowShortKeys:!1}),wm=new Uint8Array(16),Fc=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(wm.subarray(s))},ym=new Uint8Array(32);function zc(t,e,s,r,i){const n=t(e,s,ym),o=fm.create(n);i&&Fc(o,i),Fc(o,r);const a=new Uint8Array(16),c=Xg(a);Bc(c,0,BigInt(i?i.length:0),!0),Bc(c,8,BigInt(r.length),!0),o.update(a);const l=o.digest();return Wr(n,a),l}const bm=t=>(e,s,r)=>({encrypt(i,n){const o=i.length;n=jc(o+16,n,!1),n.set(i);const a=n.subarray(0,-16);t(e,s,a,a,1);const c=zc(t,e,s,a,r);return n.set(c,o),Wr(c),n},decrypt(i,n){n=jc(i.length-16,n,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=zc(t,e,s,o,r);if(!sm(a,c))throw new Error("invalid tag");return n.set(i.subarray(0,-16)),t(e,s,n,n,1),Wr(c),n}}),od=rm({blockSize:64,nonceLength:12,tagLength:16},bm(mm));let ad=class extends Fa{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,qa(e);const r=zr(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 i=this.blockLen,n=new Uint8Array(i);n.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return Fr(this),this.iHash.update(e),this}digestInto(e){Fr(this),gn(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:r,finished:i,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const io=(t,e,s)=>new ad(t,e).update(s).digest();io.create=(t,e)=>new ad(t,e);function vm(t,e,s){return qa(t),s===void 0&&(s=new Uint8Array(t.outputLen)),io(t,zr(s),zr(e))}const Io=new Uint8Array([0]),Wc=new Uint8Array;function Em(t,e,s,r=32){if(qa(t),sn(r),r>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/t.outputLen);s===void 0&&(s=Wc);const n=new Uint8Array(i*t.outputLen),o=io.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<i;l++)Io[0]=l+1,a.update(l===0?Wc:c).update(s).update(Io).digestInto(c),n.set(c,t.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Io.fill(0),n.slice(0,r)}const Cm=(t,e,s,r,i)=>Em(t,vm(t,e,s),r,i);function Im(t,e,s,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,r);const i=BigInt(32),n=BigInt(4294967295),o=Number(s>>i&n),a=Number(s&n),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function Am(t,e,s){return t&e^~t&s}function Nm(t,e,s){return t&e^t&s^e&s}let _m=class extends Fa{constructor(e,s,r,i){super(),this.blockLen=e,this.outputLen=s,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Eo(this.buffer)}update(e){Fr(this);const{view:s,buffer:r,blockLen:i}=this;e=zr(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(i-this.pos,n-o);if(a===i){const c=Eo(e);for(;i<=n-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fr(this),Gu(e,this),this.finished=!0;const{buffer:s,view:r,blockLen:i,isLE:n}=this;let{pos:o}=this;s[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let d=o;d<i;d++)s[d]=0;Im(r,i-8,BigInt(this.length*8),n),this.process(r,0);const a=Eo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],n)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const r=e.slice(0,s);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:r,length:i,finished:n,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=n,e.destroyed=o,i%s&&e.buffer.set(r),e}};const Sm=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ms=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ws=new Uint32Array(64);class Pm extends _m{constructor(){super(64,32,8,!1),this.A=ms[0]|0,this.B=ms[1]|0,this.C=ms[2]|0,this.D=ms[3]|0,this.E=ms[4]|0,this.F=ms[5]|0,this.G=ms[6]|0,this.H=ms[7]|0}get(){const{A:e,B:s,C:r,D:i,E:n,F:o,G:a,H:c}=this;return[e,s,r,i,n,o,a,c]}set(e,s,r,i,n,o,a,c){this.A=e|0,this.B=s|0,this.C=r|0,this.D=i|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let d=0;d<16;d++,s+=4)ws[d]=e.getUint32(s,!1);for(let d=16;d<64;d++){const h=ws[d-15],p=ws[d-2],w=qt(h,7)^qt(h,18)^h>>>3,f=qt(p,17)^qt(p,19)^p>>>10;ws[d]=f+ws[d-7]+w+ws[d-16]|0}let{A:r,B:i,C:n,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const h=qt(a,6)^qt(a,11)^qt(a,25),p=u+h+Am(a,c,l)+Sm[d]+ws[d]|0,w=(qt(r,2)^qt(r,13)^qt(r,22))+Nm(r,i,n)|0;u=l,l=c,c=a,a=o+p|0,o=n,n=i,i=r,r=p+w|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,i,n,o,a,c,l,u)}roundClean(){ws.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const mn=Ju(()=>new Pm);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const no=BigInt(0),oo=BigInt(1),Om=BigInt(2);function sr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wn(t){if(!sr(t))throw new Error("Uint8Array expected")}function Hr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Tm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Vr(t){wn(t);let e="";for(let s=0;s<t.length;s++)e+=Tm[t[s]];return e}function xr(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Wa(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?no:BigInt("0x"+t)}const is={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hc(t){if(t>=is._0&&t<=is._9)return t-is._0;if(t>=is.A&&t<=is.F)return t-(is.A-10);if(t>=is.a&&t<=is.f)return t-(is.a-10)}function Kr(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(s);for(let i=0,n=0;i<s;i++,n+=2){const o=Hc(t.charCodeAt(n)),a=Hc(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}r[i]=o*16+a}return r}function Ys(t){return Wa(Vr(t))}function nn(t){return wn(t),Wa(Vr(Uint8Array.from(t).reverse()))}function Gr(t,e){return Kr(t.toString(16).padStart(e*2,"0"))}function ao(t,e){return Gr(t,e).reverse()}function $m(t){return Kr(xr(t))}function mt(t,e,s){let r;if(typeof e=="string")try{r=Kr(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(sr(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof s=="number"&&i!==s)throw new Error(t+" of length "+s+" expected, got "+i);return r}function on(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];wn(i),e+=i.length}const s=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const n=t[r];s.set(n,i),i+=n.length}return s}function xm(t,e){if(t.length!==e.length)return!1;let s=0;for(let r=0;r<t.length;r++)s|=t[r]^e[r];return s===0}function km(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const Ao=t=>typeof t=="bigint"&&no<=t;function co(t,e,s){return Ao(t)&&Ao(e)&&Ao(s)&&e<=t&&t<s}function ls(t,e,s,r){if(!co(e,s,r))throw new Error("expected valid "+t+": "+s+" <= n < "+r+", got "+e)}function cd(t){let e;for(e=0;t>no;t>>=oo,e+=1);return e}function Rm(t,e){return t>>BigInt(e)&oo}function Um(t,e,s){return t|(s?oo:no)<<BigInt(e)}const Ha=t=>(Om<<BigInt(t-1))-oo,No=t=>new Uint8Array(t),Vc=t=>Uint8Array.from(t);function ld(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");let r=No(t),i=No(t),n=0;const o=()=>{r.fill(1),i.fill(0),n=0},a=(...u)=>s(i,r,...u),c=(u=No())=>{i=a(Vc([0]),u),r=a(),u.length!==0&&(i=a(Vc([1]),u),r=a())},l=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const d=[];for(;u<e;){r=a();const h=r.slice();d.push(h),u+=r.length}return on(...d)};return(u,d)=>{o(),c(u);let h;for(;!(h=d(l()));)c();return o(),h}}const Dm={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||sr(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function ri(t,e,s={}){const r=(i,n,o)=>{const a=Dm[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+n+", got "+c)};for(const[i,n]of Object.entries(e))r(i,n,!1);for(const[i,n]of Object.entries(s))r(i,n,!0);return t}const Mm=()=>{throw new Error("not implemented")};function ua(t){const e=new WeakMap;return(s,...r)=>{const i=e.get(s);if(i!==void 0)return i;const n=t(s,...r);return e.set(s,n),n}}var Lm=Object.freeze({__proto__:null,isBytes:sr,abytes:wn,abool:Hr,bytesToHex:Vr,numberToHexUnpadded:xr,hexToNumber:Wa,hexToBytes:Kr,bytesToNumberBE:Ys,bytesToNumberLE:nn,numberToBytesBE:Gr,numberToBytesLE:ao,numberToVarBytesBE:$m,ensureBytes:mt,concatBytes:on,equalBytes:xm,utf8ToBytes:km,inRange:co,aInRange:ls,bitLen:cd,bitGet:Rm,bitSet:Um,bitMask:Ha,createHmacDrbg:ld,validateObject:ri,notImplemented:Mm,memoized:ua});const We=BigInt(0),Oe=BigInt(1),qs=BigInt(2),jm=BigInt(3),da=BigInt(4),Kc=BigInt(5),Gc=BigInt(8);function lt(t,e){const s=t%e;return s>=We?s:e+s}function ud(t,e,s){if(e<We)throw new Error("invalid exponent, negatives unsupported");if(s<=We)throw new Error("invalid modulus");if(s===Oe)return We;let r=Oe;for(;e>We;)e&Oe&&(r=r*t%s),t=t*t%s,e>>=Oe;return r}function Ut(t,e,s){let r=t;for(;e-- >We;)r*=r,r%=s;return r}function ha(t,e){if(t===We)throw new Error("invert: expected non-zero number");if(e<=We)throw new Error("invert: expected positive modulus, got "+e);let s=lt(t,e),r=e,i=We,n=Oe;for(;s!==We;){const o=r/s,a=r%s,c=i-n*o;r=s,s=a,i=n,n=c}if(r!==Oe)throw new Error("invert: does not exist");return lt(i,e)}function Bm(t){const e=(t-Oe)/qs;let s,r,i;for(s=t-Oe,r=0;s%qs===We;s/=qs,r++);for(i=qs;i<t&&ud(i,e,t)!==t-Oe;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+Oe)/da;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const n=(s+Oe)/qs;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,l=o.pow(o.mul(o.ONE,i),s),u=o.pow(a,n),d=o.pow(a,s);for(;!o.eql(d,o.ONE);){if(o.eql(d,o.ZERO))return o.ZERO;let h=1;for(let w=o.sqr(d);h<c&&!o.eql(w,o.ONE);h++)w=o.sqr(w);const p=o.pow(l,Oe<<BigInt(c-h-1));l=o.sqr(p),u=o.mul(u,p),d=o.mul(d,l),c=h}return u}}function qm(t){if(t%da===jm){const e=(t+Oe)/da;return function(s,r){const i=s.pow(r,e);if(!s.eql(s.sqr(i),r))throw new Error("Cannot find square root");return i}}if(t%Gc===Kc){const e=(t-Kc)/Gc;return function(s,r){const i=s.mul(r,qs),n=s.pow(i,e),o=s.mul(r,n),a=s.mul(s.mul(o,qs),n),c=s.mul(o,s.sub(a,s.ONE));if(!s.eql(s.sqr(c),r))throw new Error("Cannot find square root");return c}}return Bm(t)}const Fm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function zm(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},s=Fm.reduce((r,i)=>(r[i]="function",r),e);return ri(t,s)}function Wm(t,e,s){if(s<We)throw new Error("invalid exponent, negatives unsupported");if(s===We)return t.ONE;if(s===Oe)return e;let r=t.ONE,i=e;for(;s>We;)s&Oe&&(r=t.mul(r,i)),i=t.sqr(i),s>>=Oe;return r}function Hm(t,e){const s=new Array(e.length),r=e.reduce((n,o,a)=>t.is0(o)?n:(s[a]=n,t.mul(n,o)),t.ONE),i=t.inv(r);return e.reduceRight((n,o,a)=>t.is0(o)?n:(s[a]=t.mul(n,s[a]),t.mul(n,o)),i),s}function dd(t,e){const s=e!==void 0?e:t.toString(2).length,r=Math.ceil(s/8);return{nBitLength:s,nByteLength:r}}function hd(t,e,s=!1,r={}){if(t<=We)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:n}=dd(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:s,BITS:i,BYTES:n,MASK:Ha(i),ZERO:We,ONE:Oe,create:c=>lt(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return We<=c&&c<t},is0:c=>c===We,isOdd:c=>(c&Oe)===Oe,neg:c=>lt(-c,t),eql:(c,l)=>c===l,sqr:c=>lt(c*c,t),add:(c,l)=>lt(c+l,t),sub:(c,l)=>lt(c-l,t),mul:(c,l)=>lt(c*l,t),pow:(c,l)=>Wm(a,c,l),div:(c,l)=>lt(c*ha(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ha(c,t),sqrt:r.sqrt||(c=>(o||(o=qm(t)),o(a,c))),invertBatch:c=>Hm(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>s?ao(c,n):Gr(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return s?nn(c):Ys(c)}});return Object.freeze(a)}function pd(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 fd(t){const e=pd(t);return e+Math.ceil(e/2)}function Vm(t,e,s=!1){const r=t.length,i=pd(e),n=fd(e);if(r<16||r<n||r>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+r);const o=s?nn(t):Ys(t),a=lt(o,e-Oe)+Oe;return s?ao(a,i):Gr(a,i)}const Jc=BigInt(0),$n=BigInt(1);function _o(t,e){const s=e.negate();return t?s:e}function gd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function So(t,e){gd(t,e);const s=Math.ceil(e/t)+1,r=2**(t-1);return{windows:s,windowSize:r}}function Km(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,r)=>{if(!(s instanceof e))throw new Error("invalid point at index "+r)})}function Gm(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,r)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+r)})}const Po=new WeakMap,md=new WeakMap;function Oo(t){return md.get(t)||1}function Jm(t,e){return{constTimeNegate:_o,hasPrecomputes(s){return Oo(s)!==1},unsafeLadder(s,r,i=t.ZERO){let n=s;for(;r>Jc;)r&$n&&(i=i.add(n)),n=n.double(),r>>=$n;return i},precomputeWindow(s,r){const{windows:i,windowSize:n}=So(r,e),o=[];let a=s,c=a;for(let l=0;l<i;l++){c=a,o.push(c);for(let u=1;u<n;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(s,r,i){const{windows:n,windowSize:o}=So(s,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**s-1),u=2**s,d=BigInt(s);for(let h=0;h<n;h++){const p=h*o;let w=Number(i&l);i>>=d,w>o&&(w-=u,i+=$n);const f=p,m=p+Math.abs(w)-1,y=h%2!==0,b=w<0;w===0?c=c.add(_o(y,r[f])):a=a.add(_o(b,r[m]))}return{p:a,f:c}},wNAFUnsafe(s,r,i,n=t.ZERO){const{windows:o,windowSize:a}=So(s,e),c=BigInt(2**s-1),l=2**s,u=BigInt(s);for(let d=0;d<o;d++){const h=d*a;if(i===Jc)break;let p=Number(i&c);if(i>>=u,p>a&&(p-=l,i+=$n),p===0)continue;let w=r[h+Math.abs(p)-1];p<0&&(w=w.negate()),n=n.add(w)}return n},getPrecomputes(s,r,i){let n=Po.get(r);
11return n||(n=this.precomputeWindow(r,s),s!==1&&Po.set(r,i(n))),n},wNAFCached(s,r,i){const n=Oo(s);return this.wNAF(n,this.getPrecomputes(n,s,i),r)},wNAFCachedUnsafe(s,r,i,n){const o=Oo(s);return o===1?this.unsafeLadder(s,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,s,i),r,n)},setWindowSize(s,r){gd(r,e),md.set(s,r),Po.delete(s)}}}function Ym(t,e,s,r){if(Km(s,t),Gm(r,e),s.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,n=cd(BigInt(s.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),l=Math.floor((e.BITS-1)/o)*o;let u=i;for(let d=l;d>=0;d-=o){c.fill(i);for(let p=0;p<r.length;p++){const w=r[p],f=Number(w>>BigInt(d)&BigInt(a));c[f]=c[f].add(s[p])}let h=i;for(let p=c.length-1,w=i;p>0;p--)w=w.add(c[p]),h=h.add(w);if(u=u.add(h),d!==0)for(let p=0;p<o;p++)u=u.double()}return u}function wd(t){return zm(t.Fp),ri(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...dd(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const pr=BigInt(0),To=BigInt(1);function Zm(t){return ri(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function Xm(t){const e=Zm(t),{P:s}=e,r=b=>lt(b,s),i=e.montgomeryBits,n=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),c=e.powPminus2||(b=>ud(b,s-BigInt(2),s));function l(b,v,C){const S=r(b*(v-C));return v=r(v-S),C=r(C+S),[v,C]}const u=(e.a-BigInt(2))/BigInt(4);function d(b,v){ls("u",b,pr,s),ls("scalar",v,pr,s);const C=v,S=b;let I=To,N=pr,U=b,E=To,k=pr,A;for(let W=BigInt(i-1);W>=pr;W--){const _=C>>W&To;k^=_,A=l(k,I,U),I=A[0],U=A[1],A=l(k,N,E),N=A[0],E=A[1],k=_;const $=I+N,O=r($*$),j=I-N,q=r(j*j),x=O-q,G=U+E,Q=U-E,se=r(Q*$),Ce=r(G*j),he=se+Ce,Te=se-Ce;U=r(he*he),E=r(S*r(Te*Te)),I=r(O*q),N=r(x*(O+r(u*x)))}A=l(k,I,U),I=A[0],U=A[1],A=l(k,N,E),N=A[0],E=A[1];const R=c(N);return r(I*R)}function h(b){return ao(r(b),n)}function p(b){const v=mt("u coordinate",b,n);return o===32&&(v[31]&=127),nn(v)}function w(b){const v=mt("scalar",b),C=v.length;if(C!==n&&C!==o){let S=""+n+" or "+o;throw new Error("invalid scalar, expected "+S+" bytes, got "+C)}return nn(a(v))}function f(b,v){const C=p(v),S=w(b),I=d(C,S);if(I===pr)throw new Error("invalid private or public key received");return h(I)}const m=h(e.Gu);function y(b){return f(b,m)}return{scalarMult:f,scalarMultBase:y,getSharedSecret:(b,v)=>f(b,v),getPublicKey:b=>y(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:m}}const pa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Qm=BigInt(1),Yc=BigInt(2),ew=BigInt(3),tw=BigInt(5);BigInt(8);function sw(t){const e=BigInt(10),s=BigInt(20),r=BigInt(40),i=BigInt(80),n=pa,o=t*t%n*t%n,a=Ut(o,Yc,n)*o%n,c=Ut(a,Qm,n)*t%n,l=Ut(c,tw,n)*c%n,u=Ut(l,e,n)*l%n,d=Ut(u,s,n)*u%n,h=Ut(d,r,n)*d%n,p=Ut(h,i,n)*h%n,w=Ut(p,i,n)*h%n,f=Ut(w,e,n)*l%n;return{pow_p_5_8:Ut(f,Yc,n)*t%n,b2:o}}function rw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const fa=Xm({P:pa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=pa,{pow_p_5_8:s,b2:r}=sw(t);return lt(Ut(s,ew,e)*r,e)},adjustScalarBytes:rw,randomBytes:si});function Zc(t){t.lowS!==void 0&&Hr("lowS",t.lowS),t.prehash!==void 0&&Hr("prehash",t.prehash)}function iw(t){const e=wd(t);ri(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:s,Fp:r,a:i}=e;if(s){if(!r.eql(i,r.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof s!="object"||typeof s.beta!="bigint"||typeof s.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:nw,hexToBytes:ow}=Lm;class aw extends Error{constructor(e=""){super(e)}}const as={Err:aw,_tlv:{encode:(t,e)=>{const{Err:s}=as;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const r=e.length/2,i=xr(r);if(i.length/2&128)throw new s("tlv.encode: long form length too big");const n=r>127?xr(i.length/2|128):"";return xr(t)+n+i+e},decode(t,e){const{Err:s}=as;let r=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new s("tlv.decode: wrong tlv");const i=e[r++],n=!!(i&128);let o=0;if(!n)o=i;else{const c=i&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(r,r+c);
vendor: 4,833 bytes, line 11
11if(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 u of l)o=o<<8|u;if(r+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=as;if(t<cs)throw new e("integer: negative integers are not allowed");let s=xr(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}=as;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 nw(t)}},toSig(t){const{Err:e,_int:s,_tlv:r}=as,i=typeof t=="string"?ow(t):t;wn(i);const{v:n,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,n),{v:l,l:u}=r.decode(2,c);if(u.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}=as,r=e.encode(2,s.encode(t.r)),i=e.encode(2,s.encode(t.s)),n=r+i;return e.encode(48,n)}},cs=BigInt(0),Be=BigInt(1);BigInt(2);const Xc=BigInt(3);BigInt(4);function cw(t){const e=iw(t),{Fp:s}=e,r=hd(e.n,e.nBitLength),i=e.toBytes||((f,m,y)=>{const b=m.toAffine();return on(Uint8Array.from([4]),s.toBytes(b.x),s.toBytes(b.y))}),n=e.fromBytes||(f=>{const m=f.subarray(1),y=s.fromBytes(m.subarray(0,s.BYTES)),b=s.fromBytes(m.subarray(s.BYTES,2*s.BYTES));return{x:y,y:b}});function o(f){const{a:m,b:y}=e,b=s.sqr(f),v=s.mul(b,f);return s.add(s.add(v,s.mul(f,m)),y)}if(!s.eql(s.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(f){return co(f,Be,e.n)}function c(f){const{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:b,n:v}=e;if(m&&typeof f!="bigint"){if(sr(f)&&(f=Vr(f)),typeof f!="string"||!m.includes(f.length))throw new Error("invalid private key");f=f.padStart(y*2,"0")}let C;try{C=typeof f=="bigint"?f:Ys(mt("private key",f,y))}catch{throw new Error("invalid private key, expected hex or "+y+" bytes, got "+typeof f)}return b&&(C=lt(C,v)),ls("private key",C,Be,v),C}function l(f){if(!(f instanceof h))throw new Error("ProjectivePoint expected")}const u=ua((f,m)=>{const{px:y,py:b,pz:v}=f;if(s.eql(v,s.ONE))return{x:y,y:b};const C=f.is0();m==null&&(m=C?s.ONE:s.inv(v));const S=s.mul(y,m),I=s.mul(b,m),N=s.mul(v,m);if(C)return{x:s.ZERO,y:s.ZERO};if(!s.eql(N,s.ONE))throw new Error("invZ was invalid");return{x:S,y:I}}),d=ua(f=>{if(f.is0()){if(e.allowInfinityPoint&&!s.is0(f.py))return;throw new Error("bad point: ZERO")}const{x:m,y}=f.toAffine();if(!s.isValid(m)||!s.isValid(y))throw new Error("bad point: x or y not FE");const b=s.sqr(y),v=o(m);if(!s.eql(b,v))throw new Error("bad point: equation left != right");if(!f.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(m,y,b){if(this.px=m,this.py=y,this.pz=b,m==null||!s.isValid(m))throw new Error("x required");if(y==null||!s.isValid(y))throw new Error("y required");if(b==null||!s.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(m){const{x:y,y:b}=m||{};if(!m||!s.isValid(y)||!s.isValid(b))throw new Error("invalid affine point");if(m instanceof h)throw new Error("projective point not allowed");const v=C=>s.eql(C,s.ZERO);return v(y)&&v(b)?h.ZERO:new h(y,b,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){const y=s.invertBatch(m.map(b=>b.pz));return m.map((b,v)=>b.toAffine(y[v])).map(h.fromAffine)}static fromHex(m){const y=h.fromAffine(n(mt("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return h.BASE.multiply(c(m))}static msm(m,y){return Ym(h,r,m,y)}_setWindowSize(m){w.setWindowSize(this,m)}assertValidity(){d(this)}hasEvenY(){const{y:m}=this.toAffine();if(s.isOdd)return!s.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){l(m);const{px:y,py:b,pz:v}=this,{px:C,py:S,pz:I}=m,N=s.eql(s.mul(y,I),s.mul(C,v)),U=s.eql(s.mul(b,I),s.mul(S,v));return N&&U}negate(){return new h(this.px,s.neg(this.py),this.pz)}double(){const{a:m,b:y}=e,b=s.mul(y,Xc),{px:v,py:C,pz:S}=this;let I=s.ZERO,N=s.ZERO,U=s.ZERO,E=s.mul(v,v),k=s.mul(C,C),A=s.mul(S,S),R=s.mul(v,C);return R=s.add(R,R),U=s.mul(v,S),U=s.add(U,U),I=s.mul(m,U),N=s.mul(b,A),N=s.add(I,N),I=s.sub(k,N),N=s.add(k,N),N=s.mul(I,N),I=s.mul(R,I),U=s.mul(b,U),A=s.mul(m,A),R=s.sub(E,A),R=s.mul(m,R),R=s.add(R,U),U=s.add(E,E),E=s.add(U,E),E=s.add(E,A),E=s.mul(E,R),N=s.add(N,E),A=s.mul(C,S),A=s.add(A,A),E=s.mul(A,R),I=s.sub(I,E),U=s.mul(A,k),U=s.add(U,U),U=s.add(U,U),new h(I,N,U)}add(m){l(m);const{px:y,py:b,pz:v}=this,{px:C,py:S,pz:I}=m;let N=s.ZERO,U=s.ZERO,E=s.ZERO;
11const k=e.a,A=s.mul(e.b,Xc);let R=s.mul(y,C),W=s.mul(b,S),_=s.mul(v,I),$=s.add(y,b),O=s.add(C,S);$=s.mul($,O),O=s.add(R,W),$=s.sub($,O),O=s.add(y,v);let j=s.add(C,I);return O=s.mul(O,j),j=s.add(R,_),O=s.sub(O,j),j=s.add(b,v),N=s.add(S,I),j=s.mul(j,N),N=s.add(W,_),j=s.sub(j,N),E=s.mul(k,O),N=s.mul(A,_),E=s.add(N,E),N=s.sub(W,E),E=s.add(W,E),U=s.mul(N,E),W=s.add(R,R),W=s.add(W,R),_=s.mul(k,_),O=s.mul(A,O),W=s.add(W,_),_=s.sub(R,_),_=s.mul(k,_),O=s.add(O,_),R=s.mul(W,O),U=s.add(U,R),R=s.mul(j,O),N=s.mul($,N),N=s.sub(N,R),R=s.mul($,W),E=s.mul(j,E),E=s.add(E,R),new h(N,U,E)}subtract(m){return this.add(m.negate())}is0(){return this.equals(h.ZERO)}wNAF(m){return w.wNAFCached(this,m,h.normalizeZ)}multiplyUnsafe(m){const{endo:y,n:b}=e;ls("scalar",m,cs,b);const v=h.ZERO;if(m===cs)return v;if(this.is0()||m===Be)return this;if(!y||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,m,h.normalizeZ);let{k1neg:C,k1:S,k2neg:I,k2:N}=y.splitScalar(m),U=v,E=v,k=this;for(;S>cs||N>cs;)S&Be&&(U=U.add(k)),N&Be&&(E=E.add(k)),k=k.double(),S>>=Be,N>>=Be;return C&&(U=U.negate()),I&&(E=E.negate()),E=new h(s.mul(E.px,y.beta),E.py,E.pz),U.add(E)}multiply(m){const{endo:y,n:b}=e;ls("scalar",m,Be,b);let v,C;if(y){const{k1neg:S,k1:I,k2neg:N,k2:U}=y.splitScalar(m);let{p:E,f:k}=this.wNAF(I),{p:A,f:R}=this.wNAF(U);E=w.constTimeNegate(S,E),A=w.constTimeNegate(N,A),A=new h(s.mul(A.px,y.beta),A.py,A.pz),v=E.add(A),C=k.add(R)}else{const{p:S,f:I}=this.wNAF(m);v=S,C=I}return h.normalizeZ([v,C])[0]}multiplyAndAddUnsafe(m,y,b){const v=h.BASE,C=(I,N)=>N===cs||N===Be||!I.equals(v)?I.multiplyUnsafe(N):I.multiply(N),S=C(this,y).add(C(m,b));return S.is0()?void 0:S}toAffine(m){return u(this,m)}isTorsionFree(){const{h:m,isTorsionFree:y}=e;if(m===Be)return!0;if(y)return y(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:m,clearCofactor:y}=e;return m===Be?this:y?y(h,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return Hr("isCompressed",m),this.assertValidity(),i(h,this,m)}toHex(m=!0){return Hr("isCompressed",m),Vr(this.toRawBytes(m))}}h.BASE=new h(e.Gx,e.Gy,s.ONE),h.ZERO=new h(s.ZERO,s.ONE,s.ZERO);const p=e.nBitLength,w=Jm(h,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function lw(t){const e=wd(t);return ri(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function uw(t){const e=lw(t),{Fp:s,n:r}=e,i=s.BYTES+1,n=2*s.BYTES+1;function o(_){return lt(_,r)}function a(_){return ha(_,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:d}=cw({...e,toBytes(_,$,O){const j=$.toAffine(),q=s.toBytes(j.x),x=on;return Hr("isCompressed",O),O?x(Uint8Array.from([$.hasEvenY()?2:3]),q):x(Uint8Array.from([4]),q,s.toBytes(j.y))},fromBytes(_){const $=_.length,O=_[0],j=_.subarray(1);if($===i&&(O===2||O===3)){const q=Ys(j);if(!co(q,Be,s.ORDER))throw new Error("Point is not on curve");const x=u(q);let G;try{G=s.sqrt(x)}catch(se){const Ce=se instanceof Error?": "+se.message:"";throw new Error("Point is not on curve"+Ce)}const Q=(G&Be)===Be;return(O&1)===1!==Q&&(G=s.neg(G)),{x:q,y:G}}else if($===n&&O===4){const q=s.fromBytes(j.subarray(0,s.BYTES)),x=s.fromBytes(j.subarray(s.BYTES,2*s.BYTES));return{x:q,y:x}}else{const q=i,x=n;throw new Error("invalid Point, expected length of "+q+", or uncompressed "+x+", got "+$)}}}),h=_=>Vr(Gr(_,e.nByteLength));function p(_){const $=r>>Be;return _>$}function w(_){return p(_)?o(-_):_}const f=(_,$,O)=>Ys(_.slice($,O));class m{constructor($,O,j){this.r=$,this.s=O,this.recovery=j,this.assertValidity()}static fromCompact($){const O=e.nByteLength;return $=mt("compactSignature",$,O*2),new m(f($,0,O),f($,O,2*O))}static fromDER($){const{r:O,s:j}=as.toSig(mt("DER",$));return new m(O,j)}assertValidity(){ls("r",this.r,Be,r),ls("s",this.s,Be,r)}addRecoveryBit($){return new m(this.r,this.s,$)}recoverPublicKey($){const{r:O,s:j,recovery:q}=this,x=I(mt("msgHash",$));if(q==null||![0,1,2,3].includes(q))throw new Error("recovery id invalid");const G=q===2||q===3?O+e.n:O;if(G>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const Q=(q&1)===0?"02":"03",se=c.fromHex(Q+h(G)),Ce=a(G),he=o(-x*Ce),Te=o(j*Ce),Me=c.BASE.multiplyAndAddUnsafe(se,he,Te);if(!Me)throw new Error("point at infinify");return Me.assertValidity(),Me}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Kr(this.toDERHex())}toDERHex(){return as.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Kr(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}const y={isValidPrivateKey(_){try{return l(_),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const _=fd(e.n);return Vm(e.randomBytes(_),e.n)},precompute(_=8,$=c.BASE){return $._setWindowSize(_),$.multiply(BigInt(3)),$}};function b(_,$=!0){return c.fromPrivateKey(_).toRawBytes($)}function v(_){const $=sr(_),O=typeof _=="string",j=($||O)&&_.length;return $?j===i||j===n:O?j===2*i||j===2*n:_ instanceof c}function C(_,$,O=!0){if(v(_))throw new Error("first arg must be private key");if(!v($))throw new Error("second arg must be public key");return c.fromHex($).multiply(l(_)).toRawBytes(O)}
11const S=e.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");const $=Ys(_),O=_.length*8-e.nBitLength;return O>0?$>>BigInt(O):$},I=e.bits2int_modN||function(_){return o(S(_))},N=Ha(e.nBitLength);function U(_){return ls("num < 2^"+e.nBitLength,_,cs,N),Gr(_,e.nByteLength)}function E(_,$,O=k){if(["recovered","canonical"].some(ke=>ke in O))throw new Error("sign() legacy options not supported");const{hash:j,randomBytes:q}=e;let{lowS:x,prehash:G,extraEntropy:Q}=O;x==null&&(x=!0),_=mt("msgHash",_),Zc(O),G&&(_=mt("prehashed msgHash",j(_)));const se=I(_),Ce=l($),he=[U(Ce),U(se)];if(Q!=null&&Q!==!1){const ke=Q===!0?q(s.BYTES):Q;he.push(mt("extraEntropy",ke))}const Te=on(...he),Me=se;function Ye(ke){const Re=S(ke);if(!d(Re))return;const ks=a(Re),Xt=c.BASE.multiply(Re).toAffine(),Bt=o(Xt.x);if(Bt===cs)return;const Qt=o(ks*o(Me+Bt*Ce));if(Qt===cs)return;let es=(Xt.x===Bt?0:2)|Number(Xt.y&Be),In=Qt;return x&&p(Qt)&&(In=w(Qt),es^=1),new m(Bt,In,es)}return{seed:Te,k2sig:Ye}}const k={lowS:e.lowS,prehash:!1},A={lowS:e.lowS,prehash:!1};function R(_,$,O=k){const{seed:j,k2sig:q}=E(_,$,O),x=e;return ld(x.hash.outputLen,x.nByteLength,x.hmac)(j,q)}c.BASE._setWindowSize(8);function W(_,$,O,j=A){var Qt;const q=_;$=mt("msgHash",$),O=mt("publicKey",O);const{lowS:x,prehash:G,format:Q}=j;if(Zc(j),"strict"in j)throw new Error("options.strict was renamed to lowS");if(Q!==void 0&&Q!=="compact"&&Q!=="der")throw new Error("format must be compact or der");const se=typeof q=="string"||sr(q),Ce=!se&&!Q&&typeof q=="object"&&q!==null&&typeof q.r=="bigint"&&typeof q.s=="bigint";if(!se&&!Ce)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let he,Te;try{if(Ce&&(he=new m(q.r,q.s)),se){try{Q!=="compact"&&(he=m.fromDER(q))}catch(es){if(!(es instanceof as.Err))throw es}!he&&Q!=="der"&&(he=m.fromCompact(q))}Te=c.fromHex(O)}catch{return!1}if(!he||x&&he.hasHighS())return!1;G&&($=e.hash($));const{r:Me,s:Ye}=he,ke=I($),Re=a(Ye),ks=o(ke*Re),Xt=o(Me*Re),Bt=(Qt=c.BASE.multiplyAndAddUnsafe(Te,ks,Xt))==null?void 0:Qt.toAffine();return Bt?o(Bt.x)===Me:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:C,sign:R,verify:W,ProjectivePoint:c,Signature:m,utils:y}}function dw(t){return{hash:t,hmac:(e,...s)=>io(t,e,gg(...s)),randomBytes:si}}function hw(t,e){const s=r=>uw({...t,...dw(r)});return{...s(e),create:s}}const yd=hd(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),pw=yd.create(BigInt("-3")),fw=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),gw=hw({a:pw,b:fw,Fp:yd,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},mn),bd="base10",tt="base16",Lt="base64pad",Es="base64url",yn="utf8",vd=0,us=1,bn=2,mw=0,Qc=1,Si=12,Va=32;function ww(){const t=fa.utils.randomPrivateKey(),e=fa.getPublicKey(t);return{privateKey:ut(t,tt),publicKey:ut(e,tt)}}function ga(){const t=si(Va);return ut(t,tt)}function yw(t,e){const s=fa.getSharedSecret(Ot(t,tt),Ot(e,tt)),r=Cm(mn,s,void 0,void 0,Va);return ut(r,tt)}function qn(t){const e=mn(Ot(t,tt));return ut(e,tt)}function Kt(t){const e=mn(Ot(t,yn));return ut(e,tt)}function Ed(t){return Ot(`${t}`,bd)}function rr(t){return Number(ut(t,bd))}function Cd(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Id(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function bw(t){const e=Ed(typeof t.type<"u"?t.type:vd);if(rr(e)===us&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?Ot(t.senderPublicKey,tt):void 0,r=typeof t.iv<"u"?Ot(t.iv,tt):si(Si),i=Ot(t.symKey,tt),n=od(i,r).encrypt(Ot(t.message,yn)),o=Ad({type:e,sealed:n,iv:r,senderPublicKey:s});return t.encoding===Es?Cd(o):o}function vw(t){const e=Ot(t.symKey,tt),{sealed:s,iv:r}=an({encoded:t.encoded,encoding:t.encoding}),i=od(e,r).decrypt(s);if(i===null)throw new Error("Failed to decrypt");return ut(i,yn)}function Ew(t,e){const s=Ed(bn),r=si(Si),i=Ot(t,yn),n=Ad({type:s,sealed:i,iv:r});return e===Es?Cd(n):n}function Cw(t,e){const{sealed:s}=an({encoded:t,encoding:e});return ut(s,yn)}function Ad(t){if(rr(t.type)===bn)return ut(Ci([t.type,t.sealed]),Lt);if(rr(t.type)===us){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return ut(Ci([t.type,t.senderPublicKey,t.iv,t.sealed]),Lt)}return ut(Ci([t.type,t.iv,t.sealed]),Lt)}function an(t){const e=(t.encoding||Lt)===Es?Id(t.encoded):t.encoded,s=Ot(e,Lt),r=s.slice(mw,Qc),i=Qc;if(rr(r)===us){const c=i+Va,l=c+Si,u=s.slice(i,c),d=s.slice(c,l),h=s.slice(l);return{type:r,sealed:h,iv:d,senderPublicKey:u}}if(rr(r)===bn){const c=s.slice(i),l=si(Si);return{type:r,sealed:c,iv:l}}const n=i+Si,o=s.slice(i,n),a=s.slice(n);return{type:r,sealed:a,iv:o}}function Iw(t,e){const s=an({encoded:t,encoding:e==null?void 0:e.encoding});return Nd({type:rr(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?ut(s.senderPublicKey,tt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Nd(t){const e=(t==null?void 0:t.type)||vd;if(e===us){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 el(t){return t.type===us&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function tl(t){return t.type===bn}function Aw(t){const e=Buffer.from(t.x,"base64"),s=Buffer.from(t.y,"base64");return Ci([new Uint8Array([4]),e,s])}function Nw(t,e){const[s,r,i]=t.split("."),n=Buffer.from(Id(i),"base64");if(n.length!==64)throw new Error("Invalid signature length");
11const o=n.slice(0,32),a=n.slice(32,64),c=`${s}.${r}`,l=mn(c),u=Aw(e);if(!gw.verify(Ci([o,a]),l,u))throw new Error("Invalid signature");return Jo(t).payload}const _w="irn";function Zn(t){return(t==null?void 0:t.relay)||{protocol:_w}}function bi(t){const e=mh[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function Sw(t,e="-"){const s={},r="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(r)){const n=i.replace(r,""),o=t[i];s[n]=o}}),s}function sl(t){if(!t.includes("wc:")){const l=Ku(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,r=t.substring(0,e),i=t.substring(e+1,s).split("@"),n=typeof s<"u"?t.substring(s):"",o=new URLSearchParams(n),a={};o.forEach((l,u)=>{a[u]=l});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:Pw(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:Sw(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Pw(t){return t.startsWith("//")?t.substring(2):t}function Ow(t,e="-"){const s="relay",r={};return Object.keys(t).forEach(i=>{const n=i,o=s+e+n;t[n]&&(r[o]=t[n])}),r}function rl(t){const e=new URLSearchParams,s=Ow(t.relay);Object.keys(s).sort().forEach(i=>{e.set(i,s[i])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const r=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${r}`}function xn(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var Tw=Object.defineProperty,$w=Object.defineProperties,xw=Object.getOwnPropertyDescriptors,il=Object.getOwnPropertySymbols,kw=Object.prototype.hasOwnProperty,Rw=Object.prototype.propertyIsEnumerable,nl=(t,e,s)=>e in t?Tw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Uw=(t,e)=>{for(var s in e||(e={}))kw.call(e,s)&&nl(t,s,e[s]);if(il)for(var s of il(e))Rw.call(e,s)&&nl(t,s,e[s]);return t},Dw=(t,e)=>$w(t,xw(e));function ii(t){const e=[];return t.forEach(s=>{const[r,i]=s.split(":");e.push(`${r}:${i}`)}),e}function Mw(t){const e=[];return Object.values(t).forEach(s=>{e.push(...ii(s.accounts))}),e}function Lw(t,e){const s=[];return Object.values(t).forEach(r=>{ii(r.accounts).includes(e)&&s.push(...r.methods)}),s}function jw(t,e){const s=[];return Object.values(t).forEach(r=>{ii(r.accounts).includes(e)&&s.push(...r.events)}),s}function lo(t){return t.includes(":")}function kr(t){return lo(t)?t.split(":")[0]:t}function ol(t){var e,s,r;const i={};if(!Ps(t))return i;for(const[n,o]of Object.entries(t)){const a=lo(n)?[n]:o.chains,c=o.methods||[],l=o.events||[],u=kr(n);i[u]=Dw(Uw({},i[u]),{chains:Jt(a,(e=i[u])==null?void 0:e.chains),methods:Jt(c,(s=i[u])==null?void 0:s.methods),events:Jt(l,(r=i[u])==null?void 0:r.events)})}return i}function Bw(t){const e={};return t==null||t.forEach(s=>{var r;const[i,n]=s.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(s),(r=e[i].chains)==null||r.push(`${i}:${n}`)}),e}function al(t,e){e=e.map(r=>r.replace("did:pkh:",""));const s=Bw(e);for(const[r,i]of Object.entries(s))i.methods?i.methods=Jt(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return s}function qw(t,e){var s,r,i,n,o,a;const c=ol(t),l=ol(e),u={},d=Object.keys(c).concat(Object.keys(l));for(const h of d)u[h]={chains:Jt((s=c[h])==null?void 0:s.chains,(r=l[h])==null?void 0:r.chains),methods:Jt((i=c[h])==null?void 0:i.methods,(n=l[h])==null?void 0:n.methods),events:Jt((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return u}const Fw={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}},zw={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 D(t,e){const{message:s,code:r}=zw[t];return{message:e?`${s} ${e}
11`:s,code:r}}function we(t,e){const{message:s,code:r}=Fw[t];return{message:e?`${s} ${e}`:s,code:r}}function Ss(t,e){return!!Array.isArray(t)}function Ps(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Ge(t){return typeof t>"u"}function xe(t,e){return e&&Ge(t)?!0:typeof t=="string"&&!!t.trim().length}function Ka(t,e){return e&&Ge(t)?!0:typeof t=="number"&&!isNaN(t)}function Ww(t,e){const{requiredNamespaces:s}=e,r=Object.keys(t.namespaces),i=Object.keys(s);let n=!0;return Vs(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=ii(a),d=s[o];(!Vs(Fu(o,d),u)||!Vs(d.methods,c)||!Vs(d.events,l))&&(n=!1)}),n):!1}function Xn(t){return xe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function Hw(t){if(xe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&Xn(s)}}return!1}function Vw(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(xe(t,!1)){if(e(t))return!0;const s=Ku(t);return e(s)}}catch{}return!1}function Kw(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function Gw(t){return t==null?void 0:t.topic}function Jw(t,e){let s=null;return xe(t==null?void 0:t.publicKey,!1)||(s=D("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function cl(t){let e=!0;return Ss(t)?t.length&&(e=t.every(s=>xe(s,!1))):e=!1,e}function Yw(t,e,s){let r=null;return Ss(e)&&e.length?e.forEach(i=>{r||Xn(i)||(r=we("UNSUPPORTED_CHAINS",`${s}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Xn(t)||(r=we("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"] }`)),r}function Zw(t,e,s){let r=null;return Object.entries(t).forEach(([i,n])=>{if(r)return;const o=Yw(i,Fu(i,n),`${e} ${s}`);o&&(r=o)}),r}function Xw(t,e){let s=null;return Ss(t)?t.forEach(r=>{s||Hw(r)||(s=we("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):s=we("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function Qw(t,e){let s=null;return Object.values(t).forEach(r=>{if(s)return;const i=Xw(r==null?void 0:r.accounts,`${e} namespace`);i&&(s=i)}),s}function ey(t,e){let s=null;return cl(t==null?void 0:t.methods)?cl(t==null?void 0:t.events)||(s=we("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=we("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function _d(t,e){let s=null;return Object.values(t).forEach(r=>{if(s)return;const i=ey(r,`${e}, namespace`);i&&(s=i)}),s}function ty(t,e,s){let r=null;if(t&&Ps(t)){const i=_d(t,e);i&&(r=i);const n=Zw(t,e,s);n&&(r=n)}else r=D("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return r}function $o(t,e){let s=null;if(t&&Ps(t)){const r=_d(t,e);r&&(s=r);const i=Qw(t,e);i&&(s=i)}else s=D("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function Sd(t){return xe(t.protocol,!0)}function sy(t,e){let s=!1;return t?t&&Ss(t)&&t.length&&t.forEach(r=>{s=Sd(r)}):s=!0,s}function ry(t){return typeof t=="number"}function ct(t){return typeof t<"u"&&typeof t!==null}function iy(t){return!(!t||typeof t!="object"||!t.code||!Ka(t.code,!1)||!t.message||!xe(t.message,!1))}function ny(t){return!(Ge(t)||!xe(t.method,!1))}function oy(t){return!(Ge(t)||Ge(t.result)&&Ge(t.error)||!Ka(t.id,!1)||!xe(t.jsonrpc,!1))}function ay(t){return!(Ge(t)||!xe(t.name,!1))}function ll(t,e){return!(!Xn(e)||!Mw(t).includes(e))}function cy(t,e,s){return xe(s,!1)?Lw(t,e).includes(s):!1}function ly(t,e,s){return xe(s,!1)?jw(t,e).includes(s):!1}function ul(t,e,s){let r=null;const i=uy(t),n=dy(e),o=Object.keys(i),a=Object.keys(n),c=dl(Object.keys(t)),l=dl(Object.keys(e)),u=c.filter(d=>!l.includes(d));return u.length&&(r=D("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
12      Required: ${u.toString()}
13      Received: ${Object.keys(e).toString()}`)),Vs(o,a)||(r=D("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.
14      Required: ${o.toString()}
15      Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||r)return;const h=ii(e[d].accounts);h.includes(d)||(r=D("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${d}
16        Required: ${d}
17        Approved: ${h.toString()}`))}),o.forEach(d=>{r||(Vs(i[d].methods,n[d].methods)?Vs(i[d].events,n[d].events)||(r=D("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${d}`)):r=D("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${d}`))}),r}function uy(t){const e={};return Object.keys(t).forEach(s=>{var r;s.includes(":")?e[s]=t[s]:(r=t[s].chains)==null||r.forEach(i=>
17{e[i]={methods:t[s].methods,events:t[s].events}})}),e}function dl(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function dy(t){const e={};return Object.keys(t).forEach(s=>{if(s.includes(":"))e[s]=t[s];else{const r=ii(t[s].accounts);r==null||r.forEach(i=>{e[i]={accounts:t[s].accounts.filter(n=>n.includes(`${i}:`)),methods:t[s].methods,events:t[s].events}})}}),e}function hy(t,e){return Ka(t,!1)&&t<=e.max&&t>=e.min}function hl(){const t=fn();return new Promise(e=>{switch(t){case yt.browser:e(py());break;case yt.reactNative:e(fy());break;case yt.node:e(gy());break;default:e(!0)}})}function py(){return ti()&&(navigator==null?void 0:navigator.onLine)}async function fy(){if(xs()&&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 gy(){return!0}function my(t){switch(fn()){case yt.browser:wy(t);break;case yt.reactNative:yy(t);break}}function wy(t){!xs()&&ti()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function yy(t){xs()&&typeof global<"u"&&global!=null&&global.NetInfo&&(global==null||global.NetInfo.addEventListener(e=>t(e==null?void 0:e.isConnected)))}function by(){var t;return ti()&&ds.getDocument()?((t=ds.getDocument())==null?void 0:t.visibilityState)==="visible":!0}const xo={};class ui{static get(e){return xo[e]}static set(e,s){xo[e]=s}static delete(e){delete xo[e]}}var vy={};const Pd="wc",Od=2,ma="core",Yt=`${Pd}@2:${ma}:`,Ey={logger:"error"},Cy={database:":memory:"},Iy="crypto",pl="client_ed25519_seed",Ay=M.ONE_DAY,Ny="keychain",_y="0.3",Sy="messages",Py="0.3",fl=M.SIX_HOURS,Oy="publisher",Td="irn",Ty="error",$d="wss://relay.walletconnect.org",$y="relayer",qe={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},xy="_subscription",Nt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},ky=.1,wa="2.21.0",Ne={link_mode:"link_mode",relay:"relay"},Fn={inbound:"inbound",outbound:"outbound"},Ry="0.3",Uy="WALLETCONNECT_CLIENT_ID",gl="WALLETCONNECT_LINK_MODE_APPS",ft={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Dy="subscription",My="0.3",Ly="pairing",jy="0.3",di={wc_pairingDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:M.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:M.ONE_DAY,prompt:!1,tag:0},res:{ttl:M.ONE_DAY,prompt:!1,tag:0}}},Fs={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},xt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},By="history",qy="0.3",Fy="expirer",Pt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},zy="0.3",Wy="verify-api",Hy="https://verify.walletconnect.com",xd="https://verify.walletconnect.org",Pi=xd,Vy=`${Pi}/v3`,Ky=[Hy,xd],Gy="echo",Jy="https://echo.walletconnect.com",Wt={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"},os={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"},kt={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"},Us={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"},Ds={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 17
17,hi={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"},Yy=.1,Zy="event-client",Xy=86400,Qy="https://pulse.walletconnect.org/batch";function eb(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),r=0;r<s.length;r++)s[r]=255;for(var i=0;i<t.length;i++){var n=t.charAt(i),o=n.charCodeAt(0);if(s[o]!==255)throw new TypeError(n+" is ambiguous");s[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var f=0,m=0,y=0,b=w.length;y!==b&&w[y]===0;)y++,f++;for(var v=(b-y)*u+1>>>0,C=new Uint8Array(v);y!==b;){for(var S=w[y],I=0,N=v-1;(S!==0||I<m)&&N!==-1;N--,I++)S+=256*C[N]>>>0,C[N]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");m=I,y++}for(var U=v-m;U!==v&&C[U]===0;)U++;for(var E=c.repeat(f);U<v;++U)E+=t.charAt(C[U]);return E}function h(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var f=0;if(w[f]!==" "){for(var m=0,y=0;w[f]===c;)m++,f++;for(var b=(w.length-f)*l+1>>>0,v=new Uint8Array(b);w[f];){var C=s[w.charCodeAt(f)];if(C===255)return;for(var S=0,I=b-1;(C!==0||S<y)&&I!==-1;I--,S++)C+=a*v[I]>>>0,v[I]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");y=S,f++}if(w[f]!==" "){for(var N=b-y;N!==b&&v[N]===0;)N++;for(var U=new Uint8Array(m+(b-N)),E=m;N!==b;)U[E++]=v[N++];return U}}}function p(w){var f=h(w);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var tb=eb,sb=tb;const kd=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")},rb=t=>new TextEncoder().encode(t),ib=t=>new TextDecoder().decode(t);class nb{constructor(e,s,r){this.name=e,this.prefix=s,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class ob{constructor(e,s,r){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=r}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 Rd(this,e)}}class ab{constructor(e){this.decoders=e}or(e){return Rd(this,e)}decode(e){const s=e[0],r=this.decoders[s];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Rd=(t,e)=>new ab({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class cb{constructor(e,s,r,i){this.name=e,this.prefix=s,this.baseEncode=r,this.baseDecode=i,this.encoder=new nb(e,s,r),this.decoder=new ob(e,s,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const uo=({name:t,prefix:e,encode:s,decode:r})=>new cb(t,e,s,r),vn=({prefix:t,name:e,alphabet:s})=>{const{encode:r,decode:i}=sb(s,e);return uo({prefix:t,name:e,encode:r,decode:n=>kd(i(n))})},lb=(t,e,s,r)=>{const i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*s/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const d=i[t[u]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<s|d,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},ub=(t,e,s)=>{const r=e[e.length-1]==="=",i=(1<<s)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,n+=e[i&a>>o];if(o&&(n+=e[i&a<<s-o]),r)for(;n.length*s&7;)n+="=";return n},Je=({name:t,prefix:e,bitsPerChar:s,alphabet:r})=>uo({prefix:e,name:t,encode(i){return ub(i,r,s)},decode(i){return lb(i,r,s,t)}}),db=uo({prefix:"\0",name:"identity",encode:t=>ib(t),decode:t=>rb(t)});var hb=Object.freeze({__proto__:null,identity:db});const pb=Je({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fb=Object.freeze({__proto__:null,base2:pb});const gb=Je({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var mb=Object.freeze({__proto__:null,base8:gb});const wb=vn({prefix:"9",name:"base10",alphabet:"0123456789"});var yb=Object.freeze({__proto__:null,base10:wb});const bb=Je({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),vb=Je({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Eb=Object.freeze({__proto__:null,base16:bb,base16upper:vb});const Cb=Je({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ib=Je({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ab=Je({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Nb=Je({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_b=Je({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Sb=Je({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Pb=Je({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ob=Je({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Tb=Je({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $b=Object.freeze({__proto__:null,base32:Cb,base32upper:Ib,base32pad:Ab,base32padupper:Nb,base32hex:_b,base32hexupper:Sb,base32hexpad:Pb,base32hexpadupper:Ob,base32z:Tb});const xb=vn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),kb=vn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Rb=Object.freeze({__proto__:null,base36:xb,base36upper:kb});const Ub=vn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Db=vn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mb=Object.freeze({__proto__:null,base58btc:Ub,base58flickr:Db});const Lb=Je({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
17+/",bitsPerChar:6}),jb=Je({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Bb=Je({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qb=Je({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Fb=Object.freeze({__proto__:null,base64:Lb,base64pad:jb,base64url:Bb,base64urlpad:qb});const Ud=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),zb=Ud.reduce((t,e,s)=>(t[s]=e,t),[]),Wb=Ud.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function Hb(t){return t.reduce((e,s)=>(e+=zb[s],e),"")}function Vb(t){const e=[];for(const s of t){const r=Wb[s.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(r)}return new Uint8Array(e)}const Kb=uo({prefix:"🚀",name:"base256emoji",encode:Hb,decode:Vb});var Gb=Object.freeze({__proto__:null,base256emoji:Kb}),Jb=Dd,ml=128,Yb=-128,Zb=Math.pow(2,31);function Dd(t,e,s){e=e||[],s=s||0;for(var r=s;t>=Zb;)e[s++]=t&255|ml,t/=128;for(;t&Yb;)e[s++]=t&255|ml,t>>>=7;return e[s]=t|0,Dd.bytes=s-r+1,e}var Xb=ya,Qb=128,wl=127;function ya(t,r){var s=0,r=r||0,i=0,n=r,o,a=t.length;do{if(n>=a)throw ya.bytes=0,new RangeError("Could not decode varint");o=t[n++],s+=i<28?(o&wl)<<i:(o&wl)*Math.pow(2,i),i+=7}while(o>=Qb);return ya.bytes=n-r,s}var ev=Math.pow(2,7),tv=Math.pow(2,14),sv=Math.pow(2,21),rv=Math.pow(2,28),iv=Math.pow(2,35),nv=Math.pow(2,42),ov=Math.pow(2,49),av=Math.pow(2,56),cv=Math.pow(2,63),lv=function(t){return t<ev?1:t<tv?2:t<sv?3:t<rv?4:t<iv?5:t<nv?6:t<ov?7:t<av?8:t<cv?9:10},uv={encode:Jb,decode:Xb,encodingLength:lv},Md=uv;const yl=(t,e,s=0)=>(Md.encode(t,e,s),e),bl=t=>Md.encodingLength(t),ba=(t,e)=>{const s=e.byteLength,r=bl(t),i=r+bl(s),n=new Uint8Array(i+s);return yl(t,n,0),yl(s,n,r),n.set(e,i),new dv(t,s,e,n)};class dv{constructor(e,s,r,i){this.code=e,this.size=s,this.digest=r,this.bytes=i}}const Ld=({name:t,code:e,encode:s})=>new hv(t,e,s);class hv{constructor(e,s,r){this.name=e,this.code=s,this.encode=r}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?ba(this.code,s):s.then(r=>ba(this.code,r))}else throw Error("Unknown type, must be binary type")}}const jd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),pv=Ld({name:"sha2-256",code:18,encode:jd("SHA-256")}),fv=Ld({name:"sha2-512",code:19,encode:jd("SHA-512")});var gv=Object.freeze({__proto__:null,sha256:pv,sha512:fv});const Bd=0,mv="identity",qd=kd,wv=t=>ba(Bd,qd(t)),yv={code:Bd,name:mv,encode:qd,digest:wv};var bv=Object.freeze({__proto__:null,identity:yv});new TextEncoder,new TextDecoder;const vl={...hb,...fb,...mb,...yb,...Eb,...$b,...Rb,...Mb,...Fb,...Gb};({...gv,...bv});function vv(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Fd(t,e,s,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:r}}}const El=Fd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ko=Fd("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=vv(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),Ev={utf8:El,"utf-8":El,hex:vl.base16,latin1:ko,ascii:ko,binary:ko,...vl};function Cv(t,e="utf8"){const s=Ev[e];
vendor: 5,218 bytes, line 17
17if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):s.decoder.decode(`${s.prefix}${t}`)}var Iv=Object.defineProperty,Av=(t,e,s)=>e in t?Iv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ft=(t,e,s)=>Av(t,typeof e!="symbol"?e+"":e,s);class Nv{constructor(e,s){this.core=e,this.logger=s,Ft(this,"keychain",new Map),Ft(this,"name",Ny),Ft(this,"version",_y),Ft(this,"initialized",!1),Ft(this,"storagePrefix",Yt),Ft(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Ft(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Ft(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),Ft(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:n}=D("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(n)}return i}),Ft(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=st(s,this.name)}get context(){return vt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,ia(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?na(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _v=Object.defineProperty,Sv=(t,e,s)=>e in t?_v(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ve=(t,e,s)=>Sv(t,typeof e!="symbol"?e+"":e,s);class Pv{constructor(e,s,r){this.core=e,this.logger=s,Ve(this,"name",Iy),Ve(this,"keychain"),Ve(this,"randomSessionIdentifier",ga()),Ve(this,"initialized",!1),Ve(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ve(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Ve(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),n=tc(i);return Eh(n.publicKey)}),Ve(this,"generateKeyPair",()=>{this.isInitialized();const i=ww();return this.setPrivateKey(i.publicKey,i.privateKey)}),Ve(this,"signJWT",async i=>{this.isInitialized();const n=await this.getClientSeed(),o=tc(n),a=this.randomSessionIdentifier;return await Ch(a,i,Ay,o)}),Ve(this,"generateSharedKey",(i,n,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=yw(a,n);return this.setSymKey(c,o)}),Ve(this,"setSymKey",async(i,n)=>{this.isInitialized();const o=n||qn(i);return await this.keychain.set(o,i),o}),Ve(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ve(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ve(this,"encode",async(i,n,o)=>{this.isInitialized();const a=Nd(o),c=Ih(n);if(tl(a))return Ew(c,o==null?void 0:o.encoding);if(el(a)){const h=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(h,p)}const l=this.getSymKey(i),{type:u,senderPublicKey:d}=a;return bw({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o==null?void 0:o.encoding})}),Ve(this,"decode",async(i,n,o)=>{this.isInitialized();const a=Iw(n,o);if(tl(a)){const c=Cw(n,o==null?void 0:o.encoding);return sc(c)}if(el(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=vw({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return sc(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ve(this,"getPayloadType",(i,n=Lt)=>{const o=an({encoded:i,encoding:n});return rr(o.type)}),Ve(this,"getPayloadSenderPublicKey",(i,n=Lt)=>{const o=an({encoded:i,encoding:n});return o.senderPublicKey?ut(o.senderPublicKey,tt):void 0}),this.core=e,this.logger=st(s,this.name),this.keychain=r||new Nv(this.core,this.logger)}get context(){return vt(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(pl)}catch{e=ga(),await this.keychain.set(pl,e)}return Cv(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ov=Object.defineProperty,Tv=Object.defineProperties,$v=Object.getOwnPropertyDescriptors,Cl=Object.getOwnPropertySymbols,xv=Object.prototype.hasOwnProperty,kv=Object.prototype.propertyIsEnumerable,va=(t,e,s)=>e in t?Ov(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Rv=(t,e)=>{for(var s in e||(e={}))xv.call(e,s)&&va(t,s,e[s]);if(Cl)for(var s of Cl(e))kv.call(e,s)&&va(t,s,e[s]);return t},Uv=(t,e)=>Tv(t,$v(e)),pt=(t,e,s)=>va(t,typeof e!="symbol"?e+"":e,s);class Dv extends ef{constructor(e,s){super(e,s),this.logger=e,this.core=s,pt(this,"messages",new Map),pt(this,"messagesWithoutClientAck",new Map),pt(this,"name",Sy),pt(this,"version",Py),pt(this,"initialized",!1),pt(this,"storagePrefix",Yt),pt(this,"init",async()=>
17{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),pt(this,"set",async(r,i,n)=>{this.isInitialized();const o=Kt(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),n===Fn.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,Uv(Rv({},c),{[o]:i}))}return await this.persist(),o}),pt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),pt(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const n of r){const o=this.messagesWithoutClientAck.get(n)||{};i[n]=Object.values(o)}return i}),pt(this,"has",(r,i)=>{this.isInitialized();const n=this.get(r),o=Kt(i);return typeof n[o]<"u"}),pt(this,"ack",async(r,i)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(r);if(typeof n>"u")return;const o=Kt(i);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,n),await this.persist()}),pt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=st(e,this.name),this.core=s}get context(){return vt(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,ia(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,ia(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?na(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?na(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Mv=Object.defineProperty,Lv=Object.defineProperties,jv=Object.getOwnPropertyDescriptors,Il=Object.getOwnPropertySymbols,Bv=Object.prototype.hasOwnProperty,qv=Object.prototype.propertyIsEnumerable,Ea=(t,e,s)=>e in t?Mv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,kn=(t,e)=>{for(var s in e||(e={}))Bv.call(e,s)&&Ea(t,s,e[s]);if(Il)for(var s of Il(e))qv.call(e,s)&&Ea(t,s,e[s]);return t},Ro=(t,e)=>Lv(t,jv(e)),Rt=(t,e,s)=>Ea(t,typeof e!="symbol"?e+"":e,s);class Fv extends tf{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Rt(this,"events",new nr.EventEmitter),Rt(this,"name",Oy),Rt(this,"queue",new Map),Rt(this,"publishTimeout",M.toMiliseconds(M.ONE_MINUTE)),Rt(this,"initialPublishTimeout",M.toMiliseconds(M.ONE_SECOND*15)),Rt(this,"needsTransportRestart",!1),Rt(this,"publish",async(r,i,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:n}});const a=(n==null?void 0:n.ttl)||fl,c=Zn(n),l=(n==null?void 0:n.prompt)||!1,u=(n==null?void 0:n.tag)||0,d=(n==null?void 0:n.id)||$r().toString(),h={topic:r,message:i,opts:{ttl:a,relay:c,prompt:l,tag:u,id:d,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},p=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const w=new Promise(async f=>{const m=({id:b})=>{h.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(qe.publish,m),f(h))};this.relayer.events.on(qe.publish,m);const y=As(new Promise((b,v)=>{this.rpcPublish({topic:r,message:i,ttl:a,prompt:l,tag:u,id:d,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(b).catch(C=>{this.logger.warn(C,C==null?void 0:C.message),v(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await y,this.events.removeListener(qe.publish,m)}catch(b){this.queue.set(d,Ro(kn({},h),{attempt:1})),this.logger.warn(b,b==null?void 0:b.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:r,message:i,opts:n}}),await As(w,this.publishTimeout,p)}catch(w){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(w),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw w}finally{this.queue.delete(d)}}),Rt(this,"on",(r,i)=>{this.events.on(r,i)}),Rt(this,"once",(r,i)=>{this.events.once(r,i)}),Rt(this,"off",(r,i)=>{this.events.off(r,i)}),Rt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=st(s,this.name),this.registerEventListeners()}get context(){return vt(this.logger)}async rpcPublish(e){var s,r,i,n;const{topic:o,message:a,ttl:c=fl,prompt:l,tag:u,id:d,attestation:h,tvf:p}=e,w={method:bi(Zn().protocol).publish,params:kn({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:h},p),id:d};Ge((s=w.params)==null?void 0:s.prompt)&&((r=w.params)==null||delete r.prompt),Ge((i=w.params)==null?void 0:i.tag)&&((n=w.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w});const f=await this.relayer.request(w);return this.relayer.events.emit(qe.publish,e),this.logger.debug("Successfully Published Payload"),f}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{const r=e.attempt+1;this.queue.set(s,Ro(kn({},e),{attempt:r}));const{topic:i,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${r}`),await this.rpcPublish(Ro(kn({},e),{topic:i,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Xr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(qe.connection_stalled);return}this.checkQueue()}),this.relayer.on(qe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var zv=Object.defineProperty,Wv=(t,e,s)=>e in t?zv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fr=(t,e,s)=>Wv(t,typeof e!="symbol"?e+"":e,s);class Hv{constructor(){fr(this,"map",new Map),fr(this,"set",(e,s)=>{const r=this.get(e);this.exists(e,s)||this.map.set(e,[...r,s])}),fr(this,"get",e=>this.map.get(e)||[]),fr(this,"exists",(e,s)=>this.get(e).includes(s)),fr(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,s))return;const i=r.filter(n=>n!==s);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),fr(this,"clear",()=>{this.map.clear()})}
vendor: 9,609 bytes, line 17
17get topics(){return Array.from(this.map.keys())}}var Vv=Object.defineProperty,Kv=Object.defineProperties,Gv=Object.getOwnPropertyDescriptors,Al=Object.getOwnPropertySymbols,Jv=Object.prototype.hasOwnProperty,Yv=Object.prototype.propertyIsEnumerable,Ca=(t,e,s)=>e in t?Vv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pi=(t,e)=>{for(var s in e||(e={}))Jv.call(e,s)&&Ca(t,s,e[s]);if(Al)for(var s of Al(e))Yv.call(e,s)&&Ca(t,s,e[s]);return t},Uo=(t,e)=>Kv(t,Gv(e)),be=(t,e,s)=>Ca(t,typeof e!="symbol"?e+"":e,s);class Zv extends nf{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,be(this,"subscriptions",new Map),be(this,"topicMap",new Hv),be(this,"events",new nr.EventEmitter),be(this,"name",Dy),be(this,"version",My),be(this,"pending",new Map),be(this,"cached",[]),be(this,"initialized",!1),be(this,"storagePrefix",Yt),be(this,"subscribeTimeout",M.toMiliseconds(M.ONE_MINUTE)),be(this,"initialSubscribeTimeout",M.toMiliseconds(M.ONE_SECOND*15)),be(this,"clientId"),be(this,"batchSubscribeTopicsLimit",500),be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),be(this,"subscribe",async(r,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const n=Zn(i),o={topic:r,relay:n,transportType:i==null?void 0:i.transportType};this.pending.set(r,o);const a=await this.rpcSubscribe(r,n,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),be(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof(i==null?void 0:i.id)<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),be(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),be(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(n=>n.topic===r))})),be(this,"on",(r,i)=>{this.events.on(r,i)}),be(this,"once",(r,i)=>{this.events.once(r,i)}),be(this,"off",(r,i)=>{this.events.off(r,i)}),be(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),be(this,"start",async()=>{await this.onConnect()}),be(this,"stop",async()=>{await this.onDisconnect()}),be(this,"restart",async()=>{await this.restore(),await this.onRestart()}),be(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),be(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Xr.pulse,async()=>{await this.checkPending()}),this.events.on(ft.created,async r=>{const i=ft.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(ft.deleted,async r=>{const i=ft.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=st(s,this.name),this.clientId=""}get context(){return vt(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 r=!1;try{r=this.getSubscription(e).topic===s}catch{}return r}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 r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,s)))}async unsubscribeById(e,s,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:r}});try{const i=Zn(r);await this.restartToComplete({topic:e,id:s,relay:i}),await this.rpcUnsubscribe(e,s,i);const n=we("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,s,r){var i;(!r||(r==null?void 0:r.transportType)===Ne.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const n={method:bi(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((r==null?void 0:r.transportType)===Ne.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(u=>this.logger.warn(u))},M.toMiliseconds(M.ONE_SECOND)),a;const c=new Promise(async u=>{const d=h=>{h.topic===e&&(this.events.removeListener(ft.created,d),u(h.id))};this.events.on(ft.created,d);try{const h=await As(new Promise((p,w)=>{this.relayer.request(n).catch(f=>{this.logger.warn(f,f==null?void 0:f.message),w(f)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(ft.created,d),u(h)}catch{}}),l=await As(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(qe.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,r={method:bi(s.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await As(new Promise(i=>{this.relayer.request(r).catch(n=>this.logger.warn(n)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(qe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,r={method:bi(s.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await As(new Promise((n,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(qe.connection_stalled)}return i}rpcUnsubscribe(e,s,r){const i={method:bi(r.protocol).unsubscribe,params:{topic:e,id:s}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,s){this.setSubscription(e,Uo(pi({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,pi({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,r){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,r),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,pi({},s)),this.topicMap.set(s.topic,e),this.events.emit(ft.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:r}=D("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(ft.deleted,Uo(pi({},r),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ft.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<s;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(ft.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:s}=D("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=>Uo(pi({}
17,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 ig(M.toMiliseconds(M.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}=D("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 Kt(e+await this.getClientId())}}var Xv=Object.defineProperty,Nl=Object.getOwnPropertySymbols,Qv=Object.prototype.hasOwnProperty,e0=Object.prototype.propertyIsEnumerable,Ia=(t,e,s)=>e in t?Xv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_l=(t,e)=>{for(var s in e||(e={}))Qv.call(e,s)&&Ia(t,s,e[s]);if(Nl)for(var s of Nl(e))e0.call(e,s)&&Ia(t,s,e[s]);return t},le=(t,e,s)=>Ia(t,typeof e!="symbol"?e+"":e,s);class t0 extends sf{constructor(e){super(e),le(this,"protocol","wc"),le(this,"version",2),le(this,"core"),le(this,"logger"),le(this,"events",new nr.EventEmitter),le(this,"provider"),le(this,"messages"),le(this,"subscriber"),le(this,"publisher"),le(this,"name",$y),le(this,"transportExplicitlyClosed",!1),le(this,"initialized",!1),le(this,"connectionAttemptInProgress",!1),le(this,"relayUrl"),le(this,"projectId"),le(this,"packageName"),le(this,"bundleId"),le(this,"hasExperiencedNetworkDisruption",!1),le(this,"pingTimeout"),le(this,"heartBeatTimeout",M.toMiliseconds(M.THIRTY_SECONDS+M.FIVE_SECONDS)),le(this,"reconnectTimeout"),le(this,"connectPromise"),le(this,"reconnectInProgress",!1),le(this,"requestsInFlight",[]),le(this,"connectTimeout",M.toMiliseconds(M.ONE_SECOND*15)),le(this,"request",async s=>{var r,i;this.logger.debug("Publishing Request Payload");const n=s.id||$r().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:s.method,topic:(r=s.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${n}:${((i=s.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(s);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),le(this,"resetPingTimeout",()=>{Jn()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var s,r,i,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(i=(r=(s=this.provider)==null?void 0:s.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||n.call(i)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),le(this,"onPayloadHandler",s=>{this.onProviderPayload(s),this.resetPingTimeout()}),le(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(qe.connect)}),le(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),le(this,"onProviderErrorHandler",s=>{this.logger.fatal(`Fatal socket error: ${s.message}`),this.events.emit(qe.error,s),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),le(this,"registerProviderListeners",()=>{this.provider.on(Nt.payload,this.onPayloadHandler),this.provider.on(Nt.connect,this.onConnectHandler),this.provider.on(Nt.disconnect,this.onDisconnectHandler),this.provider.on(Nt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?st(e.logger,this.name):ka(dn({level:e.logger||Ty})),this.messages=new Dv(this.logger,e.core),this.subscriber=new Zv(this,this.logger),this.publisher=new Fv(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||$d,this.projectId=e.projectId,Ff()?this.packageName=Ac():zf()&&(this.bundleId=Ac()),this.provider={}}
17async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return vt(this.logger)}get connected(){var e,s,r;return((r=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,s,r;return((r=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,r){this.isInitialized(),await this.publisher.publish(e,s,r),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:Ne.relay},Fn.outbound)}async subscribe(e,s){var r,i,n;this.isInitialized(),(!(s!=null&&s.transportType)||(s==null?void 0:s.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((r=s==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=s==null?void 0:s.internal)==null?void 0:i.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(ft.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(ft.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,_l({internal:{throwOnFailedPublish:o}},s)).catch(h=>{o&&d(h)})||a,u()})]),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.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(s,r)=>{await this.connect(e).then(s).catch(r).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 hl())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((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const r of s)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+(i==null?void 0:i.message))}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:r}=e;if(!s.sessionExists){const i=De(M.FIVE_MINUTES),n={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,n)}this.events.emit(qe.message,e),await this.recordMessageEvent(e,Fn.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(r,i)=>{const n=()=>
vendor: 20,847 bytes, line 17
17{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Nt.disconnect,n),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=>{i(o)}).finally(()=>{this.provider.off(Nt.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Nt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Nt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.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(r=>setTimeout(r,M.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,r,i,n;if(Jn())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((n=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Tt(new vh(Gf({sdkVersion:wa,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:r,message:i}=e;await this.messages.set(r,i,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const i=this.messages.has(s,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Ra(e)){if(!e.method.endsWith(xy))return;const s=e.params,{topic:r,message:i,publishedAt:n,attestation:o}=s.data,a={topic:r,message:i,publishedAt:n,transportType:Ne.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(_l({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ua(e)&&this.events.emit(qe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Fn.inbound),this.events.emit(qe.message,e))}async acknowledgePayload(e){const s=so(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Nt.payload,this.onPayloadHandler),this.provider.off(Nt.connect,this.onConnectHandler),this.provider.off(Nt.disconnect,this.onDisconnectHandler),this.provider.off(Nt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await hl();my(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(r=>this.logger.error(r,r==null?void 0:r.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Xr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&by())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s==null?void 0:s.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(qe.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},M.toMiliseconds(ky)))))}isInitialized(){if(!this.initialized){const{message:e}=D("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 s0(){}function Sl(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 Pl(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Ol(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const r0="[object RegExp]",i0="[object String]",n0="[object Number]",o0="[object Boolean]",Tl="[object Arguments]",a0="[object Symbol]",c0="[object Date]",l0="[object Map]",u0="[object Set]",d0="[object Array]",h0="[object Function]",p0="[object ArrayBuffer]",Do="[object Object]",f0="[object Error]",g0="[object DataView]",m0="[object Uint8Array]",w0="[object Uint8ClampedArray]",y0="[object Uint16Array]",b0="[object Uint32Array]",v0="[object BigUint64Array]",E0="[object Int8Array]",C0="[object Int16Array]",I0="[object Int32Array]",A0="[object BigInt64Array]",N0="[object Float32Array]",_0="[object Float64Array]";function S0(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function P0(t,e,s){return vi(t,e,void 0,void 0,void 0,void 0,s)}function vi(t,e,s,r,i,n,o){const a=o(t,e,s,r,i,n);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Oi(t,e,n,o)}return Oi(t,e,n,o)}function Oi(t,e,s,r){if(Object.is(t,e))return!0;let i=Ol(t),n=Ol(e);if(i===Tl&&(i=Do),n===Tl&&(n=Do),i!==n)return!1;switch(i){case i0:return t.toString()===e.toString();case n0:{const c=t.valueOf(),l=e.valueOf();return S0(c,l)}case o0:case c0:case a0:return Object.is(t.valueOf(),e.valueOf());case r0:return t.source===e.source&&t.flags===e.flags;case h0: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(i){case l0:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!vi(l,e.get(c),c,t,e,s,r))return!1;return!0}case u0:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const d=c[u],h=l.findIndex(p=>vi(d,p,void 0,t,e,s,r));if(h===-1)return!1;l.splice(h,1)}return!0}case d0:case m0:case w0:case y0:case b0:case v0:case E0:case C0:case I0:case A0:case N0:case _0:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!vi(t[c],e[c],c,t,e,s,r))return!1;return!0}case p0:return t.byteLength!==e.byteLength?!1:Oi(new Uint8Array(t),new Uint8Array(e),s,r);case g0:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Oi(new Uint8Array(t),new Uint8Array(e),s,r);case f0:return t.name===e.name&&t.message===e.message;case Do:{if(!(Oi(t.constructor,e.constructor,s,r)||Sl(t)&&Sl(e)))return!1;const c=[...Object.keys(t),...Pl(t)],l=[...Object.keys(e),...Pl(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=t[d];if(!Object.hasOwn(e,d))return!1;const p=e[d];if(!vi(h,p,d,t,e,s,r))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function O0(t,e){return P0(t,e,s0)}var T0=Object.defineProperty,$l=Object.getOwnPropertySymbols,$0=Object.prototype.hasOwnProperty,x0=Object.prototype.propertyIsEnumerable,Aa=(t,e,s)=>e in t?T0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xl=(t,e)=>{for(var s in e||(e={}))$0.call(e,s)&&Aa(t,s,e[s]);if($l)for(var s of $l(e))x0.call(e,s)&&Aa(t,s,e[s]);return t},ot=(t,e,s)=>Aa(t,typeof e!="symbol"?e+"":e,s);class lr extends rf{constructor(e,s,r,i=Yt,n=void 0){super(e,s,r,i),this.core=e,this.logger=s,this.name=r,ot(this,"map",new Map),ot(this,"version",Ry),ot(this,"cached",[]),ot(this,"initialized",!1),ot(this,"getKey"),ot(this,"storagePrefix",Yt),ot(this,"recentlyDeleted",[]),ot(this,"recentlyDeletedLimit",200),ot(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ge(o)?this.map.set(this.getKey(o),o):Kw(o)?this.map.set(o.id,o):Gw(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ot(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())}),ot(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ot(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>O0(a[c],o[c]))):this.values)),ot(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=xl(xl({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ot(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=st(s,this.name),this.storagePrefix=i,this.getKey=n}get context(){return vt(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:i}=D("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=D("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}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}=D("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}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}}var k0=Object.defineProperty,R0=(t,e,s)=>e in t?k0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ie=(t,e,s)=>R0(t,typeof e!="symbol"?e+"":e,s);class U0{constructor(e,s){this.core=e,this.logger=s,ie(this,"name",Ly),ie(this,"version",jy),ie(this,"events",new Da),ie(this,"pairings"),ie(this,"initialized",!1),ie(this,"storagePrefix",Yt),ie(this,"ignoredPayloadTypes",[us]),ie(this,"registeredMethods",[]),ie(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ie(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),ie(this,"create",async r=>{this.isInitialized();const i=ga(),n=await this.core.crypto.setSymKey(i),o=De(M.FIVE_MINUTES),a={protocol:Td},c={topic:n,expiry:o,relay:a,active:!1,methods:r==null?void 0:r.methods},l=rl({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:i,relay:a,expiryTimestamp:o,methods:r==null?void 0:r.methods});return this.events.emit(Fs.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:r==null?void 0:r.transportType}),{topic:n,uri:l}}),ie(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r==null?void 0:r.uri,trace:[Wt.pairing_started]}});this.isValidPair(r,i);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=sl(r.uri);i.props.properties.topic=n,i.addTrace(Wt.pairing_uri_validation_success),i.addTrace(Wt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),i.addTrace(Wt.existing_pairing),u.active)throw i.setError(os.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);i.addTrace(Wt.pairing_not_expired)}const d=c||De(M.FIVE_MINUTES),h={topic:n,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(n,d),await this.pairings.set(n,h),i.addTrace(Wt.store_new_pairing),r.activatePairing&&await this.activate({topic:n}),this.events.emit(Fs.create,h),i.addTrace(Wt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),i.addTrace(Wt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(os.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw i.setError(os.subscribe_pairing_topic_failure),p}return i.addTrace(Wt.subscribe_pairing_topic_success),h}),ie(this,"activate",async({topic:r})=>{this.isInitialized();const i=De(M.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),ie(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const n=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=js();this.events.once(pe("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),ie(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),ie(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),ie(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ie(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",we("USER_DISCONNECTED")),await this.deletePairing(i))}),ie(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:n,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return rl({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),ie(this,"sendRequest",async(r,i,n)=>{const o=Ws(i,n),a=await this.core.crypto.encode(r,o),c=di[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),ie(this,"sendResult",async(r,i,n)=>{const o=so(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=di[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ie(this,"sendError",async(r,i,n)=>{const o=wu(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=di[c]?di[c].res:di.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ie(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,we("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),ie(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>vs(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),ie(this,"onRelayEventRequest",async r=>{const{topic:i,payload:n}=r;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,n);default:return await this.onUnknownRpcMethodRequest(i,n)}}),ie(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n}=r,o=(await this.core.history.get(i,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,n);default:return this.onUnknownRpcMethodResponse(o)}}),ie(this,"onPairingPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult(n,r,!0),this.events.emit(Fs.ping,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),ie(this,"onPairingPingResponse",(r,i)=>{const{id:n}=i;setTimeout(()=>{ns(i)?this.events.emit(pe("pairing_ping",n),{}):Ht(i)&&this.events.emit(pe("pairing_ping",n),{error:i.error})},500)}),ie(this,"onPairingDeleteRequest",async(r,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Fs.delete,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),ie(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:n,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=we("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,r,a),this.logger.error(a)}catch(a){await this.sendError(n,r,a),this.logger.error(a)}}),ie(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(we("WC_METHOD_UNSUPPORTED",r))}),ie(this,"isValidPair",(r,i)=>{var n;if(!ct(r)){const{message:a}=D("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(os.malformed_pairing_uri),new Error(a)}if(!Vw(r.uri)){const{message:a}=D("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(os.malformed_pairing_uri),new Error(a)}const o=sl(r==null?void 0:r.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=D("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(os.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=D("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(os.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&M.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){i.setError(os.pairing_expired);const{message:a}=D("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ie(this,"isValidPing",async r=>{if(!ct(r)){const{message:n}=D("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),ie(this,"isValidDisconnect",async r=>{if(!ct(r)){const{message:n}=D("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),ie(this,"isValidPairingTopic",async r=>{if(!xe(r,!1)){const{message:i}=D("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=D("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(vs(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=D("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=st(s,this.name),this.pairings=new lr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return vt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(qe.message,async e=>{const{topic:s,message:r,transportType:i}=e;if(this.pairings.keys.includes(s)&&i!==Ne.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const n=await this.core.crypto.decode(s,r);Ra(n)?(this.core.history.set(s,n),await this.onRelayEventRequest({topic:s,payload:n})):Ua(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:s,payload:n}),this.core.history.delete(s,n.id)),await this.core.relayer.messages.ack(s,r)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(Pt.expired,async e=>{const{topic:s}=Vu(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(Fs.expire,{topic:s}))})}}var D0=Object.defineProperty,M0=(t,e,s)=>e in t?D0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ke=(t,e,s)=>M0(t,typeof e!="symbol"?e+"":e,s);class L0 extends Qp{constructor(e,s){super(e,s),this.core=e,this.logger=s,Ke(this,"records",new Map),Ke(this,"events",new nr.EventEmitter),Ke(this,"name",By),Ke(this,"version",qy),Ke(this,"cac
17hed",[]),Ke(this,"initialized",!1),Ke(this,"storagePrefix",Yt),Ke(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ke(this,"set",(r,i,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:n}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:n,expiry:De(M.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(xt.created,o)}),Ke(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=Ht(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(xt.updated,i))}),Ke(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Ke(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(n=>{if(n.topic===r){if(typeof i<"u"&&n.id!==i)return;this.records.delete(n.id),this.events.emit(xt.deleted,n)}}),this.persist()}),Ke(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Ke(this,"on",(r,i)=>{this.events.on(r,i)}),Ke(this,"once",(r,i)=>{this.events.once(r,i)}),Ke(this,"off",(r,i)=>{this.events.off(r,i)}),Ke(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=st(s,this.name)}get context(){return vt(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 r={topic:s.topic,request:Ws(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(r)}),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:r}=D("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(xt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=D("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(xt.created,e=>{const s=xt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(xt.updated,e=>{const s=xt.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(xt.deleted,e=>{const s=xt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(Xr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{M.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(xt.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}}var j0=Object.defineProperty,B0=(t,e,s)=>e in t?j0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ze=(t,e,s)=>B0(t,typeof e!="symbol"?e+"":e,s);class q0 extends of{constructor(e,s){super(e,s),this.core=e,this.logger=s,Ze(this,"expirations",new Map),Ze(this,"events",new nr.EventEmitter),Ze(this,"name",Fy),Ze(this,"version",zy),Ze(this,"cac
17hed",[]),Ze(this,"initialized",!1),Ze(this,"storagePrefix",Yt),Ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ze(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),Ze(this,"set",(r,i)=>{this.isInitialized();const n=this.formatTarget(r),o={target:n,expiry:i};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Pt.created,{target:n,expiration:o})}),Ze(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),Ze(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),n=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Pt.deleted,{target:i,expiration:n})}}),Ze(this,"on",(r,i)=>{this.events.on(r,i)}),Ze(this,"once",(r,i)=>{this.events.once(r,i)}),Ze(this,"off",(r,i)=>{this.events.off(r,i)}),Ze(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=st(s,this.name)}get context(){return vt(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 Jf(e);if(typeof e=="number")return Yf(e);const{message:s}=D("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(Pt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=D("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:r}=D("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return s}checkExpiry(e,s){const{expiry:r}=s;M.toMiliseconds(r)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(Pt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(Xr.pulse,()=>this.checkExpirations()),this.events.on(Pt.created,e=>{const s=Pt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Pt.expired,e=>{const s=Pt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Pt.deleted,e=>{const s=Pt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}}var F0=Object.defineProperty,z0=(t,e,s)=>e in t?F0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$e=(t,e,s)=>z0(t,typeof e!="symbol"?e+"":e,s);class W0 extends af{constructor(e,s,r){super(e,s,r),this.core=e,this.logger=s,this.store=r,$e(this,"name",Wy),$e(this,"abortController"),$e(this,"isDevEnv"),$e(this,"verifyUrlV3",Vy),$e(this,"storagePrefix",Yt),$e(this,"version",Od),$e(this,"publicKey"),$e(this,"fetchPromise"),$e(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&M.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),$e(this,"register",async i=>{if(!ti()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=ds.getDocument(),u=this.startAbortTimer(M.ONE_SECOND*5),d=await new Promise((h,p)=>{const w=()=>{window.removeEventListener("message",m),l.body.removeChild(f),p("attestation aborted")};this.abortController.signal.addEventListener("abort",w);const f=l.createElement("iframe");f.src=c,f.style.display="none",f.addEventListener("error",w,{signal:this.abortController.signal});const m=y=>
vendor: 11,583 bytes, line 17
17{if(y.data&&typeof y.data=="string")try{const b=JSON.parse(y.data);if(b.type==="verify_attestation"){if(Jo(b.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(f),this.abortController.signal.removeEventListener("abort",w),window.removeEventListener("message",m),h(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};l.body.appendChild(f),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),$e(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=i;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(Jo(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(i==null?void 0:i.verifyUrl);return this.fetchAttestation(o,c)}),$e(this,"fetchAttestation",async(i,n)=>{this.logger.debug(`resolving attestation: ${i} from url: ${n}`);const o=this.startAbortTimer(M.ONE_SECOND*5),a=await fetch(`${n}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),$e(this,"getVerifyUrl",i=>{let n=i||Pi;return Ky.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Pi}`),n=Pi),n}),$e(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(M.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await n.json()}catch(i){this.logger.warn(i)}}),$e(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),$e(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),$e(this,"isValidJwtAttestation",async i=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(i,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),$e(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),$e(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),$e(this,"validateAttestation",(i,n)=>{const o=Nw(i,n.publicKey),a={hasExpired:M.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=st(s,this.name),this.abortController=new AbortController,this.isDevEnv=Ba(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return vt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),M.toMiliseconds(e))}}var H0=Object.defineProperty,V0=(t,e,s)=>e in t?H0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,kl=(t,e,s)=>V0(t,typeof e!="symbol"?e+"":e,s);class K0 extends cf{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,kl(this,"context",Gy),kl(this,"registerDeviceToken",async r=>{const{clientId:i,token:n,notificationType:o,enableEncrypted:a=!1}=r,c=`${Jy}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:n,always_raw:a})})}),this.logger=st(s,this.context)}}var G0=Object.defineProperty,Rl=Object.getOwnPropertySymbols,J0=Object.prototype.hasOwnProperty,Y0=Object.prototype.propertyIsEnumerable,Na=(t,e,s)=>e in t?G0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fi=(t,e)=>{for(var s in e||(e={}))J0.call(e,s)&&Na(t,s,e[s]);if(Rl)for(var s of Rl(e))Y0.call(e,s)&&Na(t,s,e[s]);return t},Le=(t,e,s)=>Na(t,typeof e!="symbol"?e+"":e,s);class Z0 extends lf{constructor(e,s,r=!0){super(e,s,r),this.core=e,this.logger=s,Le(this,"context",Zy),Le(this,"storagePrefix",Yt),Le(this,"storageVersion",Yy),Le(this,"events",new Map),Le(this,"shouldPersist",!1),Le(this,"init",async()=>{if(!Ba())try{const i={eventId:_c(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Wu(this.core.relayer.protocol,this.core.relayer.version,wa)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Le(this,"createEvent",i=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=_c(),u=this.core.projectId||"",d=Date.now(),h=fi({eventId:l,timestamp:d,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Le(this,"getEvent",i=>{const{eventId:n,topic:o}=i;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return fi(fi({},a),this.setMethods(a.eventId))}),Le(this,"deleteEvent",i=>{const{eventId:n}=i;this.events.delete(n),this.shouldPersist=!0}),Le(this,"setEventListeners",()=>{this.core.heartbeat.on(Xr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{M.fromMiliseconds(Date.now())-M.fromMiliseconds(i.timestamp)>Xy&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Le(this,"setMethods",i=>({addTrace:n=>this.addTrace(i,n),setError:n=>this.setError(i,n)})),Le(this,"addTrace",(i,n)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(n),this.events.set(i,o),this.shouldPersist=!0)}),Le(this,"setError",(i,n)=>{const o=this.events.get(i);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Le(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Le(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(n=>{this.events.set(n.eventId,fi(fi({},n),this.setMethods(n.eventId)))})}catch(i){this.logger.warn(i)}}),Le(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[n,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const n of i)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),Le(this,"sendEvent",async i=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Qy}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${wa}${n}`,{method:"POST",body:JSON.stringify(i)})}),Le(this,"getAppDomain",()=>zu().url),this.logger=st(s,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var X0=Object.defineProperty,Ul=Object.getOwnPropertySymbols,Q0=Object.prototype.hasOwnProperty,eE=Object.prototype.propertyIsEnumerable,_a=(t,e,s)=>e in t?X0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Dl=(t,e)=>{for(var s in e||(e={}))Q0.call(e,s)&&_a(t,s,e[s]);if(Ul)for(var s of Ul(e))eE.call(e,s)&&_a(t,s,e[s]);return t},Ae=(t,e,s)=>_a(t,typeof e!="symbol"?e+"":e,s);let tE=class zd extends Jp{constructor(e){var s;super(e),Ae(this,"protocol",Pd),Ae(this,"version",Od),Ae(this,"name",ma),Ae(this,"relayUrl"),Ae(this,"projectId"),Ae(this,"customStoragePrefix"),Ae(this,"events",new nr.EventEmitter),Ae(this,"logger"),Ae(this,"heartbeat"),Ae(this,"relayer"),Ae(this,"crypto"),Ae(this,"storage"),Ae(this,"history"),Ae(this,"expirer"),Ae(this,"pairing"),Ae(this,"verify"),Ae(this,"echoClient"),Ae(this,"linkModeSupportedApps"),Ae(this,"eventClient"),Ae(this,"initialized",!1),Ae(this,"logChunkController"),Ae(this,"on",(a,c)=>this.events.on(a,c)),Ae(this,"once",(a,c)=>this.events.once(a,c)),Ae(this,"off",(a,c)=>this.events.off(a,c)),Ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Ne.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(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)||$d,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=dn({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:Ey.logger,name:ma}),{logger:n,chunkLoggerController:o}=mu({opts:i,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=st(n,this.name),this.heartbeat=new yh,this.crypto=new Pv(this,this.logger,e==null?void 0:e.keychain),this.history=new L0(this,this.logger),this.expirer=new q0(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new bh(Dl(Dl({},Cy),e==null?void 0:e.storageOptions)),this.relayer=new t0({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new U0(this,this.logger),this.verify=new W0(this,this.logger,this.storage),this.echoClient=new K0(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Z0(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new zd(e);await s.initialize();const r=await s.crypto.getClientId();return await s.storage.setItem(Uy,r),s}get context(){return vt(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(gl,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(
17),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(gl)||[],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}`,r=`${s}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} 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 r=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&vy.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const sE=tE,Wd="wc",Hd=2,Vd="client",Ga=`${Wd}@${Hd}:${Vd}:`,Mo={name:Vd,logger:"error"},Ml="WALLETCONNECT_DEEPLINK_CHOICE",rE="proposal",Ll="Proposal expired",iE="session",gr=M.SEVEN_DAYS,nE="engine",je={wc_sessionPropose:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1104},res:{ttl:M.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1106},res:{ttl:M.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1112},res:{ttl:M.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1114},res:{ttl:M.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:M.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:M.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1119}}},Lo={min:M.FIVE_MINUTES,max:M.SEVEN_DAYS},zt={idle:"IDLE",active:"ACTIVE"},jl={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},oE="request",aE=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],cE="wc",lE="auth",uE="authKeys",dE="pairingTopics",hE="requests",ho=`${cE}@${1.5}:${lE}:`,zn=`${ho}:PUB_KEY`;var pE=Object.defineProperty,fE=Object.defineProperties,gE=Object.getOwnPropertyDescriptors,Bl=Object.getOwnPropertySymbols,mE=Object.prototype.hasOwnProperty,wE=Object.prototype.propertyIsEnumerable,Sa=(t,e,s)=>e in t?pE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ve=(t,e)=>{for(var s in e||(e={}))mE.call(e,s)&&Sa(t,s,e[s]);if(Bl)for(var s of Bl(e))wE.call(e,s)&&Sa(t,s,e[s]);return t},et=(t,e)=>fE(t,gE(e)),P=(t,e,s)=>Sa(t,typeof e!="symbol"?e+"":e,s);class yE extends pf{constructor(e){super(e),P(this,"name",nE),P(this,"events",new Da),P(this,"initialized",!1),P(this,"requestQueue",{state:zt.idle,queue:[]}),P(this,"sessionRequestQueue",{state:zt.idle,queue:[]}),P(this,"requestQueueDelay",M.ONE_SECOND),P(this,"expectedPairingMethodMap",new Map),P(this,"recentlyDeletedMap",new Map),P(this,"recentlyDeletedLimit",200),P(this,"relayMessageCache",[]),P(this,"pendingSessions",new Map),P(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(je)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay)))}),P(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=et(ve({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=qw(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=r;let u=i,d,h=!1;try{if(u){const I=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=I.active}}catch(I){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),I}if(!u||!h){const{topic:I,uri:N}=await this.client.core.pairing.create();u=I,d=N}if(!u){const{message:I}=D("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(I)}const p=await this.client.core.crypto.generateKeyPair(),w=je.wc_sessionPropose.req.ttl||M.FIVE_MINUTES,f=De(w),m=et(ve(ve({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:Td}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:f,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:hs()}),y=pe("session_connect",m.id),{reject:b,resolve:v,done:C}=js(w,Ll),S=({id:I})=>
17{I===m.id&&(this.client.events.off("proposal_expire",S),this.pendingSessions.delete(m.id),this.events.emit(y,{error:{message:Ll,code:0}}))};return this.client.events.on("proposal_expire",S),this.events.once(y,({error:I,session:N})=>{this.client.events.off("proposal_expire",S),I?b(I):N&&v(N)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:m,throwOnFailedPublish:!0,clientRpcId:m.id}),await this.setProposal(m.id,m),{uri:d,approval:C}}),P(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(r){throw this.client.logger.error("pair() failed"),r}}),P(this,"approve",async s=>{var r,i,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=s==null?void 0:s.id)==null?void 0:r.toString(),trace:[kt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(E){throw o.setError(Us.no_internet_connection),E}try{await this.isValidProposalId(s==null?void 0:s.id)}catch(E){throw this.client.logger.error(`approve() -> proposal.get(${s==null?void 0:s.id}) failed`),o.setError(Us.proposal_not_found),E}try{await this.isValidApprove(s)}catch(E){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Us.session_approve_namespace_validation_failure),E}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=s,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:w,proposer:f,requiredNamespaces:m,optionalNamespaces:y}=p;let b=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:w});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:kt.session_approve_started,properties:{topic:w,trace:[kt.session_approve_started,kt.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),C=f.publicKey,S=await this.client.core.crypto.generateSharedKey(v,C),I=ve(ve(ve({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:De(gr)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),N=Ne.relay;b.addTrace(kt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(S,{transportType:N})}catch(E){throw b.setError(Us.subscribe_session_topic_failure),E}b.addTrace(kt.subscribe_session_topic_success);const U=et(ve({},I),{topic:S,requiredNamespaces:m,optionalNamespaces:y,pairingTopic:w,acknowledged:!1,self:I.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:v,transportType:Ne.relay});await this.client.session.set(S,U),b.addTrace(kt.store_session);try{b.addTrace(kt.publishing_session_settle),await this.sendRequest({topic:S,method:"wc_sessionSettle",params:I,throwOnFailedPublish:!0}).catch(E=>{throw b==null||b.setError(Us.session_settle_publish_failure),E}),b.addTrace(kt.session_settle_publish_success),b.addTrace(kt.publishing_session_approve),await this.sendResult({id:a,topic:w,result:{relay:{protocol:c??"irn"},responderPublicKey:v},throwOnFailedPublish:!0}).catch(E=>{throw b==null||b.setError(Us.session_approve_publish_failure),E}),b.addTrace(kt.session_approve_publish_success)}catch(E){throw this.client.logger.error(E),this.client.session.delete(S,we("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(S),E}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:f.metadata}),await this.client.proposal.delete(a,we("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(S,De(gr)),{topic:S,acknowledged:()=>Promise.resolve(this.client.session.get(S))}}),P(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:r,reason:i}=s;let n;try{n=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}
17n&&(await this.sendError({id:r,topic:n,error:i,rpcOpts:je.wc_sessionPropose.reject}),await this.client.proposal.delete(r,we("USER_DISCONNECTED")))}),P(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:r,namespaces:i}=s,{done:n,resolve:o,reject:a}=js(),c=hs(),l=$r().toString(),u=this.client.session.get(r).namespaces;return this.events.once(pe("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(r,{namespaces:u}),a(d)}),{acknowledged:n}}),P(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:r}=s,i=hs(),{done:n,resolve:o,reject:a}=js();return this.events.once(pe("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,De(gr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),P(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:i,topic:n,expiry:o=je.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(n);(a==null?void 0:a.transportType)===Ne.relay&&await this.confirmOnlineStateOrThrow();const c=hs(),l=$r().toString(),{done:u,resolve:d,reject:h}=js(o,"Request expired. Please try again.");this.events.once(pe("session_request",c),({error:y,result:b})=>{y?h(y):d(b)});const p="wc_sessionRequest",w=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(w)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:p,params:{request:et(ve({},i),{expiryTimestamp:De(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:w}).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),await u();const f={request:et(ve({},i),{expiryTimestamp:De(o)}),chainId:r},m=this.shouldSetTVF(p,f);return await Promise.all([new Promise(async y=>{await this.sendRequest(ve({clientRpcId:c,relayRpcId:l,topic:n,method:p,params:f,expiry:o,throwOnFailedPublish:!0},m&&{tvf:this.getTVFParams(c,f)})).catch(b=>h(b)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const v=await eg(this.client.core.storage,Ml);await Zf({id:c,topic:n,wcDeepLink:v})}y()}),u()]).then(y=>y[2])}),P(this,"respond",async s=>{this.isInitialized(),await this.isValidRespond(s);const{topic:r,response:i}=s,{id:n}=i,o=this.client.session.get(r);o.transportType===Ne.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);ns(i)?await this.sendResult({id:n,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:a}):Ht(i)&&await this.sendError({id:n,topic:r,error:i.error,appLink:a}),this.cleanupAfterResponse(s)}),P(this,"ping",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(s)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=s;if(this.client.session.keys.includes(r)){const i=hs(),n=$r().toString(),{done:o,resolve:a,reject:c}=js();this.events.once(pe("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(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:r}))}),P(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);
vendor: 10,695 bytes, line 17
17const{topic:r,event:i,chainId:n}=s,o=$r().toString(),a=hs();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),P(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:r}=s;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:we("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=D("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),P(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(r=>Ww(r,s)))),P(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),P(this,"authenticate",async(s,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(s);const n=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=n?Ne.link_mode:Ne.relay;o===Ne.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:p,nbf:w,methods:f=[],expiry:m}=s,y=[...s.resources||[]],{topic:b,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:v}});const C=await this.client.core.crypto.generateKeyPair(),S=qn(C);if(await Promise.all([this.client.auth.authKeys.set(zn,{responseTopic:S,publicKey:C}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:b})]),await this.client.core.relayer.subscribe(S,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),f.length>0){const{namespace:x}=Ur(a[0]);let G=Vg(x,"request",f);Bn(y)&&(G=Gg(G,y.pop())),y.push(G)}const I=m&&m>je.wc_sessionAuthenticate.req.ttl?m:je.wc_sessionAuthenticate.req.ttl,N={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:p,nbf:w,resources:y},requester:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:De(I)},U={eip155:{chains:a,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},E={requiredNamespaces:{},optionalNamespaces:U,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:De(je.wc_sessionPropose.req.ttl),id:hs()},{done:k,resolve:A,reject:R}=js(I,"Request expired"),W=hs(),_=pe("session_connect",E.id),$=pe("session_request",W),O=async({error:x,session:G})=>{this.events.off($,j),x?R(x):G&&A({session:G})},j=async x=>{var G,Q,se;if(await this.deletePendingAuthRequest(W,{message:"fulfilled",code:0}),x.error){const Re=we("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===Re.code?void 0:(this.events.off(_,O),R(x.error.message))}await this.deleteProposal(E.id),this.events.off(_,O);const{cacaos:Ce,responder:he}=x.result,Te=[],Me=[];for(const Re of Ce){await Rc({cacao:Re,projectId:this.client.core.projectId})||(this.client.logger.error(Re,"Signature verification failed"),R(we("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ks}=Re,Xt=Bn(ks.resources),Bt=[oa(ks.iss)],Qt=Yn(ks.iss);if(Xt){const es=Uc(Xt),In=Dc(Xt);Te.push(...es),Bt.push(...In)}for(const es of Bt)Me.push(`${es}:${Qt}`)}const Ye=await this.client.core.crypto.generateSharedKey(C,he.publicKey);let ke;Te.length>0&&(ke={topic:Ye,acknowledged:!0,self:{publicKey:C,metadata:this.client.metadata},peer:he,controller:he.publicKey,expiry:De(gr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:al([...new Set(Te)],[...new Set(Me)]),transportType:o},await this.client.core.relayer.subscribe(Ye,{transportType:o}),await this.client.session.set(Ye,ke),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:he.metadata}),ke=this.client.session.get(Ye)),(G=this.client.metadata.redirect)!=null&&G.linkMode&&(Q=he.metadata.redirect)!=null&&Q.linkMode&&(se=he.metadata.redirect)!=null&&se.universal&&r&&(this.client.core.addLinkModeSupportedApp(he.metadata.redirect.universal),this.client.session.update(Ye,{transportType:Ne.link_mode})),A({auths:Ce,session:ke})};this.events.once(_,O),this.events.once($,j);let q;try{if(n){const x=Ws("wc_sessionAuthenticate",N,W);this.client.core.history.set(b,x);const G=await this.client.core.crypto.encode("",x,{type:bn,encoding:Es});q=xn(r,b,G)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:N,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:W}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:E,expiry:je.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(x){throw this.events.off(_,O),this.events.off($,j),x}return await this.setProposal(E.id,E),await this.setAuthRequest(W,{request:et(ve({},N),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:q??v,response:k}}),P(this,"approveSessionAuthenticate",async s=>{const{id:r,auths:i}=s,n=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Ds.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw n.setError(hi.no_internet_connection),m}const o=this.getPendingAuthRequest(r);if(!o)throw n.setError(hi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Ne.relay;a===Ne.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=qn(c),d={type:us,receiverPublicKey:c,senderPublicKey:l},h=[],p=[];for(const m of i){if(!await Rc({cacao:m,projectId:this.client.core.projectId})){n.setError(hi.invalid_cacao);const S=we("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:S,encodeOpts:d}),new Error(S.message)}n.addTrace(Ds.cacaos_verified);const{p:y}=m,b=Bn(y.resources),v=[oa(y.iss)],C=Yn(y.iss);if(b){const S=Uc(b),I=Dc(b);h.push(...S),v.push(...I)}for(const S of v)p.push(`${S}:${C}`)}const w=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Ds.create_authenticated_session_topic);let f;if((h==null?void 0:h.length)>0){f={topic:w,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:De(gr),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:al([...new Set(h)],[...new Set(p)]),transportType:a},n.addTrace(Ds.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:a})}catch(m){throw n.setError(hi.subscribe_authenticated_session_topic_failure),m}n.addTrace(Ds.subscribe_authenticated_session_topic_success),await this.client.session.set(w,f),n.addTrace(Ds.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Ds.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(m){throw n.setError(hi.authenticated_session_approve_publish_failure),m}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:f}}),P(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:r,reason:i}=s,n=this.getPendingAuthRequest(r);if(!n)throw new Error(`Could not find pending auth request with id ${r}`);n.transportType===Ne.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=qn(o),l={type:us,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:l,rpcOpts:je.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.client.proposal.delete(r,we("USER_DISCONNECTED"))}),P(this,"formatAuthMessage",s=>{this.isInitialized();const{request:r,iss:i}=s;return td(r,i)}),P(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)}),P(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const r=this.client.core.pairing.pairings.get(s.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&n.topic&&n.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),P(this,"deleteSession",async s=>{var r;const{topic:i,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=s,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,we("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),n||this.client.core.expirer.del(i),this.client.core.storage.removeItem(Ml).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,we("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=zt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),P(this,"deleteProposal",async(s,r)=>{if(r)try{const i=this.client.proposal.get(s),n=this.client.core.eventClient.getEvent({topic:i.pairingTopic});n==null||n.setError(Us.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,we("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),P(this,"deletePendingSessionRequest",async(s,r,i=!1)=>
17{await Promise.all([this.client.pendingRequest.delete(s,r),i?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==s),i&&(this.sessionRequestQueue.state=zt.idle,this.client.events.emit("session_request_expire",{id:s}))}),P(this,"deletePendingAuthRequest",async(s,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(s,r),i?Promise.resolve():this.client.core.expirer.del(s)])}),P(this,"setExpiry",async(s,r)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,r),await this.client.session.update(s,{expiry:r}))}),P(this,"setProposal",async(s,r)=>{this.client.core.expirer.set(s,De(je.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,r)}),P(this,"setAuthRequest",async(s,r)=>{const{request:i,pairingTopic:n,transportType:o=Ne.relay}=r;this.client.core.expirer.set(s,i.expiryTimestamp),await this.client.auth.requests.set(s,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:s,pairingTopic:n,verifyContext:i.verifyContext,transportType:o})}),P(this,"setPendingSessionRequest",async s=>{const{id:r,topic:i,params:n,verifyContext:o}=s,a=n.request.expiryTimestamp||De(je.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:n,verifyContext:o})}),P(this,"sendRequest",async s=>{const{topic:r,method:i,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d}=s,h=Ws(i,n,c);let p;const w=!!u;try{const y=w?Es:Lt;p=await this.client.core.crypto.encode(r,h,{encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),y}let f;if(aE.includes(i)){const y=Kt(JSON.stringify(h)),b=Kt(p);f=await this.client.core.verify.register({id:b,decryptedId:y})}const m=je[i].req;if(m.attestation=f,o&&(m.ttl=o),a&&(m.id=a),this.client.core.history.set(r,h),w){const y=xn(u,r,p);await global.Linking.openURL(y,this.client.name)}else{const y=je[i].req;o&&(y.ttl=o),a&&(y.id=a),y.tvf=et(ve({},d),{correlationId:h.id}),l?(y.internal=et(ve({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,y)):this.client.core.relayer.publish(r,p,y).catch(b=>this.client.logger.error(b))}return h.id}),P(this,"sendResult",async s=>{const{id:r,topic:i,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=so(r,n);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const w=d?Es:Lt;u=await this.client.core.crypto.encode(i,l,et(ve({},a||{}),{encoding:w}))}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),w}let h,p;try{h=await this.client.core.history.get(i,r);const w=h.request;try{this.shouldSetTVF(w.method,w.params)&&(p=this.getTVFParams(r,w.params,n))}catch(f){this.client.logger.warn("sendResult() -> getTVFParams() failed",f)}}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),w}if(d){const w=xn(c,i,u);await global.Linking.openURL(w,this.client.name)}else{const w=h.request.method,f=je[w].res;f.tvf=et(ve({},p),{correlationId:r}),o?(f.internal=et(ve({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,f)):this.client.core.relayer.publish(i,u,f).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(l)}),P(this,"sendError",async s=>{const{id:r,topic:i,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=wu(r,n);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=d?Es:Lt;u=await this.client.core.crypto.encode(i,l,et(ve({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let h;try{h=await this.client.core.history.get(i,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),p}if(d){const p=xn(c,i,u);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,w=a||je[p].res;this.client.core.relayer.publish(i,u,w)}await this.client.core.history.resolve(l)}),P(this,"cleanup",async()=>{const s=[],r=[];
vendor: 14,060 bytes, line 17
17this.client.session.getAll().forEach(i=>{let n=!1;vs(i.expiry)&&(n=!0),this.client.core.crypto.keychain.has(i.topic)||(n=!0),n&&s.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{vs(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...s.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),P(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),P(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),P(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===zt.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=zt.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=zt.idle}),P(this,"processRequest",async s=>{const{topic:r,payload:i,attestation:n,transportType:o,encryptedId:a}=s,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),P(this,"onRelayEventResponse",async s=>{const{topic:r,payload:i,transportType:n}=s,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,n);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),P(this,"onRelayEventUnknownPayload",s=>{const{topic:r}=s,{message:i}=D("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),P(this,"shouldIgnorePairingRequest",s=>{const{topic:r,requestMethod:i}=s,n=this.expectedPairingMethodMap.get(r);return!n||n.includes(i)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),P(this,"onSessionProposeRequest",async s=>{const{topic:r,payload:i,attestation:n,encryptedId:o}=s,{params:a,id:c}=i;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(os.proposal_listener_not_found)),this.isValidConnect(ve({},i.params));const u=a.expiryTimestamp||De(je.wc_sessionPropose.req.ttl),d=ve({id:c,pairingTopic:r,expiryTimestamp:u},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:n,hash:Kt(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l==null||l.addTrace(Wt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:je.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),P(this,"onSessionProposeResponse",async(s,r,i)=>{const{id:n}=r;if(ns(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:s,proposalId:n,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:s})}else if(Ht(r)){await this.client.proposal.delete(n,we("USER_DISCONNECTED"));const o=pe("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),P(this,"onSessionSettleRequest",async(s,r)=>{const{id:i,params:n}=r;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=r.params,p=[...this.pendingSessions.values()].find(m=>m.sessionTopic===s);if(!p)return this.client.logger.error(`Pending session not found for topic ${s}`);const w=this.client.proposal.get(p.proposalId),f=et(ve(ve(ve({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:Ne.relay});await this.client.session.set(f.topic,f),await this.setExpiry(f.topic,f.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:f.peer.metadata}),this.client.events.emit("session_connect",{session:f}),this.events.emit(pe("session_connect",p.proposalId),{session:f}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(f),await this.sendResult({id:r.id,topic:s,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),P(this,"onSessionSettleResponse",async(s,r)=>{const{id:i}=r;ns(r)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(pe("session_approve",i),{})):Ht(r)&&(await this.client.session.delete(s,we("USER_DISCONNECTED")),this.events.emit(pe("session_approve",i),{error:r.error}))}),P(this,"onSessionUpdateRequest",async(s,r)=>{const{params:i,id:n}=r;try{const o=`${s}_session_update`,a=ui.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:s,error:we("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ve({topic:s},i));try{ui.set(o,n),await this.client.session.update(s,{namespaces:i.namespaces}),await this.sendResult({id:n,topic:s,result:!0,throwOnFailedPublish:!0})}catch(c){throw ui.delete(o),c}this.client.events.emit("session_update",{id:n,topic:s,params:i})}catch(o){await this.sendError({id:n,topic:s,error:o}),this.client.logger.error(o)}}),P(this,"isRequestOutOfSync",(s,r)=>r.toString().slice(0,-3)<s.toString().slice(0,-3)),P(this,"onSessionUpdateResponse",(s,r)=>{const{id:i}=r,n=pe("session_update",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ns(r)?this.events.emit(pe("session_update",i),{}):Ht(r)&&this.events.emit(pe("session_update",i),{error:r.error})}),P(this,"onSessionExtendRequest",async(s,r)=>{const{id:i}=r;try{this.isValidExtend({topic:s}),await this.setExpiry(s,De(gr)),await this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:s})}catch(n){await this.sendError({id:i,topic:s,error:n}),this.client.logger.error(n)}}),P(this,"onSessionExtendResponse",(s,r)=>{const{id:i}=r,n=pe("session_extend",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ns(r)?this.events.emit(pe("session_extend",i),{}):Ht(r)&&this.events.emit(pe("session_extend",i),{error:r.error})}),P(this,"onSessionPingRequest",async(s,r)=>{const{id:i}=r;try{this.isValidPing({topic:s}),await this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:s})}catch(n){await this.sendError({id:i,topic:s,error:n}),this.client.logger.error(n)}}),P(this,"onSessionPingResponse",(s,r)=>{const{id:i}=r,n=pe("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);ns(r)?this.events.emit(pe("session_ping",i),{}):Ht(r)&&this.events.emit(pe("session_ping",i),{error:r.error})},500)}),P(this,"onSessionDeleteRequest",async(s,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:s,reason:r.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(qe.publish,async()=>{n(await this.deleteSession({topic:s,id:i}))})}),this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:we("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),P(this,"onSessionRequest",async s=>{var r,i,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=s,{id:d,params:h}=a;try{await this.isValidRequest(ve({topic:o},h));const p=this.client.session.get(o),w=await this.getVerifyContext({attestationId:c,hash:Kt(JSON.stringify(Ws("wc_sessionRequest",h,d))),encryptedId:l,metadata:p.peer.metadata,transportType:u}),f={id:d,topic:o,params:h,verifyContext:w};await this.setPendingSessionRequest(f),u===Ne.link_mode&&(r=p.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(p){await this.sendError({id:d,topic:o,error:p}),this.client.logger.error(p)}}),P(this,"onSessionRequestResponse",(s,r)=>{const{id:i}=r,n=pe("session_request",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ns(r)?this.events.emit(pe("session_request",i),{result:r.result}):Ht(r)&&this.events.emit(pe("session_request",i),{error:r.error})}),P(this,"onSessionEventRequest",async(s,r)=>{const{id:i,params:n}=r;try{const o=`${s}_session_event_${n.event.name}`,a=ui.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ve({topic:s},n)),this.client.events.emit("session_event",{id:i,topic:s,params:n}),ui.set(o,i)}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),P(this,"onSessionAuthenticateResponse",(s,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:r}),ns(r)?this.events.emit(pe("session_request",i),{result:r.result}):Ht(r)&&this.events.emit(pe("session_request",i),{error:r.error})}),P(this,"onSessionAuthenticateRequest",async s=>{var r;const{topic:i,payload:n,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:u,expiryTimestamp:d}=n.params,h=await this.getVerifyContext({attestationId:o,hash:Kt(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:i,id:n.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(n.id,{request:p,pairingTopic:i,transportType:c}),c===Ne.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:n.params,id:n.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=n.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(n.params.requester.metadata,c),p={type:us,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:n.id,topic:i,error:l,encodeOpts:p,rpcOpts:je.wc_sessionAuthenticate.autoReject,appLink:h})}}),P(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),P(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=zt.idle,this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay))}),P(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(n=>n.topic===s&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=pe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(pe("session_request",n.request.id),{error:r})})}),P(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===zt.active){this.client.logger.info("session request queue is already active.");return}const s=this.sessionRequestQueue.queue[0];if(!s){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=zt.active,this.emitSessionRequest(s)}catch(r){this.client.logger.error(r)}}),P(this,"emitSessionRequest",s=>{this.client.events.emit("session_request",s)}),P(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===s.topic);
17r&&this.onSessionProposeRequest({topic:s.topic,payload:Ws("wc_sessionPropose",et(ve({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id)})}),P(this,"isValidConnect",async s=>{if(!ct(s)){const{message:l}=D("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=s;if(Ge(r)||await this.isValidPairingTopic(r),!sy(c)){const{message:l}=D("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!Ge(i)&&Ps(i)!==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(i,"requiredNamespaces")}if(!Ge(n)&&Ps(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Ge(o)||this.validateSessionProps(o,"sessionProperties"),!Ge(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(u=>l.includes(u)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),P(this,"validateNamespaces",(s,r)=>{const i=ty(s,"connect()",r);if(i)throw new Error(i.message)}),P(this,"isValidApprove",async s=>{if(!ct(s))throw new Error(D("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:r,namespaces:i,relayProtocol:n,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=$o(i,"approve()");if(l)throw new Error(l.message);const u=ul(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!xe(n,!0)){const{message:d}=D("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(d)}if(Ge(o)||this.validateSessionProps(o,"sessionProperties"),!Ge(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(i));if(!Object.keys(a).every(h=>d.has(h)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),P(this,"isValidReject",async s=>{if(!ct(s)){const{message:n}=D("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(n)}const{id:r,reason:i}=s;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!iy(i)){const{message:n}=D("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(n)}}),P(this,"isValidSessionSettleRequest",s=>{if(!ct(s)){const{message:l}=D("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:r,controller:i,namespaces:n,expiry:o}=s;if(!Sd(r)){const{message:l}=D("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Jw(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=$o(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(vs(o)){const{message:l}=D("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),P(this,"isValidUpdate",async s=>{if(!ct(s)){const{message:c}=D("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:r,namespaces:i}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const n=this.client.session.get(r),o=$o(i,"update()");if(o)throw new Error(o.message);const a=ul(n.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),P(this,"isValidExtend",async s=>{if(!ct(s)){const{message:i}=D("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(i)}const{topic:r}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),P(this,"isValidRequest",async s=>{if(!ct(s)){const{message:c}=D("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:r,request:i,chainId:n,expiry:o}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!ll(a,n)){const{message:c}=D("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!ny(i)){const{message:c}=D("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!cy(a,n,i.method)){const{message:c}=D("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!hy(o,Lo)){const{message:c}=D("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Lo.min} and ${Lo.max}`);throw new Error(c)}}),P(this,"isValidRespond",async s=>{var r;if(!ct(s)){const{message:o}=D("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(o)}const{topic:i,response:n}=s;try{await this.isValidSessionTopic(i)}catch(o){throw(r=s==null?void 0:s.response)!=null&&r.id&&this.cleanupAfterResponse(s),o}if(!oy(n)){const{message:o}=D("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),P(this,"isValidPing",async s=>{if(!ct(s)){const{message:i}=D("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(i)}const{topic:r}=s;await this.isValidSessionOrPairingTopic(r)}),P(this,"isValidEmit",async s=>{if(!ct(s)){const{message:a}=D("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}
vendor: 10,543 bytes, line 17
17const{topic:r,event:i,chainId:n}=s;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!ll(o,n)){const{message:a}=D("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!ay(i)){const{message:a}=D("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!ly(o,n,i.name)){const{message:a}=D("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),P(this,"isValidDisconnect",async s=>{if(!ct(s)){const{message:i}=D("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(i)}const{topic:r}=s;await this.isValidSessionOrPairingTopic(r)}),P(this,"isValidAuthenticate",s=>{const{chains:r,uri:i,domain:n,nonce:o}=s;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!xe(i,!1))throw new Error("uri is required parameter");if(!xe(n,!1))throw new Error("domain is required parameter");if(!xe(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Ur(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Ur(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),P(this,"getVerifyContext",async s=>{const{attestationId:r,hash:i,encryptedId:n,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||Pi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Ne.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:n,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),P(this,"validateSessionProps",(s,r)=>{Object.values(s).forEach((i,n)=>{if(i==null){const{message:o}=D("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(s)[n]}`);throw new Error(o)}})}),P(this,"getPendingAuthRequest",s=>{const r=this.client.auth.requests.get(s);return typeof r=="object"?r:void 0}),P(this,"addToRecentlyDeleted",(s,r)=>{if(this.recentlyDeletedMap.set(s,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=n)break;this.recentlyDeletedMap.delete(o)}}}),P(this,"checkRecentlyDeleted",s=>{const r=this.recentlyDeletedMap.get(s);if(r){const{message:i}=D("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${s}`);throw new Error(i)}}),P(this,"isLinkModeEnabled",(s,r)=>{var i,n,o,a,c,l,u,d,h;return!s||r!==Ne.link_mode?!1:((n=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=s==null?void 0:s.redirect)==null?void 0:u.universal)!==void 0&&((d=s==null?void 0:s.redirect)==null?void 0:d.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"}),P(this,"getAppLinkIfEnabled",(s,r)=>{var i;return this.isLinkModeEnabled(s,r)?(i=s==null?void 0:s.redirect)==null?void 0:i.universal:void 0}),P(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const r=Nc(s,"topic")||"",i=decodeURIComponent(Nc(s,"wc_ev")||""),n=this.client.session.keys.includes(r);n&&this.client.session.update(r,{transportType:Ne.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:n})}),P(this,"registerLinkModeListeners",async()=>{var s;if(Ba()||xs()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),P(this,"shouldSetTVF",(s,r)=>{if(!r||s!=="wc_sessionRequest")return!1;const{request:i}=r;return Object.keys(jl).includes(i.method)}),P(this,"getTVFParams",(s,r,i)=>{var n,o;try{const a=r.request.method,c=this.extractTxHashesFromResult(a,i);return et(ve({correlationId:s,rpcMethods:[a],chainId:r.chainId},this.isValidContractData(r.request.params)&&{contractAddresses:[(o=(n=r.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),P(this,"isValidContractData",s=>{var r;if(!s)return!1;try{const i=(s==null?void 0:s.data)||((r=s==null?void 0:s[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const n=i.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),P(this,"extractTxHashesFromResult",(s,r)=>{try{const i=jl[s];if(typeof r=="string")return[r];const n=r[i.key];if(Ss(n))return s==="solana_signAllTransactions"?n.map(o=>xg(o)):n;if(typeof n=="string")return[n]}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[r,i]of Object.entries(s))for(const n of i)try{await this.onProviderMessageEvent({topic:r,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=D("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(qe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:r,attestation:i,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(zn)?this.client.auth.authKeys.get(zn):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,r,{receiverPublicKey:o,encoding:n===Ne.link_mode?Es:Lt});Ra(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:i,transportType:n,encryptedId:Kt(r)})):Ua(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:n}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(s,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Pt.expired,async e=>{const{topic:s,id:r}=Vu(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,D("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,D("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(Fs.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Fs.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!xe(e,!1)){const{message:s}=D("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}=D("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(vs(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=D("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!xe(e,!1)){const{message:s}=D("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}=D("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(vs(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=D("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=D("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(xe(e,!1)){const{message:s}=D("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=D("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!ry(e)){const{message:s}=D("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=D("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(vs(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=D("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class bE extends lr{constructor(e,s){super(e,s,rE,Ga),this.core=e,this.logger=s}}let vE=class extends lr{constructor(e,s){super(e,s,iE,Ga),this.core=e,this.logger=s}};class EE extends lr{constructor(e,s){super(e,s,oE,Ga,r=>r.id),this.core=e,this.logger=s}}class CE extends lr{constructor(e,s){super(e,s,uE,ho,()=>zn),this.core=e,this.logger=s}}class IE extends lr{constructor(e,s){super(e,s,dE,ho),this.core=e,this.logger=s}}class AE extends lr{constructor(e,s){super(e,s,hE,ho,r=>r.id),this.core=e,this.logger=s}}var NE=Object.defineProperty,_E=(t,e,s)=>e in t?NE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,jo=(t,e,s)=>_E(t,typeof e!="symbol"?e+"":e,s);class SE{constructor(e,s){this.core=e,this.logger=s,jo(this,"authKeys"),jo(this,"pairingTopics"),jo(this,"requests"),this.authKeys=new CE(this.core,this.logger),this.pairingTopics=new IE(this.core,this.logger),this.requests=new AE(this.core,this.logger)}
17async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var PE=Object.defineProperty,OE=(t,e,s)=>e in t?PE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ne=(t,e,s)=>OE(t,typeof e!="symbol"?e+"":e,s);let TE=class Kd extends hf{constructor(e){super(e),ne(this,"protocol",Wd),ne(this,"version",Hd),ne(this,"name",Mo.name),ne(this,"metadata"),ne(this,"core"),ne(this,"logger"),ne(this,"events",new nr.EventEmitter),ne(this,"engine"),ne(this,"session"),ne(this,"proposal"),ne(this,"pendingRequest"),ne(this,"auth"),ne(this,"signConfig"),ne(this,"on",(r,i)=>this.events.on(r,i)),ne(this,"once",(r,i)=>this.events.once(r,i)),ne(this,"off",(r,i)=>this.events.off(r,i)),ne(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),ne(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),ne(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),ne(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(n){throw this.logger.error(n.message),n}}),ne(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),ne(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=(e==null?void 0:e.name)||Mo.name,this.metadata=Hf(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:ka(dn({level:(e==null?void 0:e.logger)||Mo.logger}));this.core=(e==null?void 0:e.core)||new sE(e),this.logger=st(s,this.name),this.session=new vE(this.core,this.logger),this.proposal=new bE(this.core,this.logger),this.pendingRequest=new EE(this.core,this.logger),this.engine=new yE(this),this.auth=new SE(this.core,this.logger)}static async init(e){const s=new Kd(e);return await s.initialize(),s}get context(){return vt(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},M.toMiliseconds(M.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const ql="error",$E="wss://relay.walletconnect.org",xE="wc",kE="universal_provider",Rn=`${xE}@2:${kE}:`,Gd="https://rpc.walletconnect.org/v1/",Pr="generic",RE=`${Gd}bundler`,$t={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function UE(){}function Ja(t){return t==null||typeof t!="object"&&typeof t!="function"}function Ya(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function DE(t){if(Ja(t))return t;if(Array.isArray(t)||Ya(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 r=new s(t);return r.lastIndex=t.lastIndex,r}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const r=new s(t.message);return r.stack=t.stack,r.name=t.name,r.cause=t.cause,r}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const r=Object.create(e);return Object.assign(r,t)}return t}function Fl(t){return typeof t=="object"&&t!==null}function Jd(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}
17function Yd(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const ME="[object RegExp]",Zd="[object String]",Xd="[object Number]",Qd="[object Boolean]",eh="[object Arguments]",LE="[object Symbol]",jE="[object Date]",BE="[object Map]",qE="[object Set]",FE="[object Array]",zE="[object ArrayBuffer]",WE="[object Object]",HE="[object DataView]",VE="[object Uint8Array]",KE="[object Uint8ClampedArray]",GE="[object Uint16Array]",JE="[object Uint32Array]",YE="[object Int8Array]",ZE="[object Int16Array]",XE="[object Int32Array]",QE="[object Float32Array]",eC="[object Float64Array]";function tC(t,e){return Rr(t,void 0,t,new Map,e)}function Rr(t,e,s,r=new Map,i=void 0){const n=i==null?void 0:i(t,e,s,r);if(n!=null)return n;if(Ja(t))return t;if(r.has(t))return r.get(t);if(Array.isArray(t)){const o=new Array(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Rr(t[a],a,s,r,i);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;r.set(t,o);for(const[a,c]of t)o.set(a,Rr(c,a,s,r,i));return o}if(t instanceof Set){const o=new Set;r.set(t,o);for(const a of t)o.add(Rr(a,void 0,s,r,i));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(Ya(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Rr(t[a],a,s,r,i);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 r.set(t,o),zs(o,t,s,r,i),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return r.set(t,o),zs(o,t,s,r,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return r.set(t,o),zs(o,t,s,r,i),o}if(t instanceof Error){const o=new t.constructor;return r.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,zs(o,t,s,r,i),o}if(typeof t=="object"&&sC(t)){const o=Object.create(Object.getPrototypeOf(t));return r.set(t,o),zs(o,t,s,r,i),o}return t}function zs(t,e,s=t,r,i){const n=[...Object.keys(e),...Jd(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Rr(e[a],a,s,r,i))}}function sC(t){switch(Yd(t)){case eh:case FE:case zE:case HE:case Qd:case jE:case QE:case eC:case YE:case ZE:case XE:case BE:case Xd:case WE:case ME:case qE:case Zd:case LE:case VE:case KE:case GE:case JE:return!0;default:return!1}}function rC(t,e){return tC(t,(s,r,i,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Xd:case Zd:case Qd:{const o=new t.constructor(t==null?void 0:t.valueOf());return zs(o,t),o}case eh:{const o={};return zs(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function zl(t){return rC(t)}function Wl(t){return t!==null&&typeof t=="object"&&Yd(t)==="[object Arguments]"}function iC(t){return Ya(t)}function nC(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 r=t[Symbol.toStringTag];return r==null||!((s=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&s.writable)?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function oC(t,...e){const s=e.slice(0,-1),r=e[e.length-1];let i=t;for(let n=0;n<s.length;n++){const o=s[n];i=Pa(i,o,r,new Map)}return i}function Pa(t,e,s,r){if(Ja(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(r.has(e))return DE(r.get(e));if(r.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const i=[...Object.keys(e),...Jd(e)];for(let n=0;n<i.length;n++){const o=i[n];let a=e[o],c=t[o];if(Wl(a)&&(a={...a}),Wl(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=zl(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],d=Reflect.ownKeys(c);for(let h=0;h<d.length;h++){const p=d[h];u[p]=c[p]}c=u}else c=[];const l=s(c,a,o,t,e,r);l!=null?t[o]=l:Array.isArray(a)||Fl(c)&&Fl(a)?t[o]=Pa(c,a,s,r):c==null&&nC(a)?t[o]=Pa({},a,s,r):c==null&&iC(a)?t[o]=zl(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function aC(t,...e){return oC(t,...e,UE)}var cC=Object.defineProperty,lC=Object.defineProperties,uC=Object.getOwnPropertyDescriptors,Hl=Object.getOwnPropertySymbols,dC=Object.prototype.hasOwnProperty,hC=Object.prototype.propertyIsEnumerable,Vl=(t,e,s)=>e in t?cC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Un=(t,e)=>{for(var s in e||(e={}))dC.call(e,s)&&Vl(t,s,e[s]);if(Hl)for(var s of Hl(e))hC.call(e,s)&&Vl(t,s,e[s]);return t},pC=(t,e)=>lC(t,uC(e));function bt(t,e,s){var r;const i=Ur(t);return((r=e.rpcMap)==null?void 0:r[i.reference])||`${Gd}?chainId=${i.namespace}:${i.reference}&projectId=${s}`}function ur(t){return t.includes(":")?t.split(":")[1]:t}function th(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function fC(t,e){const s=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!s.length)return[];const r=[];
17return s.forEach(i=>{const n=e.namespaces[i].accounts;r.push(...n)}),r}function Dn(t={},e={}){const s=Kl(t),r=Kl(e);return aC(s,r)}function Kl(t){var e,s,r,i,n;const o={};if(!Ps(t))return o;for(const[a,c]of Object.entries(t)){const l=lo(a)?[a]:c.chains,u=c.methods||[],d=c.events||[],h=c.rpcMap||{},p=kr(a);o[p]=pC(Un(Un({},o[p]),c),{chains:Jt(l,(e=o[p])==null?void 0:e.chains),methods:Jt(u,(s=o[p])==null?void 0:s.methods),events:Jt(d,(r=o[p])==null?void 0:r.events)}),(Ps(h)||Ps(((i=o[p])==null?void 0:i.rpcMap)||{}))&&(o[p].rpcMap=Un(Un({},h),(n=o[p])==null?void 0:n.rpcMap))}return o}function Gl(t){return t.includes(":")?t.split(":")[2]:t}function Jl(t){const e={};for(const[s,r]of Object.entries(t)){const i=r.methods||[],n=r.events||[],o=r.accounts||[],a=lo(s)?[s]:r.chains?r.chains:th(r.accounts);e[s]={chains:a,methods:i,events:n,accounts:o}}return e}function Bo(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const sh={},ue=t=>sh[t],qo=(t,e)=>{sh[t]=e};var gC=Object.defineProperty,mC=(t,e,s)=>e in t?gC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mr=(t,e,s)=>mC(t,typeof e!="symbol"?e+"":e,s);class wC{constructor(e){mr(this,"name","polkadot"),mr(this,"client"),mr(this,"httpProviders"),mr(this,"events"),mr(this,"namespace"),mr(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ur(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||bt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Tt(new jt(r,ue("disableProviderPing")))}}var yC=Object.defineProperty,bC=Object.defineProperties,vC=Object.getOwnPropertyDescriptors,Yl=Object.getOwnPropertySymbols,EC=Object.prototype.hasOwnProperty,CC=Object.prototype.propertyIsEnumerable,Oa=(t,e,s)=>e in t?yC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Zl=(t,e)=>{for(var s in e||(e={}))EC.call(e,s)&&Oa(t,s,e[s]);if(Yl)for(var s of Yl(e))CC.call(e,s)&&Oa(t,s,e[s]);return t},Xl=(t,e)=>bC(t,vC(e)),wr=(t,e,s)=>Oa(t,typeof e!="symbol"?e+"":e,s);class IC{constructor(e){wr(this,"name","eip155"),wr(this,"client"),wr(this,"chainId"),wr(this,"namespace"),wr(this,"httpProviders"),wr(this,"events"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s),this.chainId=parseInt(e),this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,s){const r=s||bt(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Tt(new jt(r,ue("disableProviderPing")))}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=parseInt(ur(s));e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}async handleSwitchChain(e){var s,r;let i=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const n=parseInt(i,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,r,i,n,o;const a=(r=(s=e.request)==null?void 0:s.params)==null?void 0:r[0],c=((n=(i=e.request)==null?void 0:i.params)==null?void 0:n[1])||[],l=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");
17const u=this.client.session.get(e.topic),d=((o=u==null?void 0:u.sessionProperties)==null?void 0:o.capabilities)||{};if(d!=null&&d[l])return d==null?void 0:d[l];const h=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Xl(Zl({},u.sessionProperties||{}),{capabilities:Xl(Zl({},d||{}),{[l]:h})})})}catch(p){console.warn("Failed to update session with capabilities",p)}return h}async getCallStatus(e){var s,r;const i=this.client.session.get(e.topic),n=(s=i.sessionProperties)==null?void 0:s.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(r=i.sessionProperties)==null?void 0:r.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,s){var r;const i=new URL(e),n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ws("eth_getUserOperationReceipt",[(r=s.request.params)==null?void 0:r[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,s){return`${RE}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}}var AC=Object.defineProperty,NC=(t,e,s)=>e in t?AC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yr=(t,e,s)=>NC(t,typeof e!="symbol"?e+"":e,s);class _C{constructor(e){yr(this,"name","solana"),yr(this,"client"),yr(this,"httpProviders"),yr(this,"events"),yr(this,"namespace"),yr(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ur(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||bt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Tt(new jt(r,ue("disableProviderPing")))}}var SC=Object.defineProperty,PC=(t,e,s)=>e in t?SC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,br=(t,e,s)=>PC(t,typeof e!="symbol"?e+"":e,s);class OC{constructor(e){br(this,"name","cosmos"),br(this,"client"),br(this,"httpProviders"),br(this,"events"),br(this,"namespace"),br(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ur(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||bt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Tt(new jt(r,ue("disableProviderPing")))}}var TC=Object.defineProperty,$C=(t,e,s)=>e in t?TC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vr=(t,e,s)=>$C(t,typeof e!="symbol"?e+"":e,s);class xC{constructor(e){vr(this,"name","algorand"),vr(this,"client"),vr(this,"httpProviders"),vr(this,"events"),vr(this,"namespace"),vr(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(!this.httpProviders[e]){const r=s||bt(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.chainId=e,this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||bt(e,this.namespace,this.client.core.projectId);return typeof r>"u"?void 0:new Tt(new jt(r,ue("disableProviderPing")))}}var kC=Object.defineProperty,RC=(t,e,s)=>e in t?kC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Er=(t,e,s)=>RC(t,typeof e!="symbol"?e+"":e,s);class UC{constructor(e){Er(this,"name","cip34"),Er(this,"client"),Er(this,"httpProviders"),Er(this,"events"),Er(this,"namespace"),Er(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{const r=this.getCardanoRPCUrl(s),i=ur(s);e[i]=this.createHttpProvider(i,r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}getCardanoRPCUrl(e){const s=this.namespace.rpcMap;if(s)return s[e]}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||this.getCardanoRPCUrl(e);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Tt(new jt(r,ue("disableProviderPing")))}}var DC=Object.defineProperty,MC=(t,e,s)=>e in t?DC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Cr=(t,e,s)=>MC(t,typeof e!="symbol"?e+"":e,s);class LC{constructor(e){Cr(this,"name","elrond"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ur(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||bt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Tt(new jt(r,ue("disableProviderPing")))}}var jC=Object.defineProperty,BC=(t,e,s)=>e in t?jC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ir=(t,e,s)=>BC(t,typeof e!="symbol"?e+"":e,s);class qC{constructor(e){Ir(this,"name","multiversx"),Ir(this,"client"),Ir(this,"httpProviders"),Ir(this,"events"),Ir(this,"namespace"),Ir(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ur(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||bt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Tt(new jt(r,ue("disableProviderPing")))}}var FC=Object.defineProperty,zC=(t,e,s)=>e in t?FC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ar=(t,e,s)=>zC(t,typeof e!="symbol"?e+"":e,s);class WC{constructor(e){Ar(this,"name","near"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||bt(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||bt(e,this.namespace);return typeof r>"u"?void 0:new Tt(new jt(r,ue("disableProviderPing")))}}var HC=Object.defineProperty,VC=(t,e,s)=>e in t?HC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Nr=(t,e,s)=>VC(t,typeof e!="symbol"?e+"":e,s);class KC{constructor(e){Nr(this,"name","tezos"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||bt(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{e[s]=this.createHttpProvider(s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||bt
17(e,this.namespace);return typeof r>"u"?void 0:new Tt(new jt(r))}}var GC=Object.defineProperty,JC=(t,e,s)=>e in t?GC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_r=(t,e,s)=>JC(t,typeof e!="symbol"?e+"":e,s);class YC{constructor(e){_r(this,"name",Pr),_r(this,"client"),_r(this,"httpProviders"),_r(this,"events"),_r(this,"namespace"),_r(this,"chainId"),this.namespace=e.namespace,this.events=ue("events"),this.client=ue("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($t.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){var e,s;const r={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(i=>{const n=Ur(i);r[`${n.namespace}:${n.reference}`]=this.createHttpProvider(i)}),r}getHttpProvider(e){const s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||bt(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Tt(new jt(r,ue("disableProviderPing")))}}var ZC=Object.defineProperty,XC=Object.defineProperties,QC=Object.getOwnPropertyDescriptors,Ql=Object.getOwnPropertySymbols,e1=Object.prototype.hasOwnProperty,t1=Object.prototype.propertyIsEnumerable,Ta=(t,e,s)=>e in t?ZC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Mn=(t,e)=>{for(var s in e||(e={}))e1.call(e,s)&&Ta(t,s,e[s]);if(Ql)for(var s of Ql(e))t1.call(e,s)&&Ta(t,s,e[s]);return t},Fo=(t,e)=>XC(t,QC(e)),_t=(t,e,s)=>Ta(t,typeof e!="symbol"?e+"":e,s);let s1=class rh{constructor(e){_t(this,"client"),_t(this,"namespaces"),_t(this,"optionalNamespaces"),_t(this,"sessionProperties"),_t(this,"scopedProperties"),_t(this,"events",new Da),_t(this,"rpcProviders",{}),_t(this,"session"),_t(this,"providerOpts"),_t(this,"logger"),_t(this,"uri"),_t(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:ka(dn({level:(e==null?void 0:e.logger)||ql})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const s=new rh(e);return await s.initialize(),s}async request(e,s,r){const[i,n]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:Mn({},e),chainId:`${i}:${n}`,topic:this.session.topic,expiry:r})}sendAsync(e,s,r,i){const n=new Date().getTime();this.request(e,r,i).then(o=>s(null,so(n,o))).catch(o=>s(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:we("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,s){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:i}=await this.client.authenticate(e,s);r&&(this.uri=r,this.events.emit("display_uri",r));const n=await i();if(this.session=n.session,this.session){const o=Jl(this.session.namespaces);this.namespaces=Dn(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}removeListener(e,s){this.events.removeListener(e,s)}off(e,s){this.events.off(e,s)}get isWalletConnect(){return!0}async pair(e){const{uri:s,approval:r}=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 i=await r();this.session=i;
17const n=Jl(i.namespaces);return this.namespaces=Dn(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,s){try{if(!this.session)return;const[r,i]=this.validateChain(e),n=this.getProvider(r);n.name===Pr?n.setDefaultChain(`${r}:${i}`,s):n.setDefaultChain(i,s)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(Ss(s)){for(const r of s)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,s;if(this.client=this.providerOpts.client||await TE.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ql,relayUrl:this.providerOpts.relayUrl||$E,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(r){throw this.logger.error("Failed to get session",r),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 r=this.client.session.getAll();this.session=r[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=>kr(s)))];qo("client",this.client),qo("events",this.events),qo("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const r=fC(s,this.session),i=th(r),n=Dn(this.namespaces,this.optionalNamespaces),o=Fo(Mn({},n[s]),{accounts:r,chains:i});switch(s){case"eip155":this.rpcProviders[s]=new IC({namespace:o});break;case"algorand":this.rpcProviders[s]=new xC({namespace:o});break;case"solana":this.rpcProviders[s]=new _C({namespace:o});break;case"cosmos":this.rpcProviders[s]=new OC({namespace:o});break;case"polkadot":this.rpcProviders[s]=new wC({namespace:o});break;case"cip34":this.rpcProviders[s]=new UC({namespace:o});break;case"elrond":this.rpcProviders[s]=new LC({namespace:o});break;case"multiversx":this.rpcProviders[s]=new qC({namespace:o});break;case"near":this.rpcProviders[s]=new WC({namespace:o});break;case"tezos":this.rpcProviders[s]=new KC({namespace:o});break;default:this.rpcProviders[Pr]?this.rpcProviders[Pr].updateNamespace(o):this.rpcProviders[Pr]=new YC({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:r}=e;r===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:r,topic:i}=e;if(i!==((s=this.session)==null?void 0:s.topic))return;const{event:n}=r;if(n.name==="accountsChanged"){const o=n.data;o&&Ss(o)&&this.events.emit("accountsChanged",o.map(Gl))}else if(n.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=kr(o),l=Bo(o)!==Bo(a)?`${c}:${Bo(a)}`:o;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var r,i;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:n}=s,o=(i=this.client)==null?void 0:i.session.get(e);this.session=Fo(Mn({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:s})}),this.client.on("session_delete",async e=>{var s;e.topic===((s=this.session)==null?void 0:s.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Fo(Mn({},we("USER_DISCONNECTED")),{data:e.topic})))}),this.on($t.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Pr]}
17onSessionUpdate(){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:r={},sessionProperties:i,scopedProperties:n}=e;this.optionalNamespaces=Dn(s,r),this.sessionProperties=i,this.scopedProperties=n}validateChain(e){const[s,r]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,r];if(s&&!Object.keys(this.namespaces||{}).map(o=>kr(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&r)return[s,r];const i=kr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[i].getDefaultChain();return[i,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,s=!1){if(!this.namespaces)return;const[r,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(r,i),this.events.emit("chainChanged",i);const n=this.getProvider(r).getDefaultChain();s||this.getProvider(r).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:r,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:s,newChainId:r}){var i,n;try{if(s===r)return;const o=(n=(i=this.session)==null?void 0:i.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(Gl);if(!Ss(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 r=this.namespaces[e]?e:`${e}:${s}`,i={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=s):this.namespaces[r]=i}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,s){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${Rn}/${e}${i}`,s)}async getFromStore(e){var s;const r=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${Rn}/${e}${r}`)}async deleteFromStore(e){var s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${Rn}/${e}${r}`)}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 r of s)r.startsWith(Rn)&&await this.client.core.storage.removeItem(r)}catch(s){this.logger.warn("Failed to cleanup storage",s)}}};const Ti={getSIWX(){return T.state.siwx},async initializeIfEnabled(){var n;const t=T.state.siwx,e=g.getActiveCaipAddress();if(!(t&&e))return;const[s,r,i]=e.split(":");if(g.checkIfSupportedNetwork(s))try{if((await t.getSessions(`${s}:${r}`,i)).length)return;await ze.open({view:"SIWXSignMessage"})}catch(o){console.error("SIWXUtil:initializeIfEnabled",o),Pe.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await((n=Y._getClient())==null?void 0:n.disconnect().catch(console.error)),re.reset("Connect"),Mt.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=T.state.siwx,e=Z.getPlainAddress(g.getActiveCaipAddress()),s=g.getActiveCaipNetwork(),r=Y._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!r)throw new Error("No ConnectionController client found");try{const i=await t.createMessage({chainId:s.caipNetworkId,accountAddress:e}),n=i.toString();B.getConnectorId(s.chainNamespace)===H.CONNECTOR_ID.AUTH&&re.pushTransactionStack({});const a=await r.signMessage(n);await t.addSession({data:i,message:n,signature:a}),ze.close(),Pe.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(i){const n=this.getSIWXEventProperties();(!ze.state.open||re.state.view==="ApproveTransaction")&&await ze.open({view:"SIWXSignMessage"}),n.isSmartAccount?Mt.showError("This application might not support Smart Accounts"):Mt.showError("Signature declined"),Pe.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:n}),console.error("SWIXUtil:requestSignMessage",i)}},async cancelSignMessage(){var t;try{const e=this.getSIWX();((t=e==null?void 0:e.getRequired)==null?void 0:t.call(e))?await Y.disconnect():ze.close(),re.reset("Connect"),Pe.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getSessions(){const t=T.state.siwx,e=Z.getPlainAddress(g.getActiveCaipAddress()),s=g.getActiveCaipNetwork();return t&&e&&s?t.getSessions(s.caipNetworkId,e):[]},async isSIWXCloseDisabled(){var e;const t=this.getSIWX();if(t){const s=re.state.view==="ApproveTransaction",r=re.state.view==="SIWXSignMessage";if(s||r)return((e=t.getRequired)==null?void 0:e.call(t))&&(await this.get
17Sessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){var a,c,l;const r=Ti.getSIWX(),i=new Set(e.map(u=>u.split(":")[0]));if(!r||i.size!==1||!i.has("eip155"))return!1;const n=await r.createMessage({chainId:((a=g.getActiveCaipNetwork())==null?void 0:a.caipNetworkId)||"",accountAddress:""}),o=await t.authenticate({nonce:n.nonce,domain:n.domain,uri:n.uri,exp:n.expirationTime,iat:n.issuedAt,nbf:n.notBefore,requestId:n.requestId,version:n.version,resources:n.resources,statement:n.statement,chainId:n.chainId,methods:s,chains:[n.chainId,...e.filter(u=>u!==n.chainId)]});if(Mt.showLoading("Authenticating...",{autoClose:!1}),z.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:(c=o.session.peer.metadata.icons)==null?void 0:c[0],type:"WALLET_CONNECT"},Array.from(i)[0]),(l=o==null?void 0:o.auths)!=null&&l.length){const u=o.auths.map(d=>{const h=t.client.formatAuthMessage({request:d.p,iss:d.p.iss});return{data:{...d.p,accountAddress:d.p.iss.split(":").slice(-1).join(""),chainId:d.p.iss.split(":").slice(2,4).join(":"),uri:d.p.aud,version:d.p.version||n.version,expirationTime:d.p.exp,issuedAt:d.p.iat,notBefore:d.p.nbf},message:h,signature:d.s.s,cacao:d}});try{await r.setSessions(u),Pe.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:Ti.getSIWXEventProperties()})}catch(d){throw console.error("SIWX:universalProviderAuth - failed to set sessions",d),Pe.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:Ti.getSIWXEventProperties()}),await t.disconnect().catch(console.error),d}finally{Mt.hide()}}return!0},getSIWXEventProperties(){var e,s;const t=g.state.activeChain;return{network:((e=g.state.activeCaipNetwork)==null?void 0:e.caipNetworkId)||"",isSmartAccount:((s=z.state.preferredAccountTypes)==null?void 0:s[t])===Ii.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};function Ln(t,e){return B.getConnectorId(t)===e}function r1(t){const e=Array.from(g.state.chains.keys());let s=[];return t?(s.push([t,g.state.chains.get(t)]),Ln(t,H.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(r=>{r!==t&&Ln(r,H.CONNECTOR_ID.WALLET_CONNECT)&&s.push([r,g.state.chains.get(r)])}):Ln(t,H.CONNECTOR_ID.AUTH)&&e.forEach(r=>{r!==t&&Ln(r,H.CONNECTOR_ID.AUTH)&&s.push([r,g.state.chains.get(r)])})):s=Array.from(g.state.chains.entries()),s}const ys={EIP155:"eip155",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED"},Qn={NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200"},ConnectorImageIds:{[H.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[H.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[H.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[H.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[H.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[H.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-454
170-9e6a2b9cae00"},ConnectorNamesMap:{[H.CONNECTOR_ID.INJECTED]:"Browser Wallet",[H.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[H.CONNECTOR_ID.COINBASE]:"Coinbase",[H.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[H.CONNECTOR_ID.LEDGER]:"Ledger",[H.CONNECTOR_ID.SAFE]:"Safe"}},Za={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,r])=>{e[`${ys.EIP155}:${s}`]=r}),e},isLowerCaseMatch(t,e){return(t==null?void 0:t.toLowerCase())===(e==null?void 0:e.toLowerCase())}};new AbortController;const Sr={UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"INVALID_APP_CONFIGURATION"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{shortMessage:"Network Not Found",longMessage:"Network not found - please make sure it is included in 'networks' array in createAppKit function"},INVALID_APP_CONFIGURATION:{shortMessage:"Invalid App Configuration",longMessage:()=>`Origin ${i1()?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},IFRAME_LOAD_FAILED:{shortMessage:"Network Error - Could not load embedded wallet",longMessage:()=>"There was an issue loading the embedded wallet. Please try again later."},IFRAME_REQUEST_TIMEOUT:{shortMessage:"Embedded Wallet Request Timed Out",longMessage:()=>"There was an issue doing the request to the embedded wallet. Please try again later."},UNVERIFIED_DOMAIN:{shortMessage:"Invalid App Configuration",longMessage:()=>"There was an issue loading the embedded wallet. Please verify that your domain is allowed at cloud.reown.com"},JWT_TOKEN_NOT_VALID:{shortMessage:"Session Expired",longMessage:"Invalid session found on UniversalProvider - please check your time settings and connect again"},INVALID_PROJECT_ID:{shortMessage:"Invalid App Configuration",longMessage:"Invalid Project ID - update configuration"},PROJECT_ID_NOT_CONFIGURED:{shortMessage:"Project ID Not Configured",longMessage:"Project ID Not Configured - update configuration on cloud.reown.com"}}};function i1(){return typeof window<"u"}const n1={createLogger(t,e="error"){const s=dn({level:e}),{logger:r}=mu({opts:s});return r.error=(...i)=>{for(const n of i)if(n instanceof Error){t(n,...i);return}t(void 0,...i)},r}},o1="rpc.walletconnect.org";function eu(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 zo=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],Or={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===o1}catch{s=!1}if(s){const r=new URL(t);return r.searchParams.has("projectId")||r.searchParams.set("projectId",e),r.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:H.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${H.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){var i,n,o;const r=(o=(n=(i=t.rpcUrls)==null?void 0:i.default)==null?void 0:n.http)==null?void 0:o[0];return zo.includes(e)?eu(e,s):r||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:r}){var h,p,w,f,m;const i=this.getChainNamespace(t),n=this.getCaipNetworkId(t),o=(h=t.rpcUrls.default.http)==null?void 0:h[0],a=this.getDefaultRpcUrl(t,n,s),c=((f=(w=(p=t==null?void 0:t.rpcUrls)==null?void 0:p.chainDefault)==null?void 0:w.http)==null?void 0:f[0])||o,l=((m=r==null?void 0:r[n])==null?void 0:m.map(y=>y.url))||[],u=[...l,a],d=[...l];return c&&!d.includes(c)&&d.push(c),{...t,chainNamespace:i,caipNetworkId:n,assets:{imageId:Qn.NetworkImageIds[t.id],imageUrl:e==null?void 0:e[t.id]},rpcUrls:{...t.rpcUrls,default:{http:u},chainDefault:{http:d}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:r}){return t.map(i=>Or.extendCaipNetwork(i,{customNetworkImageUrls:e,customRpcUrls:r,projectId:s}))}
17,getViemTransport(t,e,s){var i,n,o;const r=[];return s==null||s.forEach(a=>{r.push(Sn(a.url,a.config))}),zo.includes(t.caipNetworkId)&&r.push(Sn(eu(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),(o=(n=(i=t==null?void 0:t.rpcUrls)==null?void 0:i.default)==null?void 0:n.http)==null||o.forEach(a=>{r.push(Sn(a))}),pc(r)},extendWagmiTransports(t,e,s){if(zo.includes(t.caipNetworkId)){const r=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return pc([s,Sn(r)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:H.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){var c;const e=F.getActiveCaipNetworkId(),s=g.getAllRequestedCaipNetworks(),r=Array.from(((c=g.state.chains)==null?void 0:c.keys())||[]),i=e==null?void 0:e.split(":")[0],n=i?r.includes(i):!1,o=s==null?void 0:s.find(l=>l.caipNetworkId===e);return n&&!o&&e?this.getUnsupportedNetwork(e):o||t||(s==null?void 0:s[0])}},eo={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},at=_e({providers:{...eo},providerIds:{...eo}}),Se={state:at,subscribeKey(t,e){return Qe(at,t,e)},subscribe(t){return Xe(at,()=>{t(at)})},subscribeProviders(t){return Xe(at.providers,()=>t(at.providers))},setProvider(t,e){e&&(at.providers[t]=Qs(e))},getProvider(t){return at.providers[t]},setProviderId(t,e){e&&(at.providerIds[t]=e)},getProviderId(t){if(t)return at.providerIds[t]},reset(){at.providers={...eo},at.providerIds={...eo}},resetChain(t){at.providers[t]=void 0,at.providerIds[t]=void 0}},a1={VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},$a={filterOutDuplicatesByRDNS(t){const e=T.state.enableEIP6963?B.state.connectors:[],s=F.getRecentWallets(),r=e.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}).filter(Boolean),i=s.map(a=>a.rdns).filter(Boolean),n=r.concat(i);if(n.includes("io.metamask.mobile")&&Z.isMobile()){const a=n.indexOf("io.metamask.mobile");n[a]="io.metamask"}return t.filter(a=>!n.includes(String(a==null?void 0:a.rdns)))},filterOutDuplicatesByIds(t){const e=B.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=F.getRecentWallets(),r=e.map(a=>a.explorerId),i=s.map(a=>a.id),n=r.concat(i);return t.filter(a=>!n.includes(a==null?void 0:a.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=B.state,{featuredWalletIds:s}=T.state,r=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&&!!r[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),u=s.indexOf(a.id);if(l!==-1&&u!==-1)return l-u;if(l!==-1)return-1;if(u!==-1)return 1}return 0})},getConnectOrderMethod(t,e){var c;const s=(t==null?void 0:t.connectMethodsOrder)||((c=T.state.features)==null?void 0:c.connectMethodsOrder),r=e||B.state.connectors;if(s)return s;const{injected:i,announced:n}=Wn.getConnectorsByType(r,V.state.recommended,V.state.featured),o=i.filter(Wn.showConnector),a=n.filter(Wn.showConnector);return o.length||a.length?["wallet","email","social"]:a1.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&V.state.excludedWallets.some(r=>r.rdns===t.rdns),s=!!t.name&&V.state.excludedWallets.some(r=>Za.isLowerCaseMatch(r.name,t.name));return e||s}},Wn={getConnectorsByType(t,e,s){const{customWallets:r}=T.state,i=F.getRecentWallets(),n=$a.filterOutDuplicateWallets(e),o=$a.filterOutDuplicateWallets(s),a=t.filter(d=>d.type==="MULTI_CHAIN"),c=t.filter(d=>d.type==="ANNOUNCED"),l=t.filter(d=>d.type==="INJECTED"),u=t.filter(d=>d.type==="EXTERNAL");return{custom:r,recent:i,external:u,multiChain:a,announced:c,injected:l,recommended:n,featured:o}},showConnector(t){var i;const e=(i=t.info)==null?void 0:i.rdns,s=!!e&&V.state.excludedWallets.some(n=>!!n.rdns&&n.rdns===e),r=!!t.name&&V.state.excludedWallets.some(n=>Za.isLowerCaseMatch(n.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!Z.isMobile()||Z.isMobile()&&!e&&!Y.checkInstalled())||s||r)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||r))},getIsConnectedWithWC(){return Array.from(g.state.chains.values()).some(s=>B.getConnectorId(s.namespace)===H.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:r,announced:i,injected:n,multiChain:o,external:a,overriddenConnectors:c=(l=>(l=T.state.features)==null?void 0:l.connectorTypeOrder)()??[]}){const u=Wn.getIsConnectedWithWC(),p=[{type:"walletConnect",isEnabled:T.state.enableWalletConnect&&!u},{type:"recent",isEnabled:r.length>0},{type:"injected",isEnabled:[...n,...i,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(y=>y.isEnabled),w=new Set(p.map(y=>y.type)),f=c.filter(y=>w.has(y)).map(y=>({type:y,isEnabled:!0})),m=p.filter(({type:y})=>!f.some(({type:v})=>v===y));return Array.from(new Set([...f,...m].map(({type:y})=>y)))}};/**
18 * @license
19 * Copyright 2019 Google LLC
20 * SPDX-License-Identifier: BSD-3-Clause
21 */const Hn=globalThis,Xa=Hn.ShadowRoot&&(Hn.ShadyCSS===void 0||Hn.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Qa=Symbol(),tu=new WeakMap;let ih=class{constructor(e,s,r){if(this._$cssResult$=!0,r!==Qa)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(Xa&&e===void 0){const r=s!==void 0&&s.length===1;r&&(e=tu.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),r&&tu.
vendor: 3,882 bytes, lines 21-25
21set(s,e))}return e}toString(){return this.cssText}};const St=t=>new ih(typeof t=="string"?t:t+"",void 0,Qa),Dr=(t,...e)=>{const s=t.length===1?t[0]:e.reduce((r,i,n)=>r+(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.")})(i)+t[n+1],t[0]);return new ih(s,t,Qa)},c1=(t,e)=>{if(Xa)t.adoptedStyleSheets=e.map(s=>s instanceof CSSStyleSheet?s:s.styleSheet);else for(const s of e){const r=document.createElement("style"),i=Hn.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=s.cssText,t.appendChild(r)}},su=Xa?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const r of e.cssRules)s+=r.cssText;return St(s)})(t):t;/**
22 * @license
23 * Copyright 2017 Google LLC
24 * SPDX-License-Identifier: BSD-3-Clause
25 */const{is:l1,defineProperty:u1,getOwnPropertyDescriptor:d1,getOwnPropertyNames:h1,getOwnPropertySymbols:p1,getPrototypeOf:f1}=Object,Os=globalThis,ru=Os.trustedTypes,g1=ru?ru.emptyScript:"",Wo=Os.reactiveElementPolyfillSupport,$i=(t,e)=>t,xa={toAttribute(t,e){switch(e){case Boolean:t=t?g1: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}},nh=(t,e)=>!l1(t,e),iu={attribute:!0,type:String,converter:xa,reflect:!1,useDefault:!1,hasChanged:nh};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Os.litPropertyMetadata??(Os.litPropertyMetadata=new WeakMap);let Tr=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=iu){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 r=Symbol(),i=this.getPropertyDescriptor(e,r,s);i!==void 0&&u1(this.prototype,e,i)}}static getPropertyDescriptor(e,s,r){const{get:i,set:n}=d1(this.prototype,e)??{get(){return this[s]},set(o){this[s]=o}};return{get:i,set(o){const a=i==null?void 0:i.call(this);n==null||n.call(this,o),this.requestUpdate(e,a,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??iu}static _$Ei(){if(this.hasOwnProperty($i("elementProperties")))return;const e=f1(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty($i("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty($i("properties"))){const s=this.properties,r=[...h1(s),...p1(s)];for(const i of r)this.createProperty(i,s[i])}const e=this[Symbol.metadata];if(e!==null){const s=litPropertyMetadata.get(e);if(s!==void 0)for(const[r,i]of s)this.elementProperties.set(r,i)}this._$Eh=new Map;for(const[s,r]of this.elementProperties){const i=this._$Eu(s,r);i!==void 0&&this._$Eh.set(i,s)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const s=[];if(Array.isArray(e)){const r=new Set(e.flat(1/0).reverse());for(const i of r)s.unshift(su(i))}else e!==void 0&&s.push(su(e));return s}static _$Eu(e,s){const r=s.attribute;return r===!1?void 0:typeof r=="string"?r: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: 8,999 bytes, lines 25-31
25removeController(e){var s;(s=this._$EO)==null||s.delete(e)}_$E_(){const e=new Map,s=this.constructor.elementProperties;for(const r of s.keys())this.hasOwnProperty(r)&&(e.set(r,this[r]),delete this[r]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return c1(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 r;return(r=s.hostConnected)==null?void 0:r.call(s)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(s=>{var r;return(r=s.hostDisconnected)==null?void 0:r.call(s)})}attributeChangedCallback(e,s,r){this._$AK(e,r)}_$ET(e,s){var n;const r=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,r);if(i!==void 0&&r.reflect===!0){const o=(((n=r.converter)==null?void 0:n.toAttribute)!==void 0?r.converter:xa).toAttribute(s,r.type);this._$Em=e,o==null?this.removeAttribute(i):this.setAttribute(i,o),this._$Em=null}}_$AK(e,s){var n,o;const r=this.constructor,i=r._$Eh.get(e);if(i!==void 0&&this._$Em!==i){const a=r.getPropertyOptions(i),c=typeof a.converter=="function"?{fromAttribute:a.converter}:((n=a.converter)==null?void 0:n.fromAttribute)!==void 0?a.converter:xa;this._$Em=i;const l=c.fromAttribute(s,a.type);this[i]=l??((o=this._$Ej)==null?void 0:o.get(i))??l,this._$Em=null}}requestUpdate(e,s,r){var i;if(e!==void 0){const n=this.constructor,o=this[e];if(r??(r=n.getPropertyOptions(e)),!((r.hasChanged??nh)(o,s)||r.useDefault&&r.reflect&&o===((i=this._$Ej)==null?void 0:i.get(e))&&!this.hasAttribute(n._$Eu(e,r))))return;this.C(e,s,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,s,{useDefault:r,reflect:i,wrapped:n},o){r&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,o??s??this[e]),n!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||r||(s=void 0),this._$AL.set(e,s)),i===!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 r;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[n,o]of this._$Ep)this[n]=o;this._$Ep=void 0}const i=this.constructor.elementProperties;if(i.size>0)for(const[n,o]of i){const{wrapped:a}=o,c=this[n];a!==!0||this._$AL.has(n)||c===void 0||this.C(n,void 0,o,c)}}let e=!1;const s=this._$AL;try{e=this.shouldUpdate(s),e?(this.willUpdate(s),(r=this._$EO)==null||r.forEach(i=>{var n;return(n=i.hostUpdate)==null?void 0:n.call(i)}),this.update(s)):this._$EM()}catch(i){throw e=!1,this._$EM(),i}e&&this._$AE(s)}willUpdate(e){}_$AE(e){var s;(s=this._$EO)==null||s.forEach(r=>{var i;return(i=r.hostUpdated)==null?void 0:i.call(r)}),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){}};Tr.elementStyles=[],Tr.shadowRootOptions={mode:"open"},Tr[$i("elementProperties")]=new Map,Tr[$i("finalized")]=new Map,Wo==null||Wo({ReactiveElement:Tr}),(Os.reactiveElementVersions??(Os.reactiveElementVersions=[])).push("2.1.1");/**
26 * @license
27 * Copyright 2017 Google LLC
28 * SPDX-License-Identifier: BSD-3-Clause
29 */const xi=globalThis,to=xi.trustedTypes,nu=to?to.createPolicy("lit-html",{createHTML:t=>t}):void 0,oh="$lit$",Cs=`lit$${Math.random().toFixed(9).slice(2)}$`,ah="?"+Cs,m1=`<${ah}>`,ir=document,cn=()=>ir.createComment(""),ln=t=>t===null||typeof t!="object"&&typeof t!="function",ec=Array.isArray,w1=t=>ec(t)||typeof(t==null?void 0:t[Symbol.iterator])=="function",Ho=`[ 	
30\f\r]`,gi=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ou=/-->/g,au=/>/g,Ms=RegExp(`>|${Ho}(?:([^\\s"'>=/]+)(${Ho}*=${Ho}*(?:[^ 	
31\f\r"'\`<>=]|("|')|))|$)`,"g"),cu=/'/g,lu=/"/g,ch=/^(?:script|style|textarea|title)$/i,lh=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),oI=lh(1),aI=lh(2),Jr=Symbol.for("lit-noChange"),Fe=Symbol.for("lit-nothing"),uu=new WeakMap,Ks=ir.createTreeWalker(ir,129);function uh(t,e){if(!ec(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return nu!==void 0?nu.createHTML(e):e}const y1=(t,e)=>{const s=t.length-1,r=[];let i,n=e===2?"<svg>":e===3?"<math>":"",o=gi;for(let a=0;a<s;a++){const c=t[a];let l,u,d=-1,h=0;for(;h<c.length&&(o.lastIndex=h,u=o.exec(c),u!==null);)h=o.lastIndex,o===gi?u[1]==="!--"?o=ou:u[1]!==void 0?o=au:u[2]!==void 0?(ch.test(u[2])&&(i=RegExp("</"+u[2],"g")),o=Ms):u[3]!==void 0&&(o=Ms):o===Ms?u[0]===">"?(o=i??gi,d=-1):u[1]===void 0?d=-2:(d=o.lastIndex-u[2].length,l=u[1],o=u[3]===void 0?Ms:u[3]==='"'?lu:cu):o===lu||o===cu?o=Ms:o===ou||o===au?o=gi:(o=Ms,i=void 0);const p=o===Ms&&t[a+1].startsWith("/>")?" ":"";n+=o===gi?c+m1:d>=0?(r.push(l),c.slice(0,d)+oh+c.slice(d)+Cs+p):c+Cs+(d===-2?a:p)}return[uh(t,n+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),r]};class un{constructor({strings:e,_$litType$:s},r){let i;this.parts=[];let n=0,o=0;const a=e.length-1,c=this.parts,[l,u]=y1(e,s);if(this.el=un.createElement(l,r),Ks.currentNode=this.el.content,s===2||s===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(i=Ks.nextNode())!==null&&c.length<a;){if(i.nodeType===1){if(i.hasAttributes())for(const d of i.getAttributeNames())if(d.endsWith(oh)){const h=u[o++],p=i.getAttribute(d).split(Cs),w=/([.?@])?(.*)/.exec(h);c.push({type:1,index:n,name:w[2],strings:p,ctor:w[1]==="."?v1:w[1]==="?"?E1:w[1]==="@"?C1:po}),i.removeAttribute(d)}else d.startsWith(Cs)&&(c.push({type:6,index:n}),i.removeAttribute(d));if(ch.test(i.tagName)){const d=i.textContent.split(Cs),h=d.length-1;if(h>0){i.textContent=to?to.emptyScript:"";for(let p=0;p<h;p++)i.append(d[p],cn()),Ks.nextNode(),c.push({type:2,index:++n});i.append(d[h],cn())}}}else if(i.nodeType===8)if(i.data===ah)c.push({type:2,index:n});else{let d=-1;for(;(d=i.data.indexOf(Cs,d+1))!==-1;)c.push({type:7,index:n}),d+=Cs.length-1}n++}}static createElement(e,s){const r=ir.createElement("template");return r.innerHTML=e,r}}function Yr(t,e,s=t,r){var o,a;if(e===Jr)return e;let i=r!==void 0?(o=s._$Co)==null?void 0:o[r]:s._$Cl;const n=ln(e)?void 0:e._$litDirective$;return(i==null?void 0:i.constructor)!==n&&((a=i==null?void 0:i._$AO)==null||a.call(i,!1),n===void 0?i=void 0:(i=new n(t),i._$AT(t,s,r)),r!==void 0?(s._$Co??(s._$Co=[]))[r]=i:s._$Cl=i),i!==void 0&&(e=Yr(t,i._$AS(t,e.values),i,r)),e}class b1{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:r}=this._$AD,i=((e==null?void 0:e.creationScope)??ir).importNode(s,!0);Ks.currentNode=i;let n=Ks.nextNode(),o=0,a=0,c=r[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new En(n,n.nextSibling,this,e):c.type===1?l=new c.ctor(n,c.name,c.strings,this,e):c.type===6&&(l=new I1(n,this,e)),this._$AV.push(l),c=r[++a]}o!==(c==null?void 0:c.index)&&(n=Ks.nextNode(),o++)}return Ks.currentNode=ir,i}p(e){let s=0;for(const r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(e,r,s),s+=r.strings.length-2):r._$AI(e[s])),s++}}class En{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,s,r,i){this.type=2,this._$AH=Fe,this._$AN=void 0,this._$AA=e,this._$AB=s,this._$AM=r,this.options=i,this._$Cv=(i==null?void 0:i.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=Yr(this,e,s),ln(e)?e===Fe||e==null||e===""?(this._$AH!==Fe&&this._$AR(),this._$AH=Fe):e!==this._$AH&&e!==Jr&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):w1(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!==Fe&&ln(this._$AH)?this._$AA.nextSibling.data=e:this.T(ir.createTextNode(e)),this._$AH=e}$(e){var n;const{values:s,_$litType$:r}=e,i=typeof r=="number"?this._$AC(e):(r.el===void 0&&(r.el=un.createElement(uh(r.h,r.h[0]),this.options)),r);if(((n=this._$AH)==null?void 0:n._$AD)===i)this._$AH.p(s);else{const o=new b1(i,this),a=o.u(this.options);o.p(s),this.T(a),this._$AH=o}}_$AC(e){let s=uu.get(e.strings);return s===void 0&&uu.set(e.strings,s=new un(e)),s}k(e){ec(this._$AH)||(this._$AH=[],this._$AR());const s=this._$AH;let r,i=0;for(const n of e)i===s.length?s.push(r=new En(this.O(cn()),this.O(cn()),this,this.options)):r=s[i],r._$AI(n),i++;i<s.length&&(this._$AR(r&&r._$AB.nextSibling,i),s.length=i)}_$AR(e=this._$AA.nextSibling,s){var r;
31for((r=this._$AP)==null?void 0:r.call(this,!1,!0,s);e!==this._$AB;){const i=e.nextSibling;e.remove(),e=i}}setConnected(e){var s;this._$AM===void 0&&(this._$Cv=e,(s=this._$AP)==null||s.call(this,e))}}class po{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,r,i,n){this.type=1,this._$AH=Fe,this._$AN=void 0,this.element=e,this.name=s,this._$AM=i,this.options=n,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=Fe}_$AI(e,s=this,r,i){const n=this.strings;let o=!1;if(n===void 0)e=Yr(this,e,s,0),o=!ln(e)||e!==this._$AH&&e!==Jr,o&&(this._$AH=e);else{const a=e;let c,l;for(e=n[0],c=0;c<n.length-1;c++)l=Yr(this,a[r+c],s,c),l===Jr&&(l=this._$AH[c]),o||(o=!ln(l)||l!==this._$AH[c]),l===Fe?e=Fe:e!==Fe&&(e+=(l??"")+n[c+1]),this._$AH[c]=l}o&&!i&&this.j(e)}j(e){e===Fe?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class v1 extends po{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Fe?void 0:e}}class E1 extends po{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Fe)}}class C1 extends po{constructor(e,s,r,i,n){super(e,s,r,i,n),this.type=5}_$AI(e,s=this){if((e=Yr(this,e,s,0)??Fe)===Jr)return;const r=this._$AH,i=e===Fe&&r!==Fe||e.capture!==r.capture||e.once!==r.once||e.passive!==r.passive,n=e!==Fe&&(r===Fe||i);i&&this.element.removeEventListener(this.name,this,r),n&&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 I1{constructor(e,s,r){this.element=e,this.type=6,this._$AN=void 0,this._$AM=s,this.options=r}get _$AU(){return this._$AM._$AU}_$AI(e){Yr(this,e)}}const Vo=xi.litHtmlPolyfillSupport;Vo==null||Vo(un,En),(xi.litHtmlVersions??(xi.litHtmlVersions=[])).push("3.3.1");const A1=(t,e,s)=>{const r=(s==null?void 0:s.renderBefore)??e;let i=r._$litPart$;if(i===void 0){const n=(s==null?void 0:s.renderBefore)??null;r._$litPart$=i=new En(e.insertBefore(cn(),n),n,void 0,s??{})}return i._$AI(t),i};/**
32 * @license
33 * Copyright 2017 Google LLC
34 * SPDX-License-Identifier: BSD-3-Clause
35 */const Zs=globalThis;class Vn extends Tr{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=A1(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 Jr}}var fu;Vn._$litElement$=!0,Vn.finalized=!0,(fu=Zs.litElementHydrateSupport)==null||fu.call(Zs,{LitElement:Vn});const Ko=Zs.litElementPolyfillSupport;Ko==null||Ko({LitElement:Vn});(Zs.litElementVersions??(Zs.litElementVersions=[])).push("4.2.1");let ki,Ts,$s;function cI(t,e){ki=document.createElement("style"),Ts=document.createElement("style"),$s=document.createElement("style"),ki.textContent=Mr(t).core.cssText,Ts.textContent=Mr(t).dark.cssText,$s.textContent=Mr(t).light.cssText,document.head.appendChild(ki),document.head.appendChild(Ts),document.head.appendChild($s),dh(e)}function dh(t){Ts&&$s&&(t==="light"?(Ts.removeAttribute("media"),$s.media="enabled"):($s.removeAttribute("media"),Ts.media="enabled"))}function N1(t){ki&&Ts&&$s&&(ki.textContent=Mr(t).core.cssText,Ts.textContent=Mr(t).dark.cssText,$s.textContent=Mr(t).light.cssText)}function Mr(t){return{core:Dr`
36      @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
37      @keyframes w3m-shake {
38        0% {
39          transform: scale(1) rotate(0deg);
40        }
41        20% {
42          transform: scale(1) rotate(-1deg);
43        }
44        40% {
45          transform: scale(1) rotate(1.5deg);
46        }
47        60% {
48          transform: scale(1) rotate(-1.5deg);
49        }
50        80% {
51          transform: scale(1) rotate(1deg);
52        }
53        100% {
54          transform: scale(1) rotate(0deg);
55        }
56      }
57      @keyframes w3m-iframe-fade-out {
58        0% {
59          opacity: 1;
60        }
61        100% {
62          opacity: 0;
63        }
64      }
65      @keyframes w3m-iframe-zoom-in {
66        0% {
67          transform: translateY(50px);
68          opacity: 0;
69        }
70        100% {
71          transform: translateY(0px);
72          opacity: 1;
73        }
74      }
75      @keyframes w3m-iframe-zoom-in-mobile {
76        0% {
77          transform: scale(0.95);
78          opacity: 0;
79        }
80        100% {
81          transform: scale(1);
82          opacity: 1;
83        }
84      }
85      :root {
86        --w3m-modal-width: 360px;
87        --w3m-color-mix-strength: ${St(t!=null&&t["--w3m-color-mix-strength"]?`${t["--w3m-color-mix-strength"]}%`:"0%")};
88        --w3m-font-family: ${St((t==null?void 0:t["--w3m-font-family"])||"Inter, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;")};
89        --w3m-font-size-master: ${St((t==null?void 0:t["--w3m-font-size-master"])||"10px")};
90        --w3m-border-radius-master: ${St((t==null?void 0:t["--w3m-border-radius-master"])||"4px")};
91        --w3m-z-index: ${St((t==null?void 0:t["--w3m-z-index"])||
vendor: 15,824 bytes, lines 91-517
91999)};
92
93        --wui-font-family: var(--w3m-font-family);
94
95        --wui-font-size-mini: calc(var(--w3m-font-size-master) * 0.8);
96        --wui-font-size-micro: var(--w3m-font-size-master);
97        --wui-font-size-tiny: calc(var(--w3m-font-size-master) * 1.2);
98        --wui-font-size-small: calc(var(--w3m-font-size-master) * 1.4);
99        --wui-font-size-paragraph: calc(var(--w3m-font-size-master) * 1.6);
100        --wui-font-size-medium: calc(var(--w3m-font-size-master) * 1.8);
101        --wui-font-size-large: calc(var(--w3m-font-size-master) * 2);
102        --wui-font-size-title-6: calc(var(--w3m-font-size-master) * 2.2);
103        --wui-font-size-medium-title: calc(var(--w3m-font-size-master) * 2.4);
104        --wui-font-size-2xl: calc(var(--w3m-font-size-master) * 4);
105
106        --wui-border-radius-5xs: var(--w3m-border-radius-master);
107        --wui-border-radius-4xs: calc(var(--w3m-border-radius-master) * 1.5);
108        --wui-border-radius-3xs: calc(var(--w3m-border-radius-master) * 2);
109        --wui-border-radius-xxs: calc(var(--w3m-border-radius-master) * 3);
110        --wui-border-radius-xs: calc(var(--w3m-border-radius-master) * 4);
111        --wui-border-radius-s: calc(var(--w3m-border-radius-master) * 5);
112        --wui-border-radius-m: calc(var(--w3m-border-radius-master) * 7);
113        --wui-border-radius-l: calc(var(--w3m-border-radius-master) * 9);
114        --wui-border-radius-3xl: calc(var(--w3m-border-radius-master) * 20);
115
116        --wui-font-weight-light: 400;
117        --wui-font-weight-regular: 500;
118        --wui-font-weight-medium: 600;
119        --wui-font-weight-bold: 700;
120
121        --wui-letter-spacing-2xl: -1.6px;
122        --wui-letter-spacing-medium-title: -0.96px;
123        --wui-letter-spacing-title-6: -0.88px;
124        --wui-letter-spacing-large: -0.8px;
125        --wui-letter-spacing-medium: -0.72px;
126        --wui-letter-spacing-paragraph: -0.64px;
127        --wui-letter-spacing-small: -0.56px;
128        --wui-letter-spacing-tiny: -0.48px;
129        --wui-letter-spacing-micro: -0.2px;
130        --wui-letter-spacing-mini: -0.16px;
131
132        --wui-spacing-0: 0px;
133        --wui-spacing-4xs: 2px;
134        --wui-spacing-3xs: 4px;
135        --wui-spacing-xxs: 6px;
136        --wui-spacing-2xs: 7px;
137        --wui-spacing-xs: 8px;
138        --wui-spacing-1xs: 10px;
139        --wui-spacing-s: 12px;
140        --wui-spacing-m: 14px;
141        --wui-spacing-l: 16px;
142        --wui-spacing-2l: 18px;
143        --wui-spacing-xl: 20px;
144        --wui-spacing-xxl: 24px;
145        --wui-spacing-2xl: 32px;
146        --wui-spacing-3xl: 40px;
147        --wui-spacing-4xl: 90px;
148        --wui-spacing-5xl: 95px;
149
150        --wui-icon-box-size-xxs: 14px;
151        --wui-icon-box-size-xs: 20px;
152        --wui-icon-box-size-sm: 24px;
153        --wui-icon-box-size-md: 32px;
154        --wui-icon-box-size-mdl: 36px;
155        --wui-icon-box-size-lg: 40px;
156        --wui-icon-box-size-2lg: 48px;
157        --wui-icon-box-size-xl: 64px;
158
159        --wui-icon-size-inherit: inherit;
160        --wui-icon-size-xxs: 10px;
161        --wui-icon-size-xs: 12px;
162        --wui-icon-size-sm: 14px;
163        --wui-icon-size-md: 16px;
164        --wui-icon-size-mdl: 18px;
165        --wui-icon-size-lg: 20px;
166        --wui-icon-size-xl: 24px;
167        --wui-icon-size-xxl: 28px;
168
169        --wui-wallet-image-size-inherit: inherit;
170        --wui-wallet-image-size-sm: 40px;
171        --wui-wallet-image-size-md: 56px;
172        --wui-wallet-image-size-lg: 80px;
173
174        --wui-visual-size-size-inherit: inherit;
175        --wui-visual-size-sm: 40px;
176        --wui-visual-size-md: 55px;
177        --wui-visual-size-lg: 80px;
178
179        --wui-box-size-md: 100px;
180        --wui-box-size-lg: 120px;
181
182        --wui-ease-out-power-2: cubic-bezier(0, 0, 0.22, 1);
183        --wui-ease-out-power-1: cubic-bezier(0, 0, 0.55, 1);
184
185        --wui-ease-in-power-3: cubic-bezier(0.66, 0, 1, 1);
186        --wui-ease-in-power-2: cubic-bezier(0.45, 0, 1, 1);
187        --wui-ease-in-power-1: cubic-bezier(0.3, 0, 1, 1);
188
189        --wui-ease-inout-power-1: cubic-bezier(0.45, 0, 0.55, 1);
190
191        --wui-duration-lg: 200ms;
192        --wui-duration-md: 125ms;
193        --wui-duration-sm: 75ms;
194
195        --wui-path-network-sm: path(
196          'M15.4 2.1a5.21 5.21 0 0 1 5.2 0l11.61 6.7a5.21 5.21 0 0 1 2.61 4.52v13.4c0 1.87-1 3.59-2.6 4.52l-11.61 6.7c-1.62.93-3.6.93-5.22 0l-11.6-6.7a5.21 5.21 0 0 1-2.61-4.51v-13.4c0-1.87 1-3.6 2.6-4.52L15.4 2.1Z'
197        );
198
199        --wui-path-network-md: path(
200          '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'
201        );
202
203        --wui-path-network-lg: path(
204          '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'
205        );
206
207        --wui-width-network-sm: 36px;
208        --wui-width-network-md: 48px;
209        --wui-width-network-lg: 86px;
210
211        --wui-height-network-sm: 40px;
212        --wui-height-network-md: 54px;
213        --wui-height-network-lg: 96px;
214
215        --wui-icon-size-network-xs: 12px;
216        --wui-icon-size-network-sm: 16px;
217        --wui-icon-size-network-md: 24px;
218        --wui-icon-size-network-lg: 42px;
219
220        --wui-color-inherit: inherit;
221
222        --wui-color-inverse-100: #fff;
223        --wui-color-inverse-000: #000;
224
225        --wui-cover: rgba(20, 20, 20, 0.8);
226
227        --wui-color-modal-bg: var(--wui-color-modal-bg-base);
228
229        --wui-color-accent-100: var(--wui-color-accent-base-100);
230        --wui-color-accent-090: var(--wui-color-accent-base-090);
231        --wui-color-accent-080: var(--wui-color-accent-base-080);
232
233        --wui-color-success-100: var(--wui-color-success-base-100);
234        --wui-color-success-125: var(--wui-color-success-base-125);
235
236        --wui-color-warning-100: var(--wui-color-warning-base-100);
237
238        --wui-color-error-100: var(--wui-color-error-base-100);
239        --wui-color-error-125: var(--wui-color-error-base-125);
240
241        --wui-color-blue-100: var(--wui-color-blue-base-100);
242        --wui-color-blue-90: var(--wui-color-blue-base-90);
243
244        --wui-icon-box-bg-error-100: var(--wui-icon-box-bg-error-base-100);
245        --wui-icon-box-bg-blue-100: var(--wui-icon-box-bg-blue-base-100);
246        --wui-icon-box-bg-success-100: var(--wui-icon-box-bg-success-base-100);
247        --wui-icon-box-bg-inverse-100: var(--wui-icon-box-bg-inverse-base-100);
248
249        --wui-all-wallets-bg-100: var(--wui-all-wallets-bg-100);
250
251        --wui-avatar-border: var(--wui-avatar-border-base);
252
253        --wui-thumbnail-border: var(--wui-thumbnail-border-base);
254
255        --wui-wallet-button-bg: var(--wui-wallet-button-bg-base);
256
257        --wui-box-shadow-blue: var(--wui-color-accent-glass-020);
258      }
259
260      @supports (background: color-mix(in srgb, white 50%, black)) {
261        :root {
262          --wui-color-modal-bg: color-mix(
263            in srgb,
264            var(--w3m-color-mix) var(--w3m-color-mix-strength),
265            var(--wui-color-modal-bg-base)
266          );
267
268          --wui-box-shadow-blue: color-mix(in srgb, var(--wui-color-accent-100) 20%, transparent);
269
270          --wui-color-accent-100: color-mix(
271            in srgb,
272            var(--wui-color-accent-base-100) 100%,
273            transparent
274          );
275          --wui-color-accent-090: color-mix(
276            in srgb,
277            var(--wui-color-accent-base-100) 90%,
278            transparent
279          );
280          --wui-color-accent-080: color-mix(
281            in srgb,
282            var(--wui-color-accent-base-100) 80%,
283            transparent
284          );
285          --wui-color-accent-glass-090: color-mix(
286            in srgb,
287            var(--wui-color-accent-base-100) 90%,
288            transparent
289          );
290          --wui-color-accent-glass-080: color-mix(
291            in srgb,
292            var(--wui-color-accent-base-100) 80%,
293            transparent
294          );
295          --wui-color-accent-glass-020: color-mix(
296            in srgb,
297            var(--wui-color-accent-base-100) 20%,
298            transparent
299          );
300          --wui-color-accent-glass-015: color-mix(
301            in srgb,
302            var(--wui-color-accent-base-100) 15%,
303            transparent
304          );
305          --wui-color-accent-glass-010: color-mix(
306            in srgb,
307            var(--wui-color-accent-base-100) 10%,
308            transparent
309          );
310          --wui-color-accent-glass-005: color-mix(
311            in srgb,
312            var(--wui-color-accent-base-100) 5%,
313            transparent
314          );
315          --wui-color-accent-002: color-mix(
316            in srgb,
317            var(--wui-color-accent-base-100) 2%,
318            transparent
319          );
320
321          --wui-color-fg-100: color-mix(
322            in srgb,
323            var(--w3m-color-mix) var(--w3m-color-mix-strength),
324            var(--wui-color-fg-100)
325          );
326          --wui-color-fg-125: color-mix(
327            in srgb,
328            var(--w3m-color-mix) var(--w3m-color-mix-strength),
329            var(--wui-color-fg-125)
330          );
331          --wui-color-fg-150: color-mix(
332            in srgb,
333            var(--w3m-color-mix) var(--w3m-color-mix-strength),
334            var(--wui-color-fg-150)
335          );
336          --wui-color-fg-175: color-mix(
337            in srgb,
338            var(--w3m-color-mix) var(--w3m-color-mix-strength),
339            var(--wui-color-fg-175)
340          );
341          --wui-color-fg-200: color-mix(
342            in srgb,
343            var(--w3m-color-mix) var(--w3m-color-mix-strength),
344            var(--wui-color-fg-200)
345          );
346          --wui-color-fg-225: color-mix(
347            in srgb,
348            var(--w3m-color-mix) var(--w3m-color-mix-strength),
349            var(--wui-color-fg-225)
350          );
351          --wui-color-fg-250: color-mix(
352            in srgb,
353            var(--w3m-color-mix) var(--w3m-color-mix-strength),
354            var(--wui-color-fg-250)
355          );
356          --wui-color-fg-275: color-mix(
357            in srgb,
358            var(--w3m-color-mix) var(--w3m-color-mix-strength),
359            var(--wui-color-fg-275)
360          );
361          --wui-color-fg-300: color-mix(
362            in srgb,
363            var(--w3m-color-mix) var(--w3m-color-mix-strength),
364            var(--wui-color-fg-300)
365          );
366          --wui-color-fg-325: color-mix(
367            in srgb,
368            var(--w3m-color-mix) var(--w3m-color-mix-strength),
369            var(--wui-color-fg-325)
370          );
371          --wui-color-fg-350: color-mix(
372            in srgb,
373            var(--w3m-color-mix) var(--w3m-color-mix-strength),
374            var(--wui-color-fg-350)
375          );
376
377          --wui-color-bg-100: color-mix(
378            in srgb,
379            var(--w3m-color-mix) var(--w3m-color-mix-strength),
380            var(--wui-color-bg-100)
381          );
382          --wui-color-bg-125: color-mix(
383            in srgb,
384            var(--w3m-color-mix) var(--w3m-color-mix-strength),
385            var(--wui-color-bg-125)
386          );
387          --wui-color-bg-150: color-mix(
388            in srgb,
389            var(--w3m-color-mix) var(--w3m-color-mix-strength),
390            var(--wui-color-bg-150)
391          );
392          --wui-color-bg-175: color-mix(
393            in srgb,
394            var(--w3m-color-mix) var(--w3m-color-mix-strength),
395            var(--wui-color-bg-175)
396          );
397          --wui-color-bg-200: color-mix(
398            in srgb,
399            var(--w3m-color-mix) var(--w3m-color-mix-strength),
400            var(--wui-color-bg-200)
401          );
402          --wui-color-bg-225: color-mix(
403            in srgb,
404            var(--w3m-color-mix) var(--w3m-color-mix-strength),
405            var(--wui-color-bg-225)
406          );
407          --wui-color-bg-250: color-mix(
408            in srgb,
409            var(--w3m-color-mix) var(--w3m-color-mix-strength),
410            var(--wui-color-bg-250)
411          );
412          --wui-color-bg-275: color-mix(
413            in srgb,
414            var(--w3m-color-mix) var(--w3m-color-mix-strength),
415            var(--wui-color-bg-275)
416          );
417          --wui-color-bg-300: color-mix(
418            in srgb,
419            var(--w3m-color-mix) var(--w3m-color-mix-strength),
420            var(--wui-color-bg-300)
421          );
422          --wui-color-bg-325: color-mix(
423            in srgb,
424            var(--w3m-color-mix) var(--w3m-color-mix-strength),
425            var(--wui-color-bg-325)
426          );
427          --wui-color-bg-350: color-mix(
428            in srgb,
429            var(--w3m-color-mix) var(--w3m-color-mix-strength),
430            var(--wui-color-bg-350)
431          );
432
433          --wui-color-success-100: color-mix(
434            in srgb,
435            var(--w3m-color-mix) var(--w3m-color-mix-strength),
436            var(--wui-color-success-base-100)
437          );
438          --wui-color-success-125: color-mix(
439            in srgb,
440            var(--w3m-color-mix) var(--w3m-color-mix-strength),
441            var(--wui-color-success-base-125)
442          );
443
444          --wui-color-warning-100: color-mix(
445            in srgb,
446            var(--w3m-color-mix) var(--w3m-color-mix-strength),
447            var(--wui-color-warning-base-100)
448          );
449
450          --wui-color-error-100: color-mix(
451            in srgb,
452            var(--w3m-color-mix) var(--w3m-color-mix-strength),
453            var(--wui-color-error-base-100)
454          );
455          --wui-color-blue-100: color-mix(
456            in srgb,
457            var(--w3m-color-mix) var(--w3m-color-mix-strength),
458            var(--wui-color-blue-base-100)
459          );
460          --wui-color-blue-90: color-mix(
461            in srgb,
462            var(--w3m-color-mix) var(--w3m-color-mix-strength),
463            var(--wui-color-blue-base-90)
464          );
465          --wui-color-error-125: color-mix(
466            in srgb,
467            var(--w3m-color-mix) var(--w3m-color-mix-strength),
468            var(--wui-color-error-base-125)
469          );
470
471          --wui-icon-box-bg-error-100: color-mix(
472            in srgb,
473            var(--w3m-color-mix) var(--w3m-color-mix-strength),
474            var(--wui-icon-box-bg-error-base-100)
475          );
476          --wui-icon-box-bg-accent-100: color-mix(
477            in srgb,
478            var(--w3m-color-mix) var(--w3m-color-mix-strength),
479            var(--wui-icon-box-bg-blue-base-100)
480          );
481          --wui-icon-box-bg-success-100: color-mix(
482            in srgb,
483            var(--w3m-color-mix) var(--w3m-color-mix-strength),
484            var(--wui-icon-box-bg-success-base-100)
485          );
486          --wui-icon-box-bg-inverse-100: color-mix(
487            in srgb,
488            var(--w3m-color-mix) var(--w3m-color-mix-strength),
489            var(--wui-icon-box-bg-inverse-base-100)
490          );
491
492          --wui-all-wallets-bg-100: color-mix(
493            in srgb,
494            var(--w3m-color-mix) var(--w3m-color-mix-strength),
495            var(--wui-all-wallets-bg-100)
496          );
497
498          --wui-avatar-border: color-mix(
499            in srgb,
500            var(--w3m-color-mix) var(--w3m-color-mix-strength),
501            var(--wui-avatar-border-base)
502          );
503
504          --wui-thumbnail-border: color-mix(
505            in srgb,
506            var(--w3m-color-mix) var(--w3m-color-mix-strength),
507            var(--wui-thumbnail-border-base)
508          );
509
510          --wui-wallet-button-bg: color-mix(
511            in srgb,
512            var(--w3m-color-mix) var(--w3m-color-mix-strength),
513            var(--wui-wallet-button-bg-base)
514          );
515        }
516      }
517    `,
517light:Dr`
518      :root {
519        --w3m-color-mix: ${St((t==null?void 0:t["--w3m-color-mix"])||"#fff")};
520        --w3m-accent: ${St(Is(t,"dark")["--w3m-accent"])};
521        --w3m-default: #fff;
522
523        --wui-color-modal-bg-base: ${St(Is(t,"dark")["--w3m-background"])};
524        --wui-color-accent-base-100: var(--w3m-accent);
525
526        --wui-color-blueberry-100: hsla(230, 100%, 67%, 1);
527        --wui-color-blueberry-090: hsla(231, 76%, 61%, 1);
528        --wui-color-blueberry-080: hsla(230, 59%, 55%, 1);
529        --wui-color-blueberry-050: hsla(231, 100%, 70%, 0.1);
530
531        --wui-color-fg-100: #e4e7e7;
532        --wui-color-fg-125: #d0d5d5;
533        --wui-color-fg-150: #a8b1b1;
534        --wui-color-fg-175: #a8b0b0;
535        --wui-color-fg-200: #949e9e;
536        --wui-color-fg-225: #868f8f;
537        --wui-color-fg-250: #788080;
538        --wui-color-fg-275: #788181;
539        --wui-color-fg-300: #6e7777;
540        --wui-color-fg-325: #9a9a9a;
541        --wui-color-fg-350: #363636;
542
543        --wui-color-bg-100: #141414;
544        --wui-color-bg-125: #191a1a;
545        --wui-color-bg-150: #1e1f1f;
546        --wui-color-bg-175: #222525;
547        --wui-color-bg-200: #272a2a;
548        --wui-color-bg-225: #2c3030;
549        --wui-color-bg-250: #313535;
550        --wui-color-bg-275: #363b3b;
551        --wui-color-bg-300: #3b4040;
552        --wui-color-bg-325: #252525;
553        --wui-color-bg-350: #ffffff;
554
555        --wui-color-success-base-100: #26d962;
556        --wui-color-success-base-125: #30a46b;
557
558        --wui-color-warning-base-100: #f3a13f;
559
560        --wui-color-error-base-100: #f25a67;
561        --wui-color-error-base-125: #df4a34;
562
563        --wui-color-blue-base-100: rgba(102, 125, 255, 1);
564        --wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
565
566        --wui-color-success-glass-001: rgba(38, 217, 98, 0.01);
567        --wui-color-success-glass-002: rgba(38, 217, 98, 0.02);
568        --wui-color-success-glass-005: rgba(38, 217, 98, 0.05);
569        --wui-color-success-glass-010: rgba(38, 217, 98, 0.1);
570        --wui-color-success-glass-015: rgba(38, 217, 98, 0.15);
571        --wui-color-success-glass-020: rgba(38, 217, 98, 0.2);
572        --wui-color-success-glass-025: rgba(38, 217, 98, 0.25);
573        --wui-color-success-glass-030: rgba(38, 217, 98, 0.3);
574        --wui-color-success-glass-060: rgba(38, 217, 98, 0.6);
575        --wui-color-success-glass-080: rgba(38, 217, 98, 0.8);
576
577        --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
578
579        --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
580
581        --wui-color-error-glass-001: rgba(242, 90, 103, 0.01);
582        --wui-color-error-glass-002: rgba(242, 90, 103, 0.02);
583        --wui-color-error-glass-005: rgba(242, 90, 103, 0.05);
584        --wui-color-error-glass-010: rgba(242, 90, 103, 0.1);
585        --wui-color-error-glass-015: rgba(242, 90, 103, 0.15);
586        --wui-color-error-glass-020: rgba(242, 90, 103, 0.2);
587        --wui-color-error-glass-025: rgba(242, 90, 103, 0.25);
588        --wui-color-error-glass-030: rgba(242, 90, 103, 0.3);
589        --wui-color-error-glass-060: rgba(242, 90, 103, 0.6);
590        --wui-color-error-glass-080: rgba(242, 90, 103, 0.8);
591
592        --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
593
594        --wui-color-gray-glass-001: rgba(255, 255, 255, 0.01);
595        --wui-color-gray-glass-002: rgba(255, 255, 255, 0.02);
596        --wui-color-gray-glass-005: rgba(255, 255, 255, 0.05);
597        --wui-color-gray-glass-010: rgba(255, 255, 255, 0.1);
598        --wui-color-gray-glass-015: rgba(255, 255, 255, 0.15);
599        --wui-color-gray-glass-020: rgba(255, 255, 255, 0.2);
600        --wui-color-gray-glass-025: rgba(255, 255, 255, 0.25);
601        --wui-color-gray-glass-030: rgba(255, 255, 255, 0.3);
602        --wui-color-gray-glass-060: rgba(255, 255, 255, 0.6);
603        --wui-color-gray-glass-080: rgba(255, 255, 255, 0.8);
604        --wui-color-gray-glass-090: rgba(255, 255, 255, 0.9);
605
606        --wui-color-dark-glass-100: rgba(42, 42, 42, 1);
607
608        --wui-icon-box-bg-error-base-100: #3c2426;
609        --wui-icon-box-bg-blue-base-100: #20303f;
610        --wui-icon-box-bg-success-base-100: #1f3a28;
611        --wui-icon-box-bg-inverse-base-100: #243240;
612
613        --wui-all-wallets-bg-100: #222b35;
614
615        --wui-avatar-border-base: #252525;
616
617        --wui-thumbnail-border-base: #252525;
618
619        --wui-wallet-button-bg-base: var(--wui-color-bg-125);
620
621        --w3m-card-embedded-shadow-color: rgb(17 17 18 / 25%);
622      }
623    `,dark:Dr`
624      :root {
625        --w3m-color-mix: ${St((t==null?void 0:t["--w3m-color-mix"])||"#000")};
626        --w3m-accent: ${St(Is(t,"light")["--w3m-accent"])};
627        --w3m-default: #000;
628
629        --wui-color-modal-bg-base: ${St(Is(t,"light")["--w3m-background"])};
630        --wui-color-accent-base-100: var(--w3m-accent);
631
632        --wui-color-blueberry-100: hsla(231, 100%, 70%, 1);
633        --wui-color-blueberry-090: hsla(231, 97%, 72%, 1);
634        --wui-color-blueberry-080: hsla(231, 92%, 74%, 1);
635
636        --wui-color-fg-100: #141414;
637        --wui-color-fg-125: #2d3131;
638        --wui-color-fg-150: #474d4d;
639        --wui-color-fg-175: #636d6d;
640        --wui-color-fg-200: #798686;
641        --wui-color-fg-225: #828f8f;
642        --wui-color-fg-250: #8b9797;
643        --wui-color-fg-275: #95a0a0;
644        --wui-color-fg-300: #9ea9a9;
645        --wui-color-fg-325: #9a9a9a;
646        --wui-color-fg-350: #d0d0d0;
647
648        --wui-color-bg-100: #ffffff;
649        --wui-color-bg-125: #f5fafa;
650        --wui-color-bg-150: #f3f8f8;
651        --wui-color-bg-175: #eef4f4;
652        --wui-color-bg-200: #eaf1f1;
653        --wui-color-bg-225: #e5eded;
654        --wui-color-bg-250: #e1e9e9;
655        --wui-color-bg-275: #dce7e7;
656        --wui-color-bg-300: #d8e3e3;
657        --wui-color-bg-325: #f3f3f3;
658        --wui-color-bg-350: #202020;
659
660        --wui-color-success-base-100: #26b562;
661        --wui-color-success-base-125: #30a46b;
662
663        --wui-color-warning-base-100: #f3a13f;
664
665        --wui-color-error-base-100: #f05142;
666        --wui-color-error-base-125: #df4a34;
667
668        --wui-color-blue-base-100: rgba(102, 125, 255, 1);
669        --wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
670
671        --wui-color-success-glass-001: rgba(38, 181, 98, 0.01);
672        --wui-color-success-glass-002: rgba(38, 181, 98, 0.02);
673        --wui-color-success-glass-005: rgba(38, 181, 98, 0.05);
674        --wui-color-success-glass-010: rgba(38, 181, 98, 0.1);
675        --wui-color-success-glass-015: rgba(38, 181, 98, 0.15);
676        --wui-color-success-glass-020: rgba(38, 181, 98, 0.2);
677        --wui-color-success-glass-025: rgba(38, 181, 98, 0.25);
678        --wui-color-success-glass-030: rgba(38, 181, 98, 0.3);
679        --wui-color-success-glass-060: rgba(38, 181, 98, 0.6);
680        --wui-color-success-glass-080: rgba(38, 181, 98, 0.8);
681
682        --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
683
684        --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
685
686        --wui-color-error-glass-001: rgba(240, 81, 66, 0.01);
687        --wui-color-error-glass-002: rgba(240, 81, 66, 0.02);
688        --wui-color-error-glass-005: rgba(240, 81, 66, 0.05);
689        --wui-color-error-glass-010: rgba(240, 81, 66, 0.1);
690        --wui-color-error-glass-015: rgba(240, 81, 66, 0.15);
691        --wui-color-error-glass-020: rgba(240, 81, 66, 0.2);
692        --wui-color-error-glass-025: rgba(240, 81, 66, 0.25);
693        --wui-color-error-glass-030: rgba(240, 81, 66, 0.3);
694        --wui-color-error-glass-060: rgba(240, 81, 66, 0.6);
695        --wui-color-error-glass-080: rgba(240, 81, 66, 0.8);
696
697        --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
698
699        --wui-icon-box-bg-error-base-100: #f4dfdd;
700        --wui-icon-box-bg-blue-base-100: #d9ecfb;
701        --wui-icon-box-bg-success-base-100: #daf0e4;
702        --wui-icon-box-bg-inverse-base-100: #dcecfc;
703
704        --wui-all-wallets-bg-100: #e8f1fa;
705
706        --wui-avatar-border-base: #f3f4f4;
707
708        --wui-thumbnail-border-base: #eaefef;
709
710        --wui-wallet-button-bg-base: var(--wui-color-bg-125);
711
712        --wui-color-gray-glass-001: rgba(0, 0, 0, 0.01);
713        --wui-color-gray-glass-002: rgba(0, 0, 0, 0.02);
714        --wui-color-gray-glass-005: rgba(0, 0, 0, 0.05);
715        --wui-color-gray-glass-010: rgba(0, 0, 0, 0.1);
716        --wui-color-gray-glass-015: rgba(0, 0, 0, 0.15);
717        --wui-color-gray-glass-020: rgba(0, 0, 0, 0.2);
718        --wui-color-gray-glass-025: rgba(0, 0, 0, 0.25);
719        --wui-color-gray-glass-030: rgba(0, 0, 0, 0.3);
720        --wui-color-gray-glass-060: rgba(0, 0, 0, 0.6);
721        --wui-color-gray-glass-080: rgba(0, 0, 0, 0.8);
722        --wui-color-gray-glass-090: rgba(0, 0, 0, 0.9);
723
724        --wui-color-dark-glass-100: rgba(233, 233, 233, 1);
725
726        --w3m-card-embedded-shadow-color: rgb(224 225 233 / 25%);
727      }
728    `}}const lI=Dr`
729  *,
730  *::after,
731  *::before,
732  :host {
733    margin: 0;
734    padding: 0;
735    box-sizing: border-box;
736    font-style: normal;
737    text-rendering: optimizeSpeed;
738    -webkit-font-smoothing: antialiased;
739    -moz-osx-font-smoothing: grayscale;
740    -webkit-tap-highlight-color: transparent;
741    font-family: var(--wui-font-family);
742    backface-visibility: hidden;
743  }
744`,uI=Dr`
745  button,
746  a {
747    cursor: pointer;
748    display: flex;
749    justify-content: center;
750    align-items: center;
751    position: relative;
752    transition:
753      color var(--wui-duration-lg) var(--wui-ease-out-power-1),
754      background-color var(--wui-duration-lg) var(--wui-ease-out-power-1),
755      border var(--wui-duration-lg) var(--wui-ease-out-power-1),
756      border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1),
757      box-shadow var(--wui-duration-lg) var(--wui-ease-out-power-1);
758    will-change: background-color, color, border, box-shadow, border-radius;
759    outline: none;
760    border: none;
761    column-gap: var(--wui-spacing-3xs);
762    background-color: transparent;
763    text-decoration: none;
764  }
765
766  wui-flex {
767    transition: border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1);
768    will-change: border-radius;
769  }
770
771  button:disabled > wui-wallet-image,
772  button:disabled > wui-all-wallets-image,
773  button:disabled > wui-network-image,
774  button:disabled > wui-image,
775  button:disabled > wui-transaction-visual,
776  button:disabled > wui-logo {
777    filter: grayscale(1);
778  }
779
780  @media (hover: hover) and (pointer: fine) {
781    button:hover:enabled {
782      background-color: var(--wui-color-gray-glass-005);
783    }
784
785    button:active:enabled {
786      background-color: var(--wui-color-gray-glass-010);
787    }
788  }
789
790  button:disabled > wui-icon-box {
791    opacity: 0.5;
792  }
793
794  input {
795    border: none;
796    outline: none;
797    appearance: none;
798  }
799`,dI=Dr`
800  .wui-color-inherit {
801    color: var(--wui-color-inherit);
802  }
803
804  .wui-color-accent-100 {
805    color: var(--wui-color-accent-100);
806  }
807
808  .wui-color-error-100 {
809    color: var(--wui-color-error-100);
810  }
811
812  .wui-color-blue-100 {
813    color: var(--wui-color-blue-100);
814  }
815
816  .wui-color-blue-90 {
817    color: var(--wui-color-blue-90);
818  }
819
820  .wui-color-error-125 {
821    color: var(--wui-color-error-125);
822  }
823
824  .wui-color-success-100 {
825    color: var(--wui-color-success-100);
826  }
827
828  .wui-color-success-125 {
829    color: var(--wui-color-success-125);
830  }
831
832  .wui-color-inverse-100 {
833    color: var(--wui-color-inverse-100);
834  }
835
836  .wui-color-inverse-000 {
837    color: var(--wui-color-inverse-000);
838  }
839
840  .wui-color-fg-100 {
841    color: var(--wui-color-fg-100);
842  }
843
844  .wui-color-fg-200 {
845    color: var(--wui-color-fg-200);
846  }
847
848  .wui-color-fg-300 {
849    color: var(--wui-color-fg-300);
850  }
851
852  .wui-color-fg-325 {
853    color: var(--wui-color-fg-325);
854  }
855
856  .wui-color-fg-350 {
857    color: var(--wui-color-fg-350);
858  }
859
860  .wui-bg-color-inherit {
861    background-color: var(--wui-color-inherit);
862  }
863
864  .wui-bg-color-blue-100 {
865    background-color: var(--wui-color-accent-100);
866  }
867
868  .wui-bg-color-error-100 {
869    background-color: var(--wui-color-error-100);
870  }
871
872  .wui-bg-color-error-125 {
873    background-color: var(--wui-color-error-125);
874  }
875
876  .wui-bg-color-success-100 {
877    background-color: var(--wui-color-success-100);
878  }
879
880  .wui-bg-color-success-125 {
881    background-color: var(--wui-color-success-100);
882  }
883
884  .wui-bg-color-inverse-100 {
885    background-color: var(--wui-color-inverse-100);
886  }
887
888  .wui-bg-color-inverse-000 {
889    background-color: var(--wui-color-inverse-000);
890  }
891
892  .wui-bg-color-fg-100 {
893    background-color: var(--wui-color-fg-100);
894  }
895
896  .wui-bg-color-fg-200 {
897    background-color: var(--wui-color-fg-200);
898  }
899
900  .wui-bg-color-fg-300 {
901    background-color: var(--wui-color-fg-300);
902  }
903
904  .wui-color-fg-325 {
905    background-color: var(--wui-color-fg-325);
906  }
907
908  .wui-color-fg-350 {
909    background-color: var(--wui-color-fg-350);
910  }
911`,Ei={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]};function Cn(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const du=Cn({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"}
911),hu=Cn({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"});Cn({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"});Cn({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Cn({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const _1={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"]},Kn={getMethodsByChainNamespace(t){return _1[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const s={...t},r=new Set;if(e.methods&&Object.keys(e.methods).forEach(i=>r.add(i)),e.chains&&Object.keys(e.chains).forEach(i=>r.add(i)),e.events&&Object.keys(e.events).forEach(i=>r.add(i)),e.rpcMap&&Object.keys(e.rpcMap).forEach(i=>{const[n]=i.split(":");n&&r.add(n)}),r.forEach(i=>{s[i]||(s[i]=this.createDefaultNamespace(i))}),e.methods&&Object.entries(e.methods).forEach(([i,n])=>{s[i]&&(s[i].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([i,n])=>{s[i]&&(s[i].chains=n)}),e.events&&Object.entries(e.events).forEach(([i,n])=>{s[i]&&(s[i].events=n)}),e.rpcMap){const i=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,c]=n.split(":");!a||!c||!s[a]||(s[a].rpcMap||(s[a].rpcMap={}),i.has(a)||(s[a].rpcMap={},i.add(a)),s[a].rpcMap[c]=o)})}return s},createNamespaces(t,e){const s=t.reduce((r,i)=>{const{id:n,chainNamespace:o,rpcUrls:a}=i,c=a.default.http[0];r[o]||(r[o]=this.createDefaultNamespace(o));const l=`${o}:${n}`,u=r[o];switch(u.chains.push(l),l){case du.caipNetworkId:u.chains.push(du.deprecatedCaipNetworkId);break;case hu.caipNetworkId:u.chains.push(hu.deprecatedCaipNetworkId);break}return u!=null&&u.rpcMap&&c&&(u.rpcMap[n]=c),r},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{var r;const e=await _i.resolveName(t);return((r=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:r.address)||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],r=e.accounts.map(i=>{const[n,o]=i.split(":");return`${n}:${o}`});return Array.from(new Set([...s,...r]))})},isSessionEventData(t){return typeof t=="object"&&t!==null&&"id"in t&&"topic"in t&&"params"in t&&typeof t.params=="object"&&t.params!==null&&"chainId"in t.params&&"event"in t.params&&typeof t.params.event=="object"&&t.params.event!==null},isOriginAllowed(t,e,s){for(const r of[...e,...s])if(r.includes("*")){const n=`^${r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(n,"u").test(t))return!0}
911else try{if(new URL(r).origin===t)return!0}catch{if(r===t)return!0}return!1}};class hh{constructor({provider:e,namespace:s}){this.id=H.CONNECTOR_ID.WALLET_CONNECT,this.name=Qn.ConnectorNamesMap[H.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Qn.ConnectorImageIds[H.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(),r=T.state.universalProviderConfigOverride,i=Kn.createNamespaces(s,r);await this.provider.connect({optionalNamespaces:i})}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 Ti.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:S1})}}const S1=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"];class P1{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=s=>g.getCaipNetworks(s),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.getCaipNetworks(this.namespace)}setAuthProvider(e){this.addConnector({id:H.CONNECTOR_ID.AUTH,type:"AUTH",name:H.CONNECTOR_NAMES.AUTH,provider:e,imageId:Qn.ConnectorImageIds[H.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const s=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(r=>s.has(r.id)?!1:(s.add(r.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,s){z.setStatus(e,s)}on(e,s){var r;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(r=this.eventListeners.get(e))==null||r.add(s)}off(e,s){const r=this.eventListeners.get(e);r&&r.delete(s)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const r=this.eventListeners.get(e);r&&r.forEach(i=>i(s))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){var n;const{caipNetwork:s,providerType:r}=e;if(!e.provider)return;const i="provider"in e.provider?e.provider.provider:e.provider;if(r==="WALLET_CONNECT"){i.setDefaultChain(s.caipNetworkId);return}if(i&&r==="AUTH"){const o=i,a=(n=z.state.preferredAccountTypes)==null?void 0:n[s.chainNamespace];await o.switchNetwork(s.caipNetworkId);const c=await o.getUser({chainId:s.caipNetworkId,preferredAccountType:a});this.emit("switchNetwork",c)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s instanceof hh);if(!e)throw new Error("WalletConnectConnector not found");return e}}class O1 extends P1{setUniversalProvider(e){this.addConnector(new hh({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){var i,n,o,a;const s=this.provider,r=((a=(o=(n=(i=s==null?void 0:s.session)==null?void 0:i.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const[,,l]=c.split(":");return l}).filter((c,l,u)=>u.indexOf(c)===l))||[];return Promise.resolve({accounts:r.map(c=>Z.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var n,o,a,c,l;if(!(e.caipNetwork&&Ee.BALANCE_SUPPORTED_CHAINS.includes((n=e.caipNetwork)==null?void 0:n.chainNamespace))||(o=e.caipNetwork)!=null&&o.testnet)return{balance:"0.00",symbol:((a=e.caipNetwork)==null?void 0:a.nativeCurrency.symbol)||""};if(z.state.balanceLoading&&e.chainId===((c=g.state.activeCaipNetwork)==null?void 0:c.id))return{balance:z.state.balance||"0.00",symbol:z.state.balanceSymbol||""};const i=(await z.fetchTokenBalance()).find(u=>{var d,h;return u.chainId===`${(d=e.caipNetwork)==null?void 0:d.chainNamespace}:${e.chainId}`&&u.symbol===((h=e.caipNetwork)==null?void 0:h.nativeCurrency.symbol)});return{balance:(i==null?void 0:i.quantity.numeric)||"0.00",symbol:(i==null?void 0:i.symbol)||((l=e.caipNetwork)==null?void 0:l.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:s,message:r,address:i}=e;
911if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return((o=g.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===H.CHAIN.SOLANA?n=(await s.request({method:"solana_signMessage",params:{message:gu.encode(new TextEncoder().encode(r)),pubkey:i}},(a=g.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:n=await s.request({method:"personal_sign",params:[r,i]},(c=g.state.activeCaipNetwork)==null?void 0:c.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var i,n,o,a,c,l;const{caipNetwork:s}=e,r=this.getWalletConnectConnector();if(s.chainNamespace===H.CHAIN.EVM)try{await((i=r.provider)==null?void 0:i.request({method:"wallet_switchEthereumChain",params:[{chainId:uc(s.id)}]}))}catch(u){if(u.code===Ei.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||u.code===Ei.ERROR_INVALID_CHAIN_ID||u.code===Ei.ERROR_CODE_DEFAULT||((o=(n=u==null?void 0:u.data)==null?void 0:n.originalError)==null?void 0:o.code)===Ei.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=r.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:uc(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")}}r.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(r=>r.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}const T1=["email","socials","swaps","onramp","activity","reownBranding"],jn={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?Ee.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?Ee.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?Ee.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?Ee.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?Ee.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?Ee.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?Ee.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?Ee.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?Ee.DEFAULT_REMOTE_FEATURES.reownBranding:!!t}},$1={localSettingsOverridden:new Set,getApiConfig(t,e){return e==null?void 0:e.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=jn[e],r=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(r)}},processFeature(t,e,s,r,i){const n=jn[t],o=e[n.localFeatureName];if(i&&!n.isAvailableOnBasic)return!1;if(r){const a=this.getApiConfig(n.apiFeatureName,s);return(a==null?void 0:a.config)===null?this.processFallbackFeature(t,o):a!=null&&a.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return jn[t].processApi(e)},processFallbackFeature(t,e){return jn[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let r=null,i=!1;try{r=await V.fetchProjectConfig(),i=r!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const n=i&&!e?Ee.DEFAULT_REMOTE_FEATURES:Ee.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of T1){const a=this.processFeature(o,s,r,i,e);Object.assign(n,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),Ee.DEFAULT_REMOTE_FEATURES}if(i&&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.`;Bs.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${o}`},"warning")}return n}};class x1{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,r)=>{var i,n,o,a;if(s){const c=(n=(i=g.getNetworkData(s))==null?void 0:i.requestedCaipNetworks)==null?void 0:n.find(d=>d.id===r);if(c)return c;const l=(o=g.getNetworkData(s))==null?void 0:o.caipNetwork;return l||((a=g.getRequestedCaipNetworks(s).filter(d=>d.chainNamespace===s))==null?void 0:a[0])}return g.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>
911g.getCaipNetworks(s),this.getActiveChainNamespace=()=>g.state.activeChain,this.setRequestedCaipNetworks=(s,r)=>{g.setRequestedCaipNetworks(s,r)},this.getApprovedCaipNetworkIds=()=>g.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>g.state.activeChain===s||!s?g.state.activeCaipAddress:g.getAccountProp("caipAddress",s),this.setClientId=s=>{J.setClientId(s)},this.getProvider=s=>Se.getProvider(s),this.getProviderType=s=>Se.getProviderId(s),this.getPreferredAccountType=s=>{var r;return(r=z.state.preferredAccountTypes)==null?void 0:r[s]},this.setCaipAddress=(s,r)=>{z.setCaipAddress(s,r),s&&T.state.enableEmbedded&&this.close()},this.setBalance=(s,r,i)=>{z.setBalance(s,r,i)},this.setProfileName=(s,r)=>{z.setProfileName(s,r)},this.setProfileImage=(s,r)=>{z.setProfileImage(s,r)},this.setUser=(s,r)=>{z.setUser(s,r)},this.resetAccount=s=>{z.resetAccount(s)},this.setCaipNetwork=s=>{g.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,r)=>{g.setChainNetworkData(r,{caipNetwork:s})},this.setAllAccounts=(s,r)=>{z.setAllAccounts(s,r),T.setHasMultipleAddresses((s==null?void 0:s.length)>1)},this.setStatus=(s,r)=>{z.setStatus(s,r),B.isConnected()?F.setConnectionStatus("connected"):F.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>g.getAccountProp("address",s),this.setConnectors=s=>{const r=[...B.state.allConnectors,...s];B.setConnectors(r)},this.setConnections=(s,r)=>{Y.setConnections(s,r)},this.fetchIdentity=s=>J.fetchIdentity(s),this.getReownName=s=>_i.getNamesForAddress(s),this.getConnectors=()=>B.getConnectors(),this.getConnectorImage=s=>Cu.getConnectorImage(s),this.setConnectedWalletInfo=(s,r)=>{const i=Se.getProviderId(r),n=s?{...s,type:i}:void 0;z.setConnectedWalletInfo(n,r)},this.getIsConnectedState=()=>!!g.state.activeCaipAddress,this.addAddressLabel=(s,r,i)=>{z.addAddressLabel(s,r,i)},this.removeAddressLabel=(s,r)=>{z.removeAddressLabel(s,r)},this.getAddress=s=>g.state.activeChain===s||!s?z.state.address:g.getAccountProp("address",s),this.setApprovedCaipNetworksData=s=>g.setApprovedCaipNetworksData(s),this.resetNetwork=s=>{g.resetNetwork(s)},this.addConnector=s=>{B.addConnector(s)},this.resetWcConnection=()=>{Y.resetWcConnection()},this.setAddressExplorerUrl=(s,r)=>{z.setAddressExplorerUrl(s,r)},this.setSmartAccountDeployed=(s,r)=>{z.setSmartAccountDeployed(s,r)},this.setSmartAccountEnabledNetworks=(s,r)=>{g.setSmartAccountEnabledNetworks(s,r)},this.setPreferredAccountType=(s,r)=>{z.setPreferredAccountType(s,r)},this.setEIP6963Enabled=s=>{T.setEIP6963Enabled(s)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,s){const r=e==null?void 0:e.map(n=>n.namespace).filter(n=>!!n);if(r!=null&&r.length)return[...new Set(r)];const i=s==null?void 0:s.map(n=>n.chainNamespace);return[...new Set(i)]}async initialize(e){var s,r,i;this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),await this.syncExistingConnection(),this.remoteFeatures=await $1.fetchRemoteFeatures(e),T.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&ta.setOnrampProviders(this.remoteFeatures.onramp),((s=T.state.remoteFeatures)!=null&&s.email||Array.isArray((r=T.state.remoteFeatures)==null?void 0:r.socials)&&((i=T.state.remoteFeatures)==null?void 0:i.socials.length)>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await V.fetchAllowedOrigins();if(e&&Z.isClient()){const s=window.location.origin;Kn.isOriginAllowed(s,e,Ei.DEFAULT_ALLOWED_ANCESTORS)||Bs.open(Sr.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else Bs.open(Sr.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){var r;const{...s}=e;delete s.adapters,delete s.universalProvider,Pe.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(i=>i.id),siweConfig:{options:((r=e.siweConfig)==null?void 0:r.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&gt.setThemeMode(e.themeMode),e.themeVariables&&gt.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){Y.setWcBasic(e.basic??!1)}initializeConnectorController(){B.initialize(this.chainNamespaces)}initializeProjectSettings(e){T.setProjectId(e.projectId),T.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var o;T.setDebug(e.debug!==!1),T.setEnableWalletConnect(e.enableWalletConnect!==!1),T.setEnableWalletGuide(e.enableWalletGuide!==!1),T.setEnableWallets(e.enableWallets!==!1),T.setEIP6963Enabled(e.enableEIP6963!==!1),T.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),T.setEnableAuthLogger(e.enableAuthLogger!==!1),T.setCustomRpcUrls(e.customRpcUrls),T.setEnableEmbedded(e.enableEmbedded),T.setAllWallets(e.allWallets),T.setIncludeWalletIds(e.includeWalletIds),T.setExcludeWalletIds(e.excludeWalletIds),T.setFeaturedWalletIds(e.featuredWalletIds),T.setTokens(e.tokens),T.setTermsConditionsUrl(e.termsConditionsUrl),T.setPrivacyPolicyUrl(e.privacyPolicyUrl),T.setCustomWallets(e.customWallets),T.setFeatures(e.features),T.setAllowUnsupportedChain(e.allowUnsupportedChain),T.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),T.setPreferUniversalLinks(e.experimental_preferUniversalLinks),T.setDefaultAccountTypes(e.defaultAccountTypes);const s=F.getPreferredAccountTypes()||{},r={...T.state.defaultAccountTypes,...s};z.setPreferredAccountTypes(r);const i=this.getDefaultMetaData();if(!e.metadata&&i&&(e.metadata=i),T.setMetadata(e.metadata),T.setDisableAppend(e.disableAppend),T.setEnableEmbedded(e.enableEmbedded),T.setSIWX(e.siwx),!e.projectId){Bs.open(Sr.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((o=e.adapters)==null?void 0:o.find(a=>a.namespace===H.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");T.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,s,r,i;return Z.isClient()?{name:((s=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:s.textContent)||"",description:((r=document.querySelector('meta[property="og:description"]'))==null?void 0:r.content)||"",url:window.location.origin,icons:[((i=document.querySelector('link[rel~="icon"]'))==null?void 0:i.href)||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const r=Or.getUnsupportedNetwork(`${s}:${e}`);g.setActiveCaipNetwork(r)}}getDefaultNetwork(){return Or.getCaipNetworkFromStorage(this.defaultCaipNetwork)}
911extendCaipNetwork(e,s){return Or.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return Or.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(i=>{var n;return i.id===((n=e.defaultNetwork)==null?void 0:n.id)});return s?Or.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e){try{const s=this.getAdapter(e),r=Se.getProvider(e),i=Se.getProviderId(e),{caipAddress:n}=g.getAccountData(e)||{};this.setLoading(!0,e),n&&(s!=null&&s.disconnect)&&await s.disconnect({provider:r,providerType:i}),F.removeConnectedNamespace(e),Se.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),B.removeConnectorId(e),g.resetAccount(e),g.resetNetwork(e),this.setLoading(!1,e)}catch(s){throw this.setLoading(!1,e),new Error(`Failed to disconnect chain ${e}: ${s.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var n;const e=g.state.activeChain,s=this.getAdapter(e),r=(n=this.getCaipNetwork(e))==null?void 0:n.id;if(!s)throw new Error("Adapter not found");const i=await s.connectWalletConnect(r);this.close(),this.setClientId((i==null?void 0:i.clientId)||null),F.setConnectedNamespaces([...g.state.chains.keys()]),this.chainNamespaces.forEach(o=>{B.setConnectorId(ys.CONNECTOR_TYPE_WALLET_CONNECT,o)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:s,type:r,provider:i,chain:n,caipNetwork:o,socialUri:a})=>{var f,m,y,b,v,C;const c=g.state.activeChain,l=n||c,u=this.getAdapter(l);if(n&&n!==c&&!o){const S=this.getCaipNetworks().find(I=>I.chainNamespace===n);S&&this.setCaipNetwork(S)}if(!u)throw new Error("Adapter not found");const d=this.getCaipNetwork(l),h=await u.connect({id:e,info:s,type:r,provider:i,socialUri:a,chainId:(o==null?void 0:o.id)||(d==null?void 0:d.id),rpcUrl:((y=(m=(f=o==null?void 0:o.rpcUrls)==null?void 0:f.default)==null?void 0:m.http)==null?void 0:y[0])||((C=(v=(b=d==null?void 0:d.rpcUrls)==null?void 0:b.default)==null?void 0:v.http)==null?void 0:C[0])});if(!h)return;F.addConnectedNamespace(l),this.syncProvider({...h,chainNamespace:l});const p=z.state.allAccounts,{accounts:w}=(p==null?void 0:p.length)>0?{accounts:[...p]}:await u.getAccounts({namespace:l,id:e});this.setAllAccounts(w,l),this.setStatus("connected",l),this.syncConnectedWalletInfo(l)},reconnectExternal:async({id:e,info:s,type:r,provider:i})=>{var a;const n=g.state.activeChain,o=this.getAdapter(n);o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:s,type:r,provider:i,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),F.addConnectedNamespace(n),this.syncConnectedWalletInfo(n))},disconnect:async e=>{const s=r1(e);try{const r=await Promise.allSettled(s.map(async([n])=>this.disconnectNamespace(n)));de.resetSend(),Y.resetWcConnection(),await Ti.clearSessions(),B.setFilterByNamespace(void 0);const i=r.filter(n=>n.status==="rejected");if(i.length>0)throw new Error(i.map(n=>n.reason.message).join(", "));F.deleteConnectedSocialProvider(),Pe.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:e||"all"}})}catch(r){throw new Error(`Failed to disconnect chains: ${r.message}`)}},checkInstalled:e=>e?e.some(s=>{var r;return!!((r=window.ethereum)!=null&&r[String(s)])}):!!window.ethereum,signMessage:async e=>{const s=this.getAdapter(g.state.activeChain),r=await(s==null?void 0:s.signMessage({message:e,address:z.state.address,provider:Se.getProvider(g.state.activeChain)}));return(r==null?void 0:r.signature)||""},sendTransaction:async e=>{const s=e.chainNamespace;if(Ee.SEND_SUPPORTED_NAMESPACES.includes(s)){const r=this.getAdapter(g.state.activeChain),i=Se.getProvider(s),n=await(r==null?void 0:r.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}));return(n==null?void 0:n.hash)||""}return""},estimateGas:async e=>{if(e.chainNamespace===H.CHAIN.EVM){const s=this.getAdapter(g.state.activeChain),r=Se.getProvider(g.state.activeChain),i=this.getCaipNetwork();if(!i)throw new Error("CaipNetwork is undefined");const n=await(s==null?void 0:s.estimateGas({...e,provider:r,caipNetwork:i}));return(n==null?void 0:n.gas)||0n}return 0n},getEnsAvatar:async()=>{var e;return await this.syncIdentity({address:z.state.address,chainId:Number((e=this.getCaipNetwork())==null?void 0:e.id),chainNamespace:g.state.activeChain}),z.state.profileImage||!1},getEnsAddress:async e=>await Kn.resolveReownName(e),writeContract:async e=>{const s=this.getAdapter(g.state.activeChain),r=this.getCaipNetwork(),i=this.getCaipAddress(),n=Se.getProvider(g.state.activeChain);if(!r||!i)throw new Error("CaipNetwork or CaipAddress is undefined");const o=await(s==null?void 0:s.writeContract({...e,caipNetwork:r,provider:n,caipAddress:i}));return o==null?void 0:o.hash},parseUnits:(e,s)=>{const r=this.getAdapter(g.state.activeChain);return(r==null?void 0:r.parseUnits({value:e,decimals:s}))??0n},formatUnits:(e,s)=>{const r=this.getAdapter(g.state.activeChain);return(r==null?void 0:r.formatUnits({value:e,decimals:s}))??"0"},getCapabilities:async e=>{const s=this.getAdapter(g.state.activeChain);return await(s==null?void 0:s.getCapabilities(e))},grantPermissions:async e=>{const s=this.getAdapter(g.state.activeChain);return await(s==null?void 0:s.grantPermissions(e))},revokePermissions:async e=>{const s=this.getAdapter(g.state.activeChain);return s!=null&&s.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(g.state.activeChain);return await(s==null?void 0:s.walletGetAssets(e))??{}},updateBalance:e=>{const s=this.getCaipNetwork(e);!s||!z.state.address||this.updateNativeBalance(z.state.address,s==null?void 0:s.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Y.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var s,r,i,n,o;if(Se.getProviderId(g.state.activeChain)===ys.CONNECTOR_TYPE_WALLET_CONNECT){const a=(r=(s=this.universalProvider)==null?void 0:s.session)==null?void 0:r.namespaces;return{supportsAllNetworks:((o=(n=(i=this.universalProvider)==null?void 0:i.session)==null?void 0:n.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const i=Se.getProvider(s),n=Se.getProviderId(s);if(e.chainNamespace===g.state.activeChain){const o=this.getAdapter(s);
911await(o==null?void 0:o.switchNetwork({caipNetwork:e,provider:i,providerType:n}))}else if(this.setCaipNetwork(e),n===ys.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 r=s.chains||[],i=s.accounts.map(n=>{const{chainId:o,chainNamespace:a}=ps.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...r,...i]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,r)=>{var n;const i=e==null?void 0:e.find(o=>o.namespace===r);return i?(i.construct({namespace:r,projectId:(n=this.options)==null?void 0:n.projectId,networks:this.getCaipNetworks()}),s[r]=i):s[r]=new O1({namespace:r,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 r=F.getConnectionStatus();r==="connected"?this.setStatus("connecting",e):r==="disconnected"?(F.clearAddressCache(),this.setStatus(r,e)):this.setStatus(r,e),s.on("switchNetwork",({address:i,chainId:n})=>{const o=this.getCaipNetworks().find(l=>l.id===n||l.caipNetworkId===n),a=g.state.activeChain===e,c=g.getAccountProp("address",e);if(o){const l=a&&i?i:c;l&&this.syncAccount({address:l,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),s.on("disconnect",this.disconnect.bind(this,e)),s.on("connections",i=>{this.setConnections(i,e)}),s.on("pendingTransactions",()=>{const i=z.state.address,n=g.state.activeCaipNetwork;!i||!(n!=null&&n.id)||this.updateNativeBalance(i,n.id,n.chainNamespace)}),s.on("accountChanged",({address:i,chainId:n})=>{var a,c;const o=g.state.activeChain===e;o&&n?this.syncAccount({address:i,chainId:n,chainNamespace:e}):o&&((a=g.state.activeCaipNetwork)!=null&&a.id)?this.syncAccount({address:i,chainId:(c=g.state.activeCaipNetwork)==null?void 0:c.id,chainNamespace:e}):this.syncAccountInfo(i,n,e),this.syncAllAccounts(e)})}async createUniversalProviderForAdapter(e){var s,r,i;await this.getUniversalProvider(),this.universalProvider&&((i=(r=(s=this.chainAdapters)==null?void 0:s[e])==null?void 0:r.setUniversalProvider)==null||i.call(r,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{e===H.CHAIN.EVM&&Z.isSafeApp()&&B.setConnectorId(H.CONNECTOR_ID.SAFE,e);const s=B.getConnectorId(e);switch(this.setStatus("connecting",e),s){case H.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case H.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){var a,c,l;const s=this.getAdapter(e),r=B.getConnectorId(e),i=this.getCaipNetwork(e),o=B.getConnectors(e).find(u=>u.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(i!=null&&i.id))throw new Error("CaipNetwork not found");const u=await(s==null?void 0:s.syncConnection({namespace:e,id:o.id,chainId:i.id,rpcUrl:(l=(c=(a=i==null?void 0:i.rpcUrls)==null?void 0:a.default)==null?void 0:c.http)==null?void 0:l[0]}));if(u){const d=await(s==null?void 0:s.getAccounts({namespace:e,id:o.id}));d&&d.accounts.length>0?this.setAllAccounts(d.accounts,e):this.setAllAccounts([Z.createAccount(e,u.address,"eoa")],e),this.syncProvider({...u,chainNamespace:e}),await this.syncAccount({...u,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async s=>{var a,c,l,u,d;const r=this.getAdapter(s),i=((u=(l=(c=(a=this.universalProvider)==null?void 0:a.session)==null?void 0:c.namespaces)==null?void 0:l[s])==null?void 0:u.accounts)||[],n=(d=g.state.activeCaipNetwork)==null?void 0:d.id,o=i.find(h=>{const{chainId:p}=ps.parseCaipAddress(h);return p===(n==null?void 0:n.toString())})||i[0];
911if(o){const h=ps.validateCaipAddress(o),{chainId:p,address:w}=ps.parseCaipAddress(h);if(Se.setProviderId(s,ys.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&g.state.activeCaipNetwork&&(r==null?void 0:r.namespace)!==H.CHAIN.EVM){const f=r==null?void 0:r.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:g.state.activeCaipNetwork});Se.setProvider(s,f)}else Se.setProvider(s,this.universalProvider);B.setConnectorId(H.CONNECTOR_ID.WALLET_CONNECT,s),F.addConnectedNamespace(s),this.syncWalletConnectAccounts(s),await this.syncAccount({address:w,chainId:p,chainNamespace:s})}else this.setStatus("disconnected",s);this.syncConnectedWalletInfo(s),await g.setApprovedCaipNetworksData(s)});await Promise.all(e)}syncWalletConnectAccounts(e){var r,i,n,o,a;const s=(a=(o=(n=(i=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:i.namespaces)==null?void 0:n[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const{address:l}=ps.parseCaipAddress(c);return l}).filter((c,l,u)=>u.indexOf(c)===l);s&&this.setAllAccounts(s.map(c=>Z.createAccount(e,c,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:s,id:r,chainNamespace:i}){Se.setProviderId(i,e),Se.setProvider(i,s),B.setConnectorId(r,i)}async syncAllAccounts(e){const s=B.getConnectorId(e);if(!s)return;const r=this.getAdapter(e),i=await(r==null?void 0:r.getAccounts({namespace:e,id:s}));i&&i.accounts.length>0&&this.setAllAccounts(i.accounts,e)}async syncAccount(e){var d,h;const s=e.chainNamespace===g.state.activeChain,r=g.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:i,chainId:n,chainNamespace:o}=e,{chainId:a}=F.getActiveNetworkProps(),c=n||a,l=((d=g.state.activeCaipNetwork)==null?void 0:d.name)===H.UNSUPPORTED_NETWORK_NAME,u=g.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!u)&&c){let p=this.getCaipNetworks().find(m=>m.id.toString()===c.toString()),w=this.getCaipNetworks().find(m=>m.chainNamespace===o);if(!u&&!p&&!w){const m=this.getApprovedCaipNetworkIds()||[],y=m.find(v=>{var C;return((C=ps.parseCaipNetworkId(v))==null?void 0:C.chainId)===c.toString()}),b=m.find(v=>{var C;return((C=ps.parseCaipNetworkId(v))==null?void 0:C.chainNamespace)===o});p=this.getCaipNetworks().find(v=>v.caipNetworkId===y),w=this.getCaipNetworks().find(v=>v.caipNetworkId===b||"deprecatedCaipNetworkId"in v&&v.deprecatedCaipNetworkId===b)}const f=p||w;(f==null?void 0:f.chainNamespace)===g.state.activeChain?T.state.enableNetworkSwitch&&!T.state.allowUnsupportedChain&&((h=g.state.activeCaipNetwork)==null?void 0:h.name)===H.UNSUPPORTED_NETWORK_NAME?g.showUnsupportedChainUI():this.setCaipNetwork(f):s||r&&this.setCaipNetworkOfNamespace(r,o),this.syncConnectedWalletInfo(o),Za.isLowerCaseMatch(i,z.state.address)||this.syncAccountInfo(i,f==null?void 0:f.id,o),s?await this.syncBalance({address:i,chainId:f==null?void 0:f.id,chainNamespace:o}):await this.syncBalance({address:i,chainId:r==null?void 0:r.id,chainNamespace:o})}}async syncAccountInfo(e,s,r){const i=this.getCaipAddress(r),n=s||(i==null?void 0:i.split(":")[1]);if(!n)return;const o=`${r}:${n}:${e}`;this.setCaipAddress(o,r),await this.syncIdentity({address:e,chainId:n,chainNamespace:r})}async syncReownName(e,s){try{const r=await this.getReownName(e);if(r[0]){const i=r[0];this.setProfileName(i.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){var i;const s=B.getConnectorId(e),r=Se.getProviderId(e);if(r===ys.CONNECTOR_TYPE_ANNOUNCED||r===ys.CONNECTOR_TYPE_INJECTED){if(s){const n=this.getConnectors().find(o=>o.id===s);if(n){const{info:o,name:a,imageUrl:c}=n,l=c||this.getConnectorImage(n);this.setConnectedWalletInfo({name:a,icon:l,...o},e)}}}else if(r===ys.CONNECTOR_TYPE_WALLET_CONNECT){const n=Se.getProvider(e);n!=null&&n.session&&this.setConnectedWalletInfo({...n.session.peer.metadata,name:n.session.peer.metadata.name,icon:(i=n.session.peer.metadata.icons)==null?void 0:i[0]},e)}else if(s&&s===H.CONNECTOR_ID.COINBASE){const n=this.getConnectors().find(o=>o.id===H.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(n)},e)}}async syncBalance(e){!yu.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(r=>{var i;return r.id.toString()===((i=e.chainId)==null?void 0:i.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,r){const i=this.getAdapter(r),n=g.getCaipNetworkByNamespace(r,s);if(i){const o=await i.getBalance({address:e,chainId:s,caipNetwork:n,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,r),o}}async initializeUniversalAdapter(){var r,i,n,o,a,c,l,u,d,h;const e=n1.createLogger((p,...w)=>{p&&this.handleAlertError(p),console.error(...w)}),s={projectId:(r=this.options)==null?void 0:r.projectId,metadata:{name:(i=this.options)!=null&&i.metadata?(n=this.options)==null?void 0:n.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(c=this.options)!=null&&c.metadata?(l=this.options)==null?void 0:l.metadata.url:"",icons:(u=this.options)!=null&&u.metadata?(d=this.options)==null?void 0:d.metadata.icons:[""]},logger:e};T.setManualWCControl(!!((h=this.options)!=null&&h.manualWCControl)),this.universalProvider=this.options.universalProvider??await s1.init(s),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Y.setUri(e)}),this.universalProvider.on("connect",Y.finalizeWcConnection),this.universalProvider.on("disconnect",()=>
911{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Y.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const s=this.getCaipNetworks().find(i=>i.id==e),r=this.getCaipNetwork();if(!s){this.setUnsupportedNetwork(e);return}(r==null?void 0:r.id)!==(s==null?void 0:s.id)&&this.setCaipNetwork(s)}),this.universalProvider.on("session_event",e=>{if(Kn.isSessionEventData(e)){const{name:s,data:r}=e.params.event;s==="accountsChanged"&&Array.isArray(r)&&Z.isCaipAddress(r[0])&&this.syncAccount(ps.parseCaipAddress(r[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&Z.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Pe.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const s=Object.entries(Sr.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[r,i]=s??[],{message:n,alertErrorKey:o}=i??{};if(r&&n&&!this.reportedAlertErrors[r]){const a=Sr.ALERT_ERRORS[o];a&&(Bs.open(a,"error"),this.reportedAlertErrors[r]=!0)}}getAdapter(e){var s;if(e)return(s=this.chainAdapters)==null?void 0:s[e]}createAdapter(e){var i;if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const r=e;r.namespace=s,r.construct({namespace:s,projectId:(i=this.options)==null?void 0:i.projectId,networks:this.getCaipNetworks()}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=r)}async open(e){if(await this.injectModalUi(),e!=null&&e.uri&&Y.setUri(e.uri),e!=null&&e.arguments)switch(e==null?void 0:e.view){case"Swap":return ze.open({...e,data:{swap:e.arguments}})}return ze.open(e)}async close(){await this.injectModalUi(),ze.close()}setLoading(e,s){ze.setLoading(e,s)}async disconnect(e){await Y.disconnect(e)}getSIWX(){return T.state.siwx}getError(){return""}getChainId(){var e;return(e=g.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e){const s=this.getCaipNetworks().find(r=>r.id===e.id);if(!s){Bs.open(Sr.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await g.switchActiveNetwork(s)}getWalletProvider(){return g.state.activeChain?Se.state.providers[g.state.activeChain]:null}getWalletProviderType(){return Se.getProviderId(g.state.activeChain)}subscribeProviders(e){return Se.subscribeProviders(e)}getThemeMode(){return gt.state.themeMode}getThemeVariables(){return gt.state.themeVariables}setThemeMode(e){gt.setThemeMode(e),dh(gt.state.themeMode)}setTermsConditionsUrl(e){T.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){T.setPrivacyPolicyUrl(e)}setThemeVariables(e){gt.setThemeVariables(e),N1(gt.state.themeVariables)}subscribeTheme(e){return gt.subscribe(e)}getWalletInfo(){return z.state.connectedWalletInfo}getAccount(e){var o;const s=B.getAuthConnector(e),r=g.getAccountData(e),i=g.state.activeChain,n=F.getConnectedConnectorId(e||i);if(r)return{allAccounts:r.allAccounts,caipAddress:r.caipAddress,address:Z.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:s&&n===H.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:F.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:(o=r.preferredAccountTypes)==null?void 0:o[e||i],isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const r=()=>{const i=this.getAccount(s);i&&e(i)};s?g.subscribeChainProp("accountState",r,s):g.subscribe(r),B.subscribe(r)}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){return z.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){z.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){g.subscribeKey("activeCaipNetwork",e)}getState(){return Ns.state}subscribeState(e){return Ns.subscribe(e)}showErrorMessage(e){Mt.showError(e)}showSuccessMessage(e){Mt.showSuccess(e)}getEvent(){return{...Pe.state}}subscribeEvents(e){return Pe.subscribe(e)}replace(e){re.replace(e)}redirect(e){re.push(e)}popTransactionStack(e){re.popTransactionStack(e)}isOpen(){return ze.state.open}isTransactionStackEmpty(){return re.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){T.setFeatures(e)}updateRemoteFeatures(e){T.setRemoteFeatures(e)}updateOptions(e){const r={...T.state||{},...e};T.setOptions(r)}setConnectMethodsOrder(e){T.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){T.setWalletFeaturesOrder(e)}setCollapseWallets(e){T.setCollapseWallets(e)}setSocialsOrder(e){T.setSocialsOrder(e)}getConnectMethodsOrder(){return $a.getConnectOrderMethod(T.state.features,B.getConnectors())}
911addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const r=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(i=>i.id===r.id)||g.addNetwork(r)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(i=>i.id===s)&&g.removeNetwork(e,s)}}let pu=!1;class ph extends x1{async open(e){B.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Y.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!pu&&Z.isClient()){if(await Go(()=>import("./basic-Dt_HnegP.js"),__vite__mapDeps([2,3,0,1,4,5])),await Go(()=>import("./w3m-modal-rktXCkeb.js"),__vite__mapDeps([6,3,0,1,5])),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!T.state.disableAppend&&!T.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}pu=!0}}}const k1="1.7.8";function R1(t){return new ph({...t,basic:!0,sdkVersion:`html-core-${k1}`})}const hI=Object.freeze(Object.defineProperty({__proto__:null,AppKit:ph,createAppKit:R1},Symbol.toStringTag,{value:"Module"}));export{V as A,a1 as B,B as C,z as D,Pe as E,cI as F,hI as G,ze as M,T as O,re as R,F as S,gt as T,$a as W,Vn as a,Z as b,Wn as c,Cu as d,uI as e,Y as f,H as g,g as h,Dr as i,Dt as j,Mt as k,Ee as l,aI as m,Fe as n,dI as o,nh as p,Jr as q,lI as r,_e as s,Qe as t,xa as u,Xe as v,Et as w,oI as x,Ti as y,Bs 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.