PageSourceSearch

https://aerodrome.finance/assets/core-B3y5vm-c.js

js aerodrome.finance collected 2026-10-02 06:15:18 UTC 510,099 bytes, 896 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/basic-CDWRbdmm.js","assets/index-C2gem7KR.js","assets/index-hZR_pMzJ.js","assets/index-BUUZxY2d.css","assets/dijkstra-COg3n3zL.js","assets/index-BbP3371Q.js","assets/index.es-E5edk0SJ.js","assets/index-nibyPLVP.js","assets/browser-ponyfill-CEp-GVeJ.js","assets/w3m-modal-BDzWSbpa.js"])))=>i.map(i=>d[i]);
2import{e7 as Ur,_ as Zo,dz as Qe,e9 as ir,eb as La}from"./index-hZR_pMzJ.js";import{g as re}from"./index-BbP3371Q.js";import{I as Qr,c as $h,f as Tt,t as ht,a as D,b as ds,C as Rh,d as Uh,e as Ii,s as Qo,k as pn,A as Ou,E as it,i as Dh,h as Mh,y as Ct,g as Hs,r as ei,O as ja,o as xt,j as Lh,l as Ba,m as qa,n as no,P as cc,Q as jh,p as Bh,q as qh,u as lc,v as Tr,w as ku,x as ns,z as Kt,B as ps,D as qt}from"./index.es-E5edk0SJ.js";var uc={};const W={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 Ur<"u"&&typeof uc<"u"?uc.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},Tu={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(s=>s.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const s=t.find(i=>i.caipNetworkId===e);if(s)return s.name;const[r]=e.split(":");return W.CHAIN_NAME_MAP?.[r]||void 0}};var zh=20,Fh=1,Zs=1e6,dc=1e6,Wh=-7,Hh=21,Vh=!1,fn="[big.js] ",nr=fn+"Invalid ",oo=nr+"decimal places",Kh=nr+"rounding mode",xu=fn+"Division by zero",me={},Yt=void 0,Gh=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function $u(){function t(e){var s=this;if(!(s instanceof t))return e===Yt?$u():new t(e);if(e instanceof t)s.s=e.s,s.e=e.e,s.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(nr+"value");e=e===0&&1/e<0?"-0":String(e)}Jh(s,e)}s.constructor=t}return t.prototype=me,t.DP=zh,t.RM=Fh,t.NE=Wh,t.PE=Hh,t.strict=Vh,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function Jh(t,e){var s,r,i;if(!Gh.test(e))throw Error(nr+"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 or(t,e,s,r){var i=t.c;if(s===Yt&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(Kh);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]!==Yt))),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]!==Yt||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 ar(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}me.abs=function(){var t=new this.constructor(this);return t.s=1,t};me.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};me.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>Zs)throw Error(oo);if(!i[0])throw Error(xu);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,g=r.slice(0,a),f=g.length,b=t,y=b.c=[],v=0,C=o+(b.e=e.e-t.e)+1;for(b.s=n,n=C<0?0:C,h.unshift(0);f++<a;)g.push(0);do{for(l=0;l<10;l++){if(a!=(f=g.length))u=a>f?1:-1;else for(d=-1,u=0;++d<a;)if(i[d]!=g[d]){u=i[d]>g[d]?1:-1;break}if(u<0){for(c=f==a?i:h;f;){if(g[--f]<c[f]){for(d=f;d&&!g[--d];)g[d]=9;--g[d],g[f]+=10}g[f]-=c[f]}for(;!g[0];)g.shift()}else break}y[v++]=u?l:++l,g[0]&&u?g[f]=r[p]||0:g=[r[p]]}while((p++<w||g[0]!==Yt)&&n--);return!y[0]&&v!=1&&(y.shift(),b.e--,C--),v>C&&or(b,C,s.RM,g[0]!==Yt),b};me.eq=function(t){return this.cmp(t)===0};me.gt=function(t){return this.cmp(t)>0};me.gte=function(t){return this.cmp(t)>-1};me.lt=function(t){return this.cmp(t)<0};me.lte=function(t){return this.cmp(t)<1};me.minus=me.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};me.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(xu);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)))};me.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};me.plus=me.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};me.pow=function(t){var e=this,s=new e.constructor("1"),r=s,i=t<0;if(t!==~~t||t<-dc||t>dc)throw Error(nr+"exponent");for(i&&(t=-t);t&1&&(r=r.times(e)),t>>=1,!!t;)e=e.times(e);return i?s.div(r):r};me.prec=function(t,e){if(t!==~~t||t<1||t>Zs)throw Error(nr+"precision");return or(new this.constructor(this),t,e)};me.round=function(t,e){if(t===Yt)t=0;else if(t!==~~t||t<-Zs||t>Zs)throw Error(oo);return or(new this.constructor(this),t+this.e+1,e)};me.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(fn+"No square root");n=Math.sqrt(+ar(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 or(t,(i.DP-=4)+t.e+1,i.RM)};me.times=me.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};me.toExponential=function(t,e){var s=this,r=s.c[0];if(t!==Yt){if(t!==~~t||t<0||t>Zs)throw Error(oo);for(s=or(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return ar(s,!0,!!r)};me.toFixed=function(t,e){var s=this,r=s.c[0];if(t!==Yt){if(t!==~~t||t<0||t>Zs)throw Error(oo);for(s=or(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return ar(s,!1,!!r)};me[Symbol.for("nodejs.util.inspect.custom")]=me.toJSON=me.toString=function(){var t=this,e=t.constructor;return ar(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};me.toNumber=function(){var t=+ar(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(fn+"Imprecise conversion");return t};me.toPrecision=function(t,e){var s=this,r=s.constructor,i=s.c[0];if(t!==Yt){if(t!==~~t||t<1||t>Zs)throw Error(nr+"precision");for(s=or(new r(s),t,e);s.c.length<t;)s.c.push(0)}return ar(s,t<=s.e||s.e<=r.NE||s.e>=r.PE,!!i)};me.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(fn+"valueOf disallowed");return ar(t,t.e<=e.NE||t.e>=e.PE,!0)};var ai=$u();const Yh={bigNumber(t){return t?new ai(t):new ai(0)},multiply(t,e){if(t===void 0||e===void 0)return new ai(0);const s=new ai(t),r=new ai(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,""))}},Xh=[{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"}]}],Zh=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],Qh=[{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"}]}],ep={getERC20Abi:t=>W.USDT_CONTRACT_ADDRESSES.includes(t)?Qh:Xh,getSwapAbi:()=>Zh},fs={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,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",DEEPL
2INK_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 yo(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Z={setItem(t,e){wi()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(wi())return localStorage.getItem(t)||void 0},removeItem(t){wi()&&localStorage.removeItem(t)},clear(){wi()&&localStorage.clear()}};function wi(){return typeof window<"u"&&typeof localStorage<"u"}function As(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const tp=Symbol(),hc=Object.getPrototypeOf,ea=new WeakMap,sp=t=>t&&(ea.has(t)?ea.get(t):hc(t)===Object.prototype||hc(t)===Array.prototype),rp=t=>sp(t)&&t[tp]||null,pc=(t,e=!0)=>{ea.set(t,e)},Xn={},bo=t=>typeof t=="object"&&t!==null,vs=new WeakMap,yi=new WeakSet,ip=(t=Object.is,e=(l,u)=>new Proxy(l,u),s=l=>bo(l)&&!yi.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?.[0]===u)return h[1];const p=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return pc(p,!0),i.set(l,[u,p]),Reflect.ownKeys(l).forEach(w=>{if(Object.getOwnPropertyDescriptor(p,w))return;const g=Reflect.get(l,w),{enumerable:f}=Reflect.getOwnPropertyDescriptor(l,w),b={value:g,enumerable:f,configurable:!0};if(yi.has(g))pc(g,!1);else if(g instanceof Promise)delete b.value,b.get=()=>d(g);else if(vs.has(g)){const[y,v]=vs.get(g);b.value=n(y,v(),d)}Object.defineProperty(p,w,b)}),Object.preventExtensions(p)},o=new WeakMap,a=[1,1],c=l=>{if(!bo(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,$=++a[0])=>{d!==$&&(d=$,h.forEach(I=>I(E,$)))};let w=a[1];const g=(E=++a[1])=>(w!==E&&!h.size&&(w=E,b.forEach(([$])=>{const I=$[1](E);I>d&&(d=I)})),d),f=E=>($,I)=>{const M=[...$];M[1]=[E,...M[1]],p(M,I)},b=new Map,y=(E,$)=>{if((Xn?"production":void 0)!=="production"&&b.has(E))throw new Error("prop listener already exists");if(h.size){const I=$[3](f(E));b.set(E,[$,I])}else b.set(E,[$])},v=E=>{var $;const I=b.get(E);I&&(b.delete(E),($=I[1])==null||$.call(I))},C=E=>(h.add(E),h.size===1&&b.forEach(([I,M],H)=>{if((Xn?"production":void 0)!=="production"&&M)throw new Error("remove already exists");const S=I[3](f(H));b.set(H,[I,S])}),()=>{h.delete(E),h.size===0&&b.forEach(([I,M],H)=>{M&&(M(),b.set(H,[I]))})}),A=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),_=e(A,{deleteProperty(E,$){const I=Reflect.get(E,$);v($);const M=Reflect.deleteProperty(E,$);return M&&p(["delete",[$],I]),M},set(E,$,I,M){const H=Reflect.has(E,$),S=Reflect.get(E,$,M);if(H&&(t(S,I)||o.has(I)&&t(S,o.get(I))))return!0;v($),bo(I)&&(I=rp(I)||I);let T=I;if(I instanceof Promise)I.then(O=>{I.status="fulfilled",I.value=O,p(["resolve",[$],O])}).catch(O=>{I.status="rejected",I.reason=O,p(["reject",[$],O])});else{!vs.has(I)&&s(I)&&(T=c(I));const O=!yi.has(T)&&vs.get(T);O&&y($,O)}return Reflect.set(E,$,T,M),p(["set",[$],I,S]),!0}});o.set(l,_);const R=[A,g,n,C];return vs.set(_,R),Reflect.ownKeys(l).forEach(E=>{const $=Object.getOwnPropertyDescriptor(l,E);"value"in $&&(_[E]=l[E],delete $.value,delete $.writable),Object.defineProperty(A,E,$)}),_})=>[c,vs,yi,t,e,s,r,i,n,o,a],[np]=ip();function Se(t={}){return np(t)}function et(t,e,s){const r=vs.get(t);(Xn?"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=>
2{n.push(u),i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(n.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Di(t,e){const s=vs.get(t);(Xn?"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 yi.add(t),t}function tt(t,e,s,r){let i=t[e];return et(t,()=>{const n=t[e];Object.is(i,n)||s(i=n)})}function op(t){const e=Se({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 Ru=[{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"]}],ap="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},DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal"}},z={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=z.getActiveNamespace(),e=z.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{Z.setItem(ee.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Z.getItem(ee.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Z.removeItem(ee.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Z.setItem(ee.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Z.setItem(ee.ACTIVE_CAIP_NETWORK_ID,t),z.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Z.getItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Z.removeItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=yo(t);Z.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=z.getRecentWallets();e.find(r=>r.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Z.setItem(ee.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Z.getItem(ee.RECENT_WALLETS);return t?JSON.parse(t):[]}
vendor: 9,613 bytes, line 2
2catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const s=yo(t);Z.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Z.getItem(ee.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=yo(t);return Z.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",t)}},setConnectedSocialProvider(t){try{Z.setItem(ee.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Z.getItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Z.removeItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Z.getItem(ee.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Z.getItem(ee.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{Z.setItem(ee.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Z.getItem(ee.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Z.getItem(ee.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Z.setItem(ee.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=z.getConnectedNamespaces();e.includes(t)||(e.push(t),z.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=z.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),z.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Z.getItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Z.setItem(ee.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Z.removeItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Z.getItem(ee.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=z.getBalanceCache();Z.setItem(ee.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=z.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;z.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=z.getBalanceCache();e[t.caipAddress]=t,Z.setItem(ee.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Z.getItem(ee.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=z.getBalanceCache();Z.setItem(ee.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const s=z.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),z.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=z.getNativeBalanceCache();e[t.caipAddress]=t,Z.setItem(ee.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Z.getItem(ee.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const s=z.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;z.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=z.getEnsCache();e[t.address]=t,Z.setItem(ee.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=z.getEnsCache();Z.setItem(ee.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Z.getItem(ee.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=z.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;z.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=z.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Z.setItem(ee.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=z.getIdentityCache();Z.setItem(ee.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Z.removeItem(ee.PORTFOLIO_CACHE),Z.removeItem(ee.NATIVE_BALANCE_CACHE),Z.removeItem(ee.ENS_CACHE),Z.removeItem(ee.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Z.setItem(ee.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Z.getItem(ee.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s={...z.getConnections(),[e]:t};Z.setItem(ee.CONNECTIONS,JSON.stringify(s))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=Z.getItem(ee.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}}},X={isMobile(){return this.isClient()?!!(typeof window?.matchMedia=="function"&&window?.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return X.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=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?.self!==window?.top}catch{return!1}},isSafeApp(){if(X.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const s=new URL(t),r=new URL(e);return s.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Ee.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let s;return(...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(X.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?.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(!X.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()?z.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window.matchMedia?.("(display-mode: standalone)")?.matches,e=window?.navigator?.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,X.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){let s;if(t==="0")s="0";else if(typeof t=="string"){const r=Number(t);r&&(s=r.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}
2return{value:s??"0",rest:s==="0"?"000":"",symbol:e}},getApiUrl(){return W.W3M_API_URL},getBlockchainApiUrl(){return W.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return W.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const s={};return e&&t&&(t.forEach((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 W.CHAIN_NAME_MAP},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const 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 ci(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class gn{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 ci(n,{method:"GET",headers:e,signal:s,cache:r})).json()}async getBlob({headers:e,signal:s,...r}){const i=this.createUrl(r);return(await ci(i,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await ci(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 ci(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 ci(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 cp={getFeatureValue(t,e){const s=e?.[t];return s===void 0?Ee.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(X.isTelegram()){if(X.isIos())return t.filter(e=>e!=="google");if(X.isMac())return t.filter(e=>e!=="x");if(X.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},K=Se({features:Ee.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Ee.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),k={state:K,subscribeKey(t,e){return tt(K,t,e)},setOptions(t){Object.assign(K,t)},setRemoteFeatures(t){if(!t)return;const e={...K.remoteFeatures,...t};K.remoteFeatures=e,K.remoteFeatures?.socials&&(K.remoteFeatures.socials=cp.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 Di(K)}},lp=Object.freeze({enabled:!0,events:[]}),up=new gn({baseUrl:X.getAnalyticsUrl(),clientId:null}),dp=5,hp=60*1e3,gs=Se({...lp}),pp={state:gs,subscribeKey(t,e){return tt(gs,t,e)},async sendError(t,e){if(!gs.enabled)return;const s=Date.now();if(gs.events.filter(n=>{const o=new Date(n.properties.timestamp||"").getTime();return s-o<hp}).length>=dp)return;const i={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};gs.events.push(i);try{if(typeof window>"u")return;const{projectId:n,sdkType:o,sdkVersion:a}=k.state;await up.post({path:"/e",params:{projectId:n,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:X.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){gs.enabled=!0},disable(){gs.enabled=!1},clearEvents(){gs.events=[]}};class jr extends Error{constructor(e,s,r){super(e),this.name="AppKitError",this.category=s,this.originalError=r,Object.setPrototypeOf(this,jr.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,jr):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function fc(t,e){const s=t instanceof jr?t:new jr(t instanceof Error?t.message:String(t),e,t);throw pp.sendError(s,s.category),s}function It(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 fc(a,e)}}:n=(...o)=>{try{return i(...o)}catch(a){return fc(a,e)}},s[r]=n}else s[r]=i}),s}const Gt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},fp={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,r=encodeURIComponent(s);if(t===Gt.PHANTOM.id&&!("phantom"in window)){const i=s.startsWith("https")?"https":"http",n=s.split("/")[2],o=encodeURIComponent(`${i}://${n}`);window.location.href=`${Gt.PHANTOM.url}/ul/browse/${r}?ref=${o}`}t===Gt.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Gt.SOLFLARE.url}/ul/v1/browse/${r}?ref=${r}`),e===W.CHAIN.SOLANA&&t===Gt.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Gt.COINBASE.url}/dapp?cb_url=${r}`)}}
4,ft=Se({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),gp={state:ft,subscribeNetworkImages(t){return et(ft.networkImages,()=>t(ft.networkImages))},subscribeKey(t,e){return tt(ft,t,e)},subscribe(t){return et(ft,()=>t(ft))},setWalletImage(t,e){ft.walletImages[t]=e},setNetworkImage(t,e){ft.networkImages[t]=e},setChainImage(t,e){ft.chainImages[t]=e},setConnectorImage(t,e){ft.connectorImages={...ft.connectorImages,[t]:e}},setTokenImage(t,e){ft.tokenImages[t]=e},setCurrencyImage(t,e){ft.currencyImages[t]=e}},Lt=It(gp),mp={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},vo=Se({networkImagePromises:{}}),Uu={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||(vo.networkImagePromises[t]||(vo.networkImagePromises[t]=V._fetchNetworkImage(t)),await vo.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return Lt.state.walletImages[t]},getWalletImage(t){if(t?.image_url)return t?.image_url;if(t?.image_id)return Lt.state.walletImages[t.image_id]},getNetworkImage(t){if(t?.assets?.imageUrl)return t?.assets?.imageUrl;if(t?.assets?.imageId)return Lt.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return Lt.state.networkImages[t]},getConnectorImage(t){if(t?.imageUrl)return t.imageUrl;if(t?.imageId)return Lt.state.connectorImages[t.imageId]},getChainImage(t){return Lt.state.networkImages[mp[t]]}},ms=Se({message:"",variant:"info",open:!1}),wp={state:ms,subscribeKey(t,e){return tt(ms,t,e)},open(t,e){const{debug:s}=k.state,{shortMessage:r,longMessage:i}=t;s&&(ms.message=r,ms.variant=e,ms.open=!0),i&&console.error(typeof i=="function"?i():i)},close(){ms.open=!1,ms.message="",ms.variant="info"}},qs=It(wp),yp=X.getAnalyticsUrl(),bp=new gn({baseUrl:yp,clientId:null}),vp=["MODAL_CREATED"],ts=Se({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Oe={state:ts,subscribe(t){return et(ts,()=>t(ts))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=k.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(t){try{const e=F.state.address;if(vp.includes(t.data.event)||typeof window>"u")return;await bp.post({path:"/e",params:Oe.getSdkProperties(),body:{eventId:X.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e}}}),ts.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===W.HTTP_STATUS_CODES.FORBIDDEN&&!ts.reportedErrors.FORBIDDEN&&(qs.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${wi()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),ts.reportedErrors.FORBIDDEN=!0)}},sendEvent(t){ts.timestamp=Date.now(),ts.data=t,k.state.features?.anal
4ytics&&Oe._sendAnalyticsEvent(ts)}},Ep=X.getApiUrl(),nt=new gn({baseUrl:Ep,clientId:null}),Cp=40,gc=4,Ip=20,te=Se({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),V={state:te,subscribeKey(t,e){return tt(te,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=k.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return k.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${nt.baseUrl}/getWalletImage/${t}`,s=await nt.getBlob({path:e,params:V._getSdkProperties()});Lt.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${nt.baseUrl}/public/getAssetImage/${t}`,s=await nt.getBlob({path:e,params:V._getSdkProperties()});Lt.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${nt.baseUrl}/public/getAssetImage/${t}`,s=await nt.getBlob({path:e,params:V._getSdkProperties()});Lt.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${nt.baseUrl}/public/getCurrencyImage/${t}`,s=await nt.getBlob({path:e,params:V._getSdkProperties()});Lt.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${nt.baseUrl}/public/getTokenImage/${t}`,s=await nt.getBlob({path:e,params:V._getSdkProperties()});Lt.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){return X.isMobile()?t?.filter(s=>s.mobile_link||s.id===Gt.COINBASE.id?!0:m.state.activeChain==="solana"&&(s.id===Gt.SOLFLARE.id||s.id===Gt.PHANTOM.id)):t},async fetchProjectConfig(){return(await nt.get({path:"/appkit/v1/config",params:V._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await nt.get({path:"/projects/v1/origins",params:V._getSdkProperties()});return t}catch{return[]}},async fetchNetworkImages(){const e=m.getAllRequestedCaipNetworks()?.map(({assets:s})=>s?.imageId).filter(Boolean).filter(s=>!Uu.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>V._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=B.state,e=t.map(({imageId:s}
vendor: 3,385 bytes, line 4
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){const e=t.exclude??[];V._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Gt).map(n=>n.id));const r=await nt.get({path:"/getWallets",params:{...V._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:t.include?.join(","),exclude:e.join(",")}});return{data:V._filterWalletsByPlatform(r?.data)||[],count:r?.count}},async fetchFeaturedWallets(){const{featuredWalletIds:t}=k.state;if(t?.length){const e={...V._getSdkProperties(),page:1,entries:t?.length??gc,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}=k.state,r=[...e??[],...s??[]].filter(Boolean),i=m.getRequestedCaipNetworkIds().join(","),n={page:1,entries:gc,include:t,exclude:r,chains:i},{data:o,count:a}=await V.fetchWallets(n),c=z.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}=k.state,i=m.getRequestedCaipNetworkIds().join(","),n=[...te.recommended.map(({id:u})=>u),...s??[],...r??[]].filter(Boolean),o={page:t,entries:Cp,include:e,exclude:n,chains:i},{data:a,count:c}=await V.fetchWallets(o),l=a.slice(0,Ip).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(l.map(u=>V._fetchWalletImage(u))),te.wallets=X.uniqueBy([...te.wallets,...V._filterOutExtensions(a)],"id").filter(u=>u.chains?.some(d=>i.includes(d))),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}=k.state,i=m.getRequestedCaipNetworkIds().join(",");te.search=[];const n={page:1,entries:100,search:t?.trim(),badge_type:e,include:s,exclude:r,chains:i},{data:o}=await V.fetchWallets(n);Oe.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)),X.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)}
4,prefetchAnalyticsConfig(){k.state.features?.analytics&&V.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await nt.get({path:"/getAnalyticsConfig",params:V._getSdkProperties()});k.setFeatures({analytics:t})}catch{k.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!t?.length){te.featured=te.allFeatured,te.recommended=te.allRecommended;return}const e=m.getRequestedCaipNetworkIds().join(",");te.featured=te.allFeatured.filter(s=>s.chains?.some(r=>e.includes(r))),te.recommended=te.allRecommended.filter(s=>s.chains?.some(r=>e.includes(r))),te.filteredWallets=te.wallets.filter(s=>s.chains?.some(r=>e.includes(r)))},clearFilterByNamespaces(){te.filteredWallets=[]},setFilterByNamespace(t){if(!t){te.featured=te.allFeatured,te.recommended=te.allRecommended;return}const e=m.getRequestedCaipNetworkIds().join(",");te.featured=te.allFeatured.filter(s=>s.chains?.some(r=>e.includes(r))),te.recommended=te.allRecommended.filter(s=>s.chains?.some(r=>e.includes(r))),te.filteredWallets=te.wallets.filter(s=>s.chains?.some(r=>e.includes(r)))}},we=Se({view:"Connect",history:["Connect"],transactionStack:[]}),Ap={state:we,subscribeKey(t,e){return tt(we,t,e)},pushTransactionStack(t){we.transactionStack.push(t)},popTransactionStack(t){const e=we.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:r,onCancel:i}=e;switch(t){case"success":s?.();break;case"error":r?.(),ie.goBack();break;case"cancel":i?.(),ie.goBack();break}},push(t,e){t!==we.view&&(we.view=t,we.history.push(t),we.data=e)},reset(t,e){we.view=t,we.history=[t],we.data=e},replace(t,e){we.history.at(-1)===t||(we.view=t,we.history[we.history.length-1]=t,we.data=e)},goBack(){const t=m.state.activeCaipAddress,e=ie.state.view==="ConnectingFarcaster",s=!t&&e;if(we.history.length>1){we.history.pop();const[r]=we.history.slice(-1);r&&(t&&r==="Connect"?we.view="Account":we.view=r)}else We.close();we.data?.wallet&&(we.data.wallet=void 0),setTimeout(()=>{if(s){F.setFarcasterUrl(void 0,m.state.activeChain);const r=B.getAuthConnector();r?.provider?.reload();const i=Di(k.state);r?.provider?.syncDappData?.({metadata:i.metadata,sdkVersion:i.sdkVersion,projectId:i.projectId,sdkType:i.sdkType})}},100)},goBackToIndex(t){if(we.history.length>1){we.history=we.history.slice(0,t+1);const[e]=we.history.slice(-1);e&&(we.view=e)}},goBackOrCloseModal(){ie.state.history.length>1?ie.goBack():We.close()}},ie=It(Ap),ss=Se({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),ta={state:ss,subscribe(t){return et(ss,()=>t(ss))},setThemeMode(t){ss.themeMode=t;try{const e=B.getAuthConnector();if(e){const s=ta.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:As(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=ta.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:As(ss.themeVariables,ss.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Di(ss)}},wt=It(ta),Du={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},ce=Se({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...Du},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),Np={state:ce,subscribe(t){return et(ce,()=>{t(ce)})},subscribeKey(t,e){return tt(ce,t,e)},initialize(t){t.forEach(e=>{const s=z.getConnectedConnectorId(e);s&&B.setConnectorId(s,e)})},setActiveConnector(t){t&&(ce.activeConnector=Qs(t))},setConnectors(t){t.filter(i=>!ce.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"&&ce.allConnectors.push(Qs(i))});const s=B.getEnabledNamespaces(),r=B.getEnabledConnectors(s);ce.connectors=B.mergeMultiChainConnectors(r)},filterByNamespaces(t){Object.keys(ce.filterByNamespaceMap).forEach(e=>{ce.filterByNamespaceMap[e]=!1}),t.forEach(e=>{ce.filterByNamespaceMap[e]=!0}),B.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){ce.filterByNamespaceMap[t]=e,B.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=B.getEnabledNamespaces(),e=B.getEnabledConnectors(t),s=B.areAllNamespacesEnabled();ce.connectors=B.mergeMultiChainConnectors(e),s?V.clearFilterByNamespaces():V.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(ce.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return ce.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(ce.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=B.generateConnectorMapByName(t),s=[];return e.forEach(r=>{const i=r[0],n=i?.id===W.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?.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){if(t.id===W.CONNECTOR_ID.AUTH){const e=t,s=Di(k.state),r=wt.getSnapshot().themeMode,i=wt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,projectId:s.projectId,sdkType:s.sdkType}),e?.provider?.syncTheme({themeMode:r,themeVariables:i,w3mThemeVariables:As(i,r)}),B.setConnectors([t])}else B.setConnectors([t])},getAuthConnector(t){const e=t||m.state.activeChain,s=ce.connectors.find(r=>r.id===W.CONNECTOR_ID.AUTH);if(s)return s?.connectors?.length?s.connectors.find(i=>i.chain===e):s},getAnnouncedConnectorRdns(){return ce.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>t.info?.rdns)},getConnectorById(t){return ce.allConnectors.find(e=>e.id===t)},getConnector(t,e){return ce.allConnectors.filter(r=>r.chain===m.state.activeChain).find(r=>r.explorerId===t||r.info?.rdns===e)},syncIfAuthConnector(t){if(t.id!=="ID_AUTH")return;const e=t,s=Di(k.state),r=wt.getSnapshot().themeMode,i=wt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:r,themeVariables:i,w3mThemeVariables:As(i,r)})},getConnectorsByNamespace(t){const e=ce.allConnectors.filter(s=>s.chain===t);return B.mergeMultiChainConnectors(e)},selectWalletConnector(t){const e=B.getConnector(t.id,t.rdns),s=m.state.activeChain;fp.handleMobileDeeplinkRedirect(e?.explorerId||t.id,s),e?ie.push("ConnectingExter
4nal",{connector:e}):ie.push("ConnectingWalletConnect",{wallet:t})},getConnectors(t){return t?B.getConnectorsByNamespace(t):B.mergeMultiChainConnectors(ce.allConnectors)},setFilterByNamespace(t){ce.filterByNamespace=t,ce.connectors=B.getConnectors(t),V.setFilterByNamespace(t)},setConnectorId(t,e){t&&(ce.activeConnectorIds={...ce.activeConnectorIds,[e]:t},z.setConnectedConnectorId(e,t))},removeConnectorId(t){ce.activeConnectorIds={...ce.activeConnectorIds,[t]:void 0},z.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return ce.activeConnectorIds[t]},isConnected(t){return t?!!ce.activeConnectorIds[t]:Object.values(ce.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){ce.activeConnectorIds={...Du}}},B=It(Np),Ai={ACCOUNT_TYPES:{SMART_ACCOUNT:"smartAccount"}},js=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),De=Se({...js}),_p={state:De,subscribeKey(t,e){return tt(De,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=X.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){De.message=js.message,De.variant=js.variant,De.svg=js.svg,De.open=js.open,De.autoClose=js.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:r=js.autoClose}){De.open?(De.open=!1,setTimeout(()=>{De.message=t,De.variant=s,De.svg=e,De.open=!0,De.autoClose=r},150)):(De.message=t,De.variant=s,De.svg=e,De.open=!0,De.autoClose=r)}},jt=_p,Ie=Se({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Sp={state:Ie,subscribe(t){return et(Ie,()=>t(Ie))},setLastNetworkInView(t){Ie.lastNetworkInView=t},async fetchTransactions(t,e){if(!t)throw new Error("Transactions can't be fetched without an accountAddress");Ie.loading=!0;try{const s=await J.fetchTransactions({account:t,cursor:Ie.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:m.state.activeCaipNetwork?.caipNetworkId}),r=bi.filterSpamTransactions(s.data),i=bi.filterByConnectedChain(r),n=[...Ie.transactions,...i];Ie.loading=!1,e==="coinbase"?Ie.coinbaseTransactions=bi.groupTransactionsByYearAndMonth(Ie.coinbaseTransactions,s.data):(Ie.transactions=n,Ie.transactionsByYear=bi.groupTransactionsByYearAndMonth(Ie.transactionsByYear,i)),Ie.empty=n.length===0,Ie.next=s.next?s.next:void 0}catch{const r=m.state.activeChain;Oe.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:k.state.projectId,cursor:Ie.next,isSmartAccount:F.state.preferredAccountTypes?.[r]===Ai.ACCOUNT_TYPES.SMART_ACCOUNT}}),jt.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=>r.nft_info?.flags.is_spam===!0))},filterByConnectedChain(t){const e=m.state.activeCaipNetwork?.caipNetworkId;return t.filter(r=>r.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}},bi=It(Sp,"API_ERROR"),Ne=Se({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let Us;const Pp={state:Ne,subscribeKey(t,e){return tt(Ne,t,e)},_getClient(){return Ne._client},setClient(t){Ne._client=Qs(t)},async connectWalletConnect(){if(X.isTelegram()||X.isSafari()&&X.isIos()){if(Us){await Us,Us=void 0;return}if(!X.isPairingExpired(Ne?.wcPairingExpiry)){const t=Ne.wcUri;Ne.wcUri=t;return}Us=Y._getClient()?.connectWalletConnect?.().catch(()=>{}),Y.state.status="connecting",await Us,Us=void 0,Ne.wcPairingExpiry=void 0,Y.state.status="connected"}else await Y._getClient()?.connectWalletConnect?.()},async connectExternal(t,e,s=!0){await Y._getClient()?.connectExternal?.(t),s&&m.setActiveNamespace(e)},async reconnectExternal(t){await Y._getClient()?.reconnectExternal?.(t);const e=t.chain||m.state.activeChain;e&&B.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){We.setLoading(!0,m.state.activeChain);const s=B.getAuthConnector();s&&(F.setPreferredAccountType(t,e),await s.provider.setPreferredAccount(t),z.setPreferredAccountTypes(F.state.preferredAccountTypes??{[e]:t}),await Y.reconnectExternal(s),We.setLoading(!1,m.state.activeChain),Oe.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:m.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(t){return Y._getClient()?.signMessage(t)},parseUnits(t,e){return Y._getClient()?.parseUnits(t,e)},formatUnits(t,e){return Y._getClient()?.formatUnits(t,e)},async sendTransaction(t){return Y._getClient()?.sendTransaction(t)},async getCapabilities(t){return Y._getClient()?.getCapabilities(t)},async grantPermissions(t){return Y._getClient()?.grantPermissions(t)},async walletGetAssets(t){return Y._getClient()?.walletGetAssets(t)??{}},async estimateGas(t){return Y._getClient()?.estimateGas(t)},async writeContract(t){return Y._getClient()?.writeContract(t)},async getEnsAddress(t){return Y._getClient()?.getEnsAddress(t)},async getEnsAvatar(t){return Y._getClient()?.getEnsAvatar(t)},checkInstalled(t){return Y._getClient()?.checkInstalled?.(t)||!1},resetWcConnection(){Ne.wcUri=void 0,Ne.wcPairingExpiry=void 0,Ne.wcLinking=void 0,Ne.recentWallet=void 0,Ne.status="disconnected",bi.resetTransactions(),z.deleteWalletConnectDeepLink()},resetUri(){Ne.wcUri=void 0,Ne.wcPairingExpiry=void 0,Us=void 0},finalizeWcConnection(){const{wcLinking:t,recentWallet:e}=Y.state;t&&z.setWalletConnectDeepLink(t),e&&z.setAppKitRecent(e),Oe.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:t?"mobile":"qrcode",name:ie.state.data?.wallet?.name||"Unknown"}})},setWcBasic(t){Ne.wcBasic=t},setUri(t){Ne.wcUri=t,Ne.wcPairingExpiry=X.getPairingExpiry()},setWcLinking(t){Ne.wcLinking=t},setWcError(t){Ne.wcError=t,Ne.buffering=!1},setRecentWallet(t){Ne.recentWallet=t},setBuffering(t){Ne.buffering=t},setStatus(t){Ne.status=t},async disconnect(t){try{await Y._getClient()?.disconnect(t)}catch(e){throw new jr("Failed to disconnect","INTERNAL_SDK_ERROR",e)}},setConnections(t,e){Ne.connections.set(e,t)},switchAccount({connection:t,address:e,namespace:s}){if(B.state.activeConnectorIds[s]===t.connectorId){const n=m.state.activeCaipNetwork;if(n){const o=`${s}:${n.id}:${e}`;F.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=It(Pp),dr=Se({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),_s={state:dr,subscribe(t){return et(dr,()=>t(dr))},subscribeOpen(t){return tt(dr,"open",t)},set(t){Object.assign(dr,{...dr,...t})}};function Op(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 Eo={createBalance(t,e){const s={name:t.metadata.name||"",symbol
4: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 Op(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"}},mc={async getMyTokensWithBalance(t){const e=F.state.address,s=m.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){try{const s=Eo.getChainIdHexFromCAIP2ChainId(e.caipNetworkId);if(!(await Y.getCapabilities(t))?.[s]?.assetDiscovery?.supported)return null;const i=await Y.walletGetAssets({account:t,chainFilter:[s]});return Eo.isWalletGetAssetsResponse(i)?(i[s]||[]).map(o=>Eo.createBalance(o,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(t){return t?.map(e=>({...e,address:e?.address?e.address:m.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]}},ge=Se({tokenBalances:[],loading:!1}),kp={state:ge,subscribe(t){return et(ge,()=>t(ge))},subscribeKey(t,e){return tt(ge,t,e)},setToken(t){t&&(ge.token=Qs(t))},setTokenAmount(t){ge.sendTokenAmount=t},setReceiverAddress(t){ge.receiverAddress=t},setReceiverProfileImageUrl(t){ge.receiverProfileImageUrl=t},setReceiverProfileName(t){ge.receiverProfileName=t},setNetworkBalanceInUsd(t){ge.networkBalanceInUSD=t},setLoading(t){ge.loading=t},async sendToken(){try{switch(he.setLoading(!0),m.state.activeCaipNetwork?.chainNamespace){case"eip155":await he.sendEvmToken();return;case"solana":await he.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}finally{he.setLoading(!1)}},async sendEvmToken(){const t=m.state.activeChain,e=F.state.preferredAccountTypes?.[t];if(!he.state.sendTokenAmount||!he.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!he.state.token)throw new Error("A token is required");he.state.token?.address?(Oe.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Ai.ACCOUNT_TYPES.SMART_ACCOUNT,token:he.state.token.address,amount:he.state.sendTokenAmount,network:m.state.activeCaipNetwork?.caipNetworkId||""}}),await he.sendERC20Token({receiverAddress:he.state.receiverAddress,tokenAddress:he.state.token.address,sendTokenAmount:he.state.sendTokenAmount,decimals:he.state.token.quantity.decimals})):(Oe.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Ai.ACCOUNT_TYPES.SMART_ACCOUNT,token:he.state.token.symbol||"",amount:he.state.sendTokenAmount,network:m.state.activeCaipNetwork?.caipNetworkId||""}}),await he.sendNativeToken({receiverAddress:he.state.receiverAddress,sendTokenAmount:he.state.sendTokenAmount,decimals:he.state.token.quantity.decimals}))},async fetchTokenBalance(t){ge.loading=!0;const e=m.state.activeCaipNetwork?.caipNetworkId,s=m.state.activeCaipNetwork?.chainNamespace,r=m.state.activeCaipAddress,i=r?X.getPlainAddress(r):void 0;if(ge.lastRetry&&!X.isAllowedRetry(ge.lastRetry,30*Ee.ONE_SEC_MS))return ge.loading=!1,[];try{if(i&&e&&s){const n=await mc.getMyTokensWithBalance();return ge.tokenBalances=n,ge.lastRetry=void 0,n}}catch(n){ge.lastRetry=Date.now(),t?.(n),jt.showError("Token Balance Unavailable")}finally{ge.loading=!1}return[]},fetchNetworkBalance(){if(ge.tokenBalances.length===0)return;const t=mc.mapBalancesToSwapTokens(ge.tokenBalances);if(!t)return;const e=t.find(s=>
4s.address===m.getActiveNetworkTokenAddress());e&&(ge.networkBalanceInUSD=e?Yh.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){ie.pushTransactionStack({});const e=t.receiverAddress,s=F.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)}),Oe.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:F.state.preferredAccountTypes?.eip155===Ai.ACCOUNT_TYPES.SMART_ACCOUNT,token:he.state.token?.symbol||"",amount:t.sendTokenAmount,network:m.state.activeCaipNetwork?.caipNetworkId||""}}),Y._getClient()?.updateBalance("eip155"),he.resetSend()},async sendERC20Token(t){ie.pushTransactionStack({onSuccess(){ie.replace("Account")}});const e=Y.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));if(F.state.address&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const s=X.getPlainAddress(t.tokenAddress);await Y.writeContract({fromAddress:F.state.address,tokenAddress:s,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:ep.getERC20Abi(s),chainNamespace:"eip155"}),he.resetSend()}},async sendSolanaToken(){if(!he.state.sendTokenAmount||!he.state.receiverAddress)throw new Error("An amount and receiver address are required");ie.pushTransactionStack({onSuccess(){ie.replace("Account")}}),await Y.sendTransaction({chainNamespace:"solana",to:he.state.receiverAddress,value:he.state.sendTokenAmount}),Y._getClient()?.updateBalance("solana"),he.resetSend()},resetSend(){ge.token=void 0,ge.sendTokenAmount=void 0,ge.receiverAddress=void 0,ge.receiverProfileImageUrl=void 0,ge.receiverProfileName=void 0,ge.loading=!1,ge.tokenBalances=[]}},he=It(kp),Co={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},_n={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},L=Se({chains:op(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),Tp={state:L,subscribe(t){return et(L,()=>{t(L)})},subscribeKey(t,e){return tt(L,t,e)},subscribeChainProp(t,e,s){let r;return et(L.chains,()=>{const i=s||L.activeChain;if(i){const n=L.chains.get(i)?.[t];r!==n&&(r=n,e(n))}})},initialize(t,e,s){const{chainId:r,namespace:i}=z.getActiveNetworkProps(),n=e?.find(u=>u.id.toString()===r?.toString()),a=t.find(u=>u?.namespace===i)||t?.[0],c=t.map(u=>u.namespace).filter(u=>u!==void 0),l=k.state.enableEmbedded?new Set([...c]):new Set([...e?.map(u=>u.chainNamespace)??[]]);(t?.length===0||!a)&&(L.noAdapters=!0),L.noAdapters||(L.activeChain=a?.namespace,L.activeCaipNetwork=n,m.setChainNetworkData(a?.namespace,{caipNetwork:n}),L.activeChain&&_s.set({activeChain:a?.namespace})),l.forEach(u=>{const d=e?.filter(h=>h.chainNamespace===u);m.state.chains.set(u,{namespace:u,networkState:Se({..._n,caipNetwork:d?.[0]}),accountState:Se(Co),caipNetworks:d??[],...s}),m.setRequestedCaipNetworks(d??[],u)})},removeAdapter(t){if(L.activeChain===t){const e=Array.from(L.chains.entries()).find(([s])=>s!==t);if(e){const s=e[1]?.caipNetworks?.[0];s&&m.setActiveCaipNetwork(s)}}L.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:s},r){L.chains.set(t.namespace,{namespace:t.namespace,networkState:{..._n,caipNetwork:r[0]},accountState:Co,caipNetworks:r,connectionControllerClient:s,networkControllerClient:e}),m.setRequestedCaipNetworks(r?.filter(i=>i.chainNamespace===t.namespace)??[],t.namespace)},addNetwork(t){const e=L.chains.get(t.chainNamespace);if(e){const s=[...e.caipNetworks||[]];e.caipNetworks?.find(r=>r.id===t.id)||s.push(t),L.chains.set(t.chainNamespace,{...e,caipNetworks:s}),m.setRequestedCaipNetworks(s,t.chainNamespace),B.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){const s=L.chains.get(t);if(s){const r=L.activeCaipNetwork?.id===e,i=[...s.caipNetworks?.filter(n=>n.id!==e)||[]];r&&s?.caipNetworks?.[0]&&m.setActiveCaipNetwork(s.caipNetworks[0]),L.chains.set(t,{...s,caipNetworks:i}),m.setRequestedCaipNetworks(i||[],t),i.length===0&&B.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=L.chains.get(t);s&&(s.networkState={...s.networkState||_n,...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||Co,...e};L.chains.set(t,{...r,accountState:i}),(L.chains.size===1||L.activeChain===t)&&(e.caipAddress&&(L.activeCaipAddress=e.caipAddress),F.replaceState(i))}},setChainNetworkData(t,e){if(!t)return;const s=L.chains.get(t);if(s){const r={...s.networkState||_n,...e};L.chains.set(t,{...s,networkState:r})}}
4,setAccountProp(t,e,s,r=!0){m.setChainAccountData(s,{[t]:e},r),t==="status"&&e==="disconnected"&&s&&B.removeConnectorId(s)},setActiveNamespace(t){L.activeChain=t;const e=t?L.chains.get(t):void 0,s=e?.networkState?.caipNetwork;s?.id&&t&&(L.activeCaipAddress=e?.accountState?.caipAddress,L.activeCaipNetwork=s,m.setChainNetworkData(t,{caipNetwork:s}),z.setActiveCaipNetworkId(s?.caipNetworkId),_s.set({activeChain:t,selectedNetworkId:s?.caipNetworkId}))},setActiveCaipNetwork(t){if(!t)return;L.activeChain!==t.chainNamespace&&m.setIsSwitchingNamespace(!0);const e=L.chains.get(t.chainNamespace);L.activeChain=t.chainNamespace,L.activeCaipNetwork=t,m.setChainNetworkData(t.chainNamespace,{caipNetwork:t}),e?.accountState?.address?L.activeCaipAddress=`${t.chainNamespace}:${t.id}:${e?.accountState?.address}`:L.activeCaipAddress=void 0,m.setAccountProp("caipAddress",L.activeCaipAddress,t.chainNamespace),e&&F.replaceState(e.accountState),he.resetSend(),_s.set({activeChain:L.activeChain,selectedNetworkId:L.activeCaipNetwork?.caipNetworkId}),z.setActiveCaipNetworkId(t.caipNetworkId),!m.checkIfSupportedNetwork(t.chainNamespace)&&k.state.enableNetworkSwitch&&!k.state.allowUnsupportedChain&&!Y.state.wcBasic&&m.showUnsupportedChainUI()},addCaipNetwork(t){if(!t)return;const e=L.chains.get(t.chainNamespace);e&&e?.caipNetworks?.push(t)},async switchActiveNamespace(t){if(!t)return;const e=t!==m.state.activeChain,s=m.getNetworkData(t)?.caipNetwork,r=m.getCaipNetworkByNamespace(t,s?.id);e&&r&&await m.switchActiveNetwork(r)},async switchActiveNetwork(t){const s=!m.state.chains.get(m.state.activeChain)?.caipNetworks?.some(i=>i.id===L.activeCaipNetwork?.id),r=m.getNetworkControllerClient(t.chainNamespace);if(r){try{await r.switchCaipNetwork(t),s&&We.close()}catch{ie.goBack()}Oe.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?.connectionControllerClient)throw new Error("ConnectionController client not set");return s.connectionControllerClient},getAccountProp(t,e){let s=L.activeChain;if(e&&(s=e),!s)return;const r=L.chains.get(s)?.accountState;if(r)return r[t]},getNetworkProp(t,e){const s=L.chains.get(e)?.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=L.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:r=[]}=e?.networkState||{};return X.sortRequestedNetworks(s,r)},getAllRequestedCaipNetworks(){const t=[];return L.chains.forEach(e=>{const s=m.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){m.setAdapterNetworkState(e,{requestedCaipNetworks:t});const r=m.getAllRequestedCaipNetworks().map(n=>n.chainNamespace),i=Array.from(new Set(r));B.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const t=[];return L.chains.forEach(e=>{const s=m.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(){return L.activeCaipNetwork},getActiveCaipAddress(){return L.activeCaipAddress},getApprovedCaipNetworkIds(t){return L.chains.get(t)?.networkState?.approvedCaipNetworkIds||[]},async setApprovedCaipNetworksData(t){const s=await m.getNetworkControllerClient()?.getApprovedCaipNetworksData();m.setAdapterNetworkState(t,{approvedCaipNetworkIds:s?.approvedCaipNetworkIds,supportsAllNetworks:s?.supportsAllNetworks})},checkIfSupportedNetwork(t,e){const s=e||L.activeCaipNetwork,r=m.getRequestedCaipNetworks(t);return r.length?r?.some(i=>i.id===s?.id):!0},checkIfSupportedChainId(t){return L.activeChain?m.getRequestedCaipNetworks(L.activeChain)?.some(s=>s.id===t):!0},setSmartAccountEnabledNetworks(t,e){m.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){const t=Tu.caipNetworkIdToNumber(L.activeCaipNetwork?.caipNetworkId),e=L.activeChain;return!e||!t?!1:!!m.getNetworkProp("smartAccountEnabledNetworks",e)?.includes(Number(t))},getActiveNetworkTokenAddress(){const t=L.activeCaipNetwork?.chainNamespace||"eip155",e=L.activeCaipNetwork?.id||1,s=Ee.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`},showUnsupportedChainUI(){We.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=L.activeCaipNetwork;return!!(t?.chainNamespace&&Ee.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){m.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,m.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol
vendor: 8,859 bytes, line 4
4: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(){const t=[];let e;if(L.chains.forEach(s=>{W.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(r=>r===s.namespace)&&s.namespace&&t.push(s.namespace)}),t.length>0){const s=t[0];return e=s?L.chains.get(s)?.caipNetworks?.[0]:void 0,e}},getAccountData(t){return t?m.state.chains.get(t)?.accountState:F.state},getNetworkData(t){const e=t||L.activeChain;if(e)return m.state.chains.get(e)?.networkState},getCaipNetworkByNamespace(t,e){if(!t)return;const s=m.state.chains.get(t),r=s?.caipNetworks?.find(i=>i.id===e);return r||s?.networkState?.caipNetwork||s?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const t=B.state.filterByNamespace;return(t?[L.chains.get(t)]:Array.from(L.chains.values())).flatMap(s=>s?.caipNetworks||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?m.getRequestedCaipNetworks(t):m.getAllRequestedCaipNetworks()}},m=It(Tp),xp={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"}]}]},Mu=X.getBlockchainApiUrl(),ot=Se({clientId:null,api:new gn({baseUrl:Mu,clientId:null}),supportedChains:{http:[],ws:[]}}),J={state:ot,async get(t){const{st:e,sv:s}=J.getSdkProperties(),r=k.state.projectId,i={...t.params||{},st:e,sv:s,projectId:r};return ot.api.get({...t,params:i})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=k.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{ot.supportedChains.http.length||await J.getSupportedNetworks()}catch{return!1}return ot.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await J.get({path:"v1/supported-chains"});return ot.supportedChains=t,t}catch{return ot.supportedChains}},async fetchIdentity({address:t,caipNetworkId:e}){if(!await J.isNetworkSupported(e))return{avatar:"",name:""};const r=z.getIdentityFromCacheForAddress(t);if(r)return r;const i=await J.get({path:`/v1/identity/${t}`,params:{sender:m.state.activeCaipAddress?X.getPlainAddress(m.state.activeCaipAddress):void 0}});return z.updateIdentityCache({address:t,identity:i,timestamp:Date.now()}),i},async fetchTransactions({account:t,cursor:e,onramp:s,signal:r,cache:i,chainId:n}){return await J.isNetworkSupported(m.state.activeCaipNetwork?.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}){return await J.isNetworkSupported(m.state.activeCaipNetwork?.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}){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?J.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ot.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:k.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?J.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){const{st:e,sv:s}=J.getSdkProperties();if(!await J.isNetworkSupported(m.state.activeCaipNetwork?.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}){if(!await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ot.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:Ee.CONVERT_SLIPPAGE_TOLERANCE},projectId:k.state.projectId,from:e,to:s,userAddress:r,disableEstimate:i}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){const{st:r,sv:i}=J.getSdkProperties();if(!await J.isNetworkSupported(m.state.activeCaipNetwork?.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){const{st:r,sv:i}=J.getSdkProperties();if(!await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))return jt.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=z.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 z.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?J.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?J.get({path:`/v1/profile/reverse/${t}`,params:{sender:F.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(t){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?J.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:r}){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ot.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}){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?(await ot.api.post({path:"/v1/generators/onrampurl",params:{projectId:k.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:r,presetFiatAmount:i}})).url:""},async getOnrampOptions(){if(!await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await J.get({path:"/v1/onramp/options"})}catch{return xp}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:r}){try{return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?await ot.api.post({path:"/v1/onramp/quote",params:{projectId:k.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){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?J.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){return await J.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ot.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:k.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){ot.clientId=t,ot.api=new gn({baseUrl:Mu,clientId:t})}},Nt=Se({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),$p={state:Nt,replaceState(t){t&&Object.assign(Nt,Qs(t))},subscribe(t){return m.subscribeChainProp("accountState",e=>
4{if(e)return t(e)})},subscribeKey(t,e,s){let r;return m.subscribeChainProp("accountState",i=>{if(i){const n=i[t];r!==n&&(r=n,e(n))}},s)},setStatus(t,e){m.setAccountProp("status",t,e)},getCaipAddress(t){return m.getAccountProp("caipAddress",t)},setCaipAddress(t,e){const s=t?X.getPlainAddress(t):void 0;e===m.state.activeChain&&(m.state.activeCaipAddress=t),m.setAccountProp("caipAddress",t,e),m.setAccountProp("address",s,e)},setBalance(t,e,s){m.setAccountProp("balance",t,s),m.setAccountProp("balanceSymbol",e,s)},setProfileName(t,e){m.setAccountProp("profileName",t,e)},setProfileImage(t,e){m.setAccountProp("profileImage",t,e)},setUser(t,e){m.setAccountProp("user",t,e)},setAddressExplorerUrl(t,e){m.setAccountProp("addressExplorerUrl",t,e)},setSmartAccountDeployed(t,e){m.setAccountProp("smartAccountDeployed",t,e)},setCurrentTab(t){m.setAccountProp("currentTab",t,m.state.activeChain)},setTokenBalance(t,e){t&&m.setAccountProp("tokenBalance",t,e)},setShouldUpdateToAddress(t,e){m.setAccountProp("shouldUpdateToAddress",t,e)},setAllAccounts(t,e){m.setAccountProp("allAccounts",t,e)},addAddressLabel(t,e,s){const r=m.getAccountProp("addressLabels",s)||new Map;r.set(t,e),m.setAccountProp("addressLabels",r,s)},removeAddressLabel(t,e){const s=m.getAccountProp("addressLabels",e)||new Map;s.delete(t),m.setAccountProp("addressLabels",s,e)},setConnectedWalletInfo(t,e){m.setAccountProp("connectedWalletInfo",t,e,!1)},setPreferredAccountType(t,e){m.setAccountProp("preferredAccountTypes",{...Nt.preferredAccountTypes,[e]:t},e)},setPreferredAccountTypes(t){Nt.preferredAccountTypes=t},setSocialProvider(t,e){t&&m.setAccountProp("socialProvider",t,e)},setSocialWindow(t,e){m.setAccountProp("socialWindow",t?Qs(t):void 0,e)},setFarcasterUrl(t,e){m.setAccountProp("farcasterUrl",t,e)},async fetchTokenBalance(t){Nt.balanceLoading=!0;const e=m.state.activeCaipNetwork?.caipNetworkId,s=m.state.activeCaipNetwork?.chainNamespace,r=m.state.activeCaipAddress,i=r?X.getPlainAddress(r):void 0;if(Nt.lastRetry&&!X.isAllowedRetry(Nt.lastRetry,30*Ee.ONE_SEC_MS))return Nt.balanceLoading=!1,[];try{if(i&&e&&s){const o=(await J.getBalance(i,e)).balances.filter(a=>a.quantity.decimals!=="0");return F.setTokenBalance(o,s),Nt.lastRetry=void 0,Nt.balanceLoading=!1,o}}catch(n){Nt.lastRetry=Date.now(),t?.(n),jt.showError("Token Balance Unavailable")}finally{Nt.balanceLoading=!1}return[]},resetAccount(t){m.resetAccount(t)}},F=It($p),Rp={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const s=m.state.activeCaipNetwork,r=ie.state.data;if(t.id===s?.id)return;const n=F.getCaipAddress(m.state.activeChain),o=t.chainNamespace!==m.state.activeChain,a=F.getCaipAddress(t.chainNamespace),l=B.getConnectorId(m.state.activeChain)===W.CONNECTOR_ID.AUTH,u=W.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(d=>d===t.chainNamespace);e||l&&u?ie.push("SwitchNetwork",{...r,network:t}):n&&o&&!a?ie.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):ie.push("SwitchNetwork",{...r,network:t})}},at=Se({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),Up={state:at,subscribe(t){return et(at,()=>t(at))},subscribeKey(t,e){return tt(at,t,e)},async open(t){const e=F.state.status==="connected",s=t?.namespace,r=m.state.activeChain,i=s&&s!==r,n=m.getAccountData(t?.namespace)?.caipAddress;if(Y.state.wcBasic?V.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await V.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),B.setFilterByNamespace(t?.namespace),We.setLoading(!0,s),s&&i){const o=m.getNetworkData(s)?.caipNetwork||m.getRequestedCaipNetworks(s)[0];o&&Rp.onSwitchNetwork({network:o,ignoreSwitchConfirmation:!0})}else{const o=m.state.noAdapters;k.state.manualWCControl||o&&!n?X.isMobile()?ie.reset("AllWallets"):ie.reset("ConnectingWalletConnectBasic"):t?.view?ie.reset(t.view,t.data):n?ie.reset("Account"):ie.reset("Connect")}
4at.open=!0,_s.set({open:!0}),Oe.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!n}})},close(){const t=k.state.enableEmbedded,e=!!m.state.activeCaipAddress;at.open&&Oe.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),at.open=!1,ie.reset("Connect"),We.clearLoading(),t?e?ie.replace("Account"):ie.push("Connect"):_s.set({open:!1}),Y.resetUri()},setLoading(t,e){e&&at.loadingNamespaceMap.set(e,t),at.loading=t,_s.set({loading:t})},clearLoading(){at.loadingNamespaceMap.clear(),at.loading=!1},shake(){at.shake||(at.shake=!0,setTimeout(()=>{at.shake=!1},500))}},We=It(Up),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"}]},sa={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},Dp={providers:Ru,selectedProvider:null,error:null,purchaseCurrency:Ni,paymentCurrency:sa,purchaseCurrencies:[Ni],paymentCurrencies:[],quotesLoading:!1},ae=Se(Dp),Mp={state:ae,subscribe(t){return et(ae,()=>t(ae))},subscribeKey(t,e){return tt(ae,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=m.state.activeChain===W.CHAIN.SOLANA?"SOL":"USDC",s=F.state.address??"",r=new URL(t.url);r.searchParams.append("publicKey",ap),r.searchParams.append("destinationCurrencyCode",e),r.searchParams.append("walletAddress",s),r.searchParams.append("externalCustomerId",k.state.projectId),ae.selectedProvider={...t,url:r.toString()}}else ae.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=Ru.filter(r=>e.includes(r.name));ae.providers=s}else ae.providers=[]},setPurchaseCurrency(t){ae.purchaseCurrency=t},setPaymentCurrency(t){ae.paymentCurrency=t},setPurchaseAmount(t){ra.state.purchaseAmount=t},setPaymentAmount(t){ra.state.paymentAmount=t},async getAvailableCurrencies(){const t=await J.getOnrampOptions();ae.purchaseCurrencies=t.purchaseCurrencies,ae.paymentCurrencies=t.paymentCurrencies,ae.paymentCurrency=t.paymentCurrencies[0]||sa,ae.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(){ae.quotesLoading=!0;try{const t=await J.getOnrampQuote({purchaseCurrency:ae.purchaseCurrency,paymentCurrency:ae.paymentCurrency,amount:ae.paymentAmount?.toString()||"0",network:ae.purchaseCurrency?.symbol});return ae.quotesLoading=!1,ae.purchaseAmount=Number(t?.purchaseAmount.amount),t}catch(t){return ae.error=t.message,ae.quotesLoading=!1,null}finally{ae.quotesLoading=!1}},resetState(){ae.selectedProvider=null,ae.error=null,ae.purchaseCurrency=Ni,ae.paymentCurrency=sa,ae.purchaseCurrencies=[Ni],ae.paymentCurrencies=[],ae.paymentAmount=void 0,ae.purchaseAmount=void 0,ae.quotesLoading=!1}},ra=It(Mp),wc=2147483648,Lp={convertEVMChainIdToCoinType(t){if(t>=wc)throw new Error("Invalid chainId");return(wc|t)>>>0}},_t=Se({suggestions:[],loading:!1}),jp={state:_t,subscribe(t){return et(_t,()=>t(_t))},subscribeKey(t,e){return tt(_t,t,e)},async resolveName(t){try{return await J.lookupEnsName(t)}catch(e){const s=e;throw new Error(s?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(t){try{return await J.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{_t.loading=!0,_t.suggestions=[];const e=await J.getEnsNameSuggestions(t);return _t.suggestions=e.suggestions.map(s=>({...s,name:s.name}))||[],_t.suggestions}catch(e){const s=_i.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{_t.loading=!1}},async getNamesForAddress(t){try{if(!m.state.activeCaipNetwork)return[];const s=z.getEnsFromCacheForAddress(t);if(s)return s;const r=await J.reverseLookupEnsName({address:t});return z.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=m.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const s=F.state.address,r=B.getAuthConnector();if(!s||!r)throw new Error("Address or auth connector not found");_t.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});ie.pushTransactionStack({onCancel(){ie.replace("RegisterAccountName")}});const n=await Y.signMessage(i);_t.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=Lp.convertEVMChainIdToCoinType(Number(o));await J.registerEnsName({coinType:a,address:s,signature:n,message:i}),F.setProfileName(t,e.chainNamespace),ie.replace("RegisterAccountNameSuccess")}catch(i){const n=_i.parseEnsApiError(i,`Error registering name ${t}`);throw ie.replace("RegisterAccountName"),new Error(n)}finally{_t.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){return t?.reasons?.[0]?.description||e}},_i=It(jp);var Bp=Object.defineProperty,qp=(t,e,s)=>e in t?Bp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yc=(t,e,s)=>qp(t,typeof e!="symbol"?e+"":e,s);let zp=class extends Qr{constructor(e){super(),this.opts=e,yc(this,"protocol","wc"),yc(this,"version",2)}};var Fp=Object.defineProperty,Wp=(t,e,s)=>e in t?Fp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Hp=(t,e,s)=>Wp(t,e+"",s);let Vp=class extends Qr{constructor(e,s){super(),this.core=e,this.logger=s,Hp(this,"records",new Map)}},Kp=class{constructor(e,s){this.logger=e,this.core=s}},Gp=class extends Qr{constructor(e,s){super(),this.relayer=e,this.logger=s}},Jp=class extends Qr{constructor(e){super()}},Yp=class{constructor(e,s,r,i){this.core=e,this.logger=s,this.name=r}},Xp=class extends Qr{constructor(e,s){super(),this.relayer=e,this.logger=s}},Zp=class extends Qr{constructor(e,s){super(),this.core=e,this.logger=s}},Qp=class{constructor(e,s,r){this.core=e,this.logger=s,this.store=r}},ef=class{constructor(e,s){this.projectId=e,this.logger=s}},tf=class{constructor(e,s,r){this.core=e,this.logger=s,this.telemetryEnabled=r}};var sf=Object.defineProperty,rf=(t,e,s)=>e in t?sf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,bc=(t,e,s)=>rf(t,typeof e!="symbol"?e+"":e,s);let nf=class{constructor(e){this.opts=e,bc(this,"protocol","wc"),bc(this,"version",2)}},of=class{constructor(e){this.client=e}};function Mi(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function vc(t){return Mi(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Lu="2.23.2";let Io={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${Lu}`}
4,ao=class ia extends Error{constructor(e,s={}){const r=s.cause instanceof ia?s.cause.details:s.cause?.message?s.cause.message:s.details,i=s.cause instanceof ia&&s.cause.docsPath||s.docsPath,n=Io.getDocsUrl?.({...s,docsPath:i}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...Io.version?[`Version: ${Io.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=Lu}walk(e){return ju(this,e)}};function ju(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?ju(t.cause,e):e?null:t}let Bu=class extends ao{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 ti(t,{dir:e,size:s=32}={}){return typeof t=="string"?af(t,{dir:e,size:s}):cf(t,{dir:e,size:s})}function af(t,{dir:e,size:s=32}={}){if(s===null)return t;const r=t.replace("0x","");if(r.length>s*2)throw new Bu({size:Math.ceil(r.length/2),targetSize:s,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function cf(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new Bu({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 lf=class extends ao{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"})}},uf=class extends ao{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function si(t,{size:e}){if(vc(t)>e)throw new uf({givenSize:vc(t),maxSize:e})}function na(t,e={}){const{signed:s}=e;e.size&&si(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 df(t,e={}){return Number(na(t,e))}const hf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function oa(t,e={}){return typeof t=="number"||typeof t=="bigint"?zu(t,e):typeof t=="string"?gf(t,e):typeof t=="boolean"?pf(t,e):qu(t,e)}function pf(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(si(s,{size:e.size}),ti(s,{size:e.size})):s}function qu(t,e={}){let s="";for(let i=0;i<t.length;i++)s+=hf[t[i]];const r=`0x${s}`;return typeof e.size=="number"?(si(r,{size:e.size}),ti(r,{dir:"right",size:e.size})):r}function zu(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 lf({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?ti(a,{size:r}):a}const ff=new TextEncoder;function gf(t,e={}){const s=ff.encode(t);return qu(s,e)}const mf=new TextEncoder;function wf(t,e={}){return typeof t=="number"||typeof t=="bigint"?bf(t,e):typeof t=="boolean"?yf(t,e):Mi(t)?Fu(t,e):Wu(t,e)}function yf(t,e={}){const s=new Uint8Array(1);return s[0]=Number(t),typeof e.size=="number"?(si(s,{size:e.size}),ti(s,{size:e.size})):s}const rs={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ec(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 Fu(t,e={}){let s=t;e.size&&(si(s,{size:e.size}),s=ti(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=Ec(r.charCodeAt(a++)),l=Ec(r.charCodeAt(a++));if(c===void 0||l===void 0)throw new ao(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);n[o]=c*16+l}return n}function bf(t,e){const s=zu(t,e);return Fu(s)}function Wu(t,e={}){const s=mf.encode(t);return typeof e.size=="number"?(si(s,{size:e.size}),ti(s,{dir:"right",size:e.size})):s}function Cc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vf(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function za(t,...e){if(!vf(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 Ic(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 Ef(t,e){za(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const Sn=BigInt(2**32-1),Ac=BigInt(32);function Cf(t,e=!1){return e?{h:Number(t&Sn),l:Number(t>>Ac&Sn)}:{h:Number(t>>Ac&Sn)|0,l:Number(t&Sn)|0}}
5function If(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}=Cf(t[i],e);[s[i],r[i]]=[n,o]}return[s,r]}const Af=(t,e,s)=>t<<s|e>>>32-s,Nf=(t,e,s)=>e<<s|t>>>32-s,_f=(t,e,s)=>e<<s-32|t>>>64-s,Sf=(t,e,s)=>t<<s-32|e>>>64-s;function Pf(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}const Nc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Of(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function _c(t){for(let e=0;e<t.length;e++)t[e]=Of(t[e])}function kf(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Hu(t){return typeof t=="string"&&(t=kf(t)),za(t),t}class Tf{clone(){return this._cloneInto()}}function xf(t){const e=r=>t().update(Hu(r)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}const Vu=[],Ku=[],Gu=[],$f=BigInt(0),li=BigInt(1),Rf=BigInt(2),Uf=BigInt(7),Df=BigInt(256),Mf=BigInt(113);for(let t=0,e=li,s=1,r=0;t<24;t++){[s,r]=[r,(2*s+3*r)%5],Vu.push(2*(5*r+s)),Ku.push((t+1)*(t+2)/2%64);let i=$f;for(let n=0;n<7;n++)e=(e<<li^(e>>Uf)*Mf)%Df,e&Rf&&(i^=li<<(li<<BigInt(n))-li);Gu.push(i)}const[Lf,jf]=If(Gu,!0),Sc=(t,e,s)=>s>32?_f(t,e,s):Af(t,e,s),Pc=(t,e,s)=>s>32?Sf(t,e,s):Nf(t,e,s);function Bf(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=Sc(l,u,1)^s[a],h=Pc(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=Ku[o],c=Sc(i,n,a),l=Pc(i,n,a),u=Vu[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]^=Lf[r],t[1]^=jf[r]}s.fill(0)}class Fa extends Tf{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,Cc(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Pf(this.state)}keccak(){Nc||_c(this.state32),Bf(this.state32,this.rounds),Nc||_c(this.state32),this.posOut=0,this.pos=0}update(e){Ic(this);const{blockLen:s,state:r}=this;e=Hu(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){Ic(this,!1),za(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 Cc(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ef(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 Fa(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 qf=(t,e,s)=>xf(()=>new Fa(e,t,s)),zf=qf(1,136,256/8);function Ju(t,e){const s=e||"hex",r=zf(Mi(t,{strict:!1})?wf(t):t);return s==="bytes"?r:oa(r)}let Ff=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 Ao=new Ff(8192);function Wf(t,e){if(Ao.has(`${t}.${e}`))return Ao.get(`${t}.${e}`);const s=t.substring(2).toLowerCase(),r=Ju(Wu(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 Ao.set(`${t}.${e}`,n),n}function Hf(t){const e=Ju(`0x${t.substring(4)}`).substring(26);return Wf(`0x${e}`)}async function Vf({hash:t,signature:e}){const s=Mi(t)?t:oa(t),{secp256k1:r}=await Zo(async()=>{const{secp256k1:o}=await import("./secp256k1-D7nWsfUE.js");return{secp256k1:o}},[]);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:d,yParity:h}
5=e,p=Number(h??d),w=Oc(p);return new r.Signature(na(l),na(u)).addRecoveryBit(w)}const o=Mi(e)?e:oa(e),a=df(`0x${o.slice(130)}`),c=Oc(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(s.substring(2)).toHex(!1)}`}function Oc(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 Kf({hash:t,signature:e}){return Hf(await Vf({hash:t,signature:e}))}function Gf(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<t.length;l++){const u=t.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const s=t.length,r=t.charAt(0),i=Math.log(s)/Math.log(256),n=Math.log(256)/Math.log(s);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,h=0;const p=l.length;for(;h!==p&&l[h]===0;)h++,u++;const w=(p-h)*n+1>>>0,g=new Uint8Array(w);for(;h!==p;){let y=l[h],v=0;for(let C=w-1;(y!==0||v<d)&&C!==-1;C--,v++)y+=256*g[C]>>>0,g[C]=y%s>>>0,y=y/s>>>0;if(y!==0)throw new Error("Non-zero carry");d=v,h++}let f=w-d;for(;f!==w&&g[f]===0;)f++;let b=r.repeat(u);for(;f<w;++f)b+=t.charAt(g[f]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,h=0;for(;l[u]===r;)d++,u++;const p=(l.length-u)*i+1>>>0,w=new Uint8Array(p);for(;u<l.length;){const y=l.charCodeAt(u);if(y>255)return;let v=e[y];if(v===255)return;let C=0;for(let A=p-1;(v!==0||C<h)&&A!==-1;A--,C++)v+=s*w[A]>>>0,w[A]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");h=C,u++}let g=p-h;for(;g!==p&&w[g]===0;)g++;const f=new Uint8Array(d+(p-g));let b=d;for(;g!==p;)f[b++]=w[g++];return f}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+s+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Jf="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Yf=Gf(Jf);var Xf={};const Zf=":";function Dr(t){const[e,s]=t.split(Zf);return{namespace:e,reference:s}}function Yu(t,e){return t.includes(":")?[t]:e.chains||[]}var Qf=Object.defineProperty,eg=Object.defineProperties,tg=Object.getOwnPropertyDescriptors,kc=Object.getOwnPropertySymbols,sg=Object.prototype.hasOwnProperty,rg=Object.prototype.propertyIsEnumerable,Tc=(t,e,s)=>e in t?Qf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xc=(t,e)=>{for(var s in e||(e={}))sg.call(e,s)&&Tc(t,s,e[s]);if(kc)for(var s of kc(e))rg.call(e,s)&&Tc(t,s,e[s]);return t},ig=(t,e)=>eg(t,tg(e));const ng="ReactNative",vt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},og="js";function Zn(){return typeof Ur<"u"&&typeof Ur.versions<"u"&&typeof Ur.versions.node<"u"}function $s(){return!ds.getDocument()&&!!ds.getNavigator()&&navigator.product===ng}function ag(){return $s()&&typeof re<"u"&&typeof(re==null?void 0:re.Platform)<"u"&&(re==null?void 0:re.Platform.OS)==="android"}function cg(){return $s()&&typeof re<"u"&&typeof(re==null?void 0:re.Platform)<"u"&&(re==null?void 0:re.Platform.OS)==="ios"}function ri(){return!Zn()&&!!ds.getNavigator()&&!!ds.getDocument()}function mn(){return $s()?vt.reactNative:Zn()?vt.node:ri()?vt.browser:vt.unknown}function $c(){var t;try{return $s()&&typeof re<"u"&&typeof(re==null?void 0:re.Application)<"u"?(t=re.Application)==null?void 0:t.applicationId:void 0}catch{return}}function lg(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 ug(t){var e,s;const r=Xu();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?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),ig(xc(xc({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(s=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 Xu(){return $h.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function dg(){if(mn()===vt.reactNative&&typeof re<"u"&&typeof(re==null?void 0:re.Platform)<"u"){const{OS:s,Version:r}=re.Platform;return[s,r].join("-")}const t=Uh();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 hg(){var t;const e=mn();
vendor: 4,836 bytes, line 5
5return e===vt.browser?[e,((t=ds.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function Zu(t,e,s){const r=dg(),i=hg();return[[t,e].join("-"),[og,s].join("-"),r,i].join("/")}function pg({protocol:t,version:e,relayUrl:s,sdkVersion:r,auth:i,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),u=Zu(t,e,r),d={auth:i,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=lg(l[1]||"",d);return l[0]+"?"+h}function Vs(t,e){return t.filter(s=>e.includes(s)).length===t.length}function aa(t){return Object.fromEntries(t.entries())}function ca(t){return new Map(Object.entries(t))}function Bs(t=D.FIVE_MINUTES,e){const s=D.toMiliseconds(t||D.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 Ns(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 Qu(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 fg(t){return Qu("topic",t)}function gg(t){return Qu("id",t)}function ed(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 Me(t,e){return D.fromMiliseconds(Date.now()+D.toMiliseconds(t))}function Es(t){return Date.now()>=D.toMiliseconds(t)}function fe(t,e){return`${t}${e?`:${e}`:""}`}function Xt(t=[],e=[]){return[...new Set([...t,...e])]}async function mg({id:t,topic:e,wcDeepLink:s}){var r;try{if(!s)return;const i=typeof s=="string"?JSON.parse(s):s,n=i?.href;if(typeof n!="string")return;const o=wg(n,t,e),a=mn();if(a===vt.browser){if(!((r=ds.getDocument())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}yg(o)}else a===vt.reactNative&&typeof(re==null?void 0:re.Linking)<"u"&&await re.Linking.openURL(o)}catch(i){console.error(i)}}function wg(t,e,s){const r=`requestId=${e}&sessionTopic=${s}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${n}${Cg(r,!0)}`}else i=`${i}/wc?${r}`;return i}function yg(t){let e="_self";Eg()?e="_top":(vg()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function bg(t,e){let s="";try{if(ri()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(r){console.error(r)}return s}function Rc(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),r=s.indexOf(e);return s[r+2]}function Uc(){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 Wa(){return typeof Ur<"u"&&Xf.IS_VITEST==="true"}function vg(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Eg(){try{return window.self!==window.top}catch{return!1}}function Cg(t,e=!1){const s=Qe.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function td(t){return Qe.from(t,"base64").toString("utf-8")}function Ig(t){return new Promise(e=>setTimeout(e,t))}function Li(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ag(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wn(t,...e){if(!Ag(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 Ha(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Li(t.outputLen),Li(t.blockLen)}function Br(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 sd(t,e){wn(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const Pn=BigInt(2**32-1),Dc=BigInt(32);function Ng(t,e=!1){return e?{h:Number(t&Pn),l:Number(t>>Dc&Pn)}:{h:Number(t>>Dc&Pn)|0,l:Number(t&Pn)|0}}
5function _g(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}=Ng(t[i],e);[s[i],r[i]]=[n,o]}return[s,r]}const Sg=(t,e,s)=>t<<s|e>>>32-s,Pg=(t,e,s)=>e<<s|t>>>32-s,Og=(t,e,s)=>e<<s-32|t>>>64-s,kg=(t,e,s)=>t<<s-32|e>>>64-s,hr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Tg(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function No(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ft(t,e){return t<<32-e|t>>>e}const Mc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Lc(t){for(let e=0;e<t.length;e++)t[e]=xg(t[e])}function $g(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function qr(t){return typeof t=="string"&&(t=$g(t)),wn(t),t}function Rg(...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}let Va=class{clone(){return this._cloneInto()}};function rd(t){const e=r=>t().update(qr(r)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function ii(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 id=[],nd=[],od=[],Ug=BigInt(0),ui=BigInt(1),Dg=BigInt(2),Mg=BigInt(7),Lg=BigInt(256),jg=BigInt(113);for(let t=0,e=ui,s=1,r=0;t<24;t++){[s,r]=[r,(2*s+3*r)%5],id.push(2*(5*r+s)),nd.push((t+1)*(t+2)/2%64);let i=Ug;for(let n=0;n<7;n++)e=(e<<ui^(e>>Mg)*jg)%Lg,e&Dg&&(i^=ui<<(ui<<BigInt(n))-ui);od.push(i)}const[Bg,qg]=_g(od,!0),jc=(t,e,s)=>s>32?Og(t,e,s):Sg(t,e,s),Bc=(t,e,s)=>s>32?kg(t,e,s):Pg(t,e,s);function zg(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=jc(l,u,1)^s[a],h=Bc(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=nd[o],c=jc(i,n,a),l=Bc(i,n,a),u=id[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]^=Bg[r],t[1]^=qg[r]}s.fill(0)}let Fg=class ad extends Va{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,Li(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Tg(this.state)}keccak(){Mc||Lc(this.state32),zg(this.state32,this.rounds),Mc||Lc(this.state32),this.posOut=0,this.pos=0}update(e){Br(this);const{blockLen:s,state:r}=this;e=qr(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){Br(this,!1),wn(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 Li(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(sd(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 ad(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 Wg=(t,e,s)=>rd(()=>
vendor: 32,041 bytes, lines 5-8
5new Fg(e,t,s)),Hg=Wg(1,136,256/8),Vg="https://rpc.walletconnect.org/v1";function cd(t){const e=`�Ethereum Signed Message:
6${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Qe.from(Hg(s)).toString("hex")}async function Kg(t,e,s,r,i,n){switch(s.t){case"eip191":return await Gg(t,e,s.s);case"eip1271":return await Jg(t,e,s.s,r,i,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}async function Gg(t,e,s){return(await Kf({hash:cd(e),signature:s})).toLowerCase()===t.toLowerCase()}async function Jg(t,e,s,r,i,n){const o=Dr(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=cd(e).substring(2),h=a+d+c+l+u,p=await fetch(`${n||Vg}/?chainId=${r}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:Yg(),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 Yg(){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=Qe.from(t,"base64").slice(1,65);return Yf.encode(n)}var Zg=Object.defineProperty,Qg=Object.defineProperties,em=Object.getOwnPropertyDescriptors,qc=Object.getOwnPropertySymbols,tm=Object.prototype.hasOwnProperty,sm=Object.prototype.propertyIsEnumerable,zc=(t,e,s)=>e in t?Zg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,rm=(t,e)=>{for(var s in e||(e={}))tm.call(e,s)&&zc(t,s,e[s]);if(qc)for(var s of qc(e))sm.call(e,s)&&zc(t,s,e[s]);return t},im=(t,e)=>Qg(t,em(e));const nm="did:pkh:",Ka=t=>t?.split(":"),om=t=>{const e=t&&Ka(t);if(e)return t.includes(nm)?e[3]:e[1]},la=t=>{const e=t&&Ka(t);if(e)return e[2]+":"+e[3]},Qn=t=>{const e=t&&Ka(t);if(e)return e.pop()};async function Fc(t){const{cacao:e,projectId:s}=t,{s:r,p:i}=e,n=ld(i,i.iss),o=Qn(i.iss);return await Kg(o,n,r,la(i.iss),s)}const ld=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,r=Qn(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: ${om(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(g=>`
7- ${g}`).join("")}`:void 0,w=Fn(t.resources);if(w){const g=ji(w);i=gm(i,g)}return[s,r,"",i,"",n,o,a,c,l,u,d,h,p].filter(g=>g!=null).join(`
8`)};function am(t){return Qe.from(JSON.stringify(t)).toString("base64")}function cm(t){return JSON.parse(Qe.from(t,"base64").toString("utf-8"))}function er(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 lm(t,e,s,r={}){return s?.sort((i,n)=>i.localeCompare(n)),{att:{[t]:um(e,s,r)}}}function um(t,e,s={}){e=e?.sort((i,n)=>i.localeCompare(n));const r=e.map(i=>({[`${t}/${i}`]:[s]}));return Object.assign({},...r)}function ud(t){return er(t),`urn:recap:${am(t).replace(/=/g,"")}`}function ji(t){const e=cm(t.replace("urn:recap:",""));return er(e),e}function dm(t,e,s){const r=lm(t,e,s);return ud(r)}function hm(t){return t&&t.includes("urn:recap:")}function pm(t,e){const s=ji(t),r=ji(e),i=fm(s,r);return ud(i)}function fm(t,e){er(t),er(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]=im(rm({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((l=e.att[i])==null?void 0:l[a])})})}),r}function gm(t="",e){er(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 Wc(t){var e;const s=ji(t);er(s);const r=(e=s.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function Hc(t){const e=ji(t);er(e);const s=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(i=>{var n;(n=i?.[0])!=null&&n.chains&&s.push(i[0].chains)})}),[...new Set(s.flat())]}function Fn(t){if(!t)return;const e=t?.[t.length-1];return hm(e)?e:void 0}function _o(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function dd(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function bt(t,...e){if(!dd(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 Vc(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 mm(t,e){bt(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Kc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const Ss=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),wm=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),ym=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ym)throw new Error("Non little-endian hardware is not supported");function bm(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ua(t){if(typeof t=="string")t=bm(t);else if(dd(t))t=da(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function vm(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Em(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 Cm=(t,e)=>{function s(r,...i){if(bt(r),t.nonceLength!==void 0){const l=i[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?bt(l):bt(l,t.nonceLength)}const n=t.tagLength;n&&i[1]!==void 0&&bt(i[1]);const o=e(r,...i),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");bt(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,bt(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(bt(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 Gc(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 Jc(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 da(t){return Uint8Array.from(t)}function zr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const hd=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),Am=hd("expand 16-byte k"),Nm=hd("expand 32-byte k"),_m=Ss(Am),Sm=Ss(Nm);function le(t,e){return t<<e|t>>>32-e}function ha(t){return t.byteOffset%4===0}const On=64,Pm=16,pd=2**32-1,Yc=new Uint32Array;function Om(t,e,s,r,i,n,o,a){const c=i.length,l=new Uint8Array(On),u=Ss(l),d=ha(i)&&ha(n),h=d?Ss(i):Yc,p=d?Ss(n):Yc;for(let w=0;w<c;o++){if(t(e,s,r,u,o,a),o>=pd)throw new Error("arx: counter overflow");const g=Math.min(On,c-w);if(d&&g===On){const f=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let b=0,y;b<Pm;b++)y=f+b,p[y]=h[y]^u[b];w+=On;continue}for(let f=0,b;f<g;f++)b=w+f,n[b]=i[b]^l[f];w+=g}}function km(t,e){const{allowShortKeys:s,extendNonceFn:r,counterLength:i,counterRight:n,rounds:o}=vm({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return _o(i),_o(o),Kc(n),Kc(s),(a,c,l,u,d=0)=>{bt(a),bt(c),bt(l);const h=l.length;if(u===void 0&&(u=new Uint8Array(h)),bt(u),_o(d),d<0||d>=pd)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,g,f;if(w===32)p.push(g=da(a)),f=Sm;else if(w===16&&s)g=new Uint8Array(32),g.set(a),g.set(a,16),f=_m,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);ha(c)||p.push(c=da(c));const b=Ss(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(f,b,Ss(c.subarray(0,16)),b),c=c.subarray(16)}const y=16-i;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const C=new Uint8Array(12);C.set(c,n?0:12-c.length),c=C,p.push(c)}const v=Ss(c);return Om(t,f,b,v,l,u,d,o),zr(...p),u}}const Ve=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class Tm{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=ua(e),bt(e,32);const s=Ve(e,0),r=Ve(e,2),i=Ve(e,4),n=Ve(e,6),o=Ve(e,8),a=Ve(e,10),c=Ve(e,12),l=Ve(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|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]=Ve(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],g=o[8],f=o[9],b=Ve(e,s+0),y=Ve(e,s+2),v=Ve(e,s+4),C=Ve(e,s+6),A=Ve(e,s+8),N=Ve(e,s+10),_=Ve(e,s+12),R=Ve(e,s+14);let E=n[0]+(b&8191),$=n[1]+((b>>>13|y<<3)&8191),I=n[2]+((y>>>10|v<<6)&8191),M=n[3]+((v>>>7|C<<9)&8191),H=n[4]+((C>>>4|A<<12)&8191),S=n[5]+(A>>>1&8191),T=n[6]+((A>>>14|N<<2)&8191),O=n[7]+((N>>>11|_<<5)&8191),j=n[8]+((_>>>8|R<<8)&8191),q=n[9]+(R>>>5|i),x=0,G=x+E*a+$*(5*f)+I*(5*g)+M*(5*w)+H*(5*p);x=G>>>13,G&=8191,G+=S*(5*h)+T*(5*d)+O*(5*u)+j*(5*l)+q*(5*c),x+=G>>>13,G&=8191;let Q=x+E*c+$*a+I*(5*f)+M*(5*g)+H*(5*w);x=Q>>>13,Q&=8191,Q+=S*(5*p)+T*(5*h)+O*(5*d)+j*(5*u)+q*(5*l),x+=Q>>>13,Q&=8191;let se=x+E*l+$*c+I*a+M*(5*f)+H*(5*g);x=se>>>13,se&=8191,se+=S*(5*w)+T*(5*p)+O*(5*h)+j*(5*d)+q*(5*u),x+=se>>>13,se&=8191;let Ce=x+E*u+$*l+I*c+M*a+H*(5*f);x=Ce>>>13,Ce&=8191,Ce+=S*(5*g)+T*(5*w)+O*(5*p)+j*(5*h)+q*(5*d),x+=Ce>>>13,Ce&=8191;let pe=x+E*d+$*u+I*l+M*c+H*a;x=pe>>>13,pe&=8191,pe+=S*(5*f)+T*(5*g)+O*(5*w)+j*(5*p)+q*(5*h),x+=pe>>>13,pe&=8191;let Te=x+E*h+$*d+I*u+M*l+H*c;x=Te>>>13,Te&=8191,Te+=S*a+T*(5*f)+O*(5*g)+j*(5*w)+q*(5*p),x+=Te>>>13,Te&=8191;let Le=x+E*p+$*h+I*d+M*u+H*l;x=Le>>>13,Le&=8191,Le+=S*c+T*a+O*(5*f)+j*(5*g)+q*(5*w),x+=Le>>>13,Le&=8191;let Xe=x+E*w+$*p+I*h+M*d+H*u;x=Xe>>>13,Xe&=8191,Xe+=S*l+T*c+O*a+j*(5*f)+q*(5*g),x+=Xe>>>13,Xe&=8191;let Re=x+E*g+$*w+I*p+M*h+H*d;x=Re>>>13,Re&=8191,Re+=S*u+T*l+O*c+j*a+q*(5*f),x+=Re>>>13,Re&=8191;let Ue=x+E*f+$*g+I*w+M*p+H*h;x=Ue>>>13,Ue&=8191,Ue+=S*d+T*u+O*l+j*c+q*a,x+=Ue>>>13,Ue&=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]=pe,n[5]=Te,n[6]=Le,n[7]=Xe,n[8]=Re,n[9]=Ue}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;zr(r)}update(e){Vc(this);const{buffer:s,blockLen:r}=this;e=ua(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(){zr(this.h,this.r,this.buffer,this.pad)}digestInto(e){Vc(this),mm(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 xm(t){const e=(r,i)=>t(i).update(ua(r)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=r=>t(r),e}const $m=xm(t=>new Tm(t));function Rm(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],g=e[5],f=e[6],b=e[7],y=i,v=s[0],C=s[1],A=s[2],N=o,_=a,R=c,E=l,$=u,I=d,M=h,H=p,S=w,T=g,O=f,j=b,q=y,x=v,G=C,Q=A;for(let Ce=0;Ce<n;Ce+=2)N=N+$|0,q=le(q^N,16),S=S+q|0,$=le($^S,12),N=N+$|0,q=le(q^N,8),S=S+q|0,$=le($^S,7),_=_+I|0,x=le(x^_,16),T=T+x|0,I=le(I^T,12),_=_+I|0,x=le(x^_,8),T=T+x|0,I=le(I^T,7),R=R+M|0,G=le(G^R,16),O=O+G|0,M=le(M^O,12),R=R+M|0,G=le(G^R,8),O=O+G|0,M=le(M^O,7),E=E+H|0,Q=le(Q^E,16),j=j+Q|0,H=le(H^j,12),E=E+H|0,Q=le(Q^E,8),j=j+Q|0,H=le(H^j,7),N=N+I|0,Q=le(Q^N,16),O=O+Q|0,I=le(I^O,12),N=N+I|0,Q=le(Q^N,8),O=O+Q|0,I=le(I^O,7),_=_+M|0,q=le(q^_,16),j=j+q|0,M=le(M^j,12),_=_+M|0,q=le(q^_,8),j=j+q|0,M=le(M^j,7),R=R+H|0,x=le(x^R,16),S=S+x|0,H=le(H^S,12),R=R+H|0,x=le(x^R,8),S=S+x|0,H=le(H^S,7),E=E+$|0,G=le(G^E,16),T=T+G|0,$=le($^T,12),E=E+$|0,G=le(G^E,8),T=T+G|0,$=le($^T,7);let se=0;r[se++]=o+N|0,r[se++]=a+_|0,r[se++]=c+R|0,r[se++]=l+E|0,r[se++]=u+$|0,r[se++]=d+I|0,r[se++]=h+M|0,r[se++]=p+H|0,r[se++]=w+S|0,r[se++]=g+T|0,r[se++]=f+O|0,r[se++]=b+j|0,r[se++]=y+q|0,r[se++]=v+x|0,r[se++]=C+G|0,r[se++]=A+Q|0}const Um=km(Rm,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Dm=new Uint8Array(16),Xc=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(Dm.subarray(s))},Mm=new Uint8Array(32);function Zc(t,e,s,r,i){const n=t(e,s,Mm),o=$m.create(n);i&&Xc(o,i),Xc(o,r);const a=new Uint8Array(16),c=wm(a);Jc(c,0,BigInt(i?i.length:0),!0),Jc(c,8,BigInt(r.length),!0),o.update(a);const l=o.digest();return zr(n,a),l}const Lm=t=>(e,s,r)=>({encrypt(i,n){const o=i.length;n=Gc(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),zr(c),n},decrypt(i,n){n=Gc(i.length-16,n,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Zc(t,e,s,o,r);if(!Em(a,c))throw new Error("invalid tag");return n.set(i.subarray(0,-16)),t(e,s,n,n,1),zr(c),n}}),fd=Cm({blockSize:64,nonceLength:12,tagLength:16},Lm(Um));let gd=class extends Va{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,Ha(e);const r=qr(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 Br(this),this.iHash.update(e),this}digestInto(e){Br(this),wn(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 co=(t,e,s)=>new gd(t,e).update(s).digest();co.create=(t,e)=>new gd(t,e);function jm(t,e,s){return Ha(t),s===void 0&&(s=new Uint8Array(t.outputLen)),co(t,qr(s),qr(e))}const So=new Uint8Array([0]),Qc=new Uint8Array;function Bm(t,e,s,r=32){if(Ha(t),Li(r),r>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/t.outputLen);s===void 0&&(s=Qc);const n=new Uint8Array(i*t.outputLen),o=co.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<i;l++)So[0]=l+1,a.update(l===0?Qc:c).update(s).update(So).digestInto(c),n.set(c,t.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),So.fill(0),n.slice(0,r)}const qm=(t,e,s,r,i)=>Bm(t,jm(t,e,s),r,i);function zm(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 Fm(t,e,s){return t&e^~t&s}function Wm(t,e,s){return t&e^t&s^e&s}let Hm=class extends Va{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=No(this.buffer)}update(e){Br(this);const{view:s,buffer:r,blockLen:i}=this;e=qr(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=No(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){Br(this),sd(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;zm(r,i-8,BigInt(this.length*8),n),this.process(r,0);const a=No(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 Vm=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]),ws=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ys=new Uint32Array(64);class Km extends Hm{constructor(){super(64,32,8,!1),this.A=ws[0]|0,this.B=ws[1]|0,this.C=ws[2]|0,this.D=ws[3]|0,this.E=ws[4]|0,this.F=ws[5]|0,this.G=ws[6]|0,this.H=ws[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)ys[d]=e.getUint32(s,!1);for(let d=16;d<64;d++){const h=ys[d-15],p=ys[d-2],w=Ft(h,7)^Ft(h,18)^h>>>3,g=Ft(p,17)^Ft(p,19)^p>>>10;ys[d]=g+ys[d-7]+w+ys[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=Ft(a,6)^Ft(a,11)^Ft(a,25),p=u+h+Fm(a,c,l)+Vm[d]+ys[d]|0,w=(Ft(r,2)^Ft(r,13)^Ft(r,22))+Wm(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(){ys.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const yn=rd(()=>new Km);const lo=BigInt(0),uo=BigInt(1),Gm=BigInt(2);function tr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function bn(t){if(!tr(t))throw new Error("Uint8Array expected")}function Fr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Jm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Wr(t){bn(t);let e="";for(let s=0;s<t.length;s++)e+=Jm[t[s]];return e}function xr(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Ga(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?lo:BigInt("0x"+t)}const is={_0:48,_9:57,A:65,F:70,a:97,f:102};function el(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 Hr(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=el(t.charCodeAt(n)),a=el(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 Js(t){return Ga(Wr(t))}function Bi(t){return bn(t),Ga(Wr(Uint8Array.from(t).reverse()))}function Vr(t,e){return Hr(t.toString(16).padStart(e*2,"0"))}function ho(t,e){return Vr(t,e).reverse()}function Ym(t){return Hr(xr(t))}function yt(t,e,s){let r;if(typeof e=="string")try{r=Hr(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(tr(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 qi(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];bn(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 Zm(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const Po=t=>typeof t=="bigint"&&lo<=t;function po(t,e,s){return Po(t)&&Po(e)&&Po(s)&&e<=t&&t<s}function ls(t,e,s,r){if(!po(e,s,r))throw new Error("expected valid "+t+": "+s+" <= n < "+r+", got "+e)}function md(t){let e;for(e=0;t>lo;t>>=uo,e+=1);return e}function Qm(t,e){return t>>BigInt(e)&uo}function ew(t,e,s){return t|(s?uo:lo)<<BigInt(e)}const Ja=t=>(Gm<<BigInt(t-1))-uo,Oo=t=>new Uint8Array(t),tl=t=>Uint8Array.from(t);function wd(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=Oo(t),i=Oo(t),n=0;const o=()=>{r.fill(1),i.fill(0),n=0},a=(...u)=>s(i,r,...u),c=(u=Oo())=>{i=a(tl([0]),u),r=a(),u.length!==0&&(i=a(tl([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 qi(...d)};return(u,d)=>{o(),c(u);let h;for(;!(h=d(l()));)c();return o(),h}}const tw={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"||tr(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 ni(t,e,s={}){const r=(i,n,o)=>{const a=tw[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 sw=()=>{throw new Error("not implemented")};function pa(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 rw=Object.freeze({__proto__:null,isBytes:tr,abytes:bn,abool:Fr,bytesToHex:Wr,numberToHexUnpadded:xr,hexToNumber:Ga,hexToBytes:Hr,bytesToNumberBE:Js,bytesToNumberLE:Bi,numberToBytesBE:Vr,numberToBytesLE:ho,numberToVarBytesBE:Ym,ensureBytes:yt,concatBytes:qi,equalBytes:Xm,utf8ToBytes:Zm,inRange:po,aInRange:ls,bitLen:md,bitGet:Qm,bitSet:ew,bitMask:Ja,createHmacDrbg:wd,validateObject:ni,notImplemented:sw,memoized:pa});const He=BigInt(0),ke=BigInt(1),zs=BigInt(2),iw=BigInt(3),fa=BigInt(4),sl=BigInt(5),rl=BigInt(8);function dt(t,e){const s=t%e;return s>=He?s:e+s}function yd(t,e,s){if(e<He)throw new Error("invalid exponent, negatives unsupported");if(s<=He)throw new Error("invalid modulus");if(s===ke)return He;let r=ke;for(;e>He;)e&ke&&(r=r*t%s),t=t*t%s,e>>=ke;return r}function Mt(t,e,s){let r=t;for(;e-- >He;)r*=r,r%=s;return r}function ga(t,e){if(t===He)throw new Error("invert: expected non-zero number");if(e<=He)throw new Error("invert: expected positive modulus, got "+e);let s=dt(t,e),r=e,i=He,n=ke;for(;s!==He;){const o=r/s,a=r%s,c=i-n*o;r=s,s=a,i=n,n=c}if(r!==ke)throw new Error("invert: does not exist");return dt(i,e)}function nw(t){const e=(t-ke)/zs;let s,r,i;for(s=t-ke,r=0;s%zs===He;s/=zs,r++);for(i=zs;i<t&&yd(i,e,t)!==t-ke;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+ke)/fa;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+ke)/zs;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,ke<<BigInt(c-h-1));l=o.sqr(p),u=o.mul(u,p),d=o.mul(d,l),c=h}return u}}function ow(t){if(t%fa===iw){const e=(t+ke)/fa;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%rl===sl){const e=(t-sl)/rl;return function(s,r){const i=s.mul(r,zs),n=s.pow(i,e),o=s.mul(r,n),a=s.mul(s.mul(o,zs),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 nw(t)}const aw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function cw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},s=aw.reduce((r,i)=>(r[i]="function",r),e);return ni(t,s)}function lw(t,e,s){if(s<He)throw new Error("invalid exponent, negatives unsupported");if(s===He)return t.ONE;if(s===ke)return e;let r=t.ONE,i=e;for(;s>He;)s&ke&&(r=t.mul(r,i)),i=t.sqr(i),s>>=ke;return r}function uw(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 bd(t,e){const s=e!==void 0?e:t.toString(2).length,r=Math.ceil(s/8);return{nBitLength:s,nByteLength:r}}function vd(t,e,s=!1,r={}){if(t<=He)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:n}=bd(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:Ja(i),ZERO:He,ONE:ke,create:c=>dt(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return He<=c&&c<t},is0:c=>c===He,isOdd:c=>(c&ke)===ke,neg:c=>dt(-c,t),eql:(c,l)=>c===l,sqr:c=>dt(c*c,t),add:(c,l)=>dt(c+l,t),sub:(c,l)=>dt(c-l,t),mul:(c,l)=>dt(c*l,t),pow:(c,l)=>lw(a,c,l),div:(c,l)=>dt(c*ga(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ga(c,t),sqrt:r.sqrt||(c=>(o||(o=ow(t)),o(a,c))),invertBatch:c=>uw(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>s?ho(c,n):Vr(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return s?Bi(c):Js(c)}});return Object.freeze(a)}function Ed(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 Cd(t){const e=Ed(t);return e+Math.ceil(e/2)}function dw(t,e,s=!1){const r=t.length,i=Ed(e),n=Cd(e);if(r<16||r<n||r>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+r);const o=s?Bi(t):Js(t),a=dt(o,e-ke)+ke;return s?ho(a,i):Vr(a,i)}const il=BigInt(0),kn=BigInt(1);function ko(t,e){const s=e.negate();return t?s:e}function Id(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function To(t,e){Id(t,e);const s=Math.ceil(e/t)+1,r=2**(t-1);return{windows:s,windowSize:r}}function hw(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 pw(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 xo=new WeakMap,Ad=new WeakMap;function $o(t){return Ad.get(t)||1}function fw(t,e){return{constTimeNegate:ko,hasPrecomputes(s){return $o(s)!==1},unsafeLadder(s,r,i=t.ZERO){let n=s;for(;r>il;)r&kn&&(i=i.add(n)),n=n.double(),r>>=kn;return i},precomputeWindow(s,r){const{windows:i,windowSize:n}=To(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}=To(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+=kn);const g=p,f=p+Math.abs(w)-1,b=h%2!==0,y=w<0;w===0?c=c.add(ko(b,r[g])):a=a.add(ko(y,r[f]))}return{p:a,f:c}},wNAFUnsafe(s,r,i,n=t.ZERO){const{windows:o,windowSize:a}=To(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===il)break;let p=Number(i&c);if(i>>=u,p>a&&(p-=l,i+=kn),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=xo.get(r);
8return n||(n=this.precomputeWindow(r,s),s!==1&&xo.set(r,i(n))),n},wNAFCached(s,r,i){const n=$o(s);return this.wNAF(n,this.getPrecomputes(n,s,i),r)},wNAFCachedUnsafe(s,r,i,n){const o=$o(s);return o===1?this.unsafeLadder(s,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,s,i),r,n)},setWindowSize(s,r){Id(r,e),Ad.set(s,r),xo.delete(s)}}}function gw(t,e,s,r){if(hw(s,t),pw(r,e),s.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,n=md(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],g=Number(w>>BigInt(d)&BigInt(a));c[g]=c[g].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 Nd(t){return cw(t.Fp),ni(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...bd(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const pr=BigInt(0),Ro=BigInt(1);function mw(t){return ni(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function ww(t){const e=mw(t),{P:s}=e,r=y=>dt(y,s),i=e.montgomeryBits,n=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(y=>y),c=e.powPminus2||(y=>yd(y,s-BigInt(2),s));function l(y,v,C){const A=r(y*(v-C));return v=r(v-A),C=r(C+A),[v,C]}const u=(e.a-BigInt(2))/BigInt(4);function d(y,v){ls("u",y,pr,s),ls("scalar",v,pr,s);const C=v,A=y;let N=Ro,_=pr,R=y,E=Ro,$=pr,I;for(let H=BigInt(i-1);H>=pr;H--){const S=C>>H&Ro;$^=S,I=l($,N,R),N=I[0],R=I[1],I=l($,_,E),_=I[0],E=I[1],$=S;const T=N+_,O=r(T*T),j=N-_,q=r(j*j),x=O-q,G=R+E,Q=R-E,se=r(Q*T),Ce=r(G*j),pe=se+Ce,Te=se-Ce;R=r(pe*pe),E=r(A*r(Te*Te)),N=r(O*q),_=r(x*(O+r(u*x)))}I=l($,N,R),N=I[0],R=I[1],I=l($,_,E),_=I[0],E=I[1];const M=c(_);return r(N*M)}function h(y){return ho(r(y),n)}function p(y){const v=yt("u coordinate",y,n);return o===32&&(v[31]&=127),Bi(v)}function w(y){const v=yt("scalar",y),C=v.length;if(C!==n&&C!==o){let A=""+n+" or "+o;throw new Error("invalid scalar, expected "+A+" bytes, got "+C)}return Bi(a(v))}function g(y,v){const C=p(v),A=w(y),N=d(C,A);if(N===pr)throw new Error("invalid private or public key received");return h(N)}const f=h(e.Gu);function b(y){return g(y,f)}return{scalarMult:g,scalarMultBase:b,getSharedSecret:(y,v)=>g(y,v),getPublicKey:y=>b(y),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:f}}const ma=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const yw=BigInt(1),nl=BigInt(2),bw=BigInt(3),vw=BigInt(5);BigInt(8);function Ew(t){const e=BigInt(10),s=BigInt(20),r=BigInt(40),i=BigInt(80),n=ma,o=t*t%n*t%n,a=Mt(o,nl,n)*o%n,c=Mt(a,yw,n)*t%n,l=Mt(c,vw,n)*c%n,u=Mt(l,e,n)*l%n,d=Mt(u,s,n)*u%n,h=Mt(d,r,n)*d%n,p=Mt(h,i,n)*h%n,w=Mt(p,i,n)*h%n,g=Mt(w,e,n)*l%n;return{pow_p_5_8:Mt(g,nl,n)*t%n,b2:o}}function Cw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const wa=ww({P:ma,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=ma,{pow_p_5_8:s,b2:r}=Ew(t);return dt(Mt(s,bw,e)*r,e)},adjustScalarBytes:Cw,randomBytes:ii});function ol(t){t.lowS!==void 0&&Fr("lowS",t.lowS),t.prehash!==void 0&&Fr("prehash",t.prehash)}function Iw(t){const e=Nd(t);ni(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:Aw,hexToBytes:Nw}=rw;class _w extends Error{constructor(e=""){super(e)}}const as={Err:_w,_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: 5,523 bytes, line 8
8if(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 Aw(t)}},toSig(t){const{Err:e,_int:s,_tlv:r}=as,i=typeof t=="string"?Nw(t):t;bn(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),qe=BigInt(1);BigInt(2);const al=BigInt(3);BigInt(4);function Sw(t){const e=Iw(t),{Fp:s}=e,r=vd(e.n,e.nBitLength),i=e.toBytes||((g,f,b)=>{const y=f.toAffine();return qi(Uint8Array.from([4]),s.toBytes(y.x),s.toBytes(y.y))}),n=e.fromBytes||(g=>{const f=g.subarray(1),b=s.fromBytes(f.subarray(0,s.BYTES)),y=s.fromBytes(f.subarray(s.BYTES,2*s.BYTES));return{x:b,y}});function o(g){const{a:f,b}=e,y=s.sqr(g),v=s.mul(y,g);return s.add(s.add(v,s.mul(g,f)),b)}if(!s.eql(s.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return po(g,qe,e.n)}function c(g){const{allowedPrivateKeyLengths:f,nByteLength:b,wrapPrivateKey:y,n:v}=e;if(f&&typeof g!="bigint"){if(tr(g)&&(g=Wr(g)),typeof g!="string"||!f.includes(g.length))throw new Error("invalid private key");g=g.padStart(b*2,"0")}let C;try{C=typeof g=="bigint"?g:Js(yt("private key",g,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof g)}return y&&(C=dt(C,v)),ls("private key",C,qe,v),C}function l(g){if(!(g instanceof h))throw new Error("ProjectivePoint expected")}const u=pa((g,f)=>{const{px:b,py:y,pz:v}=g;if(s.eql(v,s.ONE))return{x:b,y};const C=g.is0();f==null&&(f=C?s.ONE:s.inv(v));const A=s.mul(b,f),N=s.mul(y,f),_=s.mul(v,f);if(C)return{x:s.ZERO,y:s.ZERO};if(!s.eql(_,s.ONE))throw new Error("invZ was invalid");return{x:A,y:N}}),d=pa(g=>{if(g.is0()){if(e.allowInfinityPoint&&!s.is0(g.py))return;throw new Error("bad point: ZERO")}const{x:f,y:b}=g.toAffine();if(!s.isValid(f)||!s.isValid(b))throw new Error("bad point: x or y not FE");const y=s.sqr(b),v=o(f);if(!s.eql(y,v))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(f,b,y){if(this.px=f,this.py=b,this.pz=y,f==null||!s.isValid(f))throw new Error("x required");if(b==null||!s.isValid(b))throw new Error("y required");if(y==null||!s.isValid(y))throw new Error("z required");Object.freeze(this)}static fromAffine(f){const{x:b,y}=f||{};if(!f||!s.isValid(b)||!s.isValid(y))throw new Error("invalid affine point");if(f instanceof h)throw new Error("projective point not allowed");const v=C=>s.eql(C,s.ZERO);return v(b)&&v(y)?h.ZERO:new h(b,y,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const b=s.invertBatch(f.map(y=>y.pz));return f.map((y,v)=>y.toAffine(b[v])).map(h.fromAffine)}static fromHex(f){const b=h.fromAffine(n(yt("pointHex",f)));return b.assertValidity(),b}static fromPrivateKey(f){return h.BASE.multiply(c(f))}static msm(f,b){return gw(h,r,f,b)}_setWindowSize(f){w.setWindowSize(this,f)}assertValidity(){d(this)}hasEvenY(){const{y:f}=this.toAffine();if(s.isOdd)return!s.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){l(f);const{px:b,py:y,pz:v}=this,{px:C,py:A,pz:N}=f,_=s.eql(s.mul(b,N),s.mul(C,v)),R=s.eql(s.mul(y,N),s.mul(A,v));return _&&R}negate(){return new h(this.px,s.neg(this.py),this.pz)}double(){const{a:f,b}=e,y=s.mul(b,al),{px:v,py:C,pz:A}=this;let N=s.ZERO,_=s.ZERO,R=s.ZERO,E=s.mul(v,v),$=s.mul(C,C),I=s.mul(A,A),M=s.mul(v,C);return M=s.add(M,M),R=s.mul(v,A),R=s.add(R,R),N=s.mul(f,R),_=s.mul(y,I),_=s.add(N,_),N=s.sub($,_),_=s.add($,_),_=s.mul(N,_),N=s.mul(M,N),R=s.mul(y,R),I=s.mul(f,I),M=s.sub(E,I),M=s.mul(f,M),M=s.add(M,R),R=s.add(E,E),E=s.add(R,E),E=s.add(E,I),E=s.mul(E,M),_=s.add(_,E),I=s.mul(C,A),I=s.add(I,I),E=s.mul(I,M),N=s.sub(N,E),R=s.mul(I,$),R=s.add(R,R),R=s.add(R,R),new h(N,_,R)}add(f){l(f);const{px:b,py:y,pz:v}=this,{px:C,py:A,pz:N}=f;let _=s.ZERO,R=s.ZERO,E=s.ZERO;const $=e.a,I=s.mul(e.b,al);let M=s.mul(b,C),H=s.mul(y,A),S=s.mul(v,N),T=s.add(b,y),O=s.add(C,A);T=s.mul(T,O),O=s.add(M,H),T=s.sub(T,O),O=s.add(b,v);let j=s.add(C,N);return O=s.mul(O,j),j=s.add(M,S),O=s.sub(O,j),j=s.add(y,v),_=s.add(A,N),j=s.mul(j,_),_=s.add(H,S),j=s.sub(j,_),E=s.mul($,O),_=s.mul(I,S),E=s.add(_,E),_=s.sub(H,E),E=s.add(H,E),R=s.mul(_,E),H=s.add(M,M),H=s.add(H,M),S=s.mul($,S),O=s.mul(I,O),H=s.add(H,S),S=s.sub(M,S),S=s.mul($,S),O=s.add(O,S),M=s.mul(H,O),R=s.add(R,M),M=s.mul(j,O),_=s.mul(T,_),_=s.sub(_,M),M=s.mul(T,H),E=s.mul(j,E),E=s.add(E,M),new h(_,R,E)}subtract(f){return this.add(f.negate())}is0(){return this.equals(h.ZERO)}wNAF(f){return w.wNAFCached(this,f,h.normalizeZ)}
8multiplyUnsafe(f){const{endo:b,n:y}=e;ls("scalar",f,cs,y);const v=h.ZERO;if(f===cs)return v;if(this.is0()||f===qe)return this;if(!b||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,f,h.normalizeZ);let{k1neg:C,k1:A,k2neg:N,k2:_}=b.splitScalar(f),R=v,E=v,$=this;for(;A>cs||_>cs;)A&qe&&(R=R.add($)),_&qe&&(E=E.add($)),$=$.double(),A>>=qe,_>>=qe;return C&&(R=R.negate()),N&&(E=E.negate()),E=new h(s.mul(E.px,b.beta),E.py,E.pz),R.add(E)}multiply(f){const{endo:b,n:y}=e;ls("scalar",f,qe,y);let v,C;if(b){const{k1neg:A,k1:N,k2neg:_,k2:R}=b.splitScalar(f);let{p:E,f:$}=this.wNAF(N),{p:I,f:M}=this.wNAF(R);E=w.constTimeNegate(A,E),I=w.constTimeNegate(_,I),I=new h(s.mul(I.px,b.beta),I.py,I.pz),v=E.add(I),C=$.add(M)}else{const{p:A,f:N}=this.wNAF(f);v=A,C=N}return h.normalizeZ([v,C])[0]}multiplyAndAddUnsafe(f,b,y){const v=h.BASE,C=(N,_)=>_===cs||_===qe||!N.equals(v)?N.multiplyUnsafe(_):N.multiply(_),A=C(this,b).add(C(f,y));return A.is0()?void 0:A}toAffine(f){return u(this,f)}isTorsionFree(){const{h:f,isTorsionFree:b}=e;if(f===qe)return!0;if(b)return b(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:b}=e;return f===qe?this:b?b(h,this):this.multiplyUnsafe(e.h)}toRawBytes(f=!0){return Fr("isCompressed",f),this.assertValidity(),i(h,this,f)}toHex(f=!0){return Fr("isCompressed",f),Wr(this.toRawBytes(f))}}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=fw(h,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Pw(t){const e=Nd(t);return ni(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Ow(t){const e=Pw(t),{Fp:s,n:r}=e,i=s.BYTES+1,n=2*s.BYTES+1;function o(S){return dt(S,r)}function a(S){return ga(S,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:d}=Sw({...e,toBytes(S,T,O){const j=T.toAffine(),q=s.toBytes(j.x),x=qi;return Fr("isCompressed",O),O?x(Uint8Array.from([T.hasEvenY()?2:3]),q):x(Uint8Array.from([4]),q,s.toBytes(j.y))},fromBytes(S){const T=S.length,O=S[0],j=S.subarray(1);if(T===i&&(O===2||O===3)){const q=Js(j);if(!po(q,qe,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&qe)===qe;return(O&1)===1!==Q&&(G=s.neg(G)),{x:q,y:G}}else if(T===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 "+T)}}}),h=S=>Wr(Vr(S,e.nByteLength));function p(S){const T=r>>qe;return S>T}function w(S){return p(S)?o(-S):S}const g=(S,T,O)=>Js(S.slice(T,O));class f{constructor(T,O,j){this.r=T,this.s=O,this.recovery=j,this.assertValidity()}static fromCompact(T){const O=e.nByteLength;return T=yt("compactSignature",T,O*2),new f(g(T,0,O),g(T,O,2*O))}static fromDER(T){const{r:O,s:j}=as.toSig(yt("DER",T));return new f(O,j)}assertValidity(){ls("r",this.r,qe,r),ls("s",this.s,qe,r)}addRecoveryBit(T){return new f(this.r,this.s,T)}recoverPublicKey(T){const{r:O,s:j,recovery:q}=this,x=N(yt("msgHash",T));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),pe=o(-x*Ce),Te=o(j*Ce),Le=c.BASE.multiplyAndAddUnsafe(se,pe,Te);if(!Le)throw new Error("point at infinify");return Le.assertValidity(),Le}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Hr(this.toDERHex())}toDERHex(){return as.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Hr(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}const b={isValidPrivateKey(S){try{return l(S),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const S=Cd(e.n);return dw(e.randomBytes(S),e.n)},precompute(S=8,T=c.BASE){return T._setWindowSize(S),T.multiply(BigInt(3)),T}};function y(S,T=!0){return c.fromPrivateKey(S).toRawBytes(T)}function v(S){const T=tr(S),O=typeof S=="string",j=(T||O)&&S.length;return T?j===i||j===n:O?j===2*i||j===2*n:S instanceof c}function C(S,T,O=!0){if(v(S))throw new Error("first arg must be private key");if(!v(T))throw new Error("second arg must be public key");return c.fromHex(T).multiply(l(S)).toRawBytes(O)}const A=e.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");
vendor: 5,758 bytes, line 8
8const T=Js(S),O=S.length*8-e.nBitLength;return O>0?T>>BigInt(O):T},N=e.bits2int_modN||function(S){return o(A(S))},_=Ja(e.nBitLength);function R(S){return ls("num < 2^"+e.nBitLength,S,cs,_),Vr(S,e.nByteLength)}function E(S,T,O=$){if(["recovered","canonical"].some(Re=>Re 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),S=yt("msgHash",S),ol(O),G&&(S=yt("prehashed msgHash",j(S)));const se=N(S),Ce=l(T),pe=[R(Ce),R(se)];if(Q!=null&&Q!==!1){const Re=Q===!0?q(s.BYTES):Q;pe.push(yt("extraEntropy",Re))}const Te=qi(...pe),Le=se;function Xe(Re){const Ue=A(Re);if(!d(Ue))return;const Rs=a(Ue),Qt=c.BASE.multiply(Ue).toAffine(),zt=o(Qt.x);if(zt===cs)return;const es=o(Rs*o(Le+zt*Ce));if(es===cs)return;let ur=(Qt.x===zt?0:2)|Number(Qt.y&qe),Nn=es;return x&&p(es)&&(Nn=w(es),ur^=1),new f(zt,Nn,ur)}return{seed:Te,k2sig:Xe}}const $={lowS:e.lowS,prehash:!1},I={lowS:e.lowS,prehash:!1};function M(S,T,O=$){const{seed:j,k2sig:q}=E(S,T,O),x=e;return wd(x.hash.outputLen,x.nByteLength,x.hmac)(j,q)}c.BASE._setWindowSize(8);function H(S,T,O,j=I){const q=S;T=yt("msgHash",T),O=yt("publicKey",O);const{lowS:x,prehash:G,format:Q}=j;if(ol(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"||tr(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 pe,Te;try{if(Ce&&(pe=new f(q.r,q.s)),se){try{Q!=="compact"&&(pe=f.fromDER(q))}catch(es){if(!(es instanceof as.Err))throw es}!pe&&Q!=="der"&&(pe=f.fromCompact(q))}Te=c.fromHex(O)}catch{return!1}if(!pe||x&&pe.hasHighS())return!1;G&&(T=e.hash(T));const{r:Le,s:Xe}=pe,Re=N(T),Ue=a(Xe),Rs=o(Re*Ue),Qt=o(Le*Ue),zt=c.BASE.multiplyAndAddUnsafe(Te,Rs,Qt)?.toAffine();return zt?o(zt.x)===Le:!1}return{CURVE:e,getPublicKey:y,getSharedSecret:C,sign:M,verify:H,ProjectivePoint:c,Signature:f,utils:b}}function kw(t){return{hash:t,hmac:(e,...s)=>co(t,e,Rg(...s)),randomBytes:ii}}function Tw(t,e){const s=r=>Ow({...t,...kw(r)});return{...s(e),create:s}}const _d=vd(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),xw=_d.create(BigInt("-3")),$w=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Rw=Tw({a:xw,b:$w,Fp:_d,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},yn),Sd="base10",rt="base16",Bt="base64pad",Cs="base64url",vn="utf8",Pd=0,us=1,En=2,Uw=0,cl=1,Si=12,Ya=32;function Dw(){const t=wa.utils.randomPrivateKey(),e=wa.getPublicKey(t);return{privateKey:ht(t,rt),publicKey:ht(e,rt)}}function ya(){const t=ii(Ya);return ht(t,rt)}function Mw(t,e){const s=wa.getSharedSecret(Tt(t,rt),Tt(e,rt)),r=qm(yn,s,void 0,void 0,Ya);return ht(r,rt)}function Wn(t){const e=yn(Tt(t,rt));return ht(e,rt)}function Jt(t){const e=yn(Tt(t,vn));return ht(e,rt)}function Od(t){return Tt(`${t}`,Sd)}function sr(t){return Number(ht(t,Sd))}function kd(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Td(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function Lw(t){const e=Od(typeof t.type<"u"?t.type:Pd);if(sr(e)===us&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?Tt(t.senderPublicKey,rt):void 0,r=typeof t.iv<"u"?Tt(t.iv,rt):ii(Si),i=Tt(t.symKey,rt),n=fd(i,r).encrypt(Tt(t.message,vn)),o=xd({type:e,sealed:n,iv:r,senderPublicKey:s});return t.encoding===Cs?kd(o):o}function jw(t){const e=Tt(t.symKey,rt),{sealed:s,iv:r}=zi({encoded:t.encoded,encoding:t.encoding}),i=fd(e,r).decrypt(s);if(i===null)throw new Error("Failed to decrypt");return ht(i,vn)}function Bw(t,e){const s=Od(En),r=ii(Si),i=Tt(t,vn),n=xd({type:s,sealed:i,iv:r});return e===Cs?kd(n):n}function qw(t,e){const{sealed:s}=zi({encoded:t,encoding:e});return ht(s,vn)}function xd(t){if(sr(t.type)===En)return ht(Ii([t.type,t.sealed]),Bt);if(sr(t.type)===us){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return ht(Ii([t.type,t.senderPublicKey,t.iv,t.sealed]),Bt)}return ht(Ii([t.type,t.iv,t.sealed]),Bt)}function zi(t){const e=(t.encoding||Bt)===Cs?Td(t.encoded):t.encoded,s=Tt(e,Bt),r=s.slice(Uw,cl),i=cl;if(sr(r)===us){const c=i+Ya,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(sr(r)===En){const c=s.slice(i),l=ii(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 zw(t,e){const s=zi({encoded:t,encoding:e?.encoding});return $d({type:sr(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?ht(s.senderPublicKey,rt):void 0,receiverPublicKey:e?.receiverPublicKey})}function $d(t){const e=t?.type||Pd;if(e===us){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function ll(t){return t.type===us&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function ul(t){return t.type===En}function Fw(t){const e=Qe.from(t.x,"base64"),s=Qe.from(t.y,"base64");return Ii([new Uint8Array([4]),e,s])}function Ww(t,e){const[s,r,i]=t.split("."),n=Qe.from(Td(i),"base64");if(n.length!==64)throw new Error("Invalid signature length");
8const o=n.slice(0,32),a=n.slice(32,64),c=`${s}.${r}`,l=yn(c),u=Fw(e);if(!Rw.verify(Ii([o,a]),l,u))throw new Error("Invalid signature");return Qo(t).payload}const Hw="irn";function eo(t){return t?.relay||{protocol:Hw}}function vi(t){const e=Rh[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function Vw(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 dl(t){if(!t.includes("wc:")){const l=td(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:Kw(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:Vw(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Kw(t){return t.startsWith("//")?t.substring(2):t}function Gw(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 hl(t){const e=new URLSearchParams,s=Gw(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 Tn(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var Jw=Object.defineProperty,Yw=Object.defineProperties,Xw=Object.getOwnPropertyDescriptors,pl=Object.getOwnPropertySymbols,Zw=Object.prototype.hasOwnProperty,Qw=Object.prototype.propertyIsEnumerable,fl=(t,e,s)=>e in t?Jw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ey=(t,e)=>{for(var s in e||(e={}))Zw.call(e,s)&&fl(t,s,e[s]);if(pl)for(var s of pl(e))Qw.call(e,s)&&fl(t,s,e[s]);return t},ty=(t,e)=>Yw(t,Xw(e));function oi(t){const e=[];return t.forEach(s=>{const[r,i]=s.split(":");e.push(`${r}:${i}`)}),e}function sy(t){const e=[];return Object.values(t).forEach(s=>{e.push(...oi(s.accounts))}),e}function ry(t,e){const s=[];return Object.values(t).forEach(r=>{oi(r.accounts).includes(e)&&s.push(...r.methods)}),s}function iy(t,e){const s=[];return Object.values(t).forEach(r=>{oi(r.accounts).includes(e)&&s.push(...r.events)}),s}function fo(t){return t.includes(":")}function $r(t){return fo(t)?t.split(":")[0]:t}function gl(t){var e,s,r;const i={};if(!Os(t))return i;for(const[n,o]of Object.entries(t)){const a=fo(n)?[n]:o.chains,c=o.methods||[],l=o.events||[],u=$r(n);i[u]=ty(ey({},i[u]),{chains:Xt(a,(e=i[u])==null?void 0:e.chains),methods:Xt(c,(s=i[u])==null?void 0:s.methods),events:Xt(l,(r=i[u])==null?void 0:r.events)})}return i}function ny(t){const e={};return 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 ml(t,e){e=e.map(r=>r.replace("did:pkh:",""));const s=ny(e);for(const[r,i]of Object.entries(s))i.methods?i.methods=Xt(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return s}function oy(t,e){var s,r,i,n,o,a;const c=gl(t),l=gl(e),u={},d=Object.keys(c).concat(Object.keys(l));for(const h of d)u[h]={chains:Xt((s=c[h])==null?void 0:s.chains,(r=l[h])==null?void 0:r.chains),methods:Xt((i=c[h])==null?void 0:i.methods,(n=l[h])==null?void 0:n.methods),events:Xt((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return u}const ay={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}},cy={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 U(t,e){const{message:s,code:r}=cy[t];return{message:e?`${s} ${e}
8`:s,code:r}}function ye(t,e){const{message:s,code:r}=ay[t];return{message:e?`${s} ${e}`:s,code:r}}function Ps(t,e){return!!Array.isArray(t)}function Os(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Je(t){return typeof t>"u"}function $e(t,e){return e&&Je(t)?!0:typeof t=="string"&&!!t.trim().length}function Xa(t,e){return e&&Je(t)?!0:typeof t=="number"&&!isNaN(t)}function ly(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=oi(a),d=s[o];(!Vs(Yu(o,d),u)||!Vs(d.methods,c)||!Vs(d.events,l))&&(n=!1)}),n):!1}function to(t){return $e(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function uy(t){if($e(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&to(s)}}return!1}function dy(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if($e(t,!1)){if(e(t))return!0;const s=td(t);return e(s)}}catch{}return!1}function hy(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function py(t){return t?.topic}function fy(t,e){let s=null;return $e(t?.publicKey,!1)||(s=U("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function wl(t){let e=!0;return Ps(t)?t.length&&(e=t.every(s=>$e(s,!1))):e=!1,e}function gy(t,e,s){let r=null;return Ps(e)&&e.length?e.forEach(i=>{r||to(i)||(r=ye("UNSUPPORTED_CHAINS",`${s}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):to(t)||(r=ye("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 my(t,e,s){let r=null;return Object.entries(t).forEach(([i,n])=>{if(r)return;const o=gy(i,Yu(i,n),`${e} ${s}`);o&&(r=o)}),r}function wy(t,e){let s=null;return Ps(t)?t.forEach(r=>{s||uy(r)||(s=ye("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):s=ye("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function yy(t,e){let s=null;return Object.values(t).forEach(r=>{if(s)return;const i=wy(r?.accounts,`${e} namespace`);i&&(s=i)}),s}function by(t,e){let s=null;return wl(t?.methods)?wl(t?.events)||(s=ye("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=ye("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function Rd(t,e){let s=null;return Object.values(t).forEach(r=>{if(s)return;const i=by(r,`${e}, namespace`);i&&(s=i)}),s}function vy(t,e,s){let r=null;if(t&&Os(t)){const i=Rd(t,e);i&&(r=i);const n=my(t,e,s);n&&(r=n)}else r=U("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return r}function Uo(t,e){let s=null;if(t&&Os(t)){const r=Rd(t,e);r&&(s=r);const i=yy(t,e);i&&(s=i)}else s=U("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function Ud(t){return $e(t.protocol,!0)}function Ey(t,e){let s=!1;return t?t&&Ps(t)&&t.length&&t.forEach(r=>{s=Ud(r)}):s=!0,s}function Cy(t){return typeof t=="number"}function ut(t){return typeof t<"u"&&typeof t!==null}function Iy(t){return!(!t||typeof t!="object"||!t.code||!Xa(t.code,!1)||!t.message||!$e(t.message,!1))}function Ay(t){return!(Je(t)||!$e(t.method,!1))}function Ny(t){return!(Je(t)||Je(t.result)&&Je(t.error)||!Xa(t.id,!1)||!$e(t.jsonrpc,!1))}function _y(t){return!(Je(t)||!$e(t.name,!1))}function yl(t,e){return!(!to(e)||!sy(t).includes(e))}function Sy(t,e,s){return $e(s,!1)?ry(t,e).includes(s):!1}function Py(t,e,s){return $e(s,!1)?iy(t,e).includes(s):!1}function bl(t,e,s){let r=null;const i=Oy(t),n=ky(e),o=Object.keys(i),a=Object.keys(n),c=vl(Object.keys(t)),l=vl(Object.keys(e)),u=c.filter(d=>!l.includes(d));return u.length&&(r=U("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
9      Required: ${u.toString()}
10      Received: ${Object.keys(e).toString()}`)),Vs(o,a)||(r=U("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.
11      Required: ${o.toString()}
12      Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||r)return;const h=oi(e[d].accounts);h.includes(d)||(r=U("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${d}
13        Required: ${d}
14        Approved: ${h.toString()}`))}),o.forEach(d=>{r||(Vs(i[d].methods,n[d].methods)?Vs(i[d].events,n[d].events)||(r=U("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${d}`)):r=U("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${d}`))}),r}function Oy(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=>
vendor: 12,714 bytes, line 14
14{e[i]={methods:t[s].methods,events:t[s].events}})}),e}function vl(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function ky(t){const e={};return Object.keys(t).forEach(s=>{s.includes(":")?e[s]=t[s]:oi(t[s].accounts)?.forEach(i=>{e[i]={accounts:t[s].accounts.filter(n=>n.includes(`${i}:`)),methods:t[s].methods,events:t[s].events}})}),e}function Ty(t,e){return Xa(t,!1)&&t<=e.max&&t>=e.min}function El(){const t=mn();return new Promise(e=>{switch(t){case vt.browser:e(xy());break;case vt.reactNative:e($y());break;case vt.node:e(Ry());break;default:e(!0)}})}function xy(){return ri()&&navigator?.onLine}async function $y(){return $s()&&typeof re<"u"&&re!=null&&re.NetInfo?(await(re==null?void 0:re.NetInfo.fetch()))?.isConnected:!0}function Ry(){return!0}function Uy(t){switch(mn()){case vt.browser:Dy(t);break;case vt.reactNative:My(t);break}}function Dy(t){!$s()&&ri()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function My(t){$s()&&typeof re<"u"&&re!=null&&re.NetInfo&&re?.NetInfo.addEventListener(e=>t(e?.isConnected))}function Ly(){var t;return ri()&&ds.getDocument()?((t=ds.getDocument())==null?void 0:t.visibilityState)==="visible":!0}const Do={};class di{static get(e){return Do[e]}static set(e,s){Do[e]=s}static delete(e){delete Do[e]}}var jy={};const Dd="wc",Md=2,ba="core",Zt=`${Dd}@2:${ba}:`,By={logger:"error"},qy={database:":memory:"},zy="crypto",Cl="client_ed25519_seed",Fy=D.ONE_DAY,Wy="keychain",Hy="0.3",Vy="messages",Ky="0.3",Il=D.SIX_HOURS,Gy="publisher",Ld="irn",Jy="error",jd="wss://relay.walletconnect.org",Yy="relayer",ze={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",St={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Zy=.1,va="2.21.0",_e={link_mode:"link_mode",relay:"relay"},Hn={inbound:"inbound",outbound:"outbound"},Qy="0.3",eb="WALLETCONNECT_CLIENT_ID",Al="WALLETCONNECT_LINK_MODE_APPS",mt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},tb="subscription",sb="0.3",rb="pairing",ib="0.3",hi={wc_pairingDelete:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:D.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:D.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:D.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:D.ONE_DAY,prompt:!1,tag:0},res:{ttl:D.ONE_DAY,prompt:!1,tag:0}}},Fs={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Rt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},nb="history",ob="0.3",ab="expirer",kt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},cb="0.3",lb="verify-api",ub="https://verify.walletconnect.com",Bd="https://verify.walletconnect.org",Pi=Bd,db=`${Pi}/v3`,hb=[ub,Bd],pb="echo",fb="https://echo.walletconnect.com",Vt={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"},Ut={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"},Ds={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"},Ms={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"},pi={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"},gb=.1,mb="event-client",wb=86400,yb="https://pulse.walletconnect.org/batch";function bb(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 g=0,f=0,b=0,y=w.length;b!==y&&w[b]===0;)b++,g++;for(var v=(y-b)*u+1>>>0,C=new Uint8Array(v);b!==y;){for(var A=w[b],N=0,_=v-1;(A!==0||N<f)&&_!==-1;_--,N++)A+=256*C[_]>>>0,C[_]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");f=N,b++}for(var R=v-f;R!==v&&C[R]===0;)R++;for(var E=c.repeat(g);R<v;++R)E+=t.charAt(C[R]);return E}function h(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var g=0;if(w[g]!==" "){for(var f=0,b=0;w[g]===c;)f++,g++;for(var y=(w.length-g)*l+1>>>0,v=new Uint8Array(y);w[g];){var C=s[w.charCodeAt(g)];if(C===255)return;for(var A=0,N=y-1;(C!==0||A<b)&&N!==-1;N--,A++)C+=a*v[N]>>>0,v[N]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");b=A,g++}if(w[g]!==" "){for(var _=y-b;_!==y&&v[_]===0;)_++;for(var R=new Uint8Array(f+(y-_)),E=f;_!==y;)R[E++]=v[_++];return R}}}function p(w){var g=h(w);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var vb=bb,Eb=vb;const qd=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")},Cb=t=>new TextEncoder().encode(t),Ib=t=>new TextDecoder().decode(t);class Ab{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 Nb{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 zd(this,e)}}class _b{constructor(e){this.decoders=e}or(e){return zd(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 zd=(t,e)=>new _b({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Sb{constructor(e,s,r,i){this.name=e,this.prefix=s,this.baseEncode=r,this.baseDecode=i,this.encoder=new Ab(e,s,r),this.decoder=new Nb(e,s,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const go=({name:t,prefix:e,encode:s,decode:r})=>new Sb(t,e,s,r),Cn=({prefix:t,name:e,alphabet:s})=>{const{encode:r,decode:i}=Eb(s,e);return go({prefix:t,name:e,encode:r,decode:n=>qd(i(n))})},Pb=(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},Ob=(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},Ye=({name:t,prefix:e,bitsPerChar:s,alphabet:r})=>go({prefix:e,name:t,encode(i){return Ob(i,r,s)},decode(i){return Pb(i,r,s,t)}}),kb=go({prefix:"\0",name:"identity",encode:t=>Ib(t),decode:t=>Cb(t)});var Tb=Object.freeze({__proto__:null,identity:kb});const xb=Ye({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $b=Object.freeze({__proto__:null,base2:xb});const Rb=Ye({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ub=Object.freeze({__proto__:null,base8:Rb});const Db=Cn({prefix:"9",name:"base10",alphabet:"0123456789"});var Mb=Object.freeze({__proto__:null,base10:Db});const Lb=Ye({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),jb=Ye({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Bb=Object.freeze({__proto__:null,base16:Lb,base16upper:jb});const qb=Ye({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),zb=Ye({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Fb=Ye({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wb=Ye({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Hb=Ye({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vb=Ye({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Kb=Ye({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Gb=Ye({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jb=Ye({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Yb=Object.freeze({__proto__:null,base32:qb,base32upper:zb,base32pad:Fb,base32padupper:Wb,base32hex:Hb,base32hexupper:Vb,base32hexpad:Kb,base32hexpadupper:Gb,base32z:Jb});const Xb=Cn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zb=Cn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Qb=Object.freeze({__proto__:null,base36:Xb,base36upper:Zb});const ev=Cn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tv=Cn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var sv=Object.freeze({__proto__:null,base58btc:ev,base58flickr:tv});const rv=Ye({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
14+/",bitsPerChar:6}),iv=Ye({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nv=Ye({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ov=Ye({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var av=Object.freeze({__proto__:null,base64:rv,base64pad:iv,base64url:nv,base64urlpad:ov});const Fd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),cv=Fd.reduce((t,e,s)=>(t[s]=e,t),[]),lv=Fd.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function uv(t){return t.reduce((e,s)=>(e+=cv[s],e),"")}function dv(t){const e=[];for(const s of t){const r=lv[s.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(r)}return new Uint8Array(e)}const hv=go({prefix:"🚀",name:"base256emoji",encode:uv,decode:dv});var pv=Object.freeze({__proto__:null,base256emoji:hv}),fv=Wd,Nl=128,gv=-128,mv=Math.pow(2,31);function Wd(t,e,s){e=e||[],s=s||0;for(var r=s;t>=mv;)e[s++]=t&255|Nl,t/=128;for(;t&gv;)e[s++]=t&255|Nl,t>>>=7;return e[s]=t|0,Wd.bytes=s-r+1,e}var wv=Ea,yv=128,_l=127;function Ea(t,r){var s=0,r=r||0,i=0,n=r,o,a=t.length;do{if(n>=a)throw Ea.bytes=0,new RangeError("Could not decode varint");o=t[n++],s+=i<28?(o&_l)<<i:(o&_l)*Math.pow(2,i),i+=7}while(o>=yv);return Ea.bytes=n-r,s}var bv=Math.pow(2,7),vv=Math.pow(2,14),Ev=Math.pow(2,21),Cv=Math.pow(2,28),Iv=Math.pow(2,35),Av=Math.pow(2,42),Nv=Math.pow(2,49),_v=Math.pow(2,56),Sv=Math.pow(2,63),Pv=function(t){return t<bv?1:t<vv?2:t<Ev?3:t<Cv?4:t<Iv?5:t<Av?6:t<Nv?7:t<_v?8:t<Sv?9:10},Ov={encode:fv,decode:wv,encodingLength:Pv},Hd=Ov;const Sl=(t,e,s=0)=>(Hd.encode(t,e,s),e),Pl=t=>Hd.encodingLength(t),Ca=(t,e)=>{const s=e.byteLength,r=Pl(t),i=r+Pl(s),n=new Uint8Array(i+s);return Sl(t,n,0),Sl(s,n,r),n.set(e,i),new kv(t,s,e,n)};class kv{constructor(e,s,r,i){this.code=e,this.size=s,this.digest=r,this.bytes=i}}const Vd=({name:t,code:e,encode:s})=>new Tv(t,e,s);class Tv{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?Ca(this.code,s):s.then(r=>Ca(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Kd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),xv=Vd({name:"sha2-256",code:18,encode:Kd("SHA-256")}),$v=Vd({name:"sha2-512",code:19,encode:Kd("SHA-512")});var Rv=Object.freeze({__proto__:null,sha256:xv,sha512:$v});const Gd=0,Uv="identity",Jd=qd,Dv=t=>Ca(Gd,Jd(t)),Mv={code:Gd,name:Uv,encode:Jd,digest:Dv};var Lv=Object.freeze({__proto__:null,identity:Mv});new TextEncoder,new TextDecoder;const Ol={...Tb,...$b,...Ub,...Mb,...Bb,...Yb,...Qb,...sv,...av,...pv};({...Rv,...Lv});function jv(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Yd(t,e,s,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:r}}}const kl=Yd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Mo=Yd("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=jv(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),Bv={utf8:kl,"utf-8":kl,hex:Ol.base16,latin1:Mo,ascii:Mo,binary:Mo,...Ol};function qv(t,e="utf8"){const s=Bv[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):s.decoder.decode(`${s.prefix}${t}`)}var zv=Object.defineProperty,Fv=(t,e,s)=>e in t?zv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Wt=(t,e,s)=>Fv(t,typeof e!="symbol"?e+"":e,s);class Wv{constructor(e,s){this.core=e,this.logger=s,Wt(this,"keychain",new Map),Wt(this,"name",Wy),Wt(this,"version",Hy),Wt(this,"initialized",!1),Wt(this,"storagePrefix",Zt),Wt(this,"init",async()=>
vendor: 4,593 bytes, line 14
14{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Wt(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Wt(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),Wt(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(n)}return i}),Wt(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=it(s,this.name)}get context(){return Ct(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,aa(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ca(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Hv=Object.defineProperty,Vv=(t,e,s)=>e in t?Hv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ke=(t,e,s)=>Vv(t,typeof e!="symbol"?e+"":e,s);class Kv{constructor(e,s,r){this.core=e,this.logger=s,Ke(this,"name",zy),Ke(this,"keychain"),Ke(this,"randomSessionIdentifier",ya()),Ke(this,"initialized",!1),Ke(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ke(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Ke(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),n=cc(i);return jh(n.publicKey)}),Ke(this,"generateKeyPair",()=>{this.isInitialized();const i=Dw();return this.setPrivateKey(i.publicKey,i.privateKey)}),Ke(this,"signJWT",async i=>{this.isInitialized();const n=await this.getClientSeed(),o=cc(n),a=this.randomSessionIdentifier;return await Bh(a,i,Fy,o)}),Ke(this,"generateSharedKey",(i,n,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=Mw(a,n);return this.setSymKey(c,o)}),Ke(this,"setSymKey",async(i,n)=>{this.isInitialized();const o=n||Wn(i);return await this.keychain.set(o,i),o}),Ke(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ke(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ke(this,"encode",async(i,n,o)=>{this.isInitialized();const a=$d(o),c=qh(n);if(ul(a))return Bw(c,o?.encoding);if(ll(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 Lw({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Ke(this,"decode",async(i,n,o)=>{this.isInitialized();const a=zw(n,o);if(ul(a)){const c=qw(n,o?.encoding);return lc(c)}if(ll(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=jw({symKey:c,encoded:n,encoding:o?.encoding});return lc(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ke(this,"getPayloadType",(i,n=Bt)=>{const o=zi({encoded:i,encoding:n});return sr(o.type)}),Ke(this,"getPayloadSenderPublicKey",(i,n=Bt)=>{const o=zi({encoded:i,encoding:n});return o.senderPublicKey?ht(o.senderPublicKey,rt):void 0}),this.core=e,this.logger=it(s,this.name),this.keychain=r||new Wv(this.core,this.logger)}get context(){return Ct(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(Cl)}catch{e=ya(),await this.keychain.set(Cl,e)}return qv(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Gv=Object.defineProperty,Jv=Object.defineProperties,Yv=Object.getOwnPropertyDescriptors,Tl=Object.getOwnPropertySymbols,Xv=Object.prototype.hasOwnProperty,Zv=Object.prototype.propertyIsEnumerable,Ia=(t,e,s)=>e in t?Gv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qv=(t,e)=>{for(var s in e||(e={}))Xv.call(e,s)&&Ia(t,s,e[s]);if(Tl)for(var s of Tl(e))Zv.call(e,s)&&Ia(t,s,e[s]);return t},e0=(t,e)=>Jv(t,Yv(e)),gt=(t,e,s)=>Ia(t,typeof e!="symbol"?e+"":e,s);class t0 extends Kp{constructor(e,s){super(e,s),this.logger=e,this.core=s,gt(this,"messages",new Map),gt(this,"messagesWithoutClientAck",new Map),gt(this,"name",Vy),gt(this,"version",Ky),gt(this,"initialized",!1),gt(this,"storagePrefix",Zt),gt(this,"init",async()=>
14{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}}}),gt(this,"set",async(r,i,n)=>{this.isInitialized();const o=Jt(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===Hn.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,e0(Qv({},c),{[o]:i}))}return await this.persist(),o}),gt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),gt(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}),gt(this,"has",(r,i)=>{this.isInitialized();const n=this.get(r),o=Jt(i);return typeof n[o]<"u"}),gt(this,"ack",async(r,i)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(r);if(typeof n>"u")return;const o=Jt(i);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,n),await this.persist()}),gt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=it(e,this.name),this.core=s}get context(){return Ct(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,aa(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,aa(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ca(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?ca(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var s0=Object.defineProperty,r0=Object.defineProperties,i0=Object.getOwnPropertyDescriptors,xl=Object.getOwnPropertySymbols,n0=Object.prototype.hasOwnProperty,o0=Object.prototype.propertyIsEnumerable,Aa=(t,e,s)=>e in t?s0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xn=(t,e)=>{for(var s in e||(e={}))n0.call(e,s)&&Aa(t,s,e[s]);if(xl)for(var s of xl(e))o0.call(e,s)&&Aa(t,s,e[s]);return t},Lo=(t,e)=>r0(t,i0(e)),Dt=(t,e,s)=>Aa(t,typeof e!="symbol"?e+"":e,s);class a0 extends Gp{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Dt(this,"events",new ir.EventEmitter),Dt(this,"name",Gy),Dt(this,"queue",new Map),Dt(this,"publishTimeout",D.toMiliseconds(D.ONE_MINUTE)),Dt(this,"initialPublishTimeout",D.toMiliseconds(D.ONE_SECOND*15)),Dt(this,"needsTransportRestart",!1),Dt(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?.ttl||Il,c=eo(n),l=n?.prompt||!1,u=n?.tag||0,d=n?.id||Tr().toString(),h={topic:r,message:i,opts:{ttl:a,relay:c,prompt:l,tag:u,id:d,attestation:n?.attestation,tvf:n?.tvf}},p=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const w=new Promise(async g=>{const f=({id:y})=>{h.opts.id===y&&(this.removeRequestFromQueue(y),this.relayer.events.removeListener(ze.publish,f),g(h))};this.relayer.events.on(ze.publish,f);const b=Ns(new Promise((y,v)=>{this.rpcPublish({topic:r,message:i,ttl:a,prompt:l,tag:u,id:d,attestation:n?.attestation,tvf:n?.tvf}).then(y).catch(C=>{this.logger.warn(C,C?.message),v(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await b,this.events.removeListener(ze.publish,f)}catch(y){this.queue.set(d,Lo(xn({},h),{attempt:1})),this.logger.warn(y,y?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:r,message:i,opts:n}}),await Ns(w,this.publishTimeout,p)}catch(w){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(w),(o=n?.internal)!=null&&o.throwOnFailedPublish)throw w}finally{this.queue.delete(d)}}),Dt(this,"on",(r,i)=>{this.events.on(r,i)}),Dt(this,"once",(r,i)=>{this.events.once(r,i)}),Dt(this,"off",(r,i)=>{this.events.off(r,i)}),Dt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=it(s,this.name),this.registerEventListeners()}get context(){return Ct(this.logger)}async rpcPublish(e){var s,r,i,n;const{topic:o,message:a,ttl:c=Il,prompt:l,tag:u,id:d,attestation:h,tvf:p}=e,w={method:vi(eo().protocol).publish,params:xn({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:h},p),id:d};Je((s=w.params)==null?void 0:s.prompt)&&((r=w.params)==null||delete r.prompt),Je((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 g=await this.relayer.request(w);return this.relayer.events.emit(ze.publish,e),this.logger.debug("Successfully Published Payload"),g}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{const r=e.attempt+1;this.queue.set(s,Lo(xn({},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(Lo(xn({},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(ei.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ze.connection_stalled);return}this.checkQueue()}),this.relayer.on(ze.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var c0=Object.defineProperty,l0=(t,e,s)=>e in t?c0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fr=(t,e,s)=>l0(t,typeof e!="symbol"?e+"":e,s);class u0{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,520 bytes, line 14
14get topics(){return Array.from(this.map.keys())}}var d0=Object.defineProperty,h0=Object.defineProperties,p0=Object.getOwnPropertyDescriptors,$l=Object.getOwnPropertySymbols,f0=Object.prototype.hasOwnProperty,g0=Object.prototype.propertyIsEnumerable,Na=(t,e,s)=>e in t?d0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fi=(t,e)=>{for(var s in e||(e={}))f0.call(e,s)&&Na(t,s,e[s]);if($l)for(var s of $l(e))g0.call(e,s)&&Na(t,s,e[s]);return t},jo=(t,e)=>h0(t,p0(e)),be=(t,e,s)=>Na(t,typeof e!="symbol"?e+"":e,s);class m0 extends Xp{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,be(this,"subscriptions",new Map),be(this,"topicMap",new u0),be(this,"events",new ir.EventEmitter),be(this,"name",tb),be(this,"version",sb),be(this,"pending",new Map),be(this,"cached",[]),be(this,"initialized",!1),be(this,"storagePrefix",Zt),be(this,"subscribeTimeout",D.toMiliseconds(D.ONE_MINUTE)),be(this,"initialSubscribeTimeout",D.toMiliseconds(D.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=eo(i),o={topic:r,relay:n,transportType: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?.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(ei.pulse,async()=>{await this.checkPending()}),this.events.on(mt.created,async r=>{const i=mt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(mt.deleted,async r=>{const i=mt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=it(s,this.name),this.clientId=""}get context(){return Ct(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=eo(r);await this.restartToComplete({topic:e,id:s,relay:i}),await this.rpcUnsubscribe(e,s,i);const n=ye("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?.transportType===_e.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const n={method:vi(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?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(r?.transportType===_e.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(u=>this.logger.warn(u))},D.toMiliseconds(D.ONE_SECOND)),a;const c=new Promise(async u=>{const d=h=>{h.topic===e&&(this.events.removeListener(mt.created,d),u(h.id))};this.events.on(mt.created,d);try{const h=await Ns(new Promise((p,w)=>{this.relayer.request(n).catch(g=>{this.logger.warn(g,g?.message),w(g)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(mt.created,d),u(h)}catch{}}),l=await Ns(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(ze.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,r={method:vi(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 Ns(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(ze.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,r={method:vi(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 Ns(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(ze.connection_stalled)}return i}rpcUnsubscribe(e,s,r){const i={method:vi(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,jo(fi({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,fi({},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,fi({},s)),this.topicMap.set(s.topic,e),this.events.emit(mt.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}=U("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(mt.deleted,jo(fi({},r),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(mt.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(mt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:s}=U("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=>jo(fi({}
14,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(D.toMiliseconds(D.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}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Jt(e+await this.getClientId())}}var w0=Object.defineProperty,Rl=Object.getOwnPropertySymbols,y0=Object.prototype.hasOwnProperty,b0=Object.prototype.propertyIsEnumerable,_a=(t,e,s)=>e in t?w0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ul=(t,e)=>{for(var s in e||(e={}))y0.call(e,s)&&_a(t,s,e[s]);if(Rl)for(var s of Rl(e))b0.call(e,s)&&_a(t,s,e[s]);return t},ue=(t,e,s)=>_a(t,typeof e!="symbol"?e+"":e,s);class v0 extends Jp{constructor(e){super(e),ue(this,"protocol","wc"),ue(this,"version",2),ue(this,"core"),ue(this,"logger"),ue(this,"events",new ir.EventEmitter),ue(this,"provider"),ue(this,"messages"),ue(this,"subscriber"),ue(this,"publisher"),ue(this,"name",Yy),ue(this,"transportExplicitlyClosed",!1),ue(this,"initialized",!1),ue(this,"connectionAttemptInProgress",!1),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"packageName"),ue(this,"bundleId"),ue(this,"hasExperiencedNetworkDisruption",!1),ue(this,"pingTimeout"),ue(this,"heartBeatTimeout",D.toMiliseconds(D.THIRTY_SECONDS+D.FIVE_SECONDS)),ue(this,"reconnectTimeout"),ue(this,"connectPromise"),ue(this,"reconnectInProgress",!1),ue(this,"requestsInFlight",[]),ue(this,"connectTimeout",D.toMiliseconds(D.ONE_SECOND*15)),ue(this,"request",async s=>{var r,i;this.logger.debug("Publishing Request Payload");const n=s.id||Tr().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}}),ue(this,"resetPingTimeout",()=>{Zn()&&(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?.message)}},this.heartBeatTimeout))}),ue(this,"onPayloadHandler",s=>{this.onProviderPayload(s),this.resetPingTimeout()}),ue(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(ze.connect)}),ue(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ue(this,"onProviderErrorHandler",s=>{this.logger.fatal(`Fatal socket error: ${s.message}`),this.events.emit(ze.error,s),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ue(this,"registerProviderListeners",()=>{this.provider.on(St.payload,this.onPayloadHandler),this.provider.on(St.connect,this.onConnectHandler),this.provider.on(St.disconnect,this.onDisconnectHandler),this.provider.on(St.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?it(e.logger,this.name):ja(pn({level:e.logger||Jy})),this.messages=new t0(this.logger,e.core),this.subscriber=new m0(this,this.logger),this.publisher=new a0(this,this.logger),this.relayUrl=e?.relayUrl||jd,this.projectId=e.projectId,ag()?this.packageName=$c():cg()&&(this.bundleId=$c()),this.provider={}}
vendor: 24,778 bytes, line 14
14async 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?.message)}}get context(){return Ct(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:_e.relay},Hn.outbound)}async subscribe(e,s){var r,i,n;this.isInitialized(),(!(s!=null&&s.transportType)||s?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=s?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=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(mt.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(mt.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,Ul({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 Ns(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 El())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const s=e.sort((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?.message)}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:r}=e;if(!s.sessionExists){const i=Me(D.FIVE_MINUTES),n={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,n)}this.events.emit(ze.message,e),await this.recordMessageEvent(e,Hn.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=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(St.disconnect,n),await Ns(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(St.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(St.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(St.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,D.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,r,i,n;if(Zn())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?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new xt(new Lh(pg({sdkVersion:va,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}),Ba(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:_e.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ul({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else qa(e)&&this.events.emit(ze.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Hn.inbound),this.events.emit(ze.message,e))}async acknowledgePayload(e){const s=no(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(St.payload,this.onPayloadHandler),this.provider.off(St.connect,this.onConnectHandler),this.provider.off(St.disconnect,this.onDisconnectHandler),this.provider.off(St.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await El();Uy(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(ei.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Ly())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(ze.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},D.toMiliseconds(Zy)))))}isInitialized(){if(!this.initialized){const{message:e}=U("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 E0(){}function Dl(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 Ml(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Ll(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const C0="[object RegExp]",I0="[object String]",A0="[object Number]",N0="[object Boolean]",jl="[object Arguments]",_0="[object Symbol]",S0="[object Date]",P0="[object Map]",O0="[object Set]",k0="[object Array]",T0="[object Function]",x0="[object ArrayBuffer]",Bo="[object Object]",$0="[object Error]",R0="[object DataView]",U0="[object Uint8Array]",D0="[object Uint8ClampedArray]",M0="[object Uint16Array]",L0="[object Uint32Array]",j0="[object BigUint64Array]",B0="[object Int8Array]",q0="[object Int16Array]",z0="[object Int32Array]",F0="[object BigInt64Array]",W0="[object Float32Array]",H0="[object Float64Array]";function V0(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function K0(t,e,s){return Ei(t,e,void 0,void 0,void 0,void 0,s)}function Ei(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=Ll(t),n=Ll(e);if(i===jl&&(i=Bo),n===jl&&(n=Bo),i!==n)return!1;switch(i){case I0:return t.toString()===e.toString();case A0:{const c=t.valueOf(),l=e.valueOf();return V0(c,l)}case N0:case S0:case _0:return Object.is(t.valueOf(),e.valueOf());case C0:return t.source===e.source&&t.flags===e.flags;case T0: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 P0:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Ei(l,e.get(c),c,t,e,s,r))return!1;return!0}case O0:{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=>Ei(d,p,void 0,t,e,s,r));if(h===-1)return!1;l.splice(h,1)}return!0}case k0:case U0:case D0:case M0:case L0:case j0:case B0:case q0:case z0:case F0:case W0:case H0:{if(typeof Qe<"u"&&Qe.isBuffer(t)!==Qe.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Ei(t[c],e[c],c,t,e,s,r))return!1;return!0}case x0:return t.byteLength!==e.byteLength?!1:Oi(new Uint8Array(t),new Uint8Array(e),s,r);case R0:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Oi(new Uint8Array(t),new Uint8Array(e),s,r);case $0:return t.name===e.name&&t.message===e.message;case Bo:{if(!(Oi(t.constructor,e.constructor,s,r)||Dl(t)&&Dl(e)))return!1;const c=[...Object.keys(t),...Ml(t)],l=[...Object.keys(e),...Ml(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(!Ei(h,p,d,t,e,s,r))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function G0(t,e){return K0(t,e,E0)}var J0=Object.defineProperty,Bl=Object.getOwnPropertySymbols,Y0=Object.prototype.hasOwnProperty,X0=Object.prototype.propertyIsEnumerable,Sa=(t,e,s)=>e in t?J0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ql=(t,e)=>{for(var s in e||(e={}))Y0.call(e,s)&&Sa(t,s,e[s]);if(Bl)for(var s of Bl(e))X0.call(e,s)&&Sa(t,s,e[s]);return t},ct=(t,e,s)=>Sa(t,typeof e!="symbol"?e+"":e,s);class cr extends Yp{constructor(e,s,r,i=Zt,n=void 0){super(e,s,r,i),this.core=e,this.logger=s,this.name=r,ct(this,"map",new Map),ct(this,"version",Qy),ct(this,"cached",[]),ct(this,"initialized",!1),ct(this,"getKey"),ct(this,"storagePrefix",Zt),ct(this,"recentlyDeleted",[]),ct(this,"recentlyDeletedLimit",200),ct(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Je(o)?this.map.set(this.getKey(o),o):hy(o)?this.map.set(o.id,o):py(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ct(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())}),ct(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ct(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>G0(a[c],o[c]))):this.values)),ct(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=ql(ql({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ct(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=it(s,this.name),this.storagePrefix=i,this.getKey=n}get context(){return Ct(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}=U("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=U("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}=U("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}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Z0=Object.defineProperty,Q0=(t,e,s)=>e in t?Z0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ne=(t,e,s)=>Q0(t,typeof e!="symbol"?e+"":e,s);class eE{constructor(e,s){this.core=e,this.logger=s,ne(this,"name",rb),ne(this,"version",ib),ne(this,"events",new La),ne(this,"pairings"),ne(this,"initialized",!1),ne(this,"storagePrefix",Zt),ne(this,"ignoredPayloadTypes",[us]),ne(this,"registeredMethods",[]),ne(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ne(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),ne(this,"create",async r=>{this.isInitialized();const i=ya(),n=await this.core.crypto.setSymKey(i),o=Me(D.FIVE_MINUTES),a={protocol:Ld},c={topic:n,expiry:o,relay:a,active:!1,methods:r?.methods},l=hl({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:i,relay:a,expiryTimestamp:o,methods: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?.transportType}),{topic:n,uri:l}}),ne(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[Vt.pairing_started]}});this.isValidPair(r,i);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=dl(r.uri);i.props.properties.topic=n,i.addTrace(Vt.pairing_uri_validation_success),i.addTrace(Vt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),i.addTrace(Vt.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(Vt.pairing_not_expired)}const d=c||Me(D.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(Vt.store_new_pairing),r.activatePairing&&await this.activate({topic:n}),this.events.emit(Fs.create,h),i.addTrace(Vt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),i.addTrace(Vt.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(Vt.subscribe_pairing_topic_success),h}),ne(this,"activate",async({topic:r})=>{this.isInitialized();const i=Me(D.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),ne(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}=Bs();this.events.once(fe("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),ne(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),ne(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),ne(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ne(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",ye("USER_DISCONNECTED")),await this.deletePairing(i))}),ne(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:n,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return hl({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),ne(this,"sendRequest",async(r,i,n)=>{const o=Hs(i,n),a=await this.core.crypto.encode(r,o),c=hi[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),ne(this,"sendResult",async(r,i,n)=>{const o=no(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=hi[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ne(this,"sendError",async(r,i,n)=>{const o=ku(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=hi[c]?hi[c].res:hi.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ne(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,ye("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),ne(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>Es(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),ne(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)}}),ne(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)}}),ne(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)}}),ne(this,"onPairingPingResponse",(r,i)=>{const{id:n}=i;setTimeout(()=>{ns(i)?this.events.emit(fe("pairing_ping",n),{}):Kt(i)&&this.events.emit(fe("pairing_ping",n),{error:i.error})},500)}),ne(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)}}),ne(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:n,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=ye("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)}}),ne(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(ye("WC_METHOD_UNSUPPORTED",r))}),ne(this,"isValidPair",(r,i)=>{var n;if(!ut(r)){const{message:a}=U("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(os.malformed_pairing_uri),new Error(a)}if(!dy(r.uri)){const{message:a}=U("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(os.malformed_pairing_uri),new Error(a)}const o=dl(r?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=U("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}=U("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(os.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&D.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(os.pairing_expired);const{message:a}=U("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ne(this,"isValidPing",async r=>{if(!ut(r)){const{message:n}=U("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),ne(this,"isValidDisconnect",async r=>{if(!ut(r)){const{message:n}=U("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),ne(this,"isValidPairingTopic",async r=>{if(!$e(r,!1)){const{message:i}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(Es(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=U("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=it(s,this.name),this.pairings=new cr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ct(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ze.message,async e=>{const{topic:s,message:r,transportType:i}=e;if(this.pairings.keys.includes(s)&&i!==_e.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const n=await this.core.crypto.decode(s,r);Ba(n)?(this.core.history.set(s,n),await this.onRelayEventRequest({topic:s,payload:n})):qa(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(kt.expired,async e=>{const{topic:s}=ed(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(Fs.expire,{topic:s}))})}}var tE=Object.defineProperty,sE=(t,e,s)=>e in t?tE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ge=(t,e,s)=>sE(t,typeof e!="symbol"?e+"":e,s);class rE extends Vp{constructor(e,s){super(e,s),this.core=e,this.logger=s,Ge(this,"records",new Map),Ge(this,"events",new ir.EventEmitter),Ge(this,"name",nb),Ge(this,"version",ob),Ge(this,"cac
14hed",[]),Ge(this,"initialized",!1),Ge(this,"storagePrefix",Zt),Ge(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)}),Ge(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:Me(D.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Rt.created,o)}),Ge(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=Kt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(Rt.updated,i))}),Ge(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))),Ge(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(Rt.deleted,n)}}),this.persist()}),Ge(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Ge(this,"on",(r,i)=>{this.events.on(r,i)}),Ge(this,"once",(r,i)=>{this.events.once(r,i)}),Ge(this,"off",(r,i)=>{this.events.off(r,i)}),Ge(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=it(s,this.name)}get context(){return Ct(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:Hs(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}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Rt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=U("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(Rt.created,e=>{const s=Rt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Rt.updated,e=>{const s=Rt.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Rt.deleted,e=>{const s=Rt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(ei.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{D.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(Rt.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var iE=Object.defineProperty,nE=(t,e,s)=>e in t?iE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ze=(t,e,s)=>nE(t,typeof e!="symbol"?e+"":e,s);class oE extends Zp{constructor(e,s){super(e,s),this.core=e,this.logger=s,Ze(this,"expirations",new Map),Ze(this,"events",new ir.EventEmitter),Ze(this,"name",ab),Ze(this,"version",cb),Ze(this,"cac
14hed",[]),Ze(this,"initialized",!1),Ze(this,"storagePrefix",Zt),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(kt.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(kt.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=it(s,this.name)}get context(){return Ct(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 fg(e);if(typeof e=="number")return gg(e);const{message:s}=U("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(kt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=U("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}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return s}checkExpiry(e,s){const{expiry:r}=s;D.toMiliseconds(r)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(kt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(ei.pulse,()=>this.checkExpirations()),this.events.on(kt.created,e=>{const s=kt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(kt.expired,e=>{const s=kt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(kt.deleted,e=>{const s=kt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var aE=Object.defineProperty,cE=(t,e,s)=>e in t?aE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xe=(t,e,s)=>cE(t,typeof e!="symbol"?e+"":e,s);class lE extends Qp{constructor(e,s,r){super(e,s,r),this.core=e,this.logger=s,this.store=r,xe(this,"name",lb),xe(this,"abortController"),xe(this,"isDevEnv"),xe(this,"verifyUrlV3",db),xe(this,"storagePrefix",Zt),xe(this,"version",Md),xe(this,"publicKey"),xe(this,"fetchPromise"),xe(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&D.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),xe(this,"register",async i=>{if(!ri()||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(D.ONE_SECOND*5),d=await new Promise((h,p)=>{const w=()=>{window.removeEventListener("message",f),l.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",w);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",w,{signal:this.abortController.signal});const f=b=>
vendor: 11,440 bytes, line 14
14{if(b.data&&typeof b.data=="string")try{const y=JSON.parse(b.data);if(y.type==="verify_attestation"){if(Qo(y.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",w),window.removeEventListener("message",f),h(y.attestation===null?"":y.attestation)}}catch(y){this.logger.warn(y)}};l.body.appendChild(g),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),xe(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(Qo(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?.verifyUrl);return this.fetchAttestation(o,c)}),xe(this,"fetchAttestation",async(i,n)=>{this.logger.debug(`resolving attestation: ${i} from url: ${n}`);const o=this.startAbortTimer(D.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}),xe(this,"getVerifyUrl",i=>{let n=i||Pi;return hb.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Pi}`),n=Pi),n}),xe(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(D.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)}}),xe(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),xe(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),xe(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")}}),xe(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),xe(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}),xe(this,"validateAttestation",(i,n)=>{const o=Ww(i,n.publicKey),a={hasExpired:D.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=it(s,this.name),this.abortController=new AbortController,this.isDevEnv=Wa(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ct(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),D.toMiliseconds(e))}}var uE=Object.defineProperty,dE=(t,e,s)=>e in t?uE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,zl=(t,e,s)=>dE(t,typeof e!="symbol"?e+"":e,s);class hE extends ef{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,zl(this,"context",pb),zl(this,"registerDeviceToken",async r=>{const{clientId:i,token:n,notificationType:o,enableEncrypted:a=!1}=r,c=`${fb}/${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=it(s,this.context)}}var pE=Object.defineProperty,Fl=Object.getOwnPropertySymbols,fE=Object.prototype.hasOwnProperty,gE=Object.prototype.propertyIsEnumerable,Pa=(t,e,s)=>e in t?pE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,gi=(t,e)=>{for(var s in e||(e={}))fE.call(e,s)&&Pa(t,s,e[s]);if(Fl)for(var s of Fl(e))gE.call(e,s)&&Pa(t,s,e[s]);return t},je=(t,e,s)=>Pa(t,typeof e!="symbol"?e+"":e,s);class mE extends tf{constructor(e,s,r=!0){super(e,s,r),this.core=e,this.logger=s,je(this,"context",mb),je(this,"storagePrefix",Zt),je(this,"storageVersion",gb),je(this,"events",new Map),je(this,"shouldPersist",!1),je(this,"init",async()=>{if(!Wa())try{const i={eventId:Uc(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Zu(this.core.relayer.protocol,this.core.relayer.version,va)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),je(this,"createEvent",i=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=Uc(),u=this.core.projectId||"",d=Date.now(),h=gi({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}),je(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 gi(gi({},a),this.setMethods(a.eventId))}),je(this,"deleteEvent",i=>{const{eventId:n}=i;this.events.delete(n),this.shouldPersist=!0}),je(this,"setEventListeners",()=>{this.core.heartbeat.on(ei.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{D.fromMiliseconds(Date.now())-D.fromMiliseconds(i.timestamp)>wb&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),je(this,"setMethods",i=>({addTrace:n=>this.addTrace(i,n),setError:n=>this.setError(i,n)})),je(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)}),je(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)}),je(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),je(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,gi(gi({},n),this.setMethods(n.eventId)))})}catch(i){this.logger.warn(i)}}),je(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)}}),je(this,"sendEvent",async i=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${yb}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${va}${n}`,{method:"POST",body:JSON.stringify(i)})}),je(this,"getAppDomain",()=>Xu().url),this.logger=it(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 wE=Object.defineProperty,Wl=Object.getOwnPropertySymbols,yE=Object.prototype.hasOwnProperty,bE=Object.prototype.propertyIsEnumerable,Oa=(t,e,s)=>e in t?wE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Hl=(t,e)=>{for(var s in e||(e={}))yE.call(e,s)&&Oa(t,s,e[s]);if(Wl)for(var s of Wl(e))bE.call(e,s)&&Oa(t,s,e[s]);return t},Ae=(t,e,s)=>Oa(t,typeof e!="symbol"?e+"":e,s);let vE=class Xd extends zp{constructor(e){var s;super(e),Ae(this,"protocol",Dd),Ae(this,"version",Md),Ae(this,"name",ba),Ae(this,"relayUrl"),Ae(this,"projectId"),Ae(this,"customStoragePrefix"),Ae(this,"events",new ir.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:_e.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(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?.projectId,this.relayUrl=e?.relayUrl||jd,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=pn({level:typeof e?.logger=="string"&&e.logger?e.logger:By.logger,name:ba}),{logger:n,chunkLoggerController:o}=Ou({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(s=this.logChunkController)!=null&&s.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=it(n,this.name),this.heartbeat=new Dh,this.crypto=new Kv(this,this.logger,e?.keychain),this.history=new rE(this,this.logger),this.expirer=new oE(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Mh(Hl(Hl({},qy),e?.storageOptions)),this.relayer=new v0({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new eE(this,this.logger),this.verify=new lE(this,this.logger,this.storage),this.echoClient=new hE(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new mE(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new Xd(e);await s.initialize();const r=await s.crypto.getClientId();return await s.storage.setItem(eb,r),s}get context(){return Ct(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(Al,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(
14),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(Al)||[],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 Ur<"u"&&jy.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const EE=vE,Zd="wc",Qd=2,eh="client",Za=`${Zd}@${Qd}:${eh}:`,qo={name:eh,logger:"error"},Vl="WALLETCONNECT_DEEPLINK_CHOICE",CE="proposal",Kl="Proposal expired",IE="session",gr=D.SEVEN_DAYS,AE="engine",Be={wc_sessionPropose:{req:{ttl:D.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1104},res:{ttl:D.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1106},res:{ttl:D.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:D.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:D.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1112},res:{ttl:D.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1114},res:{ttl:D.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:D.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:D.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1119}}},zo={min:D.FIVE_MINUTES,max:D.SEVEN_DAYS},Ht={idle:"IDLE",active:"ACTIVE"},Gl={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},NE="request",_E=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],SE="wc",PE="auth",OE="authKeys",kE="pairingTopics",TE="requests",mo=`${SE}@${1.5}:${PE}:`,Vn=`${mo}:PUB_KEY`;var xE=Object.defineProperty,$E=Object.defineProperties,RE=Object.getOwnPropertyDescriptors,Jl=Object.getOwnPropertySymbols,UE=Object.prototype.hasOwnProperty,DE=Object.prototype.propertyIsEnumerable,ka=(t,e,s)=>e in t?xE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ve=(t,e)=>{for(var s in e||(e={}))UE.call(e,s)&&ka(t,s,e[s]);if(Jl)for(var s of Jl(e))DE.call(e,s)&&ka(t,s,e[s]);return t},st=(t,e)=>$E(t,RE(e)),P=(t,e,s)=>ka(t,typeof e!="symbol"?e+"":e,s);class ME extends of{constructor(e){super(e),P(this,"name",AE),P(this,"events",new La),P(this,"initialized",!1),P(this,"requestQueue",{state:Ht.idle,queue:[]}),P(this,"sessionRequestQueue",{state:Ht.idle,queue:[]}),P(this,"requestQueueDelay",D.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(Be)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},D.toMiliseconds(this.requestQueueDelay)))}),P(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=st(ve({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=oy(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 N=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=N.active}}catch(N){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),N}if(!u||!h){const{topic:N,uri:_}=await this.client.core.pairing.create();u=N,d=_}if(!u){const{message:N}=U("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(N)}const p=await this.client.core.crypto.generateKeyPair(),w=Be.wc_
14sessionPropose.req.ttl||D.FIVE_MINUTES,g=Me(w),f=st(ve(ve({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:Ld}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:ps()}),b=fe("session_connect",f.id),{reject:y,resolve:v,done:C}=Bs(w,Kl),A=({id:N})=>{N===f.id&&(this.client.events.off("proposal_expire",A),this.pendingSessions.delete(f.id),this.events.emit(b,{error:{message:Kl,code:0}}))};return this.client.events.on("proposal_expire",A),this.events.once(b,({error:N,session:_})=>{this.client.events.off("proposal_expire",A),N?y(N):_&&v(_)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{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?.id)==null?void 0:r.toString(),trace:[Ut.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(E){throw o.setError(Ds.no_internet_connection),E}try{await this.isValidProposalId(s?.id)}catch(E){throw this.client.logger.error(`approve() -> proposal.get(${s?.id}) failed`),o.setError(Ds.proposal_not_found),E}try{await this.isValidApprove(s)}catch(E){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Ds.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:g,requiredNamespaces:f,optionalNamespaces:b}=p;let y=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:w});y||(y=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Ut.session_approve_started,properties:{topic:w,trace:[Ut.session_approve_started,Ut.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),C=g.publicKey,A=await this.client.core.crypto.generateSharedKey(v,C),N=ve(ve(ve({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:Me(gr)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),_=_e.relay;y.addTrace(Ut.subscribing_session_topic);try{await this.client.core.relayer.subscribe(A,{transportType:_})}catch(E){throw y.setError(Ds.subscribe_session_topic_failure),E}y.addTrace(Ut.subscribe_session_topic_success);const R=st(ve({},N),{topic:A,requiredNamespaces:f,optionalNamespaces:b,pairingTopic:w,acknowledged:!1,self:N.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:v,transportType:_e.relay});await this.client.session.set(A,R),y.addTrace(Ut.store_session);try{y.addTrace(Ut.publishing_session_settle),await this.sendRequest({topic:A,method:"wc_sessionSettle",params:N,throwOnFailedPublish:!0}).catch(E=>{throw y?.setError(Ds.session_settle_publish_failure),E}),y.addTrace(Ut.session_settle_publish_success),y.addTrace(Ut.publishing_session_approve),await this.sendResult({id:a,topic:w,result:{relay:{protocol:c??"irn"},responderPublicKey:v},throwOnFailedPublish:!0}).catch(E=>{throw y?.setError(Ds.session_approve_publish_failure),E}),y.addTrace(Ut.session_approve_publish_success)}catch(E){throw this.client.logger.error(E),this.client.session.delete(A,ye("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(A),E}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:g.metadata}),await this.client.proposal.delete(a,ye("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(A,Me(gr)),{topic:A,acknowledged:()=>Promise.resolve(this.client.session.get(A))}}),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}
14n&&(await this.sendError({id:r,topic:n,error:i,rpcOpts:Be.wc_sessionPropose.reject}),await this.client.proposal.delete(r,ye("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}=Bs(),c=ps(),l=Tr().toString(),u=this.client.session.get(r).namespaces;return this.events.once(fe("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=ps(),{done:n,resolve:o,reject:a}=Bs();return this.events.once(fe("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,Me(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(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:r,request:i,topic:n,expiry:o=Be.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(n);a?.transportType===_e.relay&&await this.confirmOnlineStateOrThrow();const c=ps(),l=Tr().toString(),{done:u,resolve:d,reject:h}=Bs(o,"Request expired. Please try again.");this.events.once(fe("session_request",c),({error:b,result:y})=>{b?h(b):d(y)});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:st(ve({},i),{expiryTimestamp:Me(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:w}).catch(b=>h(b)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),await u();const g={request:st(ve({},i),{expiryTimestamp:Me(o)}),chainId:r},f=this.shouldSetTVF(p,g);return await Promise.all([new Promise(async b=>{await this.sendRequest(ve({clientRpcId:c,relayRpcId:l,topic:n,method:p,params:g,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,g)})).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),b()}),new Promise(async b=>{var y;if(!((y=a.sessionConfig)!=null&&y.disableDeepLink)){const v=await bg(this.client.core.storage,Vl);await mg({id:c,topic:n,wcDeepLink:v})}b()}),u()]).then(b=>b[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===_e.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}):Kt(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=ps(),n=Tr().toString(),{done:o,resolve:a,reject:c}=Bs();this.events.once(fe("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,008 bytes, line 14
14const{topic:r,event:i,chainId:n}=s,o=Tr().toString(),a=ps();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:ye("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}=U("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=>ly(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?_e.link_mode:_e.relay;o===_e.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:p,nbf:w,methods:g=[],expiry:f}=s,b=[...s.resources||[]],{topic:y,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:y,uri:v}});const C=await this.client.core.crypto.generateKeyPair(),A=Wn(C);if(await Promise.all([this.client.auth.authKeys.set(Vn,{responseTopic:A,publicKey:C}),this.client.auth.pairingTopics.set(A,{topic:A,pairingTopic:y})]),await this.client.core.relayer.subscribe(A,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${y}`),g.length>0){const{namespace:x}=Dr(a[0]);let G=dm(x,"request",g);Fn(b)&&(G=pm(G,b.pop())),b.push(G)}const N=f&&f>Be.wc_sessionAuthenticate.req.ttl?f:Be.wc_sessionAuthenticate.req.ttl,_={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:b},requester:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Me(N)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},E={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:y,proposer:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Me(Be.wc_sessionPropose.req.ttl),id:ps()},{done:$,resolve:I,reject:M}=Bs(N,"Request expired"),H=ps(),S=fe("session_connect",E.id),T=fe("session_request",H),O=async({error:x,session:G})=>{this.events.off(T,j),x?M(x):G&&I({session:G})},j=async x=>{var G,Q,se;if(await this.deletePendingAuthRequest(H,{message:"fulfilled",code:0}),x.error){const Ue=ye("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===Ue.code?void 0:(this.events.off(S,O),M(x.error.message))}await this.deleteProposal(E.id),this.events.off(S,O);const{cacaos:Ce,responder:pe}=x.result,Te=[],Le=[];for(const Ue of Ce){await Fc({cacao:Ue,projectId:this.client.core.projectId})||(this.client.logger.error(Ue,"Signature verification failed"),M(ye("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Rs}=Ue,Qt=Fn(Rs.resources),zt=[la(Rs.iss)],es=Qn(Rs.iss);if(Qt){const ur=Wc(Qt),Nn=Hc(Qt);Te.push(...ur),zt.push(...Nn)}for(const ur of zt)Le.push(`${ur}:${es}`)}const Xe=await this.client.core.crypto.generateSharedKey(C,pe.publicKey);let Re;Te.length>0&&(Re={topic:Xe,acknowledged:!0,self:{publicKey:C,metadata:this.client.metadata},peer:pe,controller:pe.publicKey,expiry:Me(gr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:y,namespaces:ml([...new Set(Te)],[...new Set(Le)]),transportType:o},await this.client.core.relayer.subscribe(Xe,{transportType:o}),await this.client.session.set(Xe,Re),y&&await this.client.core.pairing.updateMetadata({topic:y,metadata:pe.metadata}),Re=this.client.session.get(Xe)),(G=this.client.metadata.redirect)!=null&&G.linkMode&&(Q=pe.metadata.redirect)!=null&&Q.linkMode&&(se=pe.metadata.redirect)!=null&&se.universal&&r&&(this.client.core.addLinkModeSupportedApp(pe.metadata.redirect.universal),this.client.session.update(Xe,{transportType:_e.link_mode})),I({auths:Ce,session:Re})};this.events.once(S,O),this.events.once(T,j);let q;try{if(n){const x=Hs("wc_sessionAuthenticate",_,H);this.client.core.history.set(y,x);const G=await this.client.core.crypto.encode("",x,{type:En,encoding:Cs});q=Tn(r,y,G)}else await Promise.all([this.sendRequest({topic:y,method:"wc_sessionAuthenticate",params:_,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:H}),this.sendRequest({topic:y,method:"wc_sessionPropose",params:E,expiry:Be.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(x){throw this.events.off(S,O),this.events.off(T,j),x}return await this.setProposal(E.id,E),await this.setAuthRequest(H,{request:st(ve({},_),{verifyContext:{}}),pairingTopic:y,transportType:o}),{uri:q??v,response:$}}),P(this,"approveSessionAuthenticate",async s=>{const{id:r,auths:i}=s,n=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Ms.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(pi.no_internet_connection),f}const o=this.getPendingAuthRequest(r);if(!o)throw n.setError(pi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||_e.relay;a===_e.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=Wn(c),d={type:us,receiverPublicKey:c,senderPublicKey:l},h=[],p=[];for(const f of i){if(!await Fc({cacao:f,projectId:this.client.core.projectId})){n.setError(pi.invalid_cacao);const A=ye("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:A,encodeOpts:d}),new Error(A.message)}n.addTrace(Ms.cacaos_verified);const{p:b}=f,y=Fn(b.resources),v=[la(b.iss)],C=Qn(b.iss);if(y){const A=Wc(y),N=Hc(y);h.push(...A),v.push(...N)}for(const A of v)p.push(`${A}:${C}`)}const w=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Ms.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:w,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Me(gr),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:ml([...new Set(h)],[...new Set(p)]),transportType:a},n.addTrace(Ms.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:a})}catch(f){throw n.setError(pi.subscribe_authenticated_session_topic_failure),f}n.addTrace(Ms.subscribe_authenticated_session_topic_success),await this.client.session.set(w,g),n.addTrace(Ms.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Ms.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(f){throw n.setError(pi.authenticated_session_approve_publish_failure),f}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:g}}),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===_e.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Wn(o),l={type:us,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:l,rpcOpts:Be.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,ye("USER_DISCONNECTED"))}),P(this,"formatAuthMessage",s=>{this.isInitialized();const{request:r,iss:i}=s;return ld(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,ye("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(Vl).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEac
14h(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,ye("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=Ht.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);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(Ds.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,ye("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),P(this,"deletePendingSessionRequest",async(s,r,i=!1)=>{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=Ht.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,Me(Be.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,r)}),P(this,"setAuthRequest",async(s,r)=>{const{request:i,pairingTopic:n,transportType:o=_e.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||Me(Be.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=Hs(i,n,c);let p;const w=!!u;try{const b=w?Cs:Bt;p=await this.client.core.crypto.encode(r,h,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),b}let g;if(_E.includes(i)){const b=Jt(JSON.stringify(h)),y=Jt(p);g=await this.client.core.verify.register({id:y,decryptedId:b})}const f=Be[i].req;if(f.attestation=g,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(r,h),w){const b=Tn(u,r,p);await re.Linking.openURL(b,this.client.name)}else{const b=Be[i].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=st(ve({},d),{correlationId:h.id}),l?(b.internal=st(ve({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,b)):this.client.core.relayer.publish(r,p,b).catch(y=>this.client.logger.error(y))}return h.id}),P(this,"sendResult",async s=>{const{id:r,topic:i,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=no(r,n);let u;const d=c&&typeof(re==null?void 0:re.Linking)<"u";try{const w=d?Cs:Bt;u=await this.client.core.crypto.encode(i,l,st(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(g){this.client.logger.warn("sendResult() -> getTVFParams() failed",g)}}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),w}if(d){const w=Tn(c,i,u);await re.Linking.openURL(w,this.client.name)}else{const w=h.request.method,g=Be[w].res;g.tvf=st(ve({},p),{correlationId:r}),o?(g.internal=st(ve({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,g)):this.client.core.relayer.publish(i,u,g).catch(f=>this.client.logger.error(f))}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=ku(r,n);let u;const d=c&&typeof(re==null?void 0:re.Linking)<"u";try{const p=d?Cs:Bt;u=await this.client.core.crypto.encode(i,l,st(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=Tn(c,i,u);await re.Linking.openURL(p,this.client.name)}else{const p=h.request.method,w=a||Be[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,044 bytes, line 14
14this.client.session.getAll().forEach(i=>{let n=!1;Es(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=>{Es(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===Ht.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=Ht.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=Ht.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}=U("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?.setError(os.proposal_listener_not_found)),this.isValidConnect(ve({},i.params));const u=a.expiryTimestamp||Me(Be.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:Jt(JSON.stringify(i)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(Vt.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:Be.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(Kt(r)){await this.client.proposal.delete(n,ye("USER_DISCONNECTED"));const o=fe("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(f=>f.sessionTopic===s);if(!p)return this.client.logger.error(`Pending session not found for topic ${s}`);const w=this.client.proposal.get(p.proposalId),g=st(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:_e.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(fe("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),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(fe("session_approve",i),{})):Kt(r)&&(await this.client.session.delete(s,ye("USER_DISCONNECTED")),this.events.emit(fe("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=di.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:ye("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ve({topic:s},i));try{di.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 di.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=fe("session_update",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ns(r)?this.events.emit(fe("session_update",i),{}):Kt(r)&&this.events.emit(fe("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,Me(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=fe("session_extend",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ns(r)?this.events.emit(fe("session_extend",i),{}):Kt(r)&&this.events.emit(fe("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=fe("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);ns(r)?this.events.emit(fe("session_ping",i),{}):Kt(r)&&this.events.emit(fe("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(ze.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:ye("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:Jt(JSON.stringify(Hs("wc_sessionRequest",h,d))),encryptedId:l,metadata:p.peer.metadata,transportType:u}),g={id:d,topic:o,params:h,verifyContext:w};await this.setPendingSessionRequest(g),u===_e.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(g):(this.addSessionRequestToSessionRequestQueue(g),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=fe("session_request",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ns(r)?this.events.emit(fe("session_request",i),{result:r.result}):Kt(r)&&this.events.emit(fe("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=di.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}),di.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(fe("session_request",i),{result:r.result}):Kt(r)&&this.events.emit(fe("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:Jt(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===_e.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:Be.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=Ht.idle,this.processSessionRequestQueue()},D.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=fe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(fe("session_request",n.request.id),{error:r})})}),P(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Ht.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=Ht.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);
14r&&this.onSessionProposeRequest({topic:s.topic,payload:Hs("wc_sessionPropose",st(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(!ut(s)){const{message:l}=U("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(Je(r)||await this.isValidPairingTopic(r),!Ey(c)){const{message:l}=U("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!Je(i)&&Os(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(!Je(n)&&Os(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Je(o)||this.validateSessionProps(o,"sessionProperties"),!Je(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=vy(s,"connect()",r);if(i)throw new Error(i.message)}),P(this,"isValidApprove",async s=>{if(!ut(s))throw new Error(U("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=Uo(i,"approve()");if(l)throw new Error(l.message);const u=bl(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!$e(n,!0)){const{message:d}=U("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(d)}if(Je(o)||this.validateSessionProps(o,"sessionProperties"),!Je(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(!ut(s)){const{message:n}=U("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}=U("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(n)}}),P(this,"isValidSessionSettleRequest",s=>{if(!ut(s)){const{message:l}=U("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:r,controller:i,namespaces:n,expiry:o}=s;if(!Ud(r)){const{message:l}=U("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=fy(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Uo(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Es(o)){const{message:l}=U("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),P(this,"isValidUpdate",async s=>{if(!ut(s)){const{message:c}=U("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=Uo(i,"update()");if(o)throw new Error(o.message);const a=bl(n.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),P(this,"isValidExtend",async s=>{if(!ut(s)){const{message:i}=U("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(!ut(s)){const{message:c}=U("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(!yl(a,n)){const{message:c}=U("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Ay(i)){const{message:c}=U("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!Sy(a,n,i.method)){const{message:c}=U("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!Ty(o,zo)){const{message:c}=U("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${zo.min} and ${zo.max}`);throw new Error(c)}}),P(this,"isValidRespond",async s=>{var r;if(!ut(s)){const{message:o}=U("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?.response)!=null&&r.id&&this.cleanupAfterResponse(s),o}if(!Ny(n)){const{message:o}=U("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),P(this,"isValidPing",async s=>{if(!ut(s)){const{message:i}=U("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(i)}const{topic:r}=s;await this.isValidSessionOrPairingTopic(r)}),P(this,"isValidEmit",async s=>{if(!ut(s)){const{message:a}=U("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}
vendor: 10,442 bytes, line 14
14const{topic:r,event:i,chainId:n}=s;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!yl(o,n)){const{message:a}=U("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!_y(i)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!Py(o,n,i.name)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),P(this,"isValidDisconnect",async s=>{if(!ut(s)){const{message:i}=U("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(!$e(i,!1))throw new Error("uri is required parameter");if(!$e(n,!1))throw new Error("domain is required parameter");if(!$e(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Dr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Dr(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===_e.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}=U("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}=U("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!==_e.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?.redirect)==null?void 0:u.universal)!==void 0&&((d=s?.redirect)==null?void 0:d.universal)!==""&&((h=s?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(re==null?void 0:re.Linking)<"u"}),P(this,"getAppLinkIfEnabled",(s,r)=>{var i;return this.isLinkModeEnabled(s,r)?(i=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=Rc(s,"topic")||"",i=decodeURIComponent(Rc(s,"wc_ev")||""),n=this.client.session.keys.includes(r);n&&this.client.session.update(r,{transportType:_e.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:n})}),P(this,"registerLinkModeListeners",async()=>{var s;if(Wa()||$s()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const r=re==null?void 0:re.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(Gl).includes(i.method)}),P(this,"getTVFParams",(s,r,i)=>{var n,o;try{const a=r.request.method,c=this.extractTxHashesFromResult(a,i);return st(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?.data||((r=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=Gl[s];if(typeof r=="string")return[r];const n=r[i.key];if(Ps(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}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(ze.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(Vn)?this.client.auth.authKeys.get(Vn):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,r,{receiverPublicKey:o,encoding:n===_e.link_mode?Cs:Bt});Ba(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:i,transportType:n,encryptedId:Jt(r)})):qa(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(kt.expired,async e=>{const{topic:s,id:r}=ed(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,U("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,U("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(!$e(e,!1)){const{message:s}=U("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}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(Es(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=U("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!$e(e,!1)){const{message:s}=U("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}=U("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(Es(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=U("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=U("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($e(e,!1)){const{message:s}=U("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=U("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!Cy(e)){const{message:s}=U("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=U("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(Es(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=U("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class LE extends cr{constructor(e,s){super(e,s,CE,Za),this.core=e,this.logger=s}}let jE=class extends cr{constructor(e,s){super(e,s,IE,Za),this.core=e,this.logger=s}};class BE extends cr{constructor(e,s){super(e,s,NE,Za,r=>r.id),this.core=e,this.logger=s}}class qE extends cr{constructor(e,s){super(e,s,OE,mo,()=>Vn),this.core=e,this.logger=s}}class zE extends cr{constructor(e,s){super(e,s,kE,mo),this.core=e,this.logger=s}}class FE extends cr{constructor(e,s){super(e,s,TE,mo,r=>r.id),this.core=e,this.logger=s}}var WE=Object.defineProperty,HE=(t,e,s)=>e in t?WE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Fo=(t,e,s)=>HE(t,typeof e!="symbol"?e+"":e,s);class VE{constructor(e,s){this.core=e,this.logger=s,Fo(this,"authKeys"),Fo(this,"pairingTopics"),Fo(this,"requests"),this.authKeys=new qE(this.core,this.logger),this.pairingTopics=new zE(this.core,this.logger),this.requests=new FE(this.core,this.logger)}
14async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var KE=Object.defineProperty,GE=(t,e,s)=>e in t?KE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oe=(t,e,s)=>GE(t,typeof e!="symbol"?e+"":e,s);let JE=class th extends nf{constructor(e){super(e),oe(this,"protocol",Zd),oe(this,"version",Qd),oe(this,"name",qo.name),oe(this,"metadata"),oe(this,"core"),oe(this,"logger"),oe(this,"events",new ir.EventEmitter),oe(this,"engine"),oe(this,"session"),oe(this,"proposal"),oe(this,"pendingRequest"),oe(this,"auth"),oe(this,"signConfig"),oe(this,"on",(r,i)=>this.events.on(r,i)),oe(this,"once",(r,i)=>this.events.once(r,i)),oe(this,"off",(r,i)=>this.events.off(r,i)),oe(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),oe(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),oe(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),oe(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(n){throw this.logger.error(n.message),n}}),oe(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||qo.name,this.metadata=ug(e?.metadata),this.signConfig=e?.signConfig;const s=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ja(pn({level:e?.logger||qo.logger}));this.core=e?.core||new EE(e),this.logger=it(s,this.name),this.session=new jE(this.core,this.logger),this.proposal=new LE(this.core,this.logger),this.pendingRequest=new BE(this.core,this.logger),this.engine=new ME(this),this.auth=new VE(this.core,this.logger)}static async init(e){const s=new th(e);return await s.initialize(),s}get context(){return Ct(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()},D.toMiliseconds(D.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Yl="error",YE="wss://relay.walletconnect.org",XE="wc",ZE="universal_provider",$n=`${XE}@2:${ZE}:`,sh="https://rpc.walletconnect.org/v1/",Pr="generic",QE=`${sh}bundler`,$t={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function eC(){}function Qa(t){return t==null||typeof t!="object"&&typeof t!="function"}function ec(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function tC(t){if(Qa(t))return t;if(Array.isArray(t)||ec(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 Xl(t){return typeof t=="object"&&t!==null}function rh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}
vendor: 5,234 bytes, line 14
14function ih(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const sC="[object RegExp]",nh="[object String]",oh="[object Number]",ah="[object Boolean]",ch="[object Arguments]",rC="[object Symbol]",iC="[object Date]",nC="[object Map]",oC="[object Set]",aC="[object Array]",cC="[object ArrayBuffer]",lC="[object Object]",uC="[object DataView]",dC="[object Uint8Array]",hC="[object Uint8ClampedArray]",pC="[object Uint16Array]",fC="[object Uint32Array]",gC="[object Int8Array]",mC="[object Int16Array]",wC="[object Int32Array]",yC="[object Float32Array]",bC="[object Float64Array]";function vC(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?.(t,e,s,r);if(n!=null)return n;if(Qa(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 Qe<"u"&&Qe.isBuffer(t))return t.subarray();if(ec(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),Ws(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),Ws(o,t,s,r,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return r.set(t,o),Ws(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,Ws(o,t,s,r,i),o}if(typeof t=="object"&&EC(t)){const o=Object.create(Object.getPrototypeOf(t));return r.set(t,o),Ws(o,t,s,r,i),o}return t}function Ws(t,e,s=t,r,i){const n=[...Object.keys(e),...rh(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 EC(t){switch(ih(t)){case ch:case aC:case cC:case uC:case ah:case iC:case yC:case bC:case gC:case mC:case wC:case nC:case oh:case lC:case sC:case oC:case nh:case rC:case dC:case hC:case pC:case fC:return!0;default:return!1}}function CC(t,e){return vC(t,(s,r,i,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case oh:case nh:case ah:{const o=new t.constructor(t?.valueOf());return Ws(o,t),o}case ch:{const o={};return Ws(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function Zl(t){return CC(t)}function Ql(t){return t!==null&&typeof t=="object"&&ih(t)==="[object Arguments]"}function IC(t){return ec(t)}function AC(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const s=t[Symbol.toStringTag];return s==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${s}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function NC(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=Ta(i,o,r,new Map)}return i}function Ta(t,e,s,r){if(Qa(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(r.has(e))return tC(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),...rh(e)];for(let n=0;n<i.length;n++){const o=i[n];let a=e[o],c=t[o];if(Ql(a)&&(a={...a}),Ql(c)&&(c={...c}),typeof Qe<"u"&&Qe.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)||Xl(c)&&Xl(a)?t[o]=Ta(c,a,s,r):c==null&&AC(a)?t[o]=Ta({},a,s,r):c==null&&IC(a)?t[o]=Zl(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function _C(t,...e){return NC(t,...e,eC)}var SC=Object.defineProperty,PC=Object.defineProperties,OC=Object.getOwnPropertyDescriptors,eu=Object.getOwnPropertySymbols,kC=Object.prototype.hasOwnProperty,TC=Object.prototype.propertyIsEnumerable,tu=(t,e,s)=>e in t?SC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Rn=(t,e)=>{for(var s in e||(e={}))kC.call(e,s)&&tu(t,s,e[s]);if(eu)for(var s of eu(e))TC.call(e,s)&&tu(t,s,e[s]);return t},xC=(t,e)=>PC(t,OC(e));function Et(t,e,s){var r;const i=Dr(t);return((r=e.rpcMap)==null?void 0:r[i.reference])||`${sh}?chainId=${i.namespace}:${i.reference}&projectId=${s}`}function lr(t){return t.includes(":")?t.split(":")[1]:t}function lh(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function $C(t,e){const s=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!s.length)return[];const r=[];
14return s.forEach(i=>{const n=e.namespaces[i].accounts;r.push(...n)}),r}function Un(t={},e={}){const s=su(t),r=su(e);return _C(s,r)}function su(t){var e,s,r,i,n;const o={};if(!Os(t))return o;for(const[a,c]of Object.entries(t)){const l=fo(a)?[a]:c.chains,u=c.methods||[],d=c.events||[],h=c.rpcMap||{},p=$r(a);o[p]=xC(Rn(Rn({},o[p]),c),{chains:Xt(l,(e=o[p])==null?void 0:e.chains),methods:Xt(u,(s=o[p])==null?void 0:s.methods),events:Xt(d,(r=o[p])==null?void 0:r.events)}),(Os(h)||Os(((i=o[p])==null?void 0:i.rpcMap)||{}))&&(o[p].rpcMap=Rn(Rn({},h),(n=o[p])==null?void 0:n.rpcMap))}return o}function ru(t){return t.includes(":")?t.split(":")[2]:t}function iu(t){const e={};for(const[s,r]of Object.entries(t)){const i=r.methods||[],n=r.events||[],o=r.accounts||[],a=fo(s)?[s]:r.chains?r.chains:lh(r.accounts);e[s]={chains:a,methods:i,events:n,accounts:o}}return e}function Wo(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 uh={},de=t=>uh[t],Ho=(t,e)=>{uh[t]=e};var RC=Object.defineProperty,UC=(t,e,s)=>e in t?RC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mr=(t,e,s)=>UC(t,typeof e!="symbol"?e+"":e,s);class DC{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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($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=lr(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||Et(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new xt(new qt(r,de("disableProviderPing")))}}var MC=Object.defineProperty,LC=Object.defineProperties,jC=Object.getOwnPropertyDescriptors,nu=Object.getOwnPropertySymbols,BC=Object.prototype.hasOwnProperty,qC=Object.prototype.propertyIsEnumerable,xa=(t,e,s)=>e in t?MC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ou=(t,e)=>{for(var s in e||(e={}))BC.call(e,s)&&xa(t,s,e[s]);if(nu)for(var s of nu(e))qC.call(e,s)&&xa(t,s,e[s]);return t},au=(t,e)=>LC(t,jC(e)),wr=(t,e,s)=>xa(t,typeof e!="symbol"?e+"":e,s);class zC{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=de("events"),this.client=de("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s),this.chainId=parseInt(e),this.events.emit($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||Et(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new xt(new qt(r,de("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(lr(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");const u=this.client.session.get(e.topic),d=((o=u?.sessionProperties)==null?void 0:o.capabilities)||{};if(d!=null&&d[l])return d?.[l];const h=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:au(ou({},u.sessionProperties||{}),{capabilities:au(ou({},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(Hs("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()}
14getBundlerUrl(e,s){return`${QE}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}}var FC=Object.defineProperty,WC=(t,e,s)=>e in t?FC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yr=(t,e,s)=>WC(t,typeof e!="symbol"?e+"":e,s);class HC{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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($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=lr(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||Et(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new xt(new qt(r,de("disableProviderPing")))}}var VC=Object.defineProperty,KC=(t,e,s)=>e in t?VC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,br=(t,e,s)=>KC(t,typeof e!="symbol"?e+"":e,s);class GC{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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($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=lr(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||Et(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new xt(new qt(r,de("disableProviderPing")))}}var JC=Object.defineProperty,YC=(t,e,s)=>e in t?JC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vr=(t,e,s)=>YC(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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(!this.httpProviders[e]){const r=s||Et(`${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||Et(e,this.namespace,this.client.core.projectId);return typeof r>"u"?void 0:new xt(new qt(r,de("disableProviderPing")))}}var ZC=Object.defineProperty,QC=(t,e,s)=>e in t?ZC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Er=(t,e,s)=>QC(t,typeof e!="symbol"?e+"":e,s);class e1{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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($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=lr(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 xt(new qt(r,de("disableProviderPing")))}}var t1=Object.defineProperty,s1=(t,e,s)=>e in t?t1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Cr=(t,e,s)=>s1(t,typeof e!="symbol"?e+"":e,s);class r1{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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($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=lr(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||Et(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new xt(new qt(r,de("disableProviderPing")))}}var i1=Object.defineProperty,n1=(t,e,s)=>e in t?i1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ir=(t,e,s)=>n1(t,typeof e!="symbol"?e+"":e,s);class o1{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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit($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=lr(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||Et(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new xt(new qt(r,de("disableProviderPing")))}}var a1=Object.defineProperty,c1=(t,e,s)=>e in t?a1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ar=(t,e,s)=>c1(t,typeof e!="symbol"?e+"":e,s);class l1{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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||Et(`${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||Et(e,this.namespace);return typeof r>"u"?void 0:new xt(new qt(r,de("disableProviderPing")))}}var u1=Object.defineProperty,d1=(t,e,s)=>e in t?u1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Nr=(t,e,s)=>d1(t,typeof e!="symbol"?e+"":e,s);class h1{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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||Et(`${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||Et(e,this.namespace);return typeof r>"u"?void 0:new xt(new qt(r))}}var p1=Object.defineProperty,f1=(t,e,s)=>e in t?p1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}
vendor: 9,884 bytes, line 14
14):t[e]=s,_r=(t,e,s)=>f1(t,typeof e!="symbol"?e+"":e,s);class g1{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=de("events"),this.client=de("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.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=Dr(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||Et(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new xt(new qt(r,de("disableProviderPing")))}}var m1=Object.defineProperty,w1=Object.defineProperties,y1=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,b1=Object.prototype.hasOwnProperty,v1=Object.prototype.propertyIsEnumerable,$a=(t,e,s)=>e in t?m1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Dn=(t,e)=>{for(var s in e||(e={}))b1.call(e,s)&&$a(t,s,e[s]);if(cu)for(var s of cu(e))v1.call(e,s)&&$a(t,s,e[s]);return t},Vo=(t,e)=>w1(t,y1(e)),Pt=(t,e,s)=>$a(t,typeof e!="symbol"?e+"":e,s);let E1=class dh{constructor(e){Pt(this,"client"),Pt(this,"namespaces"),Pt(this,"optionalNamespaces"),Pt(this,"sessionProperties"),Pt(this,"scopedProperties"),Pt(this,"events",new La),Pt(this,"rpcProviders",{}),Pt(this,"session"),Pt(this,"providerOpts"),Pt(this,"logger"),Pt(this,"uri"),Pt(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ja(pn({level:e?.logger||Yl})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const s=new dh(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:Dn({},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,no(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:ye("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=iu(this.session.namespaces);this.namespaces=Un(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;const n=iu(i.namespaces);return this.namespaces=Un(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(Ps(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 JE.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Yl,relayUrl:this.providerOpts.relayUrl||YE,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=>$r(s)))];Ho("client",this.client),Ho("events",this.events),Ho("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const r=$C(s,this.session),i=lh(r),n=Un(this.namespaces,this.optionalNamespaces),o=Vo(Dn({},n[s]),{accounts:r,chains:i});switch(s){case"eip155":this.rpcProviders[s]=new zC({namespace:o});break;case"algorand":this.rpcProviders[s]=new XC({namespace:o});break;case"solana":this.rpcProviders[s]=new HC({namespace:o});break;case"cosmos":this.rpcProviders[s]=new GC({namespace:o});break;case"polkadot":this.rpcProviders[s]=new DC({namespace:o});break;case"cip34":this.rpcProviders[s]=new e1({namespace:o});break;case"elrond":this.rpcProviders[s]=new r1({namespace:o});break;case"multiversx":this.rpcProviders[s]=new o1({namespace:o});break;case"near":this.rpcProviders[s]=new l1({namespace:o});break;case"tezos":this.rpcProviders[s]=new h1({namespace:o});break;default:this.rpcProviders[Pr]?this.rpcProviders[Pr].updateNamespace(o):this.rpcProviders[Pr]=new g1({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&&Ps(o)&&this.events.emit("accountsChanged",o.map(ru))}else if(n.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=$r(o),l=Wo(o)!==Wo(a)?`${c}:${Wo(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=Vo(Dn({},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",Vo(Dn({},ye("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]}
14onSessionUpdate(){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=Un(s,r),this.sessionProperties=i,this.scopedProperties=n}validateChain(e){const[s,r]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,r];if(s&&!Object.keys(this.namespaces||{}).map(o=>$r(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=$r(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(ru);if(!Ps(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(`${$n}/${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(`${$n}/${e}${r}`)}async deleteFromStore(e){var s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${$n}/${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($n)&&await this.client.core.storage.removeItem(r)}catch(s){this.logger.warn("Failed to cleanup storage",s)}}};const ki={getSIWX(){return k.state.siwx},async initializeIfEnabled(){const t=k.state.siwx,e=m.getActiveCaipAddress();if(!(t&&e))return;const[s,r,i]=e.split(":");if(m.checkIfSupportedNetwork(s))try{if((await t.getSessions(`${s}:${r}`,i)).length)return;await We.open({view:"SIWXSignMessage"})}catch(n){console.error("SIWXUtil:initializeIfEnabled",n),Oe.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await Y._getClient()?.disconnect().catch(console.error),ie.reset("Connect"),jt.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=k.state.siwx,e=X.getPlainAddress(m.getActiveCaipAddress()),s=m.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();
14B.getConnectorId(s.chainNamespace)===W.CONNECTOR_ID.AUTH&&ie.pushTransactionStack({});const a=await r.signMessage(n);await t.addSession({data:i,message:n,signature:a}),We.close(),Oe.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(i){const n=this.getSIWXEventProperties();(!We.state.open||ie.state.view==="ApproveTransaction")&&await We.open({view:"SIWXSignMessage"}),n.isSmartAccount?jt.showError("This application might not support Smart Accounts"):jt.showError("Signature declined"),Oe.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:n}),console.error("SWIXUtil:requestSignMessage",i)}},async cancelSignMessage(){try{this.getSIWX()?.getRequired?.()?await Y.disconnect():We.close(),ie.reset("Connect"),Oe.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){console.error("SIWXUtil:cancelSignMessage",t)}},async getSessions(){const t=k.state.siwx,e=X.getPlainAddress(m.getActiveCaipAddress()),s=m.getActiveCaipNetwork();return t&&e&&s?t.getSessions(s.caipNetworkId,e):[]},async isSIWXCloseDisabled(){const t=this.getSIWX();if(t){const e=ie.state.view==="ApproveTransaction",s=ie.state.view==="SIWXSignMessage";
14if(e||s)return t.getRequired?.()&&(await this.getSessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){const r=ki.getSIWX(),i=new Set(e.map(a=>a.split(":")[0]));if(!r||i.size!==1||!i.has("eip155"))return!1;const n=await r.createMessage({chainId:m.getActiveCaipNetwork()?.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(a=>a!==n.chainId)]});if(jt.showLoading("Authenticating...",{autoClose:!1}),F.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:o.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"},Array.from(i)[0]),o?.auths?.length){const a=o.auths.map(c=>{const l=t.client.formatAuthMessage({request:c.p,iss:c.p.iss});return{data:{...c.p,accountAddress:c.p.iss.split(":").slice(-1).join(""),chainId:c.p.iss.split(":").slice(2,4).join(":"),uri:c.p.aud,version:c.p.version||n.version,expirationTime:c.p.exp,issuedAt:c.p.iat,notBefore:c.p.nbf},message:l,signature:c.s.s,cacao:c}});try{await r.setSessions(a),Oe.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:ki.getSIWXEventProperties()})}catch(c){throw console.error("SIWX:universalProviderAuth - failed to set sessions",c),Oe.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:ki.getSIWXEventProperties()}),await t.disconnect().catch(console.error),c}finally{jt.hide()}}return!0},getSIWXEventProperties(){const t=m.state.activeChain;return{network:m.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:F.state.preferredAccountTypes?.[t]===Ai.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};function Mn(t,e){return B.getConnectorId(t)===e}function C1(t){const e=Array.from(m.state.chains.keys());let s=[];return t?(s.push([t,m.state.chains.get(t)]),Mn(t,W.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(r=>{r!==t&&Mn(r,W.CONNECTOR_ID.WALLET_CONNECT)&&s.push([r,m.state.chains.get(r)])}):Mn(t,W.CONNECTOR_ID.AUTH)&&e.forEach(r=>{r!==t&&Mn(r,W.CONNECTOR_ID.AUTH)&&s.push([r,m.state.chains.get(r)])})):s=Array.from(m.state.chains.entries()),s}const bs={EIP155:"eip155",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED"},so={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:{[W.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[W.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[W.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[W.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[W.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[W.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-454
140-9e6a2b9cae00"},ConnectorNamesMap:{[W.CONNECTOR_ID.INJECTED]:"Browser Wallet",[W.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[W.CONNECTOR_ID.COINBASE]:"Coinbase",[W.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[W.CONNECTOR_ID.LEDGER]:"Ledger",[W.CONNECTOR_ID.SAFE]:"Safe"}},tc={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,r])=>{e[`${bs.EIP155}:${s}`]=r}),e},isLowerCaseMatch(t,e){return t?.toLowerCase()===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 A1={createLogger(t,e="error"){const s=pn({level:e}),{logger:r}=Ou({opts:s});return r.error=(...i)=>{for(const n of i)if(n instanceof Error){t(n,...i);return}t(void 0,...i)},r}};function N1(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function lu(t){return N1(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const hh="2.33.1";let Ko={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${hh}`},hs=class Ra extends Error{constructor(e,s={}
14){const r=s.cause instanceof Ra?s.cause.details:s.cause?.message?s.cause.message:s.details,i=s.cause instanceof Ra&&s.cause.docsPath||s.docsPath,n=Ko.getDocsUrl?.({...s,docsPath:i}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...Ko.version?[`Version: ${Ko.version}`]:[]].join(`
15`);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=hh}walk(e){return ph(this,e)}};function ph(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?ph(t.cause,e):e?null:t}let fh=class extends hs{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 _1(t,{dir:e,size:s=32}={}){return typeof t=="string"?S1(t,{dir:e,size:s}):P1(t,{dir:e,size:s})}function S1(t,{dir:e,size:s=32}={}){if(s===null)return t;const r=t.replace("0x","");if(r.length>s*2)throw new fh({size:Math.ceil(r.length/2),targetSize:s,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function P1(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new fh({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 O1=class extends hs{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function k1(t,{size:e}){if(lu(t)>e)throw new O1({givenSize:lu(t),maxSize:e})}const T1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function x1(t,e={}){let s="";for(let i=0;i<t.length;i++)s+=T1[t[i]];const r=`0x${s}`;return typeof e.size=="number"?(k1(r,{size:e.size}),_1(r,{dir:"right",size:e.size})):r}const $1=new TextEncoder;function R1(t,e={}){const s=$1.encode(t);return x1(s,e)}class U1 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 Ys=(t,e,s)=>JSON.stringify(t,(r,i)=>typeof i=="bigint"?i.toString():i,s),sc=t=>t;class Ti extends hs{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: ${sc(o)}`,e&&`Request body: ${Ys(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=i,this.status=n,this.url=o}}class gh extends hs{constructor({body:e,error:s,url:r}){super("RPC Request failed.",{cause:s,details:s.message,metaMessages:[`URL: ${sc(r)}`,`Request body: ${Ys(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 uu extends hs{constructor({body:e,url:s}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${sc(s)}`,`Request body: ${Ys(e)}`],name:"TimeoutError"})}}const D1=-1;class pt extends hs{constructor(e,{code:s,docsPath:r,metaMessages:i,name:n,shortMessage:o}
vendor: 5,577 bytes, lines 15-17
15){super(o,{cause:e,docsPath:r,metaMessages:i||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 gh?e.code:s??D1}}class At extends pt{constructor(e,s){super(e,s),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=s.data}}class Fi extends pt{constructor(e){super(e,{code:Fi.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Fi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Wi extends pt{constructor(e){super(e,{code:Wi.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Wi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Hi extends pt{constructor(e,{method:s}={}){super(e,{code:Hi.code,name:"MethodNotFoundRpcError",shortMessage:`The method${s?` "${s}"`:""} does not exist / is not available.`})}}Object.defineProperty(Hi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Vi extends pt{constructor(e){super(e,{code:Vi.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
16`)})}}Object.defineProperty(Vi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Kr extends pt{constructor(e){super(e,{code:Kr.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Kr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class Ki extends pt{constructor(e){super(e,{code:Ki.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
17`)})}}Object.defineProperty(Ki,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Gi extends pt{constructor(e){super(e,{code:Gi.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Gi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Ji extends pt{constructor(e){super(e,{code:Ji.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Ji,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Gr extends pt{constructor(e){super(e,{code:Gr.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Gr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Ks extends pt{constructor(e,{method:s}={}){super(e,{code:Ks.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${s?` "${s}"`:""} is not supported.`})}}Object.defineProperty(Ks,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class Jr extends pt{constructor(e){super(e,{code:Jr.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Jr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Yi extends pt{constructor(e){super(e,{code:Yi.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Yi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Xs extends At{constructor(e){super(e,{code:Xs.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Xs,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class Xi extends At{constructor(e){super(e,{code:Xi.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(Xi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Zi extends At{constructor(e,{method:s}={}){super(e,{code:Zi.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${s?` " ${s}"`:""}.`})}}Object.defineProperty(Zi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Qi extends At{constructor(e){super(e,{code:Qi.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Qi,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class en extends At{constructor(e){super(e,{code:en.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(en,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class tn extends At{constructor(e){super(e,{code:tn.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(tn,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class sn extends At{constructor(e){super(e,{code:sn.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(sn,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class rn extends At{constructor(e){super(e,{code:rn.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(rn,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});
17class nn extends At{constructor(e){super(e,{code:nn.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(nn,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class on extends At{constructor(e){super(e,{code:on.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(on,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class an extends At{constructor(e){super(e,{code:an.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(an,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class cn extends At{constructor(e){super(e,{code:cn.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(cn,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class ln extends At{constructor(e){super(e,{code:ln.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(ln,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class M1 extends pt{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}class rc extends hs{constructor({cause:e,message:s}={}){const r=s?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${r?`with reason: ${r}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(rc,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(rc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});function L1(){let t=()=>{},e=()=>{};return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}}const Go=new Map;function j1({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?.([h[p],h])}}).catch(h=>{for(let p=0;p<u.length;p++){const{reject:w}=u[p];w?.(h)}})},o=()=>Go.delete(e),a=()=>c().map(({args:u})=>u),c=()=>Go.get(e)||[],l=u=>Go.set(e,[...c(),u]);return{flush:o,async schedule(u){const{promise:d,resolve:h,reject:p}=L1();return 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 mh(t){return new Promise(e=>setTimeout(e,t))}const Ua=256;let Ln=Ua,jn;function B1(t=11){if(!jn||Ln+t>Ua*2){jn="",Ln=0;for(let e=0;e<Ua;e++)jn+=(256+Math.random()*256|0).toString(16).substring(1)}return jn.substring(Ln,Ln+++t)}const Bn=new U1(8192);function q1(t,{enabled:e=!0,id:s}){if(!e||!s)return t();if(Bn.get(s))return Bn.get(s);const r=t().finally(()=>Bn.delete(s));return Bn.set(s,r),r}function z1(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 mh(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()})}function F1(t,e={}){return async(s,r={})=>{const{dedupe:i=!1,methods:n,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...r},{method:l}=s;if(n?.exclude?.includes(l))throw new Ks(new Error("method not supported"),{method:l});if(n?.include&&!n.include.includes(l))throw new Ks(new Error("method not supported"),{method:l});const u=i?R1(`${c}.${Ys(s)}`):void 0;return q1(()=>z1(async()=>{try{return await t(s)}catch(d){const h=d;switch(h.code){case Fi.code:throw new Fi(h);case Wi.code:throw new Wi(h);case Hi.code:throw new Hi(h,{method:s.method});case Vi.code:throw new Vi(h);case Kr.code:throw new Kr(h);case Ki.code:throw new Ki(h);case Gi.code:throw new Gi(h);case Ji.code:throw new Ji(h);case Gr.code:throw new Gr(h);case Ks.code:throw new Ks(h,{method:s.method});case Jr.code:throw new Jr(h);case Yi.code:throw new Yi(h);case Xs.code:throw new Xs(h);case Xi.code:throw new Xi(h);case Zi.code:throw new Zi(h);case Qi.code:throw new Qi(h);case en.code:throw new en(h);case tn.code:throw new tn(h);case sn.code:throw new sn(h);case rn.code:throw new rn(h);case nn.code:throw new nn(h);case on.code:throw new on(h);case an.code:throw new an(h);case cn.code:throw new cn(h);case ln.code:throw new ln(h);case 5e3:throw new Xs(h);default:throw d instanceof hs?d:new M1(h)}}},{delay:({count:d,error:h})=>{if(h&&h instanceof Ti){const p=h?.headers?.get("Retry-After");if(p?.match(/\d/))return Number.parseInt(p)*1e3}return~~(1<<d)*o},retryCount:a,shouldRetry:({error:d})=>W1(d)}),{enabled:i,id:u})}}function W1(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===Jr.code||t.code===Kr.code:t instanceof Ti&&t.status?t.status===403||t.status===408||t.status===4
1713||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function wh({key:t,methods:e,name:s,request:r,retryCount:i=3,retryDelay:n=150,timeout:o,type:a},c){const l=B1();return{config:{key:t,methods:e,name:s,request:r,retryCount:i,retryDelay:n,timeout:o,type:a},request:F1(r,{methods:e,retryCount:i,retryDelay:n,uid:l}),value:c}}function du(t,e={}){const{key:s="fallback",name:r="Fallback",rank:i=!1,shouldThrow:n=H1,retryCount:o,retryDelay:a}=e;return(({chain:c,pollingInterval:l=4e3,timeout:u,...d})=>{let h=t,p=()=>{};const w=wh({key:s,name:r,async request({method:g,params:f}){let b;const y=async(v=0)=>{const C=h[v]({...d,chain:c,retryCount:0,timeout:u});try{const A=await C.request({method:g,params:f});return p({method:g,params:f,response:A,transport:C,status:"success"}),A}catch(A){if(p({error:A,method:g,params:f,transport:C,status:"error"}),n(A)||v===h.length-1||(b??(b=h.slice(v+1).some(N=>{const{include:_,exclude:R}=N({chain:c}).config.methods||{};return _?_.includes(g):R?!R.includes(g):!0})),!b))throw A;return y(v+1)}};return y()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:g=>p=g,transports:h.map(g=>g({chain:c,retryCount:0}))});if(i){const g=typeof i=="object"?i:{};V1({chain:c,interval:g.interval??l,onTransports:f=>h=f,ping:g.ping,sampleCount:g.sampleCount,timeout:g.timeout,transports:h,weights:g.weights})}return w})}function H1(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===Gr.code||t.code===Xs.code||rc.nodeMessage.test(t.message)||t.code===5e3))}function V1({chain:t,interval:e=4e3,onTransports:s,ping:r,sampleCount: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 g=>{const f=g({chain:t,retryCount:0,timeout:n}),b=Date.now();let y,v;try{await(r?r({transport:f}):f.request({method:"net_listening"})),v=1}catch{v=0}finally{y=Date.now()}return{latency:y-b,success:v}}));u.push(h),u.length>i&&u.shift();const p=Math.max(...u.map(g=>Math.max(...g.map(({latency:f})=>f)))),w=o.map((g,f)=>{const b=u.map(N=>N[f].latency),v=1-b.reduce((N,_)=>N+_,0)/b.length/p,C=u.map(N=>N[f].success),A=C.reduce((N,_)=>N+_,0)/C.length;return A===0?[0,f]:[l*v+c*A,f]}).sort((g,f)=>f[0]-g[0]);s(w.map(([,g])=>o[g])),await mh(e),d()};d()}class K1 extends hs{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 G1(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?.signal||null}))}catch(a){a?.name==="AbortError"&&n(e),n(a)}finally{clearTimeout(o)}})()})}function J1(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const hu=J1();function Y1(t,e={}){return{async request(s){const{body:r,onRequest:i=e.onRequest,onResponse:n=e.onResponse,timeout:o=e.timeout??1e4}=s,a={...e.fetchOptions??{},...s.fetchOptions??{}},{headers:c,method:l,signal:u}=a;try{const d=await G1(async({signal:p})=>{const w={...a,body:Array.isArray(r)?Ys(r.map(y=>({jsonrpc:"2.0",id:y.id??hu.take(),...y}))):Ys({jsonrpc:"2.0",id:r.id??hu.take(),...r}),headers:{"Content-Type":"application/json",...c},method:l||"POST",signal:u||(o>0?p:null)},g=new Request(t,w),f=await i?.(g,w)??{...w,url:t};return await fetch(f.url??t,f)},{errorInstance:new uu({body:r,url:t}),timeout:o,signal:!0});n&&await n(d);let h;if(d.headers.get("Content-Type")?.startsWith("application/json"))h=await d.json();else{h=await d.text();try{h=JSON.parse(h||"{}")}catch(p){if(d.ok)throw p;h={error:h}}}if(!d.ok)throw new Ti({body:r,details:Ys(h.error)||d.statusText,headers:d.headers,status:d.status,url:t});return h}catch(d){throw d instanceof Ti||d instanceof uu?d:new Ti({body:r,cause:d,url:t})}}}}function qn(t,e={}){const{batch:s,fetchOptions:r,key:i="http",methods:n,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:l,raw:u}=e;return({chain:d,retryCount:h,timeout:p})=>{const{batchSize:w=1e3,wait:g=0}=typeof s=="object"?s:{},f=e.retryCount??h,b=p??e.timeout??1e4,y=t||d?.rpcUrls.default.http[0];if(!y)throw new K1;const v=Y1(y,{fetchOptions:r,onRequest:a,onResponse:c,timeout:b});return wh({key:i,methods:n,name:o,async request({method:C,params:A}){const N={method:C,params:A},{schedule:_}=j1({id:y,wait:g,shouldSplitBatch(I){return I.length>w},fn:I=>v.request({body:I}),sort:(I,M)=>I.id-M.id}),R=async I=>s?_(I):[await v.request({body:I})],[{error:E,result:$}]=await R(N);if(u)return{error:E,result:$};if(E)throw new gh({body:N,error:E,url:y});return $},retryCount:f,retryDelay:l,timeout:b,type:"http"},{fetchOptions:r,url:y})}}const X1="rpc.walletconnect.org";function pu(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 Jo=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:
1756","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===X1}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:W.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${W.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){const r=t.rpcUrls?.default?.http?.[0];return Jo.includes(e)?pu(e,s):r||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:r}){const i=this.getChainNamespace(t),n=this.getCaipNetworkId(t),o=t.rpcUrls.default.http?.[0],a=this.getDefaultRpcUrl(t,n,s),c=t?.rpcUrls?.chainDefault?.http?.[0]||o,l=r?.[n]?.map(h=>h.url)||[],u=[...l,a],d=[...l];return c&&!d.includes(c)&&d.push(c),{...t,chainNamespace:i,caipNetworkId:n,assets:{imageId:so.NetworkImageIds[t.id],imageUrl: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}))},getViemTransport(t,e,s){const r=[];return s?.forEach(i=>{r.push(qn(i.url,i.config))}),Jo.includes(t.caipNetworkId)&&r.push(qn(pu(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),t?.rpcUrls?.default?.http?.forEach(i=>{r.push(qn(i))}),du(r)},extendWagmiTransports(t,e,s){if(Jo.includes(t.caipNetworkId)){const r=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return du([s,qn(r)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:W.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){const e=z.getActiveCaipNetworkId(),s=m.getAllRequestedCaipNetworks(),r=Array.from(m.state.chains?.keys()||[]),i=e?.split(":")[0],n=i?r.includes(i):!1,o=s?.find(c=>c.caipNetworkId===e);return n&&!o&&e?this.getUnsupportedNetwork(e):o||t||s?.[0]}},ro={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},lt=Se({providers:{...ro},providerIds:{...ro}}),Pe={state:lt,subscribeKey(t,e){return tt(lt,t,e)},subscribe(t){return et(lt,()=>{t(lt)})},subscribeProviders(t){return et(lt.providers,()=>t(lt.providers))},setProvider(t,e){e&&(lt.providers[t]=Qs(e))},getProvider(t){return lt.providers[t]},setProviderId(t,e){e&&(lt.providerIds[t]=e)},getProviderId(t){if(t)return lt.providerIds[t]},reset(){lt.providers={...ro},lt.providerIds={...ro}},resetChain(t){lt.providers[t]=void 0,lt.providerIds[t]=void 0}},Z1={VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},Da={filterOutDuplicatesByRDNS(t){const e=k.state.enableEIP6963?B.state.connectors:[],s=z.getRecentWallets(),r=e.map(a=>a.info?.rdns).filter(Boolean),i=s.map(a=>a.rdns).filter(Boolean),n=r.concat(i);if(n.includes("io.metamask.mobile")&&X.isMobile()){const a=n.indexOf("io.metamask.mobile");n[a]="io.metamask"}return t.filter(a=>!n.includes(String(a?.rdns)))},filterOutDuplicatesByIds(t){const e=B.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=z.getRecentWallets(),r=e.map(a=>a.explorerId),i=s.map(a=>a.id),n=r.concat(i);return t.filter(a=>!n.includes(a?.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=B.state,{featuredWalletIds:s}=k.state,r=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>(a.info?.rdns&&(o[a.info.rdns]=!0),o),{});return t.map(o=>({...o,installed:!!o.rdns&&!!r[o.rdns??""]}
17)).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(s?.length){const l=s.indexOf(o.id),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){const s=t?.connectMethodsOrder||k.state.features?.connectMethodsOrder,r=e||B.state.connectors;if(s)return s;const{injected:i,announced:n}=Kn.getConnectorsByType(r,V.state.recommended,V.state.featured),o=i.filter(Kn.showConnector),a=n.filter(Kn.showConnector);return o.length||a.length?["wallet","email","social"]:Z1.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=>tc.isLowerCaseMatch(r.name,t.name));return e||s}},Kn={getConnectorsByType(t,e,s){const{customWallets:r}=k.state,i=z.getRecentWallets(),n=Da.filterOutDuplicateWallets(e),o=Da.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){const e=t.info?.rdns,s=!!e&&V.state.excludedWallets.some(i=>!!i.rdns&&i.rdns===e),r=!!t.name&&V.state.excludedWallets.some(i=>tc.isLowerCaseMatch(i.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!X.isMobile()||X.isMobile()&&!e&&!Y.checkInstalled())||s||r)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||r))},getIsConnectedWithWC(){return Array.from(m.state.chains.values()).some(s=>B.getConnectorId(s.namespace)===W.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:r,announced:i,injected:n,multiChain:o,external:a,overriddenConnectors:c=k.state.features?.connectorTypeOrder??[]}){const l=Kn.getIsConnectedWithWC(),h=[{type:"walletConnect",isEnabled:k.state.enableWalletConnect&&!l},{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(f=>f.isEnabled),p=new Set(h.map(f=>f.type)),w=c.filter(f=>p.has(f)).map(f=>({type:f,isEnabled:!0})),g=h.filter(({type:f})=>!w.some(({type:y})=>y===f));return Array.from(new Set([...w,...g].map(({type:f})=>f)))}};const Gn=globalThis,ic=Gn.ShadowRoot&&(Gn.ShadyCSS===void 0||Gn.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,nc=Symbol(),fu=new WeakMap;let yh=class{constructor(e,s,r){if(this._$cssResult$=!0,r!==nc)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(ic&&e===void 0){const r=s!==void 0&&s.length===1;r&&(e=fu.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),r&&fu.set(s,e))}return e}toString(){return this.cssText}};const Ot=t=>new yh(typeof t=="string"?t:t+"",void 0,nc),Mr=(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 yh(s,t,nc)},Q1=(t,e)=>{if(ic)t.adoptedStyleSheets=e.map((s=>s instanceof CSSStyleSheet?s:s.styleSheet));else for(const s of e){const r=document.createElement("style"),i=Gn.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=s.cssText,t.appendChild(r)}},gu=ic?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const r of e.cssRules)s+=r.cssText;return Ot(s)})(t):t;const{is:eI,defineProperty:tI,getOwnPropertyDescriptor:sI,getOwnPropertyNames:rI,getOwnPropertySymbols:iI,getPrototypeOf:nI}=Object,ks=globalThis,mu=ks.trustedTypes,oI=mu?mu.emptyScript:"",aI=ks.reactiveElementPolyfillSupport,xi=(t,e)=>t,Ma={toAttribute(t,e){switch(e){case Boolean:t=t?oI: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}},bh=(t,e)=>!eI(t,e),wu={attribute:!0,type:String,converter:Ma,reflect:!1,useDefault:!1,hasChanged:bh};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ks.litPropertyMetadata??(ks.litPropertyMetadata=new WeakMap);let kr=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=wu){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&&tI(this.prototype,e,i)}}static getPropertyDescriptor(e,s,r){const{get:i,set:n}=sI(this.prototype,e)??{get(){return this[s]},set(o){this[s]=o}};return{get:i,set(o){const a=i?.call(this);n?.call(this,o),this.requestUpdate(e,a,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??wu}static _$Ei(){if(this.hasOwnProperty(xi("elementProperties")))return;const e=nI(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(xi("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(xi("properties"))){const s=this.properties,r=[...rI(s),...iI(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(gu(i))}else e!==void 0&&s.push(gu(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(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}
17removeController(e){this._$EO?.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 Q1(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,s,r){this._$AK(e,r)}_$ET(e,s){const r=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,r);if(i!==void 0&&r.reflect===!0){const n=(r.converter?.toAttribute!==void 0?r.converter:Ma).toAttribute(s,r.type);this._$Em=e,n==null?this.removeAttribute(i):this.setAttribute(i,n),this._$Em=null}}_$AK(e,s){const r=this.constructor,i=r._$Eh.get(e);if(i!==void 0&&this._$Em!==i){const n=r.getPropertyOptions(i),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Ma;this._$Em=i;const a=o.fromAttribute(s,n.type);this[i]=a??this._$Ej?.get(i)??a,this._$Em=null}}requestUpdate(e,s,r){if(e!==void 0){const i=this.constructor,n=this[e];if(r??(r=i.getPropertyOptions(e)),!((r.hasChanged??bh)(n,s)||r.useDefault&&r.reflect&&n===this._$Ej?.get(e)&&!this.hasAttribute(i._$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(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[i,n]of this._$Ep)this[i]=n;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[i,n]of r){const{wrapped:o}=n,a=this[i];o!==!0||this._$AL.has(i)||a===void 0||this.C(i,void 0,n,a)}}let e=!1;const s=this._$AL;try{e=this.shouldUpdate(s),e?(this.willUpdate(s),this._$EO?.forEach((r=>r.hostUpdate?.())),this.update(s)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(s)}willUpdate(e){}_$AE(e){this._$EO?.forEach((s=>s.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach((s=>this._$ET(s,this[s])))),this._$EM()}updated(e){}firstUpdated(e){}};kr.elementStyles=[],kr.shadowRootOptions={mode:"open"},kr[xi("elementProperties")]=new Map,kr[xi("finalized")]=new Map,aI?.({ReactiveElement:kr}),(ks.reactiveElementVersions??(ks.reactiveElementVersions=[])).push("2.1.1");const $i=globalThis,io=$i.trustedTypes,yu=io?io.createPolicy("lit-html",{createHTML:t=>t}):void 0,vh="$lit$",Is=`lit$${Math.random().toFixed(9).slice(2)}$`,Eh="?"+Is,cI=`<${Eh}>`,rr=document,un=()=>rr.createComment(""),dn=t=>t===null||typeof t!="object"&&typeof t!="function",oc=Array.isArray,lI=t=>oc(t)||typeof t?.[Symbol.iterator]=="function",Yo=`[ 	
18\f\r]`,mi=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,bu=/-->/g,vu=/>/g,Ls=RegExp(`>|${Yo}(?:([^\\s"'>=/]+)(${Yo}*=${Yo}*(?:[^ 	
19\f\r"'\`<>=]|("|')|))|$)`,"g"),Eu=/'/g,Cu=/"/g,Ch=/^(?:script|style|textarea|title)$/i,Ih=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),mA=Ih(1),wA=Ih(2),Yr=Symbol.for("lit-noChange"),Fe=Symbol.for("lit-nothing"),Iu=new WeakMap,Gs=rr.createTreeWalker(rr,129);function Ah(t,e){if(!oc(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return yu!==void 0?yu.createHTML(e):e}const uI=(t,e)=>{const s=t.length-1,r=[];let i,n=e===2?"<svg>":e===3?"<math>
19":"",o=mi;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===mi?u[1]==="!--"?o=bu:u[1]!==void 0?o=vu:u[2]!==void 0?(Ch.test(u[2])&&(i=RegExp("</"+u[2],"g")),o=Ls):u[3]!==void 0&&(o=Ls):o===Ls?u[0]===">"?(o=i??mi,d=-1):u[1]===void 0?d=-2:(d=o.lastIndex-u[2].length,l=u[1],o=u[3]===void 0?Ls:u[3]==='"'?Cu:Eu):o===Cu||o===Eu?o=Ls:o===bu||o===vu?o=mi:(o=Ls,i=void 0);const p=o===Ls&&t[a+1].startsWith("/>")?" ":"";n+=o===mi?c+cI:d>=0?(r.push(l),c.slice(0,d)+vh+c.slice(d)+Is+p):c+Is+(d===-2?a:p)}return[Ah(t,n+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),r]};class hn{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]=uI(e,s);if(this.el=hn.createElement(l,r),Gs.currentNode=this.el.content,s===2||s===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(i=Gs.nextNode())!==null&&c.length<a;){if(i.nodeType===1){if(i.hasAttributes())for(const d of i.getAttributeNames())if(d.endsWith(vh)){const h=u[o++],p=i.getAttribute(d).split(Is),w=/([.?@])?(.*)/.exec(h);c.push({type:1,index:n,name:w[2],strings:p,ctor:w[1]==="."?hI:w[1]==="?"?pI:w[1]==="@"?fI:wo}),i.removeAttribute(d)}else d.startsWith(Is)&&(c.push({type:6,index:n}),i.removeAttribute(d));if(Ch.test(i.tagName)){const d=i.textContent.split(Is),h=d.length-1;if(h>0){i.textContent=io?io.emptyScript:"";for(let p=0;p<h;p++)i.append(d[p],un()),Gs.nextNode(),c.push({type:2,index:++n});i.append(d[h],un())}}}else if(i.nodeType===8)if(i.data===Eh)c.push({type:2,index:n});else{let d=-1;for(;(d=i.data.indexOf(Is,d+1))!==-1;)c.push({type:7,index:n}),d+=Is.length-1}n++}}static createElement(e,s){const r=rr.createElement("template");return r.innerHTML=e,r}}function Xr(t,e,s=t,r){if(e===Yr)return e;let i=r!==void 0?s._$Co?.[r]:s._$Cl;const n=dn(e)?void 0:e._$litDirective$;return i?.constructor!==n&&(i?._$AO?.(!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=Xr(t,i._$AS(t,e.values),i,r)),e}class dI{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?.creationScope??rr).importNode(s,!0);Gs.currentNode=i;let n=Gs.nextNode(),o=0,a=0,c=r[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new In(n,n.nextSibling,this,e):c.type===1?l=new c.ctor(n,c.name,c.strings,this,e):c.type===6&&(l=new gI(n,this,e)),this._$AV.push(l),c=r[++a]}o!==c?.index&&(n=Gs.nextNode(),o++)}return Gs.currentNode=rr,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 In{get _$AU(){return this._$AM?._$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?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const s=this._$AM;return s!==void 0&&e?.nodeType===11&&(e=s.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,s=this){e=Xr(this,e,s),dn(e)?e===Fe||e==null||e===""?(this._$AH!==Fe&&this._$AR(),this._$AH=Fe):e!==this._$AH&&e!==Yr&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):lI(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&&dn(this._$AH)?this._$AA.nextSibling.data=e:this.T(rr.createTextNode(e)),this._$AH=e}$(e){const{values:s,_$litType$:r}=e,i=typeof r=="number"?this._$AC(e):(r.el===void 0&&(r.el=hn.createElement(Ah(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===i)this._$AH.p(s);else{const n=new dI(i,this),o=n.u(this.options);n.p(s),this.T(o),this._$AH=n}}_$AC(e){let s=Iu.get(e.strings);return s===void 0&&Iu.set(e.strings,s=new hn(e)),s}k(e){oc(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 In(this.O(un()),this.O(un()),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){for(this._$AP?.(!1,!0,s);e!==this._$AB;){const r=e.nextSibling;e.remove(),e=r}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}}class wo{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=Xr(this,e,s,0),o=!dn(e)||e!==this._$AH&&e!==Yr,o&&(this._$AH=e);else{const a=e;let c,l;
19for(e=n[0],c=0;c<n.length-1;c++)l=Xr(this,a[r+c],s,c),l===Yr&&(l=this._$AH[c]),o||(o=!dn(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 hI extends wo{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Fe?void 0:e}}class pI extends wo{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Fe)}}class fI extends wo{constructor(e,s,r,i,n){super(e,s,r,i,n),this.type=5}_$AI(e,s=this){if((e=Xr(this,e,s,0)??Fe)===Yr)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){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}}class gI{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){Xr(this,e)}}const mI=$i.litHtmlPolyfillSupport;mI?.(hn,In),($i.litHtmlVersions??($i.litHtmlVersions=[])).push("3.3.1");const wI=(t,e,s)=>{const r=s?.renderBefore??e;let i=r._$litPart$;if(i===void 0){const n=s?.renderBefore??null;r._$litPart$=i=new In(e.insertBefore(un(),n),n,void 0,s??{})}return i._$AI(t),i};const Ri=globalThis;class Jn extends kr{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=wI(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Yr}}Jn._$litElement$=!0,Jn.finalized=!0,Ri.litElementHydrateSupport?.({LitElement:Jn});const yI=Ri.litElementPolyfillSupport;yI?.({LitElement:Jn});(Ri.litElementVersions??(Ri.litElementVersions=[])).push("4.2.1");let Ui,Ts,xs;function yA(t,e){Ui=document.createElement("style"),Ts=document.createElement("style"),xs=document.createElement("style"),Ui.textContent=Lr(t).core.cssText,Ts.textContent=Lr(t).dark.cssText,xs.textContent=Lr(t).light.cssText,document.head.appendChild(Ui),document.head.appendChild(Ts),document.head.appendChild(xs),Nh(e)}function Nh(t){Ts&&xs&&(t==="light"?(Ts.removeAttribute("media"),xs.media="enabled"):(xs.removeAttribute("media"),Ts.media="enabled"))}function bI(t){Ui&&Ts&&xs&&(Ui.textContent=Lr(t).core.cssText,Ts.textContent=Lr(t).dark.cssText,xs.textContent=Lr(t).light.cssText)}function Lr(t){return{core:Mr`
20      @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
21      @keyframes w3m-shake {
22        0% {
23          transform: scale(1) rotate(0deg);
24        }
25        20% {
26          transform: scale(1) rotate(-1deg);
27        }
28        40% {
29          transform: scale(1) rotate(1.5deg);
30        }
31        60% {
32          transform: scale(1) rotate(-1.5deg);
33        }
34        80% {
35          transform: scale(1) rotate(1deg);
36        }
37        100% {
38          transform: scale(1) rotate(0deg);
39        }
40      }
41      @keyframes w3m-iframe-fade-out {
42        0% {
43          opacity: 1;
44        }
45        100% {
46          opacity: 0;
47        }
48      }
49      @keyframes w3m-iframe-zoom-in {
50        0% {
51          transform: translateY(50px);
52          opacity: 0;
53        }
54        100% {
55          transform: translateY(0px);
56          opacity: 1;
57        }
58      }
59      @keyframes w3m-iframe-zoom-in-mobile {
60        0% {
61          transform: scale(0.95);
62          opacity: 0;
63        }
64        100% {
65          transform: scale(1);
66          opacity: 1;
67        }
68      }
69      :root {
70        --w3m-modal-width: 360px;
71        --w3m-color-mix-strength: ${Ot(t?.["--w3m-color-mix-strength"]?`${t["--w3m-color-mix-strength"]}%`:"0%")};
72        --w3m-font-family: ${Ot(t?.["--w3m-font-family"]||"Inter, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;")};
73        --w3m-font-size-master: ${Ot(t?.["--w3m-font-size-master"]||"10px")};
74        --w3m-border-radius-master: ${Ot(t?.["--w3m-border-radius-master"]||"4px")};
75        --w3m-z-index: ${Ot(t?.["--w3m-z-index"]||
vendor: 15,824 bytes, lines 75-501
75999)};
76
77        --wui-font-family: var(--w3m-font-family);
78
79        --wui-font-size-mini: calc(var(--w3m-font-size-master) * 0.8);
80        --wui-font-size-micro: var(--w3m-font-size-master);
81        --wui-font-size-tiny: calc(var(--w3m-font-size-master) * 1.2);
82        --wui-font-size-small: calc(var(--w3m-font-size-master) * 1.4);
83        --wui-font-size-paragraph: calc(var(--w3m-font-size-master) * 1.6);
84        --wui-font-size-medium: calc(var(--w3m-font-size-master) * 1.8);
85        --wui-font-size-large: calc(var(--w3m-font-size-master) * 2);
86        --wui-font-size-title-6: calc(var(--w3m-font-size-master) * 2.2);
87        --wui-font-size-medium-title: calc(var(--w3m-font-size-master) * 2.4);
88        --wui-font-size-2xl: calc(var(--w3m-font-size-master) * 4);
89
90        --wui-border-radius-5xs: var(--w3m-border-radius-master);
91        --wui-border-radius-4xs: calc(var(--w3m-border-radius-master) * 1.5);
92        --wui-border-radius-3xs: calc(var(--w3m-border-radius-master) * 2);
93        --wui-border-radius-xxs: calc(var(--w3m-border-radius-master) * 3);
94        --wui-border-radius-xs: calc(var(--w3m-border-radius-master) * 4);
95        --wui-border-radius-s: calc(var(--w3m-border-radius-master) * 5);
96        --wui-border-radius-m: calc(var(--w3m-border-radius-master) * 7);
97        --wui-border-radius-l: calc(var(--w3m-border-radius-master) * 9);
98        --wui-border-radius-3xl: calc(var(--w3m-border-radius-master) * 20);
99
100        --wui-font-weight-light: 400;
101        --wui-font-weight-regular: 500;
102        --wui-font-weight-medium: 600;
103        --wui-font-weight-bold: 700;
104
105        --wui-letter-spacing-2xl: -1.6px;
106        --wui-letter-spacing-medium-title: -0.96px;
107        --wui-letter-spacing-title-6: -0.88px;
108        --wui-letter-spacing-large: -0.8px;
109        --wui-letter-spacing-medium: -0.72px;
110        --wui-letter-spacing-paragraph: -0.64px;
111        --wui-letter-spacing-small: -0.56px;
112        --wui-letter-spacing-tiny: -0.48px;
113        --wui-letter-spacing-micro: -0.2px;
114        --wui-letter-spacing-mini: -0.16px;
115
116        --wui-spacing-0: 0px;
117        --wui-spacing-4xs: 2px;
118        --wui-spacing-3xs: 4px;
119        --wui-spacing-xxs: 6px;
120        --wui-spacing-2xs: 7px;
121        --wui-spacing-xs: 8px;
122        --wui-spacing-1xs: 10px;
123        --wui-spacing-s: 12px;
124        --wui-spacing-m: 14px;
125        --wui-spacing-l: 16px;
126        --wui-spacing-2l: 18px;
127        --wui-spacing-xl: 20px;
128        --wui-spacing-xxl: 24px;
129        --wui-spacing-2xl: 32px;
130        --wui-spacing-3xl: 40px;
131        --wui-spacing-4xl: 90px;
132        --wui-spacing-5xl: 95px;
133
134        --wui-icon-box-size-xxs: 14px;
135        --wui-icon-box-size-xs: 20px;
136        --wui-icon-box-size-sm: 24px;
137        --wui-icon-box-size-md: 32px;
138        --wui-icon-box-size-mdl: 36px;
139        --wui-icon-box-size-lg: 40px;
140        --wui-icon-box-size-2lg: 48px;
141        --wui-icon-box-size-xl: 64px;
142
143        --wui-icon-size-inherit: inherit;
144        --wui-icon-size-xxs: 10px;
145        --wui-icon-size-xs: 12px;
146        --wui-icon-size-sm: 14px;
147        --wui-icon-size-md: 16px;
148        --wui-icon-size-mdl: 18px;
149        --wui-icon-size-lg: 20px;
150        --wui-icon-size-xl: 24px;
151        --wui-icon-size-xxl: 28px;
152
153        --wui-wallet-image-size-inherit: inherit;
154        --wui-wallet-image-size-sm: 40px;
155        --wui-wallet-image-size-md: 56px;
156        --wui-wallet-image-size-lg: 80px;
157
158        --wui-visual-size-size-inherit: inherit;
159        --wui-visual-size-sm: 40px;
160        --wui-visual-size-md: 55px;
161        --wui-visual-size-lg: 80px;
162
163        --wui-box-size-md: 100px;
164        --wui-box-size-lg: 120px;
165
166        --wui-ease-out-power-2: cubic-bezier(0, 0, 0.22, 1);
167        --wui-ease-out-power-1: cubic-bezier(0, 0, 0.55, 1);
168
169        --wui-ease-in-power-3: cubic-bezier(0.66, 0, 1, 1);
170        --wui-ease-in-power-2: cubic-bezier(0.45, 0, 1, 1);
171        --wui-ease-in-power-1: cubic-bezier(0.3, 0, 1, 1);
172
173        --wui-ease-inout-power-1: cubic-bezier(0.45, 0, 0.55, 1);
174
175        --wui-duration-lg: 200ms;
176        --wui-duration-md: 125ms;
177        --wui-duration-sm: 75ms;
178
179        --wui-path-network-sm: path(
180          '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'
181        );
182
183        --wui-path-network-md: path(
184          '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'
185        );
186
187        --wui-path-network-lg: path(
188          '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'
189        );
190
191        --wui-width-network-sm: 36px;
192        --wui-width-network-md: 48px;
193        --wui-width-network-lg: 86px;
194
195        --wui-height-network-sm: 40px;
196        --wui-height-network-md: 54px;
197        --wui-height-network-lg: 96px;
198
199        --wui-icon-size-network-xs: 12px;
200        --wui-icon-size-network-sm: 16px;
201        --wui-icon-size-network-md: 24px;
202        --wui-icon-size-network-lg: 42px;
203
204        --wui-color-inherit: inherit;
205
206        --wui-color-inverse-100: #fff;
207        --wui-color-inverse-000: #000;
208
209        --wui-cover: rgba(20, 20, 20, 0.8);
210
211        --wui-color-modal-bg: var(--wui-color-modal-bg-base);
212
213        --wui-color-accent-100: var(--wui-color-accent-base-100);
214        --wui-color-accent-090: var(--wui-color-accent-base-090);
215        --wui-color-accent-080: var(--wui-color-accent-base-080);
216
217        --wui-color-success-100: var(--wui-color-success-base-100);
218        --wui-color-success-125: var(--wui-color-success-base-125);
219
220        --wui-color-warning-100: var(--wui-color-warning-base-100);
221
222        --wui-color-error-100: var(--wui-color-error-base-100);
223        --wui-color-error-125: var(--wui-color-error-base-125);
224
225        --wui-color-blue-100: var(--wui-color-blue-base-100);
226        --wui-color-blue-90: var(--wui-color-blue-base-90);
227
228        --wui-icon-box-bg-error-100: var(--wui-icon-box-bg-error-base-100);
229        --wui-icon-box-bg-blue-100: var(--wui-icon-box-bg-blue-base-100);
230        --wui-icon-box-bg-success-100: var(--wui-icon-box-bg-success-base-100);
231        --wui-icon-box-bg-inverse-100: var(--wui-icon-box-bg-inverse-base-100);
232
233        --wui-all-wallets-bg-100: var(--wui-all-wallets-bg-100);
234
235        --wui-avatar-border: var(--wui-avatar-border-base);
236
237        --wui-thumbnail-border: var(--wui-thumbnail-border-base);
238
239        --wui-wallet-button-bg: var(--wui-wallet-button-bg-base);
240
241        --wui-box-shadow-blue: var(--wui-color-accent-glass-020);
242      }
243
244      @supports (background: color-mix(in srgb, white 50%, black)) {
245        :root {
246          --wui-color-modal-bg: color-mix(
247            in srgb,
248            var(--w3m-color-mix) var(--w3m-color-mix-strength),
249            var(--wui-color-modal-bg-base)
250          );
251
252          --wui-box-shadow-blue: color-mix(in srgb, var(--wui-color-accent-100) 20%, transparent);
253
254          --wui-color-accent-100: color-mix(
255            in srgb,
256            var(--wui-color-accent-base-100) 100%,
257            transparent
258          );
259          --wui-color-accent-090: color-mix(
260            in srgb,
261            var(--wui-color-accent-base-100) 90%,
262            transparent
263          );
264          --wui-color-accent-080: color-mix(
265            in srgb,
266            var(--wui-color-accent-base-100) 80%,
267            transparent
268          );
269          --wui-color-accent-glass-090: color-mix(
270            in srgb,
271            var(--wui-color-accent-base-100) 90%,
272            transparent
273          );
274          --wui-color-accent-glass-080: color-mix(
275            in srgb,
276            var(--wui-color-accent-base-100) 80%,
277            transparent
278          );
279          --wui-color-accent-glass-020: color-mix(
280            in srgb,
281            var(--wui-color-accent-base-100) 20%,
282            transparent
283          );
284          --wui-color-accent-glass-015: color-mix(
285            in srgb,
286            var(--wui-color-accent-base-100) 15%,
287            transparent
288          );
289          --wui-color-accent-glass-010: color-mix(
290            in srgb,
291            var(--wui-color-accent-base-100) 10%,
292            transparent
293          );
294          --wui-color-accent-glass-005: color-mix(
295            in srgb,
296            var(--wui-color-accent-base-100) 5%,
297            transparent
298          );
299          --wui-color-accent-002: color-mix(
300            in srgb,
301            var(--wui-color-accent-base-100) 2%,
302            transparent
303          );
304
305          --wui-color-fg-100: color-mix(
306            in srgb,
307            var(--w3m-color-mix) var(--w3m-color-mix-strength),
308            var(--wui-color-fg-100)
309          );
310          --wui-color-fg-125: color-mix(
311            in srgb,
312            var(--w3m-color-mix) var(--w3m-color-mix-strength),
313            var(--wui-color-fg-125)
314          );
315          --wui-color-fg-150: color-mix(
316            in srgb,
317            var(--w3m-color-mix) var(--w3m-color-mix-strength),
318            var(--wui-color-fg-150)
319          );
320          --wui-color-fg-175: color-mix(
321            in srgb,
322            var(--w3m-color-mix) var(--w3m-color-mix-strength),
323            var(--wui-color-fg-175)
324          );
325          --wui-color-fg-200: color-mix(
326            in srgb,
327            var(--w3m-color-mix) var(--w3m-color-mix-strength),
328            var(--wui-color-fg-200)
329          );
330          --wui-color-fg-225: color-mix(
331            in srgb,
332            var(--w3m-color-mix) var(--w3m-color-mix-strength),
333            var(--wui-color-fg-225)
334          );
335          --wui-color-fg-250: color-mix(
336            in srgb,
337            var(--w3m-color-mix) var(--w3m-color-mix-strength),
338            var(--wui-color-fg-250)
339          );
340          --wui-color-fg-275: color-mix(
341            in srgb,
342            var(--w3m-color-mix) var(--w3m-color-mix-strength),
343            var(--wui-color-fg-275)
344          );
345          --wui-color-fg-300: color-mix(
346            in srgb,
347            var(--w3m-color-mix) var(--w3m-color-mix-strength),
348            var(--wui-color-fg-300)
349          );
350          --wui-color-fg-325: color-mix(
351            in srgb,
352            var(--w3m-color-mix) var(--w3m-color-mix-strength),
353            var(--wui-color-fg-325)
354          );
355          --wui-color-fg-350: color-mix(
356            in srgb,
357            var(--w3m-color-mix) var(--w3m-color-mix-strength),
358            var(--wui-color-fg-350)
359          );
360
361          --wui-color-bg-100: color-mix(
362            in srgb,
363            var(--w3m-color-mix) var(--w3m-color-mix-strength),
364            var(--wui-color-bg-100)
365          );
366          --wui-color-bg-125: color-mix(
367            in srgb,
368            var(--w3m-color-mix) var(--w3m-color-mix-strength),
369            var(--wui-color-bg-125)
370          );
371          --wui-color-bg-150: color-mix(
372            in srgb,
373            var(--w3m-color-mix) var(--w3m-color-mix-strength),
374            var(--wui-color-bg-150)
375          );
376          --wui-color-bg-175: color-mix(
377            in srgb,
378            var(--w3m-color-mix) var(--w3m-color-mix-strength),
379            var(--wui-color-bg-175)
380          );
381          --wui-color-bg-200: color-mix(
382            in srgb,
383            var(--w3m-color-mix) var(--w3m-color-mix-strength),
384            var(--wui-color-bg-200)
385          );
386          --wui-color-bg-225: color-mix(
387            in srgb,
388            var(--w3m-color-mix) var(--w3m-color-mix-strength),
389            var(--wui-color-bg-225)
390          );
391          --wui-color-bg-250: color-mix(
392            in srgb,
393            var(--w3m-color-mix) var(--w3m-color-mix-strength),
394            var(--wui-color-bg-250)
395          );
396          --wui-color-bg-275: color-mix(
397            in srgb,
398            var(--w3m-color-mix) var(--w3m-color-mix-strength),
399            var(--wui-color-bg-275)
400          );
401          --wui-color-bg-300: color-mix(
402            in srgb,
403            var(--w3m-color-mix) var(--w3m-color-mix-strength),
404            var(--wui-color-bg-300)
405          );
406          --wui-color-bg-325: color-mix(
407            in srgb,
408            var(--w3m-color-mix) var(--w3m-color-mix-strength),
409            var(--wui-color-bg-325)
410          );
411          --wui-color-bg-350: color-mix(
412            in srgb,
413            var(--w3m-color-mix) var(--w3m-color-mix-strength),
414            var(--wui-color-bg-350)
415          );
416
417          --wui-color-success-100: color-mix(
418            in srgb,
419            var(--w3m-color-mix) var(--w3m-color-mix-strength),
420            var(--wui-color-success-base-100)
421          );
422          --wui-color-success-125: color-mix(
423            in srgb,
424            var(--w3m-color-mix) var(--w3m-color-mix-strength),
425            var(--wui-color-success-base-125)
426          );
427
428          --wui-color-warning-100: color-mix(
429            in srgb,
430            var(--w3m-color-mix) var(--w3m-color-mix-strength),
431            var(--wui-color-warning-base-100)
432          );
433
434          --wui-color-error-100: color-mix(
435            in srgb,
436            var(--w3m-color-mix) var(--w3m-color-mix-strength),
437            var(--wui-color-error-base-100)
438          );
439          --wui-color-blue-100: color-mix(
440            in srgb,
441            var(--w3m-color-mix) var(--w3m-color-mix-strength),
442            var(--wui-color-blue-base-100)
443          );
444          --wui-color-blue-90: color-mix(
445            in srgb,
446            var(--w3m-color-mix) var(--w3m-color-mix-strength),
447            var(--wui-color-blue-base-90)
448          );
449          --wui-color-error-125: color-mix(
450            in srgb,
451            var(--w3m-color-mix) var(--w3m-color-mix-strength),
452            var(--wui-color-error-base-125)
453          );
454
455          --wui-icon-box-bg-error-100: color-mix(
456            in srgb,
457            var(--w3m-color-mix) var(--w3m-color-mix-strength),
458            var(--wui-icon-box-bg-error-base-100)
459          );
460          --wui-icon-box-bg-accent-100: color-mix(
461            in srgb,
462            var(--w3m-color-mix) var(--w3m-color-mix-strength),
463            var(--wui-icon-box-bg-blue-base-100)
464          );
465          --wui-icon-box-bg-success-100: color-mix(
466            in srgb,
467            var(--w3m-color-mix) var(--w3m-color-mix-strength),
468            var(--wui-icon-box-bg-success-base-100)
469          );
470          --wui-icon-box-bg-inverse-100: color-mix(
471            in srgb,
472            var(--w3m-color-mix) var(--w3m-color-mix-strength),
473            var(--wui-icon-box-bg-inverse-base-100)
474          );
475
476          --wui-all-wallets-bg-100: color-mix(
477            in srgb,
478            var(--w3m-color-mix) var(--w3m-color-mix-strength),
479            var(--wui-all-wallets-bg-100)
480          );
481
482          --wui-avatar-border: color-mix(
483            in srgb,
484            var(--w3m-color-mix) var(--w3m-color-mix-strength),
485            var(--wui-avatar-border-base)
486          );
487
488          --wui-thumbnail-border: color-mix(
489            in srgb,
490            var(--w3m-color-mix) var(--w3m-color-mix-strength),
491            var(--wui-thumbnail-border-base)
492          );
493
494          --wui-wallet-button-bg: color-mix(
495            in srgb,
496            var(--w3m-color-mix) var(--w3m-color-mix-strength),
497            var(--wui-wallet-button-bg-base)
498          );
499        }
500      }
501    `,
501light:Mr`
502      :root {
503        --w3m-color-mix: ${Ot(t?.["--w3m-color-mix"]||"#fff")};
504        --w3m-accent: ${Ot(As(t,"dark")["--w3m-accent"])};
505        --w3m-default: #fff;
506
507        --wui-color-modal-bg-base: ${Ot(As(t,"dark")["--w3m-background"])};
508        --wui-color-accent-base-100: var(--w3m-accent);
509
510        --wui-color-blueberry-100: hsla(230, 100%, 67%, 1);
511        --wui-color-blueberry-090: hsla(231, 76%, 61%, 1);
512        --wui-color-blueberry-080: hsla(230, 59%, 55%, 1);
513        --wui-color-blueberry-050: hsla(231, 100%, 70%, 0.1);
514
515        --wui-color-fg-100: #e4e7e7;
516        --wui-color-fg-125: #d0d5d5;
517        --wui-color-fg-150: #a8b1b1;
518        --wui-color-fg-175: #a8b0b0;
519        --wui-color-fg-200: #949e9e;
520        --wui-color-fg-225: #868f8f;
521        --wui-color-fg-250: #788080;
522        --wui-color-fg-275: #788181;
523        --wui-color-fg-300: #6e7777;
524        --wui-color-fg-325: #9a9a9a;
525        --wui-color-fg-350: #363636;
526
527        --wui-color-bg-100: #141414;
528        --wui-color-bg-125: #191a1a;
529        --wui-color-bg-150: #1e1f1f;
530        --wui-color-bg-175: #222525;
531        --wui-color-bg-200: #272a2a;
532        --wui-color-bg-225: #2c3030;
533        --wui-color-bg-250: #313535;
534        --wui-color-bg-275: #363b3b;
535        --wui-color-bg-300: #3b4040;
536        --wui-color-bg-325: #252525;
537        --wui-color-bg-350: #ffffff;
538
539        --wui-color-success-base-100: #26d962;
540        --wui-color-success-base-125: #30a46b;
541
542        --wui-color-warning-base-100: #f3a13f;
543
544        --wui-color-error-base-100: #f25a67;
545        --wui-color-error-base-125: #df4a34;
546
547        --wui-color-blue-base-100: rgba(102, 125, 255, 1);
548        --wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
549
550        --wui-color-success-glass-001: rgba(38, 217, 98, 0.01);
551        --wui-color-success-glass-002: rgba(38, 217, 98, 0.02);
552        --wui-color-success-glass-005: rgba(38, 217, 98, 0.05);
553        --wui-color-success-glass-010: rgba(38, 217, 98, 0.1);
554        --wui-color-success-glass-015: rgba(38, 217, 98, 0.15);
555        --wui-color-success-glass-020: rgba(38, 217, 98, 0.2);
556        --wui-color-success-glass-025: rgba(38, 217, 98, 0.25);
557        --wui-color-success-glass-030: rgba(38, 217, 98, 0.3);
558        --wui-color-success-glass-060: rgba(38, 217, 98, 0.6);
559        --wui-color-success-glass-080: rgba(38, 217, 98, 0.8);
560
561        --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
562
563        --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
564
565        --wui-color-error-glass-001: rgba(242, 90, 103, 0.01);
566        --wui-color-error-glass-002: rgba(242, 90, 103, 0.02);
567        --wui-color-error-glass-005: rgba(242, 90, 103, 0.05);
568        --wui-color-error-glass-010: rgba(242, 90, 103, 0.1);
569        --wui-color-error-glass-015: rgba(242, 90, 103, 0.15);
570        --wui-color-error-glass-020: rgba(242, 90, 103, 0.2);
571        --wui-color-error-glass-025: rgba(242, 90, 103, 0.25);
572        --wui-color-error-glass-030: rgba(242, 90, 103, 0.3);
573        --wui-color-error-glass-060: rgba(242, 90, 103, 0.6);
574        --wui-color-error-glass-080: rgba(242, 90, 103, 0.8);
575
576        --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
577
578        --wui-color-gray-glass-001: rgba(255, 255, 255, 0.01);
579        --wui-color-gray-glass-002: rgba(255, 255, 255, 0.02);
580        --wui-color-gray-glass-005: rgba(255, 255, 255, 0.05);
581        --wui-color-gray-glass-010: rgba(255, 255, 255, 0.1);
582        --wui-color-gray-glass-015: rgba(255, 255, 255, 0.15);
583        --wui-color-gray-glass-020: rgba(255, 255, 255, 0.2);
584        --wui-color-gray-glass-025: rgba(255, 255, 255, 0.25);
585        --wui-color-gray-glass-030: rgba(255, 255, 255, 0.3);
586        --wui-color-gray-glass-060: rgba(255, 255, 255, 0.6);
587        --wui-color-gray-glass-080: rgba(255, 255, 255, 0.8);
588        --wui-color-gray-glass-090: rgba(255, 255, 255, 0.9);
589
590        --wui-color-dark-glass-100: rgba(42, 42, 42, 1);
591
592        --wui-icon-box-bg-error-base-100: #3c2426;
593        --wui-icon-box-bg-blue-base-100: #20303f;
594        --wui-icon-box-bg-success-base-100: #1f3a28;
595        --wui-icon-box-bg-inverse-base-100: #243240;
596
597        --wui-all-wallets-bg-100: #222b35;
598
599        --wui-avatar-border-base: #252525;
600
601        --wui-thumbnail-border-base: #252525;
602
603        --wui-wallet-button-bg-base: var(--wui-color-bg-125);
604
605        --w3m-card-embedded-shadow-color: rgb(17 17 18 / 25%);
606      }
607    `,dark:Mr`
608      :root {
609        --w3m-color-mix: ${Ot(t?.["--w3m-color-mix"]||"#000")};
610        --w3m-accent: ${Ot(As(t,"light")["--w3m-accent"])};
611        --w3m-default: #000;
612
613        --wui-color-modal-bg-base: ${Ot(As(t,"light")["--w3m-background"])};
614        --wui-color-accent-base-100: var(--w3m-accent);
615
616        --wui-color-blueberry-100: hsla(231, 100%, 70%, 1);
617        --wui-color-blueberry-090: hsla(231, 97%, 72%, 1);
618        --wui-color-blueberry-080: hsla(231, 92%, 74%, 1);
619
620        --wui-color-fg-100: #141414;
621        --wui-color-fg-125: #2d3131;
622        --wui-color-fg-150: #474d4d;
623        --wui-color-fg-175: #636d6d;
624        --wui-color-fg-200: #798686;
625        --wui-color-fg-225: #828f8f;
626        --wui-color-fg-250: #8b9797;
627        --wui-color-fg-275: #95a0a0;
628        --wui-color-fg-300: #9ea9a9;
629        --wui-color-fg-325: #9a9a9a;
630        --wui-color-fg-350: #d0d0d0;
631
632        --wui-color-bg-100: #ffffff;
633        --wui-color-bg-125: #f5fafa;
634        --wui-color-bg-150: #f3f8f8;
635        --wui-color-bg-175: #eef4f4;
636        --wui-color-bg-200: #eaf1f1;
637        --wui-color-bg-225: #e5eded;
638        --wui-color-bg-250: #e1e9e9;
639        --wui-color-bg-275: #dce7e7;
640        --wui-color-bg-300: #d8e3e3;
641        --wui-color-bg-325: #f3f3f3;
642        --wui-color-bg-350: #202020;
643
644        --wui-color-success-base-100: #26b562;
645        --wui-color-success-base-125: #30a46b;
646
647        --wui-color-warning-base-100: #f3a13f;
648
649        --wui-color-error-base-100: #f05142;
650        --wui-color-error-base-125: #df4a34;
651
652        --wui-color-blue-base-100: rgba(102, 125, 255, 1);
653        --wui-color-blue-base-90: rgba(102, 125, 255, 0.9);
654
655        --wui-color-success-glass-001: rgba(38, 181, 98, 0.01);
656        --wui-color-success-glass-002: rgba(38, 181, 98, 0.02);
657        --wui-color-success-glass-005: rgba(38, 181, 98, 0.05);
658        --wui-color-success-glass-010: rgba(38, 181, 98, 0.1);
659        --wui-color-success-glass-015: rgba(38, 181, 98, 0.15);
660        --wui-color-success-glass-020: rgba(38, 181, 98, 0.2);
661        --wui-color-success-glass-025: rgba(38, 181, 98, 0.25);
662        --wui-color-success-glass-030: rgba(38, 181, 98, 0.3);
663        --wui-color-success-glass-060: rgba(38, 181, 98, 0.6);
664        --wui-color-success-glass-080: rgba(38, 181, 98, 0.8);
665
666        --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2);
667
668        --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2);
669
670        --wui-color-error-glass-001: rgba(240, 81, 66, 0.01);
671        --wui-color-error-glass-002: rgba(240, 81, 66, 0.02);
672        --wui-color-error-glass-005: rgba(240, 81, 66, 0.05);
673        --wui-color-error-glass-010: rgba(240, 81, 66, 0.1);
674        --wui-color-error-glass-015: rgba(240, 81, 66, 0.15);
675        --wui-color-error-glass-020: rgba(240, 81, 66, 0.2);
676        --wui-color-error-glass-025: rgba(240, 81, 66, 0.25);
677        --wui-color-error-glass-030: rgba(240, 81, 66, 0.3);
678        --wui-color-error-glass-060: rgba(240, 81, 66, 0.6);
679        --wui-color-error-glass-080: rgba(240, 81, 66, 0.8);
680
681        --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2);
682
683        --wui-icon-box-bg-error-base-100: #f4dfdd;
684        --wui-icon-box-bg-blue-base-100: #d9ecfb;
685        --wui-icon-box-bg-success-base-100: #daf0e4;
686        --wui-icon-box-bg-inverse-base-100: #dcecfc;
687
688        --wui-all-wallets-bg-100: #e8f1fa;
689
690        --wui-avatar-border-base: #f3f4f4;
691
692        --wui-thumbnail-border-base: #eaefef;
693
694        --wui-wallet-button-bg-base: var(--wui-color-bg-125);
695
696        --wui-color-gray-glass-001: rgba(0, 0, 0, 0.01);
697        --wui-color-gray-glass-002: rgba(0, 0, 0, 0.02);
698        --wui-color-gray-glass-005: rgba(0, 0, 0, 0.05);
699        --wui-color-gray-glass-010: rgba(0, 0, 0, 0.1);
700        --wui-color-gray-glass-015: rgba(0, 0, 0, 0.15);
701        --wui-color-gray-glass-020: rgba(0, 0, 0, 0.2);
702        --wui-color-gray-glass-025: rgba(0, 0, 0, 0.25);
703        --wui-color-gray-glass-030: rgba(0, 0, 0, 0.3);
704        --wui-color-gray-glass-060: rgba(0, 0, 0, 0.6);
705        --wui-color-gray-glass-080: rgba(0, 0, 0, 0.8);
706        --wui-color-gray-glass-090: rgba(0, 0, 0, 0.9);
707
708        --wui-color-dark-glass-100: rgba(233, 233, 233, 1);
709
710        --w3m-card-embedded-shadow-color: rgb(224 225 233 / 25%);
711      }
712    `}}const bA=Mr`
713  *,
714  *::after,
715  *::before,
716  :host {
717    margin: 0;
718    padding: 0;
719    box-sizing: border-box;
720    font-style: normal;
721    text-rendering: optimizeSpeed;
722    -webkit-font-smoothing: antialiased;
723    -moz-osx-font-smoothing: grayscale;
724    -webkit-tap-highlight-color: transparent;
725    font-family: var(--wui-font-family);
726    backface-visibility: hidden;
727  }
728`,vA=Mr`
729  button,
730  a {
731    cursor: pointer;
732    display: flex;
733    justify-content: center;
734    align-items: center;
735    position: relative;
736    transition:
737      color var(--wui-duration-lg) var(--wui-ease-out-power-1),
738      background-color var(--wui-duration-lg) var(--wui-ease-out-power-1),
739      border var(--wui-duration-lg) var(--wui-ease-out-power-1),
740      border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1),
741      box-shadow var(--wui-duration-lg) var(--wui-ease-out-power-1);
742    will-change: background-color, color, border, box-shadow, border-radius;
743    outline: none;
744    border: none;
745    column-gap: var(--wui-spacing-3xs);
746    background-color: transparent;
747    text-decoration: none;
748  }
749
750  wui-flex {
751    transition: border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1);
752    will-change: border-radius;
753  }
754
755  button:disabled > wui-wallet-image,
756  button:disabled > wui-all-wallets-image,
757  button:disabled > wui-network-image,
758  button:disabled > wui-image,
759  button:disabled > wui-transaction-visual,
760  button:disabled > wui-logo {
761    filter: grayscale(1);
762  }
763
764  @media (hover: hover) and (pointer: fine) {
765    button:hover:enabled {
766      background-color: var(--wui-color-gray-glass-005);
767    }
768
769    button:active:enabled {
770      background-color: var(--wui-color-gray-glass-010);
771    }
772  }
773
774  button:disabled > wui-icon-box {
775    opacity: 0.5;
776  }
777
778  input {
779    border: none;
780    outline: none;
781    appearance: none;
782  }
783`,EA=Mr`
784  .wui-color-inherit {
785    color: var(--wui-color-inherit);
786  }
787
788  .wui-color-accent-100 {
789    color: var(--wui-color-accent-100);
790  }
791
792  .wui-color-error-100 {
793    color: var(--wui-color-error-100);
794  }
795
796  .wui-color-blue-100 {
797    color: var(--wui-color-blue-100);
798  }
799
800  .wui-color-blue-90 {
801    color: var(--wui-color-blue-90);
802  }
803
804  .wui-color-error-125 {
805    color: var(--wui-color-error-125);
806  }
807
808  .wui-color-success-100 {
809    color: var(--wui-color-success-100);
810  }
811
812  .wui-color-success-125 {
813    color: var(--wui-color-success-125);
814  }
815
816  .wui-color-inverse-100 {
817    color: var(--wui-color-inverse-100);
818  }
819
820  .wui-color-inverse-000 {
821    color: var(--wui-color-inverse-000);
822  }
823
824  .wui-color-fg-100 {
825    color: var(--wui-color-fg-100);
826  }
827
828  .wui-color-fg-200 {
829    color: var(--wui-color-fg-200);
830  }
831
832  .wui-color-fg-300 {
833    color: var(--wui-color-fg-300);
834  }
835
836  .wui-color-fg-325 {
837    color: var(--wui-color-fg-325);
838  }
839
840  .wui-color-fg-350 {
841    color: var(--wui-color-fg-350);
842  }
843
844  .wui-bg-color-inherit {
845    background-color: var(--wui-color-inherit);
846  }
847
848  .wui-bg-color-blue-100 {
849    background-color: var(--wui-color-accent-100);
850  }
851
852  .wui-bg-color-error-100 {
853    background-color: var(--wui-color-error-100);
854  }
855
856  .wui-bg-color-error-125 {
857    background-color: var(--wui-color-error-125);
858  }
859
860  .wui-bg-color-success-100 {
861    background-color: var(--wui-color-success-100);
862  }
863
864  .wui-bg-color-success-125 {
865    background-color: var(--wui-color-success-100);
866  }
867
868  .wui-bg-color-inverse-100 {
869    background-color: var(--wui-color-inverse-100);
870  }
871
872  .wui-bg-color-inverse-000 {
873    background-color: var(--wui-color-inverse-000);
874  }
875
876  .wui-bg-color-fg-100 {
877    background-color: var(--wui-color-fg-100);
878  }
879
880  .wui-bg-color-fg-200 {
881    background-color: var(--wui-color-fg-200);
882  }
883
884  .wui-bg-color-fg-300 {
885    background-color: var(--wui-color-fg-300);
886  }
887
888  .wui-color-fg-325 {
889    background-color: var(--wui-color-fg-325);
890  }
891
892  .wui-color-fg-350 {
893    background-color: var(--wui-color-fg-350);
894  }
895`;function vI(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<t.length;l++){const u=t.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const s=t.length,r=t.charAt(0),i=Math.log(s)/Math.log(256),n=Math.log(256)/Math.log(s);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,h=0;const p=l.length;for(;h!==p&&l[h]===0;)h++,u++;const w=(p-h)*n+1>>>0,g=new Uint8Array(w);for(;h!==p;){let y=l[h],v=0;for(let C=w-1;(y!==0||v<d)&&C!==-1;C--,v++)y+=256*g[C]>>>0,g[C]=y%s>>>0,y=y/s>>>0;if(y!==0)throw new Error("Non-zero carry");d=v,h++}let f=w-d;for(;f!==w&&g[f]===0;)f++;let b=r.repeat(u);for(;f<w;++f)b+=t.charAt(g[f]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,h=0;for(;l[u]===r;)d++,u++;const p=(l.length-u)*i+1>>>0,w=new Uint8Array(p);for(;u<l.length;){const y=l.charCodeAt(u);if(y>255)return;let v=e[y];if(v===255)return;let C=0;for(let A=p-1;(v!==0||C<h)&&A!==-1;A--,C++)v+=s*w[A]>>>0,w[A]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");h=C,u++}let g=p-h;for(;g!==p&&w[g]===0;)g++;const f=new Uint8Array(d+(p-g));let b=d;for(;g!==p;)f[b++]=w[g++];return f}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+s+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var EI="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const CI=vI(EI);
895function II(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Au(t){return II(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const _h="2.33.1";let Xo={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${_h}`};class Zr extends Error{constructor(e,s={}){const r=s.cause instanceof Zr?s.cause.details:s.cause?.message?s.cause.message:s.details,i=s.cause instanceof Zr&&s.cause.docsPath||s.docsPath,n=Xo.getDocsUrl?.({...s,docsPath:i}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...Xo.version?[`Version: ${Xo.version}`]:[]].join(`
896`);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=_h}walk(e){return Sh(this,e)}}function Sh(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Sh(t.cause,e):e?null:t}class Ph extends Zr{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 ac(t,{dir:e,size:s=32}={}){return typeof t=="string"?AI(t,{dir:e,size:s}):NI(t,{dir:e,size:s})}function AI(t,{dir:e,size:s=32}={}){if(s===null)return t;const r=t.replace("0x","");if(r.length>s*2)throw new Ph({size:Math.ceil(r.length/2),targetSize:s,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function NI(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new Ph({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 _I extends Zr{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 SI extends Zr{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Oh(t,{size:e}){if(Au(t)>e)throw new SI({givenSize:Au(t),maxSize:e})}const PI=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Nu(t,e={}){return typeof t=="number"||typeof t=="bigint"?kI(t,e):typeof t=="string"?xI(t,e):typeof t=="boolean"?OI(t,e):kh(t,e)}function OI(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(Oh(s,{size:e.size}),ac(s,{size:e.size})):s}function kh(t,e={}){let s="";for(let i=0;i<t.length;i++)s+=PI[t[i]];const r=`0x${s}`;return typeof e.size=="number"?(Oh(r,{size:e.size}),ac(r,{dir:"right",size:e.size})):r}function kI(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 _I({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?ac(a,{size:r}):a}const TI=new TextEncoder;function xI(t,e={}){const s=TI.encode(t);return kh(s,e)}const Ci={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 An(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const _u=An({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"}
896),Su=An({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"});An({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"});An({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});An({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 $I={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"]},Yn={getMethodsByChainNamespace(t){return $I[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 _u.caipNetworkId:u.chains.push(_u.deprecatedCaipNetworkId);break;case Su.caipNetworkId:u.chains.push(Su.deprecatedCaipNetworkId);break}return u?.rpcMap&&c&&(u.rpcMap[n]=c),r},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{const e=await _i.resolveName(t);return(Object.values(e?.addresses)||[])[0]?.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}
896else try{if(new URL(r).origin===t)return!0}catch{if(r===t)return!0}return!1}};class Th{constructor({provider:e,namespace:s}){this.id=W.CONNECTOR_ID.WALLET_CONNECT,this.name=so.ConnectorNamesMap[W.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=so.ConnectorImageIds[W.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=m.getCaipNetworks.bind(m),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=k.state.universalProviderConfigOverride,i=Yn.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 ki.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:RI})}}const RI=["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 UI{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=s=>m.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:W.CONNECTOR_ID.AUTH,type:"AUTH",name:W.CONNECTOR_NAMES.AUTH,provider:e,imageId:so.ConnectorImageIds[W.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){F.setStatus(e,s)}on(e,s){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(s)}off(e,s){const 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){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 n=i,o=F.state.preferredAccountTypes?.[s.chainNamespace];await n.switchNetwork(s.caipNetworkId);const a=await n.getUser({chainId:s.caipNetworkId,preferredAccountType:o});this.emit("switchNetwork",a)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s instanceof Th);if(!e)throw new Error("WalletConnectConnector not found");return e}}class DI extends UI{setUniversalProvider(e){this.addConnector(new Th({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}){const r=this.provider?.session?.namespaces?.[e]?.accounts?.map(i=>{const[,,n]=i.split(":");return n}).filter((i,n,o)=>o.indexOf(i)===n)||[];return Promise.resolve({accounts:r.map(i=>X.createAccount(e,i,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&Ee.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(F.state.balanceLoading&&e.chainId===m.state.activeCaipNetwork?.id)return{balance:F.state.balance||"0.00",symbol:F.state.balanceSymbol||""};const i=(await F.fetchTokenBalance()).find(n=>n.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&n.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:i?.quantity.numeric||"0.00",symbol:i?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:s,message:r,address:i}=e;
vendor: 5,290 bytes, line 896
896if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return m.state.activeCaipNetwork?.chainNamespace===W.CHAIN.SOLANA?n=(await s.request({method:"solana_signMessage",params:{message:CI.encode(new TextEncoder().encode(r)),pubkey:i}},m.state.activeCaipNetwork?.caipNetworkId)).signature:n=await s.request({method:"personal_sign",params:[r,i]},m.state.activeCaipNetwork?.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){const{caipNetwork:s}=e,r=this.getWalletConnectConnector();if(s.chainNamespace===W.CHAIN.EVM)try{await r.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:Nu(s.id)}]})}catch(i){if(i.code===Ci.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||i.code===Ci.ERROR_INVALID_CHAIN_ID||i.code===Ci.ERROR_CODE_DEFAULT||i?.data?.originalError?.code===Ci.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await r.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:Nu(s.id),rpcUrls:[s?.rpcUrls.chainDefault?.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[s.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}r.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(r=>r.type==="WALLET_CONNECT")?.provider}}const MI=["email","socials","swaps","onramp","activity","reownBranding"],zn={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?Ee.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(s=>s!=="email"):!1},processFallback:t=>t===void 0?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?.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?.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}},LI={localSettingsOverridden:new Set,getApiConfig(t,e){return e?.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=zn[e],r=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(r)}},processFeature(t,e,s,r,i){const n=zn[t],o=e[n.localFeatureName];if(i&&!n.isAvailableOnBasic)return!1;if(r){const a=this.getApiConfig(n.apiFeatureName,s);return a?.config===null?this.processFallbackFeature(t,o):a?.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return zn[t].processApi(e)},processFallbackFeature(t,e){return zn[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 MI){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.`;qs.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${o}`},"warning")}return n}};
896class jI{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,r)=>{if(s){const i=m.getNetworkData(s)?.requestedCaipNetworks?.find(a=>a.id===r);if(i)return i;const n=m.getNetworkData(s)?.caipNetwork;return n||m.getRequestedCaipNetworks(s).filter(a=>a.chainNamespace===s)?.[0]}return m.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>m.getCaipNetworks(s),this.getActiveChainNamespace=()=>m.state.activeChain,this.setRequestedCaipNetworks=(s,r)=>{m.setRequestedCaipNetworks(s,r)},this.getApprovedCaipNetworkIds=()=>m.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>m.state.activeChain===s||!s?m.state.activeCaipAddress:m.getAccountProp("caipAddress",s),this.setClientId=s=>{J.setClientId(s)},this.getProvider=s=>Pe.getProvider(s),this.getProviderType=s=>Pe.getProviderId(s),this.getPreferredAccountType=s=>F.state.preferredAccountTypes?.[s],this.setCaipAddress=(s,r)=>{F.setCaipAddress(s,r),s&&k.state.enableEmbedded&&this.close()},this.setBalance=(s,r,i)=>{F.setBalance(s,r,i)},this.setProfileName=(s,r)=>{F.setProfileName(s,r)},this.setProfileImage=(s,r)=>{F.setProfileImage(s,r)},this.setUser=(s,r)=>{F.setUser(s,r)},this.resetAccount=s=>{F.resetAccount(s)},this.setCaipNetwork=s=>{m.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,r)=>{m.setChainNetworkData(r,{caipNetwork:s})},this.setAllAccounts=(s,r)=>{F.setAllAccounts(s,r),k.setHasMultipleAddresses(s?.length>1)},this.setStatus=(s,r)=>{F.setStatus(s,r),B.isConnected()?z.setConnectionStatus("connected"):z.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>m.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=>Uu.getConnectorImage(s),this.setConnectedWalletInfo=(s,r)=>{const i=Pe.getProviderId(r),n=s?{...s,type:i}:void 0;F.setConnectedWalletInfo(n,r)},this.getIsConnectedState=()=>!!m.state.activeCaipAddress,this.addAddressLabel=(s,r,i)=>{F.addAddressLabel(s,r,i)},this.removeAddressLabel=(s,r)=>{F.removeAddressLabel(s,r)},this.getAddress=s=>m.state.activeChain===s||!s?F.state.address:m.getAccountProp("address",s),this.setApprovedCaipNetworksData=s=>m.setApprovedCaipNetworksData(s),this.resetNetwork=s=>{m.resetNetwork(s)},this.addConnector=s=>{B.addConnector(s)},this.resetWcConnection=()=>{Y.resetWcConnection()},this.setAddressExplorerUrl=(s,r)=>{F.setAddressExplorerUrl(s,r)},this.setSmartAccountDeployed=(s,r)=>{F.setSmartAccountDeployed(s,r)},this.setSmartAccountEnabledNetworks=(s,r)=>{m.setSmartAccountEnabledNetworks(s,r)},this.setPreferredAccountType=(s,r)=>{F.setPreferredAccountType(s,r)},this.setEIP6963Enabled=s=>{k.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?.map(n=>n.namespace).filter(n=>!!n);if(r?.length)return[...new Set(r)];const i=s?.map(n=>n.chainNamespace);return[...new Set(i)]}async initialize(e){this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),await this.syncExistingConnection(),this.remoteFeatures=await LI.fetchRemoteFeatures(e),k.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&ra.setOnrampProviders(this.remoteFeatures.onramp),(k.state.remoteFeatures?.email||Array.isArray(k.state.remoteFeatures?.socials)&&k.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await V.fetchAllowedOrigins();if(e&&X.isClient()){const s=window.location.origin;Yn.isOriginAllowed(s,e,Ci.DEFAULT_ALLOWED_ANCESTORS)||qs.open(Sr.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else qs.open(Sr.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){const{...s}=e;delete s.adapters,delete s.universalProvider,Oe.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(r=>r.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&wt.setThemeMode(e.themeMode),e.themeVariables&&wt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");m.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const s=this.getDefaultNetwork();s&&m.setActiveCaipNetwork(s)}initializeConnectionController(e){Y.setWcBasic(e.basic??!1)}initializeConnectorController(){B.initialize(this.chainNamespaces)}initializeProjectSettings(e){k.setProjectId(e.projectId),k.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){k.setDebug(e.debug!==!1),k.setEnableWalletConnect(e.enableWalletConnect!==!1),k.setEnableWalletGuide(e.enableWalletGuide!==!1),k.setEnableWallets(e.enableWallets!==!1),k.setEIP6963Enabled(e.enableEIP6963!==!1),k.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),k.setEnableAuthLogger(e.enableAuthLogger!==!1),k.setCustomRpcUrls(e.customRpcUrls),k.setEnableEmbedded(e.enableEmbedded),k.setAllWallets(e.allWallets),k.setIncludeWalletIds(e.includeWalletIds),k.setExcludeWalletIds(e.excludeWalletIds),k.setFeaturedWalletIds(e.featuredWalletIds),k.setTokens(e.tokens),k.setTermsConditionsUrl(e.termsConditionsUrl),k.setPrivacyPolicyUrl(e.privacyPolicyUrl),k.setCustomWallets(e.customWallets),k.setFeatures(e.features),k.setAllowUnsupportedChain(e.allowUnsupportedChain),k.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),k.setPreferUniversalLinks(e.experimental_preferUniversalLinks),k.setDefaultAccountTypes(e.defaultAccountTypes);const s=z.getPreferredAccountTypes()||{},r={...k.state.defaultAccountTypes,...s};F.setPreferredAccountTypes(r);const i=this.getDefaultMetaData();if(!e.metadata&&i&&(e.metadata=i),k.setMetadata(e.metadata),k.setDisableAppend(e.disableAppend),k.setEnableEmbedded(e.enableEmbedded),k.setSIWX(e.siwx),!e.projectId){qs.open(Sr.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(o=>o.namespace===W.CHAIN.EVM)&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");k.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return X.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const r=Or.getUnsupportedNetwork(`${s}:${e}`);m.setActiveCaipNetwork(r)}}getDefaultNetwork(){return Or.getCaipNetworkFromStorage(this.defaultCaipNetwork)}
896extendCaipNetwork(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=>i.id===e.defaultNetwork?.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=Pe.getProvider(e),i=Pe.getProviderId(e),{caipAddress:n}=m.getAccountData(e)||{};this.setLoading(!0,e),n&&s?.disconnect&&await s.disconnect({provider:r,providerType:i}),z.removeConnectedNamespace(e),Pe.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),B.removeConnectorId(e),m.resetAccount(e),m.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()=>{const e=m.state.activeChain,s=this.getAdapter(e),r=this.getCaipNetwork(e)?.id;if(!s)throw new Error("Adapter not found");const i=await s.connectWalletConnect(r);this.close(),this.setClientId(i?.clientId||null),z.setConnectedNamespaces([...m.state.chains.keys()]),this.chainNamespaces.forEach(n=>{B.setConnectorId(bs.CONNECTOR_TYPE_WALLET_CONNECT,n)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:s,type:r,provider:i,chain:n,caipNetwork:o,socialUri:a})=>{const c=m.state.activeChain,l=n||c,u=this.getAdapter(l);if(n&&n!==c&&!o){const g=this.getCaipNetworks().find(f=>f.chainNamespace===n);g&&this.setCaipNetwork(g)}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?.id||d?.id,rpcUrl:o?.rpcUrls?.default?.http?.[0]||d?.rpcUrls?.default?.http?.[0]});if(!h)return;z.addConnectedNamespace(l),this.syncProvider({...h,chainNamespace:l});const p=F.state.allAccounts,{accounts:w}=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})=>{const n=m.state.activeChain,o=this.getAdapter(n);o?.reconnect&&(await o?.reconnect({id:e,info:s,type:r,provider:i,chainId:this.getCaipNetwork()?.id}),z.addConnectedNamespace(n),this.syncConnectedWalletInfo(n))},disconnect:async e=>{const s=C1(e);try{const r=await Promise.allSettled(s.map(async([n])=>this.disconnectNamespace(n)));he.resetSend(),Y.resetWcConnection(),await ki.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(", "));z.deleteConnectedSocialProvider(),Oe.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=>!!window.ethereum?.[String(s)]):!!window.ethereum,signMessage:async e=>(await this.getAdapter(m.state.activeChain)?.signMessage({message:e,address:F.state.address,provider:Pe.getProvider(m.state.activeChain)}))?.signature||"",sendTransaction:async e=>{const s=e.chainNamespace;if(Ee.SEND_SUPPORTED_NAMESPACES.includes(s)){const r=this.getAdapter(m.state.activeChain),i=Pe.getProvider(s);return(await r?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}))?.hash||""}return""},estimateGas:async e=>{if(e.chainNamespace===W.CHAIN.EVM){const s=this.getAdapter(m.state.activeChain),r=Pe.getProvider(m.state.activeChain),i=this.getCaipNetwork();if(!i)throw new Error("CaipNetwork is undefined");return(await s?.estimateGas({...e,provider:r,caipNetwork:i}))?.gas||0n}return 0n},getEnsAvatar:async()=>(await this.syncIdentity({address:F.state.address,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:m.state.activeChain}),F.state.profileImage||!1),getEnsAddress:async e=>await Yn.resolveReownName(e),writeContract:async e=>{const s=this.getAdapter(m.state.activeChain),r=this.getCaipNetwork(),i=this.getCaipAddress(),n=Pe.getProvider(m.state.activeChain);if(!r||!i)throw new Error("CaipNetwork or CaipAddress is undefined");return(await s?.writeContract({...e,caipNetwork:r,provider:n,caipAddress:i}))?.hash},parseUnits:(e,s)=>this.getAdapter(m.state.activeChain)?.parseUnits({value:e,decimals:s})??0n,formatUnits:(e,s)=>this.getAdapter(m.state.activeChain)?.formatUnits({value:e,decimals:s})??"0",getCapabilities:async e=>await this.getAdapter(m.state.activeChain)?.getCapabilities(e),grantPermissions:async e=>await this.getAdapter(m.state.activeChain)?.grantPermissions(e),revokePermissions:async e=>{const s=this.getAdapter(m.state.activeChain);return s?.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>await this.getAdapter(m.state.activeChain)?.walletGetAssets(e)??{},updateBalance:e=>{const s=this.getCaipNetwork(e);!s||!F.state.address||this.updateNativeBalance(F.state.address,s?.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Y.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){if(Pe.getProviderId(m.state.activeChain)===bs.CONNECTOR_TYPE_WALLET_CONNECT){const s=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(s)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const i=Pe.getProvider(s),n=Pe.getProviderId(s);if(e.chainNamespace===m.state.activeChain)await this.getAdapter(s)?.switchNetwork({caipNetwork:e,provider:i,providerType:n});else if(this.setCaipNetwork(e),n===bs.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)}
896getChainsFromNamespaces(e={}){return Object.values(e).flatMap(s=>{const r=s.chains||[],i=s.accounts.map(n=>{const{chainId:o,chainNamespace:a}=fs.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...r,...i]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,r)=>{const i=e?.find(n=>n.namespace===r);return i?(i.construct({namespace:r,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),s[r]=i):s[r]=new DI({namespace:r,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e),await this.chainAdapters?.[e].syncConnectors(this.options,this),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){this.getAdapter(e)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const r=z.getConnectionStatus();r==="connected"?this.setStatus("connecting",e):r==="disconnected"?(z.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=m.state.activeChain===e,c=m.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=F.state.address,n=m.state.activeCaipNetwork;!i||!n?.id||this.updateNativeBalance(i,n.id,n.chainNamespace)}),s.on("accountChanged",({address:i,chainId:n})=>{const o=m.state.activeChain===e;o&&n?this.syncAccount({address:i,chainId:n,chainNamespace:e}):o&&m.state.activeCaipNetwork?.id?this.syncAccount({address:i,chainId:m.state.activeCaipNetwork?.id,chainNamespace:e}):this.syncAccountInfo(i,n,e),this.syncAllAccounts(e)})}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{e===W.CHAIN.EVM&&X.isSafeApp()&&B.setConnectorId(W.CONNECTOR_ID.SAFE,e);const s=B.getConnectorId(e);switch(this.setStatus("connecting",e),s){case W.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case W.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){const s=this.getAdapter(e),r=B.getConnectorId(e),i=this.getCaipNetwork(e),o=B.getConnectors(e).find(a=>a.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!i?.id)throw new Error("CaipNetwork not found");const a=await s?.syncConnection({namespace:e,id:o.id,chainId:i.id,rpcUrl:i?.rpcUrls?.default?.http?.[0]});if(a){const c=await s?.getAccounts({namespace:e,id:o.id});c&&c.accounts.length>0?this.setAllAccounts(c.accounts,e):this.setAllAccounts([X.createAccount(e,a.address,"eoa")],e),this.syncProvider({...a,chainNamespace:e}),await this.syncAccount({...a,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=>{const r=this.getAdapter(s),i=this.universalProvider?.session?.namespaces?.[s]?.accounts||[],n=m.state.activeCaipNetwork?.id,o=i.find(a=>{const{chainId:c}=fs.parseCaipAddress(a);return c===n?.toString()})||i[0];if(o){const a=fs.validateCaipAddress(o),{chainId:c,address:l}=fs.parseCaipAddress(a);if(Pe.setProviderId(s,bs.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&m.state.activeCaipNetwork&&r?.namespace!==W.CHAIN.EVM){const u=r?.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:m.state.activeCaipNetwork});Pe.setProvider(s,u)}else Pe.setProvider(s,this.universalProvider);B.setConnectorId(W.CONNECTOR_ID.WALLET_CONNECT,s),z.addConnectedNamespace(s),this.syncWalletConnectAccounts(s),await this.syncAccount({address:l,chainId:c,chainNamespace:s})}else this.setStatus("disconnected",s);this.syncConnectedWalletInfo(s),await m.setApprovedCaipNetworksData(s)});await Promise.all(e)}syncWalletConnectAccounts(e){const s=this.universalProvider?.session?.namespaces?.[e]?.accounts?.map(r=>{const{address:i}=fs.parseCaipAddress(r);return i}).filter((r,i,n)=>n.indexOf(r)===i);s&&this.setAllAccounts(s.map(r=>X.createAccount(e,r,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:s,id:r,chainNamespace:i}){Pe.setProviderId(i,e),Pe.setProvider(i,s),B.setConnectorId(r,i)}async syncAllAccounts(e){const s=B.getConnectorId(e);if(!s)return;const i=await this.getAdapter(e)?.getAccounts({namespace:e,id:s});i&&i.accounts.length>0&&this.setAllAccounts(i.accounts,e)}async syncAccount(e){const s=e.chainNamespace===m.state.activeChain,r=m.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:i,chainId:n,chainNamespace:o}=e,{chainId:a}=z.getActiveNetworkProps(),c=n||a,l=m.state.activeCaipNetwork?.name===W.UNSUPPORTED_NETWORK_NAME,u=m.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!u)&&c){let d=this.getCaipNetworks().find(w=>w.id.toString()===c.toString()),h=this.getCaipNetworks().find(w=>w.chainNamespace===o);if(!u&&!d&&!h){const w=this.getApprovedCaipNetworkIds()||[],g=w.find(b=>fs.parseCaipNetworkId(b)?.chainId===c.toString()),f=w.find(b=>fs.parseCaipNetworkId(b)?.chainNamespace===o);d=this.getCaipNetworks().find(b=>b.caipNetworkId===g),h=this.getCaipNetworks().find(b=>b.caipNetworkId===f||"deprecatedCaipNetworkId"in b&&b.deprecatedCaipNetworkId===f)}const p=d||h;p?.chainNamespace===m.state.activeChain?k.state.enableNetworkSwitch&&!k.state.allowUnsupportedChain&&m.state.activeCaipNetwork?.name===W.UNSUPPORTED_NETWORK_NAME?m.showUnsupportedChainUI():this.setCaipNetwork(p):s||r&&this.setCaipNetworkOfNamespace(r,o),this.syncConnectedWalletInfo(o),tc.isLowerCaseMatch(i,F.state.address)||this.syncAccountInfo(i,p?.id,o),s?await this.syncBalance({address:i,chainId:p?.id,chainNamespace:o}):await this.syncBalance({address:i,chainId:r?.id,chainNamespace:o})}}async syncAccountInfo(e,s,r){const i=this.getCaipAddress(r),n=s||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);
896if(r[0]){const i=r[0];this.setProfileName(i.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){const s=B.getConnectorId(e),r=Pe.getProviderId(e);if(r===bs.CONNECTOR_TYPE_ANNOUNCED||r===bs.CONNECTOR_TYPE_INJECTED){if(s){const i=this.getConnectors().find(n=>n.id===s);if(i){const{info:n,name:o,imageUrl:a}=i,c=a||this.getConnectorImage(i);this.setConnectedWalletInfo({name:o,icon:c,...n},e)}}}else if(r===bs.CONNECTOR_TYPE_WALLET_CONNECT){const i=Pe.getProvider(e);i?.session&&this.setConnectedWalletInfo({...i.session.peer.metadata,name:i.session.peer.metadata.name,icon:i.session.peer.metadata.icons?.[0]},e)}else if(s&&s===W.CONNECTOR_ID.COINBASE){const i=this.getConnectors().find(n=>n.id===W.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(i)},e)}}async syncBalance(e){!Tu.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(r=>r.id.toString()===e.chainId?.toString())||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,r){const i=this.getAdapter(r),n=m.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(){const e=A1.createLogger((r,...i)=>{r&&this.handleAlertError(r),console.error(...i)}),s={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};k.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await E1.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",()=>{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?.id!==s?.id&&this.setCaipNetwork(s)}),this.universalProvider.on("session_event",e=>{if(Yn.isSessionEventData(e)){const{name:s,data:r}=e.params.event;s==="accountsChanged"&&Array.isArray(r)&&X.isCaipAddress(r[0])&&this.syncAccount(fs.parseCaipAddress(r[0]))}}))}createUniversalProvider(){return!this.universalProviderInitPromise&&X.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}
896async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Oe.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&&(qs.open(a,"error"),this.reportedAlertErrors[r]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const r=e;r.namespace=s,r.construct({namespace:s,projectId:this.options?.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?.uri&&Y.setUri(e.uri),e?.arguments)switch(e?.view){case"Swap":return We.open({...e,data:{swap:e.arguments}})}return We.open(e)}async close(){await this.injectModalUi(),We.close()}setLoading(e,s){We.setLoading(e,s)}async disconnect(e){await Y.disconnect(e)}getSIWX(){return k.state.siwx}getError(){return""}getChainId(){return m.state.activeCaipNetwork?.id}async switchNetwork(e){const s=this.getCaipNetworks().find(r=>r.id===e.id);if(!s){qs.open(Sr.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await m.switchActiveNetwork(s)}getWalletProvider(){return m.state.activeChain?Pe.state.providers[m.state.activeChain]:null}getWalletProviderType(){return Pe.getProviderId(m.state.activeChain)}subscribeProviders(e){return Pe.subscribeProviders(e)}getThemeMode(){return wt.state.themeMode}getThemeVariables(){return wt.state.themeVariables}setThemeMode(e){wt.setThemeMode(e),Nh(wt.state.themeMode)}setTermsConditionsUrl(e){k.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){k.setPrivacyPolicyUrl(e)}setThemeVariables(e){wt.setThemeVariables(e),bI(wt.state.themeVariables)}subscribeTheme(e){return wt.subscribe(e)}getWalletInfo(){return F.state.connectedWalletInfo}getAccount(e){const s=B.getAuthConnector(e),r=m.getAccountData(e),i=m.state.activeChain,n=z.getConnectedConnectorId(e||i);if(r)return{allAccounts:r.allAccounts,caipAddress:r.caipAddress,address:X.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:s&&n===W.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:z.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:r.preferredAccountTypes?.[e||i],isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const r=()=>{const i=this.getAccount(s);i&&e(i)};s?m.subscribeChainProp("accountState",r,s):m.subscribe(r),B.subscribe(r)}subscribeNetwork(e){return m.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s?.id,caipNetworkId:s?.caipNetworkId})})}subscribeWalletInfo(e){return F.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){F.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){m.subscribeKey("activeCaipNetwork",e)}getState(){return _s.state}subscribeState(e){return _s.subscribe(e)}showErrorMessage(e){jt.showError(e)}showSuccessMessage(e){jt.showSuccess(e)}getEvent(){return{...Oe.state}}subscribeEvents(e){return Oe.subscribe(e)}replace(e){ie.replace(e)}redirect(e){ie.push(e)}popTransactionStack(e){ie.popTransactionStack(e)}isOpen(){return We.state.open}isTransactionStackEmpty(){return ie.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){k.setFeatures(e)}updateRemoteFeatures(e){k.setRemoteFeatures(e)}updateOptions(e){const r={...k.state||{},...e};k.setOptions(r)}setConnectMethodsOrder(e){k.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){k.setWalletFeaturesOrder(e)}setCollapseWallets(e){k.setCollapseWallets(e)}setSocialsOrder(e){k.setSocialsOrder(e)}getConnectMethodsOrder(){return Da.getConnectOrderMethod(k.state.features,B.getConnectors())}
896addNetwork(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)||m.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)&&m.removeNetwork(e,s)}}let Pu=!1;class xh extends jI{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&&X.isClient()){if(await Zo(()=>import("./basic-CDWRbdmm.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])),await Zo(()=>import("./w3m-modal-BDzWSbpa.js"),__vite__mapDeps([9,1,2,3,5,6,7,8])),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!k.state.disableAppend&&!k.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}Pu=!0}}}const BI="1.7.8";function qI(t){return new xh({...t,basic:!0,sdkVersion:`html-core-${BI}`})}const CA=Object.freeze(Object.defineProperty({__proto__:null,AppKit:xh,createAppKit:qI},Symbol.toStringTag,{value:"Module"}));export{V as A,Z1 as B,B as C,F as D,Oe as E,yA as F,CA as G,We as M,k as O,ie as R,z as S,wt as T,Da as W,Jn as a,X as b,Kn as c,Uu as d,vA as e,Y as f,W as g,m as h,Mr as i,Lt as j,jt as k,Ee as l,wA as m,Fe as n,EA as o,bh as p,Yr as q,bA as r,Se as s,tt as t,Ma as u,et as v,It as w,mA as x,ki as y,qs 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.