1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1.js-Cwel67ap.js","assets/chunk-ZLwEzXoy.js","assets/chunk-64Y5F-uU.js","assets/chunk-Gmj5k1uE.js","assets/chunk-CdSArBFG.js","assets/basic.js-CTBEV7tZ.js","assets/chunk-BzFVculG.js","assets/w3m-modal.js-Cy8msb3B.js"])))=>i.map(i=>d[i]); 2var e;import{_ as t}from"./chunk-ZLwEzXoy.js";import{I as s,b as i,c as r,a as n,d as o,C as a,e as c,s as l,f as d,g as u,k as h,A as p,E as g,i as f,h as m,y as w,j as v,r as y,O as b,o as E,l as C,m as I,n as N,p as A,N as S,P,Q as k,q as _,t as O,u as x,v as T,w as R,x as U,z as $,B as D,D as M}from"./chunk-CdSArBFG.js";var j={};const L={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"}
vendor: 4,966 bytes, line 2
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:("undefined"!=typeof process?j.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},q={caipNetworkIdToNumber:e=>e?Number(e.split(":")[1]):void 0,parseEvmChainId(e){return"string"==typeof e?this.caipNetworkIdToNumber(e):e},getNetworksByNamespace:(e,t)=>(null==e?void 0:e.filter(e=>e.chainNamespace===t))||[],getFirstNetworkByNamespace(e,t){return this.getNetworksByNamespace(e,t)[0]},getNetworkNameByCaipNetworkId(e,t){var s;if(!t)return;const i=e.find(e=>e.caipNetworkId===t);if(i)return i.name;const[r]=t.split(":");return(null==(s=L.CHAIN_NAME_MAP)?void 0:s[r])||void 0}};var B=1e6,z=1e6,F="[big.js] ",W=F+"Invalid ",V=W+"decimal places",H=W+"rounding mode",K=F+"Division by zero",G={},J=void 0,Y=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function X(e,t,s,i){var r=e.c;if(s===J&&(s=e.constructor.RM),0!==s&&1!==s&&2!==s&&3!==s)throw Error(H);if(t<1)i=3===s&&(i||!!r[0])||0===t&&(1===s&&r[0]>=5||2===s&&(r[0]>5||5===r[0]&&(i||r[1]!==J))),r.length=1,i?(e.e=e.e-t+1,r[0]=1):r[0]=e.e=0;else if(t<r.length){if(i=1===s&&r[t]>=5||2===s&&(r[t]>5||5===r[t]&&(i||r[t+1]!==J||1&r[t-1]))||3===s&&(i||!!r[0]),r.length=t,i)for(;++r[--t]>9;)if(r[t]=0,0===t){++e.e,r.unshift(1);break}for(t=r.length;!r[--t];)r.pop()}return e}function Z(e,t,s){var i=e.e,r=e.c.join(""),n=r.length;if(t)r=r.charAt(0)+(n>1?"."+r.slice(1):"")+(i<0?"e":"e+")+i;else if(i<0){for(;++i;)r="0"+r;r="0."+r}else if(i>0)if(++i>n)for(i-=n;i--;)r+="0";else i<n&&(r=r.slice(0,i)+"."+r.slice(i));else n>1&&(r=r.charAt(0)+"."+r.slice(1));return e.s<0&&s?"-"+r:r}G.abs=function(){var e=new this.constructor(this);return e.s=1,e},G.cmp=function(e){var t,s=this,i=s.c,r=(e=new s.constructor(e)).c,n=s.s,o=e.s,a=s.e,c=e.e;if(!i[0]||!r[0])return i[0]?n:r[0]?-o:0;if(n!=o)return n;if(t=n<0,a!=c)return a>c^t?1:-1;for(o=(a=i.length)<(c=r.length)?a:c,n=-1;++n<o;)if(i[n]!=r[n])return i[n]>r[n]^t?1:-1;return a==c?0:a>c^t?1:-1},G.div=function(e){var t=this,s=t.constructor,i=t.c,r=(e=new s(e)).c,n=t.s==e.s?1:-1,o=s.DP;if(o!==~~o||o<0||o>B)throw Error(V);if(!r[0])throw Error(K);if(!i[0])return e.s=n,e.c=[e.e=0],e;var a,c,l,d,u,h=r.slice(),p=a=r.length,g=i.length,f=i.slice(0,a),m=f.length,w=e,v=w.c=[],y=0,b=o+(w.e=t.e-e.e)+1;for(w.s=n,n=b<0?0:b,h.unshift(0);m++<a;)f.push(0);do{for(l=0;l<10;l++){if(a!=(m=f.length))d=a>m?1:-1;else for(u=-1,d=0;++u<a;)if(r[u]!=f[u]){d=r[u]>f[u]?1:-1;break}if(!(d<0))break;for(c=m==a?r:h;m;){if(f[--m]<c[m]){for(u=m;u&&!f[--u];)f[u]=9;--f[u],f[m]+=10}f[m]-=c[m]}for(;!f[0];)f.shift()}v[y++]=d?l:++l,f[0]&&d?f[m]=i[p]||0:f=[i[p]]}while((p++<g||f[0]!==J)&&n--);return v[0]||1==y||(v.shift(),w.e--,b--),y>b&&X(w,b,s.RM,f[0]!==J),w},G.eq=function(e){return 0===this.cmp(e)},G.gt=function(e){return this.cmp(e)>0},G.gte=function(e){return this.cmp(e)>-1},G.lt=function(e){return this.cmp(e)<0},G.lte=function(e){return this.cmp(e)<1},G.minus=G.sub=function(e){var t,s,i,r,n=this,o=n.constructor,a=n.s,c=(e=new o(e)).s;if(a!=c)return e.s=-c,n.plus(e);var l=n.c.slice(),d=n.e,u=e.c,h=e.e;if(!l[0]||!u[0])return u[0]?e.s=-c:l[0]?e=new o(n):e.s=1,e;if(a=d-h){for((r=a<0)?(a=-a,i=l):(h=d,i=u),i.reverse(),c=a;c--;)i.push(0);i.reverse()}else for(s=((r=l.length<u.length)?l:u).length,a=c=0;c<s;c++)if(l[c]!=u[c]){r=l[c]<u[c];break}if(r&&(i=l,l=u,u=i,e.s=-e.s),(c=(s=u.length)-(t=l.length))>0)for(;c--;)l[t++]=0;for(c=t;s>a;){if(l[--s]<u[s]){for(t=s;t&&!l[--t];)l[t]=9;--l[t],l[s]+=10}l[s]-=u[s]}for(;0===l[--c];)l.pop();for(;0===l[0];)l.shift(),--h;return l[0]||(e.s=1,l=[h=0]),e.c=l,e.e=h,e},G.mod=function(e){var t,s=this,i=s.constructor,r=s.s,n=(e=new i(e)).s;if(!e.c[0])throw Error(K);return s.s=e.s=1,t=1==e.cmp(s),s.s=r,e.s=n,t?new i(s):(r=i.DP,n=i.RM,i.DP=i.RM=0,s=s.div(e),i.DP=r,i.RM=n,this.minus(s.times(e)))},G.neg=function(){var e=new this.constructor(this);return e.s=-e.s,e},G.plus=G.add=function(e){var t,s,i,r=this,n=r.constructor;if(e=new n(e),r.s!=e.s)return e.s=-e.s,r.minus(e);var o=r.e,a=r.c,c=e.e,l=e.c;if(!a[0]||!l[0])return l[0]||(a[0]?e=new n(r):e.s=r.s),e;if(a=a.slice(),t=o-c){for(t>0?(c=o,i=l):(t=-t,i=a),i.reverse();t--;)i.push(0);i.reverse()}for(a.length-l.length<0&&(i=l,l=a,a=i),t=l.length,s=0;t;a[t]%=10)s=(a[--t]=a[t]+l[t]+s)/10|0;for(s&&(a.unshift(s),++c),t=a.length;0===a[--t];)a.pop();return e.c=a,e.e=c,e},G.pow=function(e){var t=this,s=new t.constructor("1"),i=s,r=e<0;
2if(e!==~~e||e<-1e6||e>z)throw Error(W+"exponent");for(r&&(e=-e);1&e&&(i=i.times(t)),e>>=1;)t=t.times(t);return r?s.div(i):i},G.prec=function(e,t){if(e!==~~e||e<1||e>B)throw Error(W+"precision");return X(new this.constructor(this),e,t)},G.round=function(e,t){if(e===J)e=0;else if(e!==~~e||e<-B||e>B)throw Error(V);return X(new this.constructor(this),e+this.e+1,t)},G.sqrt=function(){var e,t,s,i=this,r=i.constructor,n=i.s,o=i.e,a=new r("0.5");if(!i.c[0])return new r(i);if(n<0)throw Error(F+"No square root");0===(n=Math.sqrt(+Z(i,!0,!0)))||n===1/0?((t=i.c.join("")).length+o&1||(t+="0"),o=((o+1)/2|0)-(o<0||1&o),e=new r(((n=Math.sqrt(t))==1/0?"5e":(n=n.toExponential()).slice(0,n.indexOf("e")+1))+o)):e=new r(n+""),o=e.e+(r.DP+=4);do{s=e,e=a.times(s.plus(i.div(s)))}while(s.c.slice(0,o).join("")!==e.c.slice(0,o).join(""));return X(e,(r.DP-=4)+e.e+1,r.RM)},G.times=G.mul=function(e){var t,s=this,i=s.constructor,r=s.c,n=(e=new i(e)).c,o=r.length,a=n.length,c=s.e,l=e.e;if(e.s=s.s==e.s?1:-1,!r[0]||!n[0])return e.c=[e.e=0],e;for(e.e=c+l,o<a&&(t=r,r=n,n=t,l=o,o=a,a=l),t=new Array(l=o+a);l--;)t[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=t[l]+n[c]*r[l-c-1]+a,t[l--]=a%10,a=a/10|0;t[l]=a}for(a?++e.e:t.shift(),c=t.length;!t[--c];)t.pop();return e.c=t,e},G.toExponential=function(e,t){var s=this,i=s.c[0];if(e!==J){if(e!==~~e||e<0||e>B)throw Error(V);for(s=X(new s.constructor(s),++e,t);s.c.length<e;)s.c.push(0)}return Z(s,!0,!!i)},G.toFixed=function(e,t){var s=this,i=s.c[0];if(e!==J){if(e!==~~e||e<0||e>B)throw Error(V);for(e=e+(s=X(new s.constructor(s),e+s.e+1,t)).e+1;s.c.length<e;)s.c.push(0)}return Z(s,!1,!!i)},G[Symbol.for("nodejs.util.inspect.custom")]=G.toJSON=G.toString=function(){var e=this,t=e.constructor;return Z(e,e.e<=t.NE||e.e>=t.PE,!!e.c[0])},G.toNumber=function(){var e=+Z(this,!0,!0);if(!0===this.constructor.strict&&!this.eq(e.toString()))throw Error(F+"Imprecise conversion");return e},G.toPrecision=function(e,t){var s=this,i=s.constructor,r=s.c[0];if(e!==J){if(e!==~~e||e<1||e>B)throw Error(W+"precision");for(s=X(new i(s),e,t);s.c.length<e;)s.c.push(0)}return Z(s,e<=s.e||s.e<=i.NE||s.e>=i.PE,!!r)},G.valueOf=function(){var e=this,t=e.constructor;if(!0===t.strict)throw Error(F+"valueOf disallowed");return Z(e,e.e<=t.NE||e.e>=t.PE,!0)};var Q=function e(){function t(s){var i=this;if(!(i instanceof t))return s===J?e():new t(s);if(s instanceof t)i.s=s.s,i.e=s.e,i.c=s.c.slice();else{if("string"!=typeof s){if(!0===t.strict&&"bigint"!=typeof s)throw TypeError(W+"value");s=0===s&&1/s<0?"-0":String(s)}!function(e,t){var s,i,r;if(!Y.test(t))throw Error(W+"number");e.s="-"==t.charAt(0)?(t=t.slice(1),-1):1,(s=t.indexOf("."))>-1&&(t=t.replace(".",""));(i=t.search(/e/i))>0?(s<0&&(s=i),s+=+t.slice(i+1),t=t.substring(0,i)):s<0&&(s=t.length);for(r=t.length,i=0;i<r&&"0"==t.charAt(i);)++i;if(i==r)e.c=[e.e=0];else{for(;r>0&&"0"==t.charAt(--r););for(e.e=s-i-1,e.c=[],s=0;i<=r;)e.c[s++]=+t.charAt(i++)}}(i,s)}i.constructor=t}return t.prototype=G,t.DP=20,t.RM=1,t.NE=-7,t.PE=21,t.strict=false,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}();const ee={bigNumber:e=>new Q(e||0),multiply(e,t){if(void 0===e||void 0===t)return new Q(0);const s=new Q(e),i=new Q(t);return s.times(i)},formatNumberToLocalString:(e,t=2)=>void 0===e?"0.00":"number"==typeof e?e.toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t}):parseFloat(e).toLocaleString("en-US",{maximumFractionDigits:t,minimumFractionDigits:t}),parseLocalStringToNumber:e=>void 0===e?0:parseFloat(e.replace(/,/gu,""))},te=[{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"}]}],se=[{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"}]}],ie=e=>L.USDT_CONTRACT_ADDRESSES.includes(e)?se:te,re={validateCaipAddress(e){var t;if(3!==(null==(t=e.split(":"))?void 0:t.length))throw new Error("Invalid CAIP Address");return e},parseCaipAddress(e){const t=e.split(":");if(3!==t.length)throw new Error(`Invalid CAIP-10 address: ${e}`);const[s,i,r]=t;if(!s||!i||!r)throw new Error(`Invalid CAIP-10 address: ${e}`);return{chainNamespace:s,chainId:i,address:r}},parseCaipNetworkId(e){const t=e.split(":");if(2!==t.length)throw new Error(`Invalid CAIP-2 network id: ${e}`);const[s,i]=t;if(!s||!i)throw new Error(`Invalid CAIP-2 network id: ${e}`);return{chainNamespace:s,chainId:i}}},ne="@appkit/active_caip_network_id",oe="@appkit/connected_social",ae="@appkit-wallet/SOCIAL_USERNAME",ce="@appkit/recent_wallets",le="WALLETCONNECT_DEEPLINK_CHOICE",de
2="@appkit/active_namespace",ue="@appkit/connected_namespaces",he="@appkit/connection_status",pe="@appkit/social_provider",ge="@appkit/native_balance_cache",fe="@appkit/portfolio_cache",me="@appkit/ens_cache",we="@appkit/identity_cache",ve="@appkit/preferred_account_types",ye="@appkit/connections";function be(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const Ee={setItem(e,t){Ce()&&void 0!==t&&localStorage.setItem(e,t)},getItem(e){if(Ce())return localStorage.getItem(e)||void 0},removeItem(e){Ce()&&localStorage.removeItem(e)},clear(){Ce()&&localStorage.clear()}};function Ce(){return"undefined"!=typeof window&&"undefined"!=typeof localStorage}function Ie(e,t){return"light"===t?{"--w3m-accent":(null==e?void 0:e["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(null==e?void 0:e["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const Ne=Symbol(),Ae=Object.getPrototypeOf,Se=new WeakMap,Pe=e=>(e=>e&&(Se.has(e)?Se.get(e):Ae(e)===Object.prototype||Ae(e)===Array.prototype))(e)&&e[Ne]||null,ke=(e,t=!0)=>{Se.set(e,t)},_e={},Oe=e=>"object"==typeof e&&null!==e,xe=new WeakMap,Te=new WeakSet,[Re]=((e=Object.is,t=(e,t)=>new Proxy(e,t),s=e=>Oe(e)&&!Te.has(e)&&(Array.isArray(e)||!(Symbol.iterator in e))&&!(e instanceof WeakMap)&&!(e instanceof WeakSet)&&!(e instanceof Error)&&!(e instanceof Number)&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof RegExp)&&!(e instanceof ArrayBuffer),i=e=>{switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:throw e}},r=new WeakMap,n=(e,t,s=i)=>{const o=r.get(e);if((null==o?void 0:o[0])===t)return o[1];const a=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return ke(a,!0),r.set(e,[t,a]),Reflect.ownKeys(e).forEach(t=>{if(Object.getOwnPropertyDescriptor(a,t))return;const i=Reflect.get(e,t),{enumerable:r}=Reflect.getOwnPropertyDescriptor(e,t),o={value:i,enumerable:r,configurable:!0};if(Te.has(i))ke(i,!1);else if(i instanceof Promise)delete o.value,o.get=()=>s(i);else if(xe.has(i)){const[e,t]=xe.get(i);o.value=n(e,t(),s)}Object.defineProperty(a,t,o)}),Object.preventExtensions(a)},o=new WeakMap,a=[1,1],c=i=>{if(!Oe(i))throw new Error("object required");const r=o.get(i);if(r)return r;let l=a[0];const d=new Set,u=(e,t=++a[0])=>{l!==t&&(l=t,d.forEach(s=>s(e,t)))};let h=a[1];const p=e=>(t,s)=>{const i=[...t];i[1]=[e,...i[1]],u(i,s)},g=new Map,f=e=>{var t;const s=g.get(e);s&&(g.delete(e),null==(t=s[1])||t.call(s))},m=Array.isArray(i)?[]:Object.create(Object.getPrototypeOf(i)),w=t(m,{deleteProperty(e,t){const s=Reflect.get(e,t);f(t);const i=Reflect.deleteProperty(e,t);return i&&u(["delete",[t],s]),i},set(t,i,r,n){const a=Reflect.has(t,i),l=Reflect.get(t,i,n);if(a&&(e(l,r)||o.has(r)&&e(l,o.get(r))))return!0;f(i),Oe(r)&&(r=Pe(r)||r);let h=r;if(r instanceof Promise)r.then(e=>{r.status="fulfilled",r.value=e,u(["resolve",[i],e])}).catch(e=>{r.status="rejected",r.reason=e,u(["reject",[i],e])});else{!xe.has(r)&&s(r)&&(h=c(r));const e=!Te.has(h)&&xe.get(h);e&&((e,t)=>{if("production"!==(_e?"production":void 0)&&g.has(e))throw new Error("prop listener already exists");if(d.size){const s=t[3](p(e));g.set(e,[t,s])}else g.set(e,[t])})(i,e)}return Reflect.set(t,i,h,n),u(["set",[i],r,l]),!0}});o.set(i,w);const v=[m,(e=++a[1])=>(h===e||d.size||(h=e,g.forEach(([t])=>{const s=t[1](e);s>l&&(l=s)})),l),n,e=>{d.add(e),1===d.size&&g.forEach(([e,t],s)=>{if("production"!==(_e?"production":void 0)&&t)throw new Error("remove already exists");const i=e[3](p(s));g.set(s,[e,i])});return()=>{d.delete(e),0===d.size&&g.forEach(([e,t],s)=>{t&&(t(),g.set(s,[e]))})}}];
2return xe.set(w,v),Reflect.ownKeys(i).forEach(e=>{const t=Object.getOwnPropertyDescriptor(i,e);"value"in t&&(w[e]=i[e],delete t.value,delete t.writable),Object.defineProperty(m,e,t)}),w})=>[c,xe,Te,e,t,s,i,r,n,o,a])();function Ue(e={}){return Re(e)}function $e(e,t,s){const i=xe.get(e);let r;const n=[],o=i[3];let a=!1;const c=o(e=>{n.push(e),r||(r=Promise.resolve().then(()=>{r=void 0,a&&t(n.splice(0))}))});return a=!0,()=>{a=!1,c()}}function De(e,t){const s=xe.get(e),[i,r,n]=s;return n(i,r(),t)}function Me(e){return Te.add(e),e}function je(e,t,s,i){let r=e[t];return $e(e,()=>{const i=e[t];Object.is(r,i)||s(r=i)})}const Le=[{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"]}],qe={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"}},Be={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired:(e,t)=>Date.now()-e>t,getActiveNetworkProps(){const e=Be.getActiveNamespace(),t=Be.getActiveCaipNetworkId(),s=t?t.split(":")[1]:void 0;return{namespace:e,caipNetworkId:t,chainId:s?isNaN(Number(s))?s:Number(s):void 0}},setWalletConnectDeepLink({name:e,href:t}){try{Ee.setItem(le,JSON.stringify({href:t,name:e}))}catch{}},getWalletConnectDeepLink(){try{const e=Ee.getItem(le);if(e)return JSON.parse(e)}catch{}},deleteWalletConnectDeepLink(){try{Ee.removeItem(le)}catch{}},setActiveNamespace(e){try{Ee.setItem(de,e)}catch{}},setActiveCaipNetworkId(e){try{Ee.setItem(ne,e),Be.setActiveNamespace(e.split(":")[0])}catch{}},getActiveCaipNetworkId(){try{return Ee.getItem(ne)}catch{return}},deleteActiveCaipNetworkId(){try{Ee.removeItem(ne)}catch{}},deleteConnectedConnectorId(e){try{const t=be(e);Ee.removeItem(t)}catch{}},setAppKitRecent(e){try{const t=Be.getRecentWallets();t.find(t=>t.id===e.id)||(t.unshift(e),t.length>2&&t.pop(),Ee.setItem(ce,JSON.stringify(t)))}catch{}},getRecentWallets(){try{const e=Ee.getItem(ce);return e?JSON.parse(e):[]}catch{}return[]},setConnectedConnectorId(e,t){try{const s=be(e);Ee.setItem(s,t)}catch{}},getActiveNamespace(){try{return Ee.getItem(de)}catch{}},getConnectedConnectorId(e){if(e)try{const t=be(e);return Ee.getItem(t)}catch(wn){}},setConnectedSocialProvider(e){try{Ee.setItem(oe,e)}catch{}},getConnectedSocialProvider(){try{return Ee.getItem(oe)}catch{}},deleteConnectedSocialProvider(){try{Ee.removeItem(oe)}catch{}},getConnectedSocialUsername(){try{return Ee.getItem(ae)}catch{}},getStoredActiveCaipNetworkId(){var e;const t=Ee.getItem(ne);return null==(e=null==t?void 0:t.split(":"))?void 0:e[1]},setConnectionStatus(e){try{Ee.setItem(he,e)}catch{}},getConnectionStatus(){try{return Ee.getItem(he)}catch{return}},getConnectedNamespaces(){try{const e=Ee.getItem(ue);return(null==e?void 0:e.length)?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));Ee.setItem(ue,t.join(","))}catch{}},addConnectedNamespace(e){try{const t=Be.getConnectedNamespaces();t.includes(e)||(t.push(e),Be.setConnectedNamespaces(t))}catch{}},removeConnectedNamespace(e){try{const t=Be.getConnectedNamespaces(),s=t.indexOf(e);s>-1&&(t.splice(s,1),Be.setConnectedNamespaces(t))}catch{}},getTelegramSocialProvider(){try{return Ee.getItem(pe)}catch{return null}},setTelegramSocialProvider(e){try{Ee.setItem(pe,e)}catch{}},removeTelegramSocialProvider(){try{Ee.removeItem(pe)}catch{}},getBalanceCache(){let e={};try{const t=Ee.getItem(fe);e=t?JSON.parse(t):{}}catch{}return e},removeAddressFromBalanceCache(e){try{const t=Be.getBalanceCache();Ee.setItem(fe,JSON.stringify({...t,[e]:void 0}))}catch{}},getBalanceCacheForCaipAddress(e){try{const t=Be.getBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;Be.removeAddressFromBalanceCache(e)}catch{}},updateBalanceCache(e){try{const t=Be.getBalanceCache();t[e.caipAddress]=e,Ee.setItem(fe,JSON.stringify(t))}catch{}},getNativeBalanceCache(){let e={};try{const t=Ee.getItem(ge);e=t?JSON.parse(t):{}}catch{}return e},removeAddressFromNativeBalanceCache(e){try{const t=Be.getBalanceCache();Ee.setItem(ge,JSON.stringify({...t,[e]:void 0}))}catch{}},getNativeBalanceCacheForCaipAddress(e){try{const t=Be.getNativeBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;Be.removeAddressFromBalanceCache(e)}catch{}},updateNativeBalanceCache(e){try{const t=Be.getNativeBalanceCache();t[e.caipAddress]=e,Ee.setItem(ge,JSON.stringify(t))}catch{}},getEnsCache(){let e={};try{const t=Ee.getItem(me);e=t?JSON.parse(t):{}}catch{}return e}
2,getEnsFromCacheForAddress(e){try{const t=Be.getEnsCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;Be.removeEnsFromCache(e)}catch{}},updateEnsCache(e){try{const t=Be.getEnsCache();t[e.address]=e,Ee.setItem(me,JSON.stringify(t))}catch{}},removeEnsFromCache(e){try{const t=Be.getEnsCache();Ee.setItem(me,JSON.stringify({...t,[e]:void 0}))}catch{}},getIdentityCache(){let e={};try{const t=Ee.getItem(we);e=t?JSON.parse(t):{}}catch{}return e},getIdentityFromCacheForAddress(e){try{const t=Be.getIdentityCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;Be.removeIdentityFromCache(e)}catch{}},updateIdentityCache(e){try{const t=Be.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},Ee.setItem(we,JSON.stringify(t))}catch{}},removeIdentityFromCache(e){try{const t=Be.getIdentityCache();Ee.setItem(we,JSON.stringify({...t,[e]:void 0}))}catch{}},clearAddressCache(){try{Ee.removeItem(fe),Ee.removeItem(ge),Ee.removeItem(me),Ee.removeItem(we)}catch{}},setPreferredAccountTypes(e){try{Ee.setItem(ve,JSON.stringify(e))}catch{}},getPreferredAccountTypes(){try{const e=Ee.getItem(ve);return e?JSON.parse(e):{}}catch{}return{}},setConnections(e,t){try{const s={...Be.getConnections(),[t]:e};Ee.setItem(ye,JSON.stringify(s))}catch(s){}},getConnections(){try{const e=Ee.getItem(ye);return e?JSON.parse(e):{}}catch(e){return{}}}},ze={isMobile(){var e;return!!this.isClient()&&Boolean("function"==typeof(null==window?void 0:window.matchMedia)&&(null==(e=null==window?void 0:window.matchMedia("(pointer:coarse)"))?void 0:e.matches)||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent))},checkCaipNetwork:(e,t="")=>null==e?void 0:e.caipNetworkId.toLocaleLowerCase().includes(t.toLowerCase()),isAndroid(){if(!this.isMobile())return!1;const e=null==window?void 0:window.navigator.userAgent.toLowerCase();return ze.isMobile()&&e.includes("android")},isIos(){if(!this.isMobile())return!1;const e=null==window?void 0:window.navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")},isSafari(){if(!this.isClient())return!1;return(null==window?void 0:window.navigator.userAgent.toLowerCase()).includes("safari")},isClient:()=>"undefined"!=typeof window,isPairingExpired:e=>!e||e-Date.now()<=qe.TEN_SEC_MS,isAllowedRetry:(e,t=qe.ONE_SEC_MS)=>Date.now()-e>=t,copyToClopboard(e){navigator.clipboard.writeText(e)},isIframe(){try{return(null==window?void 0:window.self)!==(null==window?void 0:window.top)}catch(wn){return!1}},isSafeApp(){var e,t;if(ze.isClient()&&window.self!==window.top)try{const s=null==(t=null==(e=null==window?void 0:window.location)?void 0:e.ancestorOrigins)?void 0:t[0],i="https://app.safe.global";if(s){const e=new URL(s),t=new URL(i);return e.hostname===t.hostname}}catch{return!1}return!1},getPairingExpiry:()=>Date.now()+qe.FOUR_MINUTES_MS,getNetworkId:e=>null==e?void 0:e.split(":")[1],getPlainAddress:e=>null==e?void 0:e.split(":")[2],wait:async e=>new Promise(t=>{setTimeout(t,e)}),debounce(e,t=500){let s;return(...i)=>{s&&clearTimeout(s),s=setTimeout(function(){e(...i)},t)}},isHttpUrl:e=>e.startsWith("http://")||e.startsWith("https://"),formatNativeUrl(e,t,s=null){if(ze.isHttpUrl(e))return this.formatUniversalUrl(e,t);let i=e,r=s;i.includes("://")||(i=e.replaceAll("/","").replaceAll(":",""),i=`${i}://`),i.endsWith("/")||(i=`${i}/`),r&&!(null==r?void 0:r.endsWith("/"))&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(t=encodeURIComponent(t));const n=encodeURIComponent(t);return{redirect:`${i}wc?uri=${n}`,redirectUniversalLink:r?`${r}wc?uri=${n}`:void 0,href:i}},formatUniversalUrl(e,t){if(!ze.isHttpUrl(e))return this.formatNativeUrl(e,t);let s=e;s.endsWith("/")||(s=`${s}/`);return{redirect:`${s}wc?uri=${encodeURIComponent(t)}`,href:s}},getOpenTargetForPlatform(e){return"popupWindow"===e?e:this.isTelegram()?Be.getTelegramSocialProvider()?"_top":"_blank":e},openHref(e,t,s){null==window||window.open(e,this.getOpenTargetForPlatform(t),s||"noreferrer noopener")},returnOpenHref(e,t,s){return null==window?void 0:window.open(e,this.getOpenTargetForPlatform(t),s||"noreferrer noopener")},isTelegram:()=>"undefined"!=typeof window&&(Boolean(window.TelegramWebviewProxy)||Boolean(window.Telegram)||Boolean(window.TelegramWebviewProxyProto)),isPWA(){var e,t,s;if("undefined"==typeof window)return!1;const i=null==(t=null==(e=window.matchMedia)?void 0:e.call(window,"(display-mode: standalone)"))?void 0:t.matches,r
2=null==(s=null==window?void 0:window.navigator)?void 0:s.standalone;return Boolean(i||r)},async preloadImage(e){const t=new Promise((t,s)=>{const i=new Image;i.onload=t,i.onerror=s,i.crossOrigin="anonymous",i.src=e});return Promise.race([t,ze.wait(2e3)])},formatBalance(e,t){let s="0.000";if("string"==typeof e){const t=Number(e);if(t){const e=Math.floor(1e3*t)/1e3;e&&(s=e.toString())}}return`${s}${t?` ${t}`:""}`},formatBalance2(e,t){var s;let i;if("0"===e)i="0";else if("string"==typeof e){const t=Number(e);t&&(i=null==(s=t.toString().match(/^-?\d+(?:\.\d{0,3})?/u))?void 0:s[0])}return{value:i??"0",rest:"0"===i?"000":"",symbol:t}},getApiUrl:()=>L.W3M_API_URL,getBlockchainApiUrl:()=>L.BLOCKCHAIN_API_RPC_URL,getAnalyticsUrl:()=>L.PULSE_API_URL,getUUID:()=>(null==crypto?void 0:crypto.randomUUID)?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),parseError(e){var t,s;return"string"==typeof e?e:"string"==typeof(null==(s=null==(t=null==e?void 0:e.issues)?void 0:t[0])?void 0:s.message)?e.issues[0].message:e instanceof Error?e.message:"Unknown error"},sortRequestedNetworks(e,t=[]){const s={};return t&&e&&(e.forEach((e,t)=>{s[e]=t}),t.sort((e,t)=>{const i=s[e.id],r=s[t.id];return void 0!==i&&void 0!==r?i-r:void 0!==i?-1:void 0!==r?1:0})),t},calculateBalance(e){let t=0;for(const s of e)t+=s.value??0;return t},formatTokenBalance(e){const t=e.toFixed(2),[s,i]=t.split(".");return{dollars:s,pennies:i}},isAddress(e,t="eip155"){switch(t){case"eip155":return!!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!(!/^(?:0x)?[0-9a-f]{40}$/iu.test(e)&&!/^(?:0x)?[0-9A-F]{40}$/iu.test(e));case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(e);default:return!1}},uniqueBy(e,t){const s=new Set;return e.filter(e=>{const i=e[t];return!s.has(i)&&(s.add(i),!0)})},generateSdkVersion:(e,t,s)=>`${t}-${0===e.length?qe.ADAPTER_TYPES.UNIVERSAL:e.map(e=>e.adapterType).join(",")}-${s}`,createAccount:(e,t,s,i,r)=>({namespace:e,address:t,type:s,publicKey:i,path:r}),isCaipAddress(e){if("string"!=typeof e)return!1;const t=e.split(":"),s=t[0];return 3===t.filter(Boolean).length&&s in L.CHAIN_NAME_MAP},isMac(){const e=null==window?void 0:window.navigator.userAgent.toLowerCase();return e.includes("macintosh")&&!e.includes("safari")},formatTelegramSocialLoginUrl(e){const t=`--${encodeURIComponent(null==window?void 0:window.location.href)}`,s="state=";if("auth.magic.link"===new URL(e).host){const i="provider_authorization_url=",r=e.substring(e.indexOf(i)+i.length),n=this.injectIntoUrl(decodeURIComponent(r),s,t);return e.replace(r,encodeURIComponent(n))}return this.injectIntoUrl(e,s,t)},injectIntoUrl(e,t,s){const i=e.indexOf(t);if(-1===i)throw new Error(`${t} parameter not found in the URL: ${e}`);const r=e.indexOf("&",i),n=t.length,o=-1!==r?r:e.length;return e.substring(0,i+n)+(e.substring(i+n,o)+s)+e.substring(r)}};async function Fe(...e){const t=await fetch(...e);if(!t.ok){throw new Error(`HTTP status code: ${t.status}`,{cause:t})}return t}class We{constructor({baseUrl:e,clientId:t}){this.baseUrl=e,this.clientId=t}async get({headers:e,signal:t,cache:s,...i}){const r=this.createUrl(i);return(await Fe(r,{method:"GET",headers:e,signal:t,cache:s})).json()}async getBlob({headers:e,signal:t,...s}){const i=this.createUrl(s);return(await Fe(i,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:s,...i}){const r=this.createUrl(i);return(await Fe(r,{method:"POST",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}async put({body:e,headers:t,signal:s,...i}){const r=this.createUrl(i);return(await Fe(r,{method:"PUT",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}async delete({body:e,headers:t,signal:s,...i}){const r=this.createUrl(i);return(await Fe(r,{method:"DELETE",headers:t,body:e?JSON.stringify(e):void 0,signal:s})).json()}createUrl({path:e,params:t}){const s=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([e,t])=>{t&&s.searchParams.append(e,t)}),this.clientId&&s.searchParams.append("clientId",this.clientId),s}}const Ve={getFeatureValue(e,t){const s=null==t?void 0:t[e];return void 0===s?qe.DEFAULT_FEATURES[e]:s}
2,filterSocialsByPlatform(e){if(!e||!e.length)return e;if(ze.isTelegram()){if(ze.isIos())return e.filter(e=>"google"!==e);if(ze.isMac())return e.filter(e=>"x"!==e);if(ze.isAndroid())return e.filter(e=>!["facebook","x"].includes(e))}return e}},He=Ue({features:qe.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:qe.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),Ke={state:He,subscribeKey:(e,t)=>je(He,e,t),setOptions(e){Object.assign(He,e)},setRemoteFeatures(e){var t;if(!e)return;const s={...He.remoteFeatures,...e};He.remoteFeatures=s,(null==(t=He.remoteFeatures)?void 0:t.socials)&&(He.remoteFeatures.socials=Ve.filterSocialsByPlatform(He.remoteFeatures.socials))},setFeatures(e){if(!e)return;He.features||(He.features=qe.DEFAULT_FEATURES);const t={...He.features,...e};He.features=t},setProjectId(e){He.projectId=e},setCustomRpcUrls(e){He.customRpcUrls=e},setAllWallets(e){He.allWallets=e},setIncludeWalletIds(e){He.includeWalletIds=e},setExcludeWalletIds(e){He.excludeWalletIds=e},setFeaturedWalletIds(e){He.featuredWalletIds=e},setTokens(e){He.tokens=e},setTermsConditionsUrl(e){He.termsConditionsUrl=e},setPrivacyPolicyUrl(e){He.privacyPolicyUrl=e},setCustomWallets(e){He.customWallets=e},setIsSiweEnabled(e){He.isSiweEnabled=e},setIsUniversalProvider(e){He.isUniversalProvider=e},setSdkVersion(e){He.sdkVersion=e},setMetadata(e){He.metadata=e},setDisableAppend(e){He.disableAppend=e},setEIP6963Enabled(e){He.enableEIP6963=e},setDebug(e){He.debug=e},setEnableWalletConnect(e){He.enableWalletConnect=e},setEnableWalletGuide(e){He.enableWalletGuide=e},setEnableAuthLogger(e){He.enableAuthLogger=e},setEnableWallets(e){He.enableWallets=e},setPreferUniversalLinks(e){He.experimental_preferUniversalLinks=e},setHasMultipleAddresses(e){He.hasMultipleAddresses=e},setSIWX(e){He.siwx=e},setConnectMethodsOrder(e){He.features={...He.features,connectMethodsOrder:e}},setWalletFeaturesOrder(e){He.features={...He.features,walletFeaturesOrder:e}},setSocialsOrder(e){He.remoteFeatures={...He.remoteFeatures,socials:e}},setCollapseWallets(e){He.features={...He.features,collapseWallets:e}},setEnableEmbedded(e){He.enableEmbedded=e},setAllowUnsupportedChain(e){He.allowUnsupportedChain=e},setManualWCControl(e){He.manualWCControl=e},setEnableNetworkSwitch(e){He.enableNetworkSwitch=e},setDefaultAccountTypes(e={}){Object.entries(e).forEach(([e,t])=>{t&&(He.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(e){He.universalProviderConfigOverride=e},getUniversalProviderConfigOverride:()=>He.universalProviderConfigOverride,getSnapshot:()=>De(He)},Ge=Object.freeze({enabled:!0,events:[]}),Je=new We({baseUrl:ze.getAnalyticsUrl(),clientId:null}),Ye=Ue({...Ge}),Xe={state:Ye,subscribeKey:(e,t)=>je(Ye,e,t),async sendError(e,t){if(!Ye.enabled)return;const s=Date.now();if(Ye.events.filter(e=>{const t=new Date(e.properties.timestamp||"").getTime();return s-t<6e4}).length>=5)return;const i={type:"error",event:t,properties:{errorType:e.name,errorMessage:e.message,stackTrace:e.stack,timestamp:(new Date).toISOString()}};Ye.events.push(i);try{if("undefined"==typeof window)return;const{projectId:s,sdkType:i,sdkVersion:r}=Ke.state;await Je.post({path:"/e",params:{projectId:s,st:i,sv:r||"html-wagmi-4.2.2"},body:{eventId:ze.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:(new Date).toISOString(),props:{type:"error",event:t,errorType:e.name,errorMessage:e.message,stackTrace:e.stack}}})}catch{}},enable(){Ye.enabled=!0},disable(){Ye.enabled=!1},clearEvents(){Ye.events=[]}};class Ze extends Error{constructor(e,t,s){super(e),this.name="AppKitError",this.category=t,this.originalError=s,Object.setPrototypeOf(this,Ze.prototype);let i=!1;if(s instanceof Error&&"string"==typeof s.stack&&s.stack){const e=s.stack,t=e.indexOf("\n");if(t>-1){const s=e.substring(t+1);this.stack=`${this.name}: ${this.message}\n${s}`,i=!0}}i||(Error.captureStackTrace?Error.captureStackTrace(this,Ze):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Qe(e,t){const s=e instanceof Ze?e:new Ze(e instanceof Error?e.message:String(e),t,e);throw Xe.sendError(s,s.category),s}
2function et(e,t="INTERNAL_SDK_ERROR"){const s={};return Object.keys(e).forEach(i=>{const r=e[i];if("function"==typeof r){let e=r;e="AsyncFunction"===r.constructor.name?async(...e)=>{try{return await r(...e)}catch(s){return Qe(s,t)}}:(...e)=>{try{return r(...e)}catch(s){return Qe(s,t)}},s[i]=e}else s[i]=r}),s}const tt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},st={handleMobileDeeplinkRedirect(e,t){const s=window.location.href,i=encodeURIComponent(s);if(e===tt.PHANTOM.id&&!("phantom"in window)){const e=s.startsWith("https")?"https":"http",t=s.split("/")[2],r=encodeURIComponent(`${e}://${t}`);window.location.href=`${tt.PHANTOM.url}/ul/browse/${i}?ref=${r}`}e!==tt.SOLFLARE.id||"solflare"in window||(window.location.href=`${tt.SOLFLARE.url}/ul/v1/browse/${i}?ref=${i}`),t===L.CHAIN.SOLANA&&(e!==tt.COINBASE.id||"coinbaseSolana"in window||(window.location.href=`${tt.COINBASE.url}/dapp?cb_url=${i}`))}},it=Ue({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),rt=et({state:it,subscribeNetworkImages:e=>$e(it.networkImages,()=>e(it.networkImages)),subscribeKey:(e,t)=>je(it,e,t),subscribe:e=>$e(it,()=>e(it)),setWalletImage(e,t){it.walletImages[e]=t},setNetworkImage(e,t){it.networkImages[e]=t},setChainImage(e,t){it.chainImages[e]=t},setConnectorImage(e,t){it.connectorImages={...it.connectorImages,[e]:t}},setTokenImage(e,t){it.tokenImages[e]=t},setCurrencyImage(e,t){it.currencyImages[e]=t}}),nt={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},ot=Ue({networkImagePromises:{}}),at={async fetchWalletImage(e){if(e)return await vt._fetchWalletImage(e),this.getWalletImageById(e)},async fetchNetworkImage(e){if(!e)return;const t=this.getNetworkImageById(e);return t||(ot.networkImagePromises[e]||(ot.networkImagePromises[e]=vt._fetchNetworkImage(e)),await ot.networkImagePromises[e],this.getNetworkImageById(e))},getWalletImageById(e){if(e)return rt.state.walletImages[e]},getWalletImage:e=>(null==e?void 0:e.image_url)?null==e?void 0:e.image_url:(null==e?void 0:e.image_id)?rt.state.walletImages[e.image_id]:void 0,getNetworkImage(e){var t,s,i;return(null==(t=null==e?void 0:e.assets)?void 0:t.imageUrl)?null==(s=null==e?void 0:e.assets)?void 0:s.imageUrl:(null==(i=null==e?void 0:e.assets)?void 0:i.imageId)?rt.state.networkImages[e.assets.imageId]:void 0},getNetworkImageById(e){if(e)return rt.state.networkImages[e]},getConnectorImage:e=>(null==e?void 0:e.imageUrl)?e.imageUrl:(null==e?void 0:e.imageId)?rt.state.connectorImages[e.imageId]:void 0,getChainImage:e=>rt.state.networkImages[nt[e]]},ct=Ue({message:"",variant:"info",open:!1}),lt=et({state:ct,subscribeKey:(e,t)=>je(ct,e,t),open(e,t){const{debug:s}=Ke.state,{shortMessage:i,longMessage:r}=e;s&&(ct.message=i,ct.variant=t,ct.open=!0)},close(){ct.open=!1,ct.message="",ct.variant="info"}}),dt=ze.getAnalyticsUrl(),ut=new We({baseUrl:dt,clientId:null}),ht=["MODAL_CREATED"],pt=Ue({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),gt={state:pt,subscribe:e=>$e(pt,()=>e(pt)),getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=Ke.state;return{projectId:e,st:t,sv:s||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(e){try{const t=Zt.state.address;if(ht.includes(e.data.event)||"undefined"==typeof window)return;await ut.post({path:"/e",params:gt.getSdkProperties(),body:{eventId:ze.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:e.timestamp,props:{...e.data,address:t}}}),pt.reportedErrors.FORBIDDEN=!1}catch(t){t instanceof Error&&t.cause instanceof Response&&t.cause.status===L.HTTP_STATUS_CODES.FORBIDDEN&&!pt.reportedErrors.FORBIDDEN&&(lt.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${Ce()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),pt.reportedErrors.FORBIDDEN=!0)}},sendEvent(e){var t;pt.timestamp=Date.now(),pt.data=e,(null==(t=Ke.state.features)?void 0:t.analytics)&>._sendAnalyticsEvent(pt)}},ft=ze.getApiUrl(),mt=new We({baseUrl:ft,clientId:null}),wt=Ue({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),vt={state:wt,subscribeKey:(e,t)=>je(wt,e,t),_getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=Ke.state;return{projectId:e,st:t||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions:e=>Ke.state.isUniversalProvider?e.filter(e=>Boolean(e.mobile_link||e.desktop_link||e.webapp_link)):e,async _fetchWalletImage(e){const t=`${mt.baseUrl}/getWalletImage/${e}`,s=await mt.getBlob({path:t,params:vt._getSdkProperties()});rt.setWalletImage(e,URL.createObjectURL(s))},async _fetchNetworkImage(e){const t=`${mt.baseUrl}/public/getAssetImage/${e}`,s=await mt.getBlob({path:t,params:vt._getSdkProperties()});rt.setNetworkImage(e,URL.createObjectURL(s))},async _fetchConnectorImage(e){const t=`${mt.baseUrl}/public/getAssetImage/${e}`,s=await mt.getBlob({path:t,params:vt._getSdkProperties()});rt.setConnectorImage(e,URL.createObjectURL(s))},async _fetchCurrencyImage(e){const t=`${mt.baseUrl}/public/getCurrencyImage/${e}`,s=await mt.getBlob({path:t,params:vt._getSdkProperties()});rt.setCurrencyImage(e,URL.createObjectURL(s))},async _fetchTokenImage(e){const t=`${mt.baseUrl}/public/getTokenImage/${e}`,s=await mt.getBlob({path:t,params:vt._getSdkProperties()});rt.setTokenImage(e,URL.createObjectURL(s))},_filterWalletsByPlatform:e=>ze.isMobile()?null==e?void 0:e.filter(e=>{if(e.mobile_link)return!0;
2if(e.id===tt.COINBASE.id)return!0;return"solana"===Ht.state.activeChain&&(e.id===tt.SOLFLARE.id||e.id===tt.PHANTOM.id)}):e,fetchProjectConfig:async()=>(await mt.get({path:"/appkit/v1/config",params:vt._getSdkProperties()})).features,async fetchAllowedOrigins(){try{const{allowedOrigins:e}=await mt.get({path:"/projects/v1/origins",params:vt._getSdkProperties()});return e}catch(e){return[]}},async fetchNetworkImages(){const e=Ht.getAllRequestedCaipNetworks(),t=null==e?void 0:e.map(({assets:e})=>null==e?void 0:e.imageId).filter(Boolean).filter(e=>!at.getNetworkImageById(e));t&&await Promise.allSettled(t.map(e=>vt._fetchNetworkImage(e)))},async fetchConnectorImages(){const{connectors:e}=St.state,t=e.map(({imageId:e})=>e).filter(Boolean);await Promise.allSettled(t.map(e=>vt._fetchConnectorImage(e)))},async fetchCurrencyImages(e=[]){await Promise.allSettled(e.map(e=>vt._fetchCurrencyImage(e)))},async fetchTokenImages(e=[]){await Promise.allSettled(e.map(e=>vt._fetchTokenImage(e)))},async fetchWallets(e){var t;const s=e.exclude??[];vt._getSdkProperties().sv.startsWith("html-core-")&&s.push(...Object.values(tt).map(e=>e.id));const i=await mt.get({path:"/getWallets",params:{...vt._getSdkProperties(),...e,page:String(e.page),entries:String(e.entries),include:null==(t=e.include)?void 0:t.join(","),exclude:s.join(",")}});return{data:vt._filterWalletsByPlatform(null==i?void 0:i.data)||[],count:null==i?void 0:i.count}},async fetchFeaturedWallets(){const{featuredWalletIds:e}=Ke.state;if(null==e?void 0:e.length){const t={...vt._getSdkProperties(),page:1,entries:(null==e?void 0:e.length)??4,include:e},{data:s}=await vt.fetchWallets(t),i=[...s].sort((t,s)=>e.indexOf(t.id)-e.indexOf(s.id)),r=i.map(e=>e.image_id).filter(Boolean);await Promise.allSettled(r.map(e=>vt._fetchWalletImage(e))),wt.featured=i,wt.allFeatured=i}},async fetchRecommendedWallets(){try{wt.isFetchingRecommendedWallets=!0;const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:s}=Ke.state,i=[...t??[],...s??[]].filter(Boolean),r={page:1,entries:4,include:e,exclude:i,chains:Ht.getRequestedCaipNetworkIds().join(",")},{data:n,count:o}=await vt.fetchWallets(r),a=Be.getRecentWallets(),c=n.map(e=>e.image_id).filter(Boolean),l=a.map(e=>e.image_id).filter(Boolean);await Promise.allSettled([...c,...l].map(e=>vt._fetchWalletImage(e))),wt.recommended=n,wt.allRecommended=n,wt.count=o??0}catch{}finally{wt.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:e}){const{includeWalletIds:t,excludeWalletIds:s,featuredWalletIds:i}=Ke.state,r=Ht.getRequestedCaipNetworkIds().join(","),n={page:e,entries:40,include:t,exclude:[...wt.recommended.map(({id:e})=>e),...s??[],...i??[]].filter(Boolean),chains:r},{data:o,count:a}=await vt.fetchWallets(n),c=o.slice(0,20).map(e=>e.image_id).filter(Boolean);await Promise.allSettled(c.map(e=>vt._fetchWalletImage(e))),wt.wallets=ze.uniqueBy([...wt.wallets,...vt._filterOutExtensions(o)],"id").filter(e=>{var t;return null==(t=e.chains)?void 0:t.some(e=>r.includes(e))}),wt.count=a>wt.count?a:wt.count,wt.page=e},async initializeExcludedWallets({ids:e}){const t={page:1,entries:e.length,include:e},{data:s}=await vt.fetchWallets(t);s&&s.forEach(e=>{wt.excludedWallets.push({rdns:e.rdns,name:e.name})})},async searchWallet({search:e,badge:t}){const{includeWalletIds:s,excludeWalletIds:i}=Ke.state,r=Ht.getRequestedCaipNetworkIds().join(",");wt.search=[];const n={page:1,entries:100,search:null==e?void 0:e.trim(),badge_type:t,include:s,exclude:i,chains:r},{data:o}=await vt.fetchWallets(n);gt.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:t??"",search:e??""}});const a=o.map(e=>e.image_id).filter(Boolean);await Promise.allSettled([...a.map(e=>vt._fetchWalletImage(e)),ze.wait(300)]),wt.search=vt._filterOutExtensions(o)},initPromise(e,t){const s=wt.promises[e];return s||(wt.promises[e]=t())},prefetch({fetchConnectorImages:e=!0,fetchFeaturedWallets:t=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:i=!0}={}){const r=[e&&vt.initPromise("connectorImages",vt.fetchConnectorImages),t&&vt.initPromise("featuredWallets",vt.fetchFeaturedWallets),s&&vt.initPromise("recommendedWallets",vt.fetchRecommendedWallets),i&&vt.initPromise("networkImages",vt.fetchNetworkImages)].filter(
2Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){var e;(null==(e=Ke.state.features)?void 0:e.analytics)&&vt.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:e}=await mt.get({path:"/getAnalyticsConfig",params:vt._getSdkProperties()});Ke.setFeatures({analytics:e})}catch(e){Ke.setFeatures({analytics:!1})}},filterByNamespaces(e){if(!(null==e?void 0:e.length))return wt.featured=wt.allFeatured,void(wt.recommended=wt.allRecommended);const t=Ht.getRequestedCaipNetworkIds().join(",");wt.featured=wt.allFeatured.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))}),wt.recommended=wt.allRecommended.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))}),wt.filteredWallets=wt.wallets.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))})},clearFilterByNamespaces(){wt.filteredWallets=[]},setFilterByNamespace(e){if(!e)return wt.featured=wt.allFeatured,void(wt.recommended=wt.allRecommended);const t=Ht.getRequestedCaipNetworkIds().join(",");wt.featured=wt.allFeatured.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))}),wt.recommended=wt.allRecommended.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))}),wt.filteredWallets=wt.wallets.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))})}},yt=Ue({view:"Connect",history:["Connect"],transactionStack:[]}),bt=et({state:yt,subscribeKey:(e,t)=>je(yt,e,t),pushTransactionStack(e){yt.transactionStack.push(e)},popTransactionStack(e){const t=yt.transactionStack.pop();if(!t)return;const{onSuccess:s,onError:i,onCancel:r}=t;switch(e){case"success":null==s||s();break;case"error":null==i||i(),bt.goBack();break;case"cancel":null==r||r(),bt.goBack()}},push(e,t){e!==yt.view&&(yt.view=e,yt.history.push(e),yt.data=t)},reset(e,t){yt.view=e,yt.history=[e],yt.data=t}
2,replace(e,t){yt.history.at(-1)===e||(yt.view=e,yt.history[yt.history.length-1]=e,yt.data=t)},goBack(){var e;const t=Ht.state.activeCaipAddress,s="ConnectingFarcaster"===bt.state.view,i=!t&&s;if(yt.history.length>1){yt.history.pop();const[e]=yt.history.slice(-1);if(e){const s="Connect"===e;yt.view=t&&s?"Account":e}}else ts.close();(null==(e=yt.data)?void 0:e.wallet)&&(yt.data.wallet=void 0),setTimeout(()=>{var e,t,s;if(i){Zt.setFarcasterUrl(void 0,Ht.state.activeChain);const i=St.getAuthConnector();null==(e=null==i?void 0:i.provider)||e.reload();const r=De(Ke.state);null==(s=null==(t=null==i?void 0:i.provider)?void 0:t.syncDappData)||s.call(t,{metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType})}},100)},goBackToIndex(e){if(yt.history.length>1){yt.history=yt.history.slice(0,e+1);const[t]=yt.history.slice(-1);t&&(yt.view=t)}},goBackOrCloseModal(){bt.state.history.length>1?bt.goBack():ts.close()}}),Et=Ue({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Ct={state:Et,subscribe:e=>$e(Et,()=>e(Et)),setThemeMode(e){Et.themeMode=e;try{const t=St.getAuthConnector();if(t){const s=Ct.getSnapshot().themeVariables;t.provider.syncTheme({themeMode:e,themeVariables:s,w3mThemeVariables:Ie(s,e)})}}catch{}},setThemeVariables(e){Et.themeVariables={...Et.themeVariables,...e};try{const e=St.getAuthConnector();if(e){const t=Ct.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:Ie(Et.themeVariables,Et.themeMode)})}}catch{}},getSnapshot:()=>De(Et)},It=et(Ct),Nt={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},At=Ue({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...Nt},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),St=et({state:At,subscribe:e=>$e(At,()=>{e(At)}),subscribeKey:(e,t)=>je(At,e,t),initialize(e){e.forEach(e=>{const t=Be.getConnectedConnectorId(e);t&&St.setConnectorId(t,e)})},setActiveConnector(e){e&&(At.activeConnector=Me(e))},setConnectors(e){e.filter(e=>!At.allConnectors.some(t=>t.id===e.id&&St.getConnectorName(t.name)===St.getConnectorName(e.name)&&t.chain===e.chain)).forEach(e=>{"MULTI_CHAIN"!==e.type&&At.allConnectors.push(Me(e))});const t=St.getEnabledNamespaces(),s=St.getEnabledConnectors(t);At.connectors=St.mergeMultiChainConnectors(s)},filterByNamespaces(e){Object.keys(At.filterByNamespaceMap).forEach(e=>{At.filterByNamespaceMap[e]=!1}),e.forEach(e=>{At.filterByNamespaceMap[e]=!0}),St.updateConnectorsForEnabledNamespaces()},filterByNamespace(e,t){At.filterByNamespaceMap[e]=t,St.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const e=St.getEnabledNamespaces(),t=St.getEnabledConnectors(e),s=St.areAllNamespacesEnabled();At.connectors=St.mergeMultiChainConnectors(t),s?vt.clearFilterByNamespaces():vt.filterByNamespaces(e)},getEnabledNamespaces:()=>Object.entries(At.filterByNamespaceMap).filter(([e,t])=>t).map(([e])=>e),getEnabledConnectors:e=>At.allConnectors.filter(t=>e.includes(t.chain)),areAllNamespacesEnabled:()=>Object.values(At.filterByNamespaceMap).every(e=>e),mergeMultiChainConnectors(e){const t=St.generateConnectorMapByName(e),s=[];return t.forEach(e=>{const t=e[0],i=(null==t?void 0:t.id)===L.CONNECTOR_ID.AUTH;e.length>1&&t?s.push({name:t.name,imageUrl:t.imageUrl,imageId:t.imageId,connectors:[...e],type:i?"AUTH":"MULTI_CHAIN",chain:"eip155",id:(null==t?void 0:t.id)||""}):t&&s.push(t)}),s},generateConnectorMapByName(e){const t=new Map;return e.forEach(e=>{const{name:s}=e,i=St.getConnectorName(s);if(!i)return;const r=t.get(i)||[];r.find(t=>t.chain===e.chain)||r.push(e),t.set(i,r)}),t},getConnectorName(e){if(!e)return e;return{"Trust Wallet":"Trust"}[e]||e},getUniqueConnectorsByName(e){const t=[];return e.forEach(e=>{t.find(t=>t.chain===e.chain)||t.push(e)}),t},addConnector(e){var t,s,i;if(e.id===L.CONNECTOR_ID.AUTH){const r=e,n=De(Ke.state),o=It.getSnapshot().themeMode,a=It.getSnapshot().themeVariables;null==(s=null==(t=null==r?void 0:r.provider)?void 0:t.syncDappData)||s.call(t,{metadata:n.metadata,sdkVersion:n.sdkVersion,projectId:n.projectId,sdkType:n.sdkType}),null==(i=null==r?void 0:r.provider)||i.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:Ie(a,o)}),St.setConnectors([e])}else St.setConnectors([e])},getAuthConnector(e){var t;const s=e||Ht.state.activeChain,i=At.connectors.find(e=>e.id===L.CONNECTOR_ID.AUTH);if(i){if(null==(t=null==i?void 0:i.connectors)?void 0:t.length){return i.connectors.find(e=>e.chain===s)}return i}},getAnnouncedConnectorRdns:()=>At.connectors.filter(e=>"ANNOUNCED"===e.type).map(e=>{var t;return null==(t=e.info)?void 0:t.rdns}),getConnectorById:e=>At.allConnectors.find(t=>
2t.id===e),getConnector:(e,t)=>At.allConnectors.filter(e=>e.chain===Ht.state.activeChain).find(s=>{var i;return s.explorerId===e||(null==(i=s.info)?void 0:i.rdns)===t}),syncIfAuthConnector(e){var t,s;if("ID_AUTH"!==e.id)return;const i=e,r=De(Ke.state),n=It.getSnapshot().themeMode,o=It.getSnapshot().themeVariables;null==(s=null==(t=null==i?void 0:i.provider)?void 0:t.syncDappData)||s.call(t,{metadata:r.metadata,sdkVersion:r.sdkVersion,sdkType:r.sdkType,projectId:r.projectId}),i.provider.syncTheme({themeMode:n,themeVariables:o,w3mThemeVariables:Ie(o,n)})},getConnectorsByNamespace(e){const t=At.allConnectors.filter(t=>t.chain===e);return St.mergeMultiChainConnectors(t)},selectWalletConnector(e){const t=St.getConnector(e.id,e.rdns),s=Ht.state.activeChain;st.handleMobileDeeplinkRedirect((null==t?void 0:t.explorerId)||e.id,s),t?bt.push("ConnectingExternal",{connector:t}):bt.push("ConnectingWalletConnect",{wallet:e})},getConnectors:e=>e?St.getConnectorsByNamespace(e):St.mergeMultiChainConnectors(At.allConnectors),setFilterByNamespace(e){At.filterByNamespace=e,At.connectors=St.getConnectors(e),vt.setFilterByNamespace(e)},setConnectorId(e,t){e&&(At.activeConnectorIds={...At.activeConnectorIds,[t]:e},Be.setConnectedConnectorId(t,e))},removeConnectorId(e){At.activeConnectorIds={...At.activeConnectorIds,[e]:void 0},Be.deleteConnectedConnectorId(e)},getConnectorId(e){if(e)return At.activeConnectorIds[e]},isConnected:e=>e?Boolean(At.activeConnectorIds[e]):Object.values(At.activeConnectorIds).some(e=>Boolean(e)),resetConnectorIds(){At.activeConnectorIds={...Nt}}}),Pt={SMART_ACCOUNT:"smartAccount"},kt=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),_t=Ue({...kt}),Ot={state:_t,subscribeKey:(e,t)=>je(_t,e,t),showLoading(e,t={}){this._showMessage({message:e,variant:"loading",...t})},showSuccess(e){this._showMessage({message:e,variant:"success"})},showSvg(e,t){this._showMessage({message:e,svg:t})},showError(e){const t=ze.parseError(e);this._showMessage({message:t,variant:"error"})},hide(){_t.message=kt.message,_t.variant=kt.variant,_t.svg=kt.svg,_t.open=kt.open,_t.autoClose=kt.autoClose},_showMessage({message:e,svg:t,variant:s="success",autoClose:i=kt.autoClose}){_t.open?(_t.open=!1,setTimeout(()=>{_t.message=e,_t.variant=s,_t.svg=t,_t.open=!0,_t.autoClose=i},150)):(_t.message=e,_t.variant=s,_t.svg=t,_t.open=!0,_t.autoClose=i)}},xt=Ue({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Tt=et({state:xt,subscribe:e=>$e(xt,()=>e(xt)),setLastNetworkInView(e){xt.lastNetworkInView=e},async fetchTransactions(e,t){var s,i;if(!e)throw new Error("Transactions can't be fetched without an accountAddress");xt.loading=!0;try{const i=await Yt.fetchTransactions({account:e,cursor:xt.next,onramp:t,cache:"coinbase"===t?"no-cache":void 0,chainId:null==(s=Ht.state.activeCaipNetwork)?void 0:s.caipNetworkId}),r=Tt.filterSpamTransactions(i.data),n=Tt.filterByConnectedChain(r),o=[...xt.transactions,...n];xt.loading=!1,"coinbase"===t?xt.coinbaseTransactions=Tt.groupTransactionsByYearAndMonth(xt.coinbaseTransactions,i.data):(xt.transactions=o,xt.transactionsByYear=Tt.groupTransactionsByYearAndMonth(xt.transactionsByYear,n)),xt.empty=0===o.length,xt.next=i.next?i.next:void 0}catch(r){const t=Ht.state.activeChain;gt.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:e,projectId:Ke.state.projectId,cursor:xt.next,isSmartAccount:(null==(i=Zt.state.preferredAccountTypes)?void 0:i[t])===Pt.SMART_ACCOUNT}}),Ot.showError("Failed to fetch transactions"),xt.loading=!1,xt.empty=!0,xt.next=void 0}},groupTransactionsByYearAndMonth(e={},t=[]){const s=e;return t.forEach(e=>{const t=new Date(e.metadata.minedAt).getFullYear(),i=new Date(e.metadata.minedAt).getMonth(),r=s[t]??{},n=(r[i]??[]).filter(t=>t.id!==e.id);s[t]={...r,[i]:[...n,e].sort((e,t)=>new Date(t.metadata.minedAt).getTime()-new Date(e.metadata.minedAt).getTime())}}),s},filterSpamTransactions:e=>e.filter(e=>!e.transfers.every(e=>{var t;return!0===(null==(t=e.nft_info)?void 0:t.flags.is_spam)})),filterByConnectedChain(e){var t;const s=null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId;return e.filter(e=>e.metadata.chain===s)}
2,clearCursor(){xt.next=void 0},resetTransactions(){xt.transactions=[],xt.transactionsByYear={},xt.lastNetworkInView=void 0,xt.loading=!1,xt.empty=!1,xt.next=void 0}},"API_ERROR"),Rt=Ue({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let Ut;const $t=et({state:Rt,subscribeKey:(e,t)=>je(Rt,e,t),_getClient:()=>Rt._client,setClient(e){Rt._client=Me(e)},async connectWalletConnect(){var e,t,s,i;if(ze.isTelegram()||ze.isSafari()&&ze.isIos()){if(Ut)return await Ut,void(Ut=void 0);if(!ze.isPairingExpired(null==Rt?void 0:Rt.wcPairingExpiry)){const e=Rt.wcUri;return void(Rt.wcUri=e)}Ut=null==(t=null==(e=$t._getClient())?void 0:e.connectWalletConnect)?void 0:t.call(e).catch(()=>{}),$t.state.status="connecting",await Ut,Ut=void 0,Rt.wcPairingExpiry=void 0,$t.state.status="connected"}else await(null==(i=null==(s=$t._getClient())?void 0:s.connectWalletConnect)?void 0:i.call(s))},async connectExternal(e,t,s=!0){var i,r;await(null==(r=null==(i=$t._getClient())?void 0:i.connectExternal)?void 0:r.call(i,e)),s&&Ht.setActiveNamespace(t)},async reconnectExternal(e){var t,s;await(null==(s=null==(t=$t._getClient())?void 0:t.reconnectExternal)?void 0:s.call(t,e));const i=e.chain||Ht.state.activeChain;i&&St.setConnectorId(e.id,i)},async setPreferredAccountType(e,t){var s;ts.setLoading(!0,Ht.state.activeChain);const i=St.getAuthConnector();i&&(Zt.setPreferredAccountType(e,t),await i.provider.setPreferredAccount(e),Be.setPreferredAccountTypes(Zt.state.preferredAccountTypes??{[t]:e}),await $t.reconnectExternal(i),ts.setLoading(!1,Ht.state.activeChain),gt.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:e,network:(null==(s=Ht.state.activeCaipNetwork)?void 0:s.caipNetworkId)||""}}))},async signMessage(e){var t;return null==(t=$t._getClient())?void 0:t.signMessage(e)},parseUnits(e,t){var s;return null==(s=$t._getClient())?void 0:s.parseUnits(e,t)},formatUnits(e,t){var s;return null==(s=$t._getClient())?void 0:s.formatUnits(e,t)},async sendTransaction(e){var t;return null==(t=$t._getClient())?void 0:t.sendTransaction(e)},async getCapabilities(e){var t;return null==(t=$t._getClient())?void 0:t.getCapabilities(e)},async grantPermissions(e){var t;return null==(t=$t._getClient())?void 0:t.grantPermissions(e)},async walletGetAssets(e){var t;return(null==(t=$t._getClient())?void 0:t.walletGetAssets(e))??{}},async estimateGas(e){var t;return null==(t=$t._getClient())?void 0:t.estimateGas(e)},async writeContract(e){var t;return null==(t=$t._getClient())?void 0:t.writeContract(e)},async getEnsAddress(e){var t;return null==(t=$t._getClient())?void 0:t.getEnsAddress(e)},async getEnsAvatar(e){var t;return null==(t=$t._getClient())?void 0:t.getEnsAvatar(e)},checkInstalled(e){var t,s;return(null==(s=null==(t=$t._getClient())?void 0:t.checkInstalled)?void 0:s.call(t,e))||!1},resetWcConnection(){Rt.wcUri=void 0,Rt.wcPairingExpiry=void 0,Rt.wcLinking=void 0,Rt.recentWallet=void 0,Rt.status="disconnected",Tt.resetTransactions(),Be.deleteWalletConnectDeepLink()},resetUri(){Rt.wcUri=void 0,Rt.wcPairingExpiry=void 0,Ut=void 0},finalizeWcConnection(){var e,t;const{wcLinking:s,recentWallet:i}=$t.state;s&&Be.setWalletConnectDeepLink(s),i&&Be.setAppKitRecent(i),gt.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s?"mobile":"qrcode",name:(null==(t=null==(e=bt.state.data)?void 0:e.wallet)?void 0:t.name)||"Unknown"}})},setWcBasic(e){Rt.wcBasic=e},setUri(e){Rt.wcUri=e,Rt.wcPairingExpiry=ze.getPairingExpiry()},setWcLinking(e){Rt.wcLinking=e},setWcError(e){Rt.wcError=e,Rt.buffering=!1},setRecentWallet(e){Rt.recentWallet=e},setBuffering(e){Rt.buffering=e},setStatus(e){Rt.status=e},async disconnect(e){var t;try{await(null==(t=$t._getClient())?void 0:t.disconnect(e))}catch(s){throw new Ze("Failed to disconnect","INTERNAL_SDK_ERROR",s)}},setConnections(e,t){Rt.connections.set(t,e)},switchAccount({connection:e,address:t,namespace:s}){if(St.state.activeConnectorIds[s]===e.connectorId){const e=Ht.state.activeCaipNetwork;if(e){const i=`${s}:${e.id}:${t}`;Zt.setCaipAddress(i,s)}}else{const t=St.getConnector(e.connectorId);t&&$t.connectExternal(t,s)}}}),Dt=Ue({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),Mt={state:Dt,subscribe:e=>$e(Dt,()=>e(Dt)),subscribeOpen:e=>je(Dt,"open",e),set(e){Object.assign(Dt,{...Dt,...e})}};const jt={createBalance(e,t){const s={name:e.metadata.name||"",symbol
2:e.metadata.symbol||"",decimals:e.metadata.decimals||0,value:e.metadata.value||0,price:e.metadata.price||0,iconUrl:e.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:t,address:"native"===e.address?void 0:this.convertAddressToCAIP10Address(e.address,t),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:e.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance:({hex:e,decimals:t})=>function(e,t){let s=e.toString();const i=s.startsWith("-");i&&(s=s.slice(1)),s=s.padStart(t,"0");let[r,n]=[s.slice(0,s.length-t),s.slice(s.length-t)];return n=n.replace(/(0+)$/,""),`${i?"-":""}${r||"0"}${n?`.${n}`:""}`}(BigInt(e),t),convertAddressToCAIP10Address:(e,t)=>`${t}:${e}`,createCAIP2ChainId:(e,t)=>`${t}:${parseInt(e,16)}`,getChainIdHexFromCAIP2ChainId(e){const t=e.split(":");if(t.length<2||!t[1])return"0x0";const s=t[1],i=parseInt(s,10);return isNaN(i)?"0x0":`0x${i.toString(16)}`},isWalletGetAssetsResponse(e){return"object"==typeof e&&null!==e&&Object.values(e).every(e=>Array.isArray(e)&&e.every(e=>this.isValidAsset(e)))},isValidAsset:e=>"object"==typeof e&&null!==e&&"string"==typeof e.address&&"string"==typeof e.balance&&("ERC20"===e.type||"NATIVE"===e.type)&&"object"==typeof e.metadata&&null!==e.metadata&&"string"==typeof e.metadata.name&&"string"==typeof e.metadata.symbol&&"number"==typeof e.metadata.decimals&&"number"==typeof e.metadata.price&&"string"==typeof e.metadata.iconUrl},Lt={async getMyTokensWithBalance(e){const t=Zt.state.address,s=Ht.state.activeCaipNetwork;if(!t||!s)return[];if("eip155"===s.chainNamespace){const e=await this.getEIP155Balances(t,s);if(e)return this.filterLowQualityTokens(e)}const i=await Yt.getBalance(t,s.caipNetworkId,e);return this.filterLowQualityTokens(i.balances)},async getEIP155Balances(e,t){var s,i;try{const r=jt.getChainIdHexFromCAIP2ChainId(t.caipNetworkId),n=await $t.getCapabilities(e);if(!(null==(i=null==(s=null==n?void 0:n[r])?void 0:s.assetDiscovery)?void 0:i.supported))return null;const o=await $t.walletGetAssets({account:e,chainFilter:[r]});if(!jt.isWalletGetAssetsResponse(o))return null;return(o[r]||[]).map(e=>jt.createBalance(e,t.caipNetworkId))}catch(r){return null}},filterLowQualityTokens:e=>e.filter(e=>"0"!==e.quantity.decimals),mapBalancesToSwapTokens:e=>(null==e?void 0:e.map(e=>({...e,address:(null==e?void 0:e.address)?e.address:Ht.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]},qt=Ue({tokenBalances:[],loading:!1}),Bt=et({state:qt,subscribe:e=>$e(qt,()=>e(qt)),subscribeKey:(e,t)=>je(qt,e,t),setToken(e){e&&(qt.token=Me(e))},setTokenAmount(e){qt.sendTokenAmount=e},setReceiverAddress(e){qt.receiverAddress=e},setReceiverProfileImageUrl(e){qt.receiverProfileImageUrl=e},setReceiverProfileName(e){qt.receiverProfileName=e},setNetworkBalanceInUsd(e){qt.networkBalanceInUSD=e},setLoading(e){qt.loading=e},async sendToken(){var e;try{switch(Bt.setLoading(!0),null==(e=Ht.state.activeCaipNetwork)?void 0:e.chainNamespace){case"eip155":return void(await Bt.sendEvmToken());case"solana":return void(await Bt.sendSolanaToken());default:throw new Error("Unsupported chain")}}finally{Bt.setLoading(!1)}},async sendEvmToken(){var e,t,s,i;const r=Ht.state.activeChain,n=null==(e=Zt.state.preferredAccountTypes)?void 0:e[r];if(!Bt.state.sendTokenAmount||!Bt.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!Bt.state.token)throw new Error("A token is required");(null==(t=Bt.state.token)?void 0:t.address)?(gt.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:n===Pt.SMART_ACCOUNT,token:Bt.state.token.address,amount:Bt.state.sendTokenAmount,network:(null==(s=Ht.state.activeCaipNetwork)?void 0:s.caipNetworkId)||""}}),await Bt.sendERC20Token({receiverAddress:Bt.state.receiverAddress,tokenAddress:Bt.state.token.address,sendTokenAmount:Bt.state.sendTokenAmount,decimals:Bt.state.token.quantity.decimals})):(gt.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:n===Pt.SMART_ACCOUNT,token:Bt.state.token.symbol||"",amount:Bt.state.sendTokenAmount,network:(null==(i=Ht.state.activeCaipNetwork)?void 0:i.caipNetworkId)||""}}),await Bt.sendNativeToken({receiverAddress:Bt.state.receiverAddress,sendTokenAmount:Bt.state.sendTokenAmount,decimals:Bt.state.token.quantity.decimals}))},async fetchTokenBalance(e){var t,s;qt.loading=!0;const i=null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId,r=null==(s=Ht.state.activeCaipNetwork)?void 0:s.chainNamespace,n=Ht.state.activeCaipAddress,o=n?ze.getPlainAddress(n):void 0;if(qt.lastRetry&&!ze.isAllowedRetry(qt.lastRetry,30*qe.ONE_SEC_MS))return qt.loading=!1,[];try{if(o&&i&&r){const e=await Lt.getMyTokensWithBalance();return qt.tokenBalances=e,qt.lastRetry=void 0,e}}catch(a){qt.lastRetry=Date.now(),null==e||e(a),Ot.showError("Token Balance Unavailable")}finally{qt.loading=!1}return[]},fetchNetworkBalance(){if(0===qt.tokenBalances.length)return;const e=Lt.mapBalancesToSwapTokens(qt.tokenBalances);if(!e)return;const t=e.find(e=>e.address===Ht.getActiveNetworkTokenAddress());t&&(qt.networkBalanceInUSD=t?ee.multiply(t.quantity.numeric,t.price).toString():"0")},async sendNativeToken(e){var t,s,i,r;bt.pushTransactionStack({});const n=e.receiverAddress,o=Zt.state.address,a=$t.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals));await $t.sendTransaction({chainNamespace:"eip155",to:n,address:o,data:"0x",value:a??BigInt(0)}),gt.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:(null==(t=Zt.state.preferredAccountTypes)?void 0:t.eip155)===Pt.SMART_ACCOUNT,token:(null==(s=Bt.state.token)?void 0:s.symbol)||"",amount:e.sendTokenAmount,network:(null==(i=Ht.state.activeCaipNetwork)?void 0:i.caipNetworkId)||""}}),null==(r=$t._getClient())||r.updateBalance("eip155"),Bt.resetSend()},async sendERC20Token(e){bt.pushTransactionStack({onSuccess(){bt.replace("Account")}});const t=$t.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals));if(Zt.state.address&&e.sendTokenAmount&&e.receiverAddress&&e.tokenAddress){const s=ze.getPlainAddress(e.tokenAddress);await $t.writeContract({fromAddress:Zt.state.address,tokenAddress:s,args:[e.receiverAddress,t??BigInt(0)],method:"transfer",abi:ie(s),chainNamespace:"eip155"}),Bt.resetSend()}},async sendSolanaToken(){var e;if(!Bt.state.sendTokenAmount||!Bt.state.receiverAddress)throw new Error("An amount and receiver address are required");bt.pushTransactionStack({onSuccess(){bt.replace("Account")}}),await $t.sendTransaction({chainNamespace:"solana",to:Bt.state.receiverAddress,value:Bt.state.sendTokenAmount}),null==(e=$t._getClient())||e.updateBalance("solana"),Bt.resetSend()},resetSend(){qt.token=void 0,qt.sendTokenAmount=void 0,qt.receiverAddress=void 0,qt.receiverProfileImageUrl=void 0,qt.receiverProfileName=void 0,qt.loading=!1,qt.tokenBalances=[]}}),zt={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},Ft={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},Wt=Ue({chains:function(){const e=Ue({data:Array.from([]),has(e){return this.data.some(t=>t[0]===e)},set(e,t){const s=this.data.find(t=>t[0]===e);return s?s[1]=t:this.data.push([e,t]),this},get(e){var t;return null==(t=this.data.find(t=>t[0]===e))?void 0:t[1]},delete(e){const t=this.data.findIndex(t=>t[0]===e);return-1!==t&&(this.data.splice(t,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)}
2,forEach(e){this.data.forEach(t=>{e(t[1],t[0],this)})},keys(){return this.data.map(e=>e[0]).values()},values(){return this.data.map(e=>e[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}(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),Vt={state:Wt,subscribe:e=>$e(Wt,()=>{e(Wt)}),subscribeKey:(e,t)=>je(Wt,e,t),subscribeChainProp(e,t,s){let i;return $e(Wt.chains,()=>{var r;const n=s||Wt.activeChain;if(n){const s=null==(r=Wt.chains.get(n))?void 0:r[e];i!==s&&(i=s,t(s))}})},initialize(e,t,s){const{chainId:i,namespace:r}=Be.getActiveNetworkProps(),n=null==t?void 0:t.find(e=>e.id.toString()===(null==i?void 0:i.toString())),o=e.find(e=>(null==e?void 0:e.namespace)===r)||(null==e?void 0:e[0]),a=e.map(e=>e.namespace).filter(e=>void 0!==e),c=Ke.state.enableEmbedded?new Set([...a]):new Set([...(null==t?void 0:t.map(e=>e.chainNamespace))??[]]);0!==(null==e?void 0:e.length)&&o||(Wt.noAdapters=!0),Wt.noAdapters||(Wt.activeChain=null==o?void 0:o.namespace,Wt.activeCaipNetwork=n,Ht.setChainNetworkData(null==o?void 0:o.namespace,{caipNetwork:n}),Wt.activeChain&&Mt.set({activeChain:null==o?void 0:o.namespace})),c.forEach(e=>{const i=null==t?void 0:t.filter(t=>t.chainNamespace===e);Ht.state.chains.set(e,{namespace:e,networkState:Ue({...Ft,caipNetwork:null==i?void 0:i[0]}),accountState:Ue(zt),caipNetworks:i??[],...s}),Ht.setRequestedCaipNetworks(i??[],e)})},removeAdapter(e){var t,s;if(Wt.activeChain===e){const i=Array.from(Wt.chains.entries()).find(([t])=>t!==e);if(i){const e=null==(s=null==(t=i[1])?void 0:t.caipNetworks)?void 0:s[0];e&&Ht.setActiveCaipNetwork(e)}}Wt.chains.delete(e)},addAdapter(e,{networkControllerClient:t,connectionControllerClient:s},i){Wt.chains.set(e.namespace,{namespace:e.namespace,networkState:{...Ft,caipNetwork:i[0]},accountState:zt,caipNetworks:i,connectionControllerClient:s,networkControllerClient:t}),Ht.setRequestedCaipNetworks((null==i?void 0:i.filter(t=>t.chainNamespace===e.namespace))??[],e.namespace)},addNetwork(e){var t;const s=Wt.chains.get(e.chainNamespace);if(s){const i=[...s.caipNetworks||[]];(null==(t=s.caipNetworks)?void 0:t.find(t=>t.id===e.id))||i.push(e),Wt.chains.set(e.chainNamespace,{...s,caipNetworks:i}),Ht.setRequestedCaipNetworks(i,e.chainNamespace),St.filterByNamespace(e.chainNamespace,!0)}},removeNetwork(e,t){var s,i,r;const n=Wt.chains.get(e);if(n){const o=(null==(s=Wt.activeCaipNetwork)?void 0:s.id)===t,a=[...(null==(i=n.caipNetworks)?void 0:i.filter(e=>e.id!==t))||[]];o&&(null==(r=null==n?void 0:n.caipNetworks)?void 0:r[0])&&Ht.setActiveCaipNetwork(n.caipNetworks[0]),Wt.chains.set(e,{...n,caipNetworks:a}),Ht.setRequestedCaipNetworks(a||[],e),0===a.length&&St.filterByNamespace(e,!1)}},setAdapterNetworkState(e,t){const s=Wt.chains.get(e);s&&(s.networkState={...s.networkState||Ft,...t},Wt.chains.set(e,s))},setChainAccountData(e,t,s=!0){if(!e)throw new Error("Chain is required to update chain account data");const i=Wt.chains.get(e);if(i){const s={...i.accountState||zt,...t};Wt.chains.set(e,{...i,accountState:s}),1!==Wt.chains.size&&Wt.activeChain!==e||(t.caipAddress&&(Wt.activeCaipAddress=t.caipAddress),Zt.replaceState(s))}},setChainNetworkData(e,t){if(!e)return;const s=Wt.chains.get(e);if(s){const i={...s.networkState||Ft,...t};Wt.chains.set(e,{...s,networkState:i})}},setAccountProp(e,t,s,i=!0){Ht.setChainAccountData(s,{[e]:t},i),"status"===e&&"disconnected"===t&&s&&St.removeConnectorId(s)},setActiveNamespace(e){var t,s;Wt.activeChain=e;const i=e?Wt.chains.get(e):void 0,r=null==(t=null==i?void 0:i.networkState)?void 0:t.caipNetwork;(null==r?void 0:r.id)&&e&&(Wt.activeCaipAddress=null==(s=null==i?void 0:i.accountState)?void 0:s.caipAddress,Wt.activeCaipNetwork=r,Ht.setChainNetworkData(e,{caipNetwork:r}),Be.setActiveCaipNetworkId(null==r?void 0:r.caipNetworkId),Mt.set({activeChain:e,selectedNetworkId:null==r?void 0:r.caipNetworkId}))},setActiveCaipNetwork(e){var t,s,i;if(!e)return;Wt.activeChain!==e.chainNamespace&&Ht.setIsSwitchingNamespace(!0);const r=Wt.chains.get(e.chainNamespace);Wt.activeChain=e.chainNamespace,Wt.activeCaipNetwork=e,Ht.setChainNetworkData(e.chainNamespace,{caipNetwork:e}),(null==(t=null==r?void 0:r.accountState)?void 0:t.address)?Wt.activeCaipAddress=`${e.chainNamespace}:${e.id}:${null==(s=null==r?void 0:r.accountState)?void 0:s.address}`:Wt.activeCaipAddress=void 0,Ht.setAccountProp("caipAddress",Wt.activeCaipAddress,e.chainNamespace),r&&Zt.replaceState(r.accountState),Bt.resetSend(),Mt.set({activeChain:Wt.activeChain,selectedNetworkId:null==(i=Wt.activeCaipNetwork)?void 0:i.caipNetworkId}),Be.setActiveCaipNetworkId(e.caipNetworkId);Ht.checkIfSupportedNetwork(e.chainNamespace)||!Ke.state.enableNetworkSwitch||Ke.state.allowUnsupportedChain||$t.state.wcBasic||Ht.showUnsupportedChainUI()},addCaipNetwork(e){var t;if(!e)return;const s=Wt.chains.get(e.chainNamespace);s&&(null==(t=null==s?void 0:s.caipNetworks)||t.push(e))},async switchActiveNamespace(e){var t;if(!e)return;const s=e!==Ht.state.activeChain,i=null==(t=Ht.getNetworkData(e))?void 0:t.caipNetwork,r=Ht.getCaipNetworkByNamespace(e,null==i?void 0:i.id);s&&r&&await Ht.switchActiveNetwork(r)},async switchActiveNetwork(e){var t;const s=Ht.state.chains.get(Ht.state.activeChain),i=!(null==(t=null==s?void 0:s.caipNetworks)?void 0:t.some(e=>{var t;return e.id===(null==(t=Wt.activeCaipNetwork)?void 0:t.id)})),r=Ht.getNetworkControllerClient(e.chainNamespace);if(r){try{await r.switchCaipNetwork(e),i&&ts.close()}catch(n){bt.goBack()}gt.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:e.caipNetworkId}})}},getNetworkControllerClient(e){const t=e||Wt.activeChain,s=Wt.chains.get(t);if(!s)throw new Error("Chain adapter not found");if(!s.networkControllerClient)throw new Error("NetworkController client not set");return s.networkControllerClient},getConnectionControllerClient(e){const t=e||Wt.activeChain;if(!t)throw new Error("Chain is required to get connection controller client");const s=Wt.chains.get(t);if(!(null==s?void 0:s.connectionControllerClient))throw new Error("ConnectionController client not set");return s.connectionControllerClient},getAccountProp(e,t){var s;let i=Wt.activeChain;if(t&&(i=t),!i)return;const r=null==(s=Wt.chains.get(i))?void 0:s.accountState;return r?r[e]:void 0},getNetworkProp(e,t){var s;const i=null==(s=Wt.chains.get(t))?void 0:s.networkState;if(i)return i[e]},getRequestedCaipNetworks(e){const t=Wt.chains.get(e),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:i=[]}=(null==t?void 0:t.networkState)||{};return ze.sortRequestedNetworks(s,i)},getAllRequestedCaipNetworks(){const e=[];return Wt.chains.forEach(t=>{const s=Ht.getRequestedCaipNetworks(t.namespace);e.push(...s)}),e},setRequestedCaipNetworks(e,t){Ht.setAdapterNetworkState(t,{requestedCaipNetworks:e});const s=Ht.getAllRequestedCaipNetworks().map(e=>e.chainNamespace),i=Array.from(new Set(s));St.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const e=[];return Wt.chains.forEach(t=>{const s=Ht.getApprovedCaipNetworkIds(t.namespace);e.push(...s)}),e},getActiveCaipNetwork:()=>Wt.activeCaipNetwork,getActiveCaipAddress:()=>Wt.activeCaipAddress,getApprovedCaipNetworkIds(e){var t;const s=Wt.chains.get(e);return(null==(t=null==s?void 0:s.networkState)?void 0:t.approvedCaipNetworkIds)||[]},async setApprovedCaipNetworksData(e){const t=Ht.getNetworkControllerClient(),s=await(null==t?void 0:t.getApprovedCaipNetworksData());Ht.setAdapterNetworkState(e,{approvedCaipNetworkIds:null==s?void 0:s.approvedCaipNetworkIds,supportsAllNetworks:null==s?void 0:s.supportsAllNetworks})},checkIfSupportedNetwork(e,t){const s=t||Wt.activeCaipNetwork,i=Ht.getRequestedCaipNetworks(e);return!i.length||(null==i?void 0:i.some(e=>e.id===(null==s?void 0:s.id)))},checkIfSupportedChainId(e){if(!Wt.activeChain)return!0;const t=Ht.getRequestedCaipNetworks(Wt.activeChain);return null==t?void 0:t.some(t=>t.id===e)},setSmartAccountEnabledNetworks(e,t){Ht.setAdapterNetworkState(t,{smartAccountEnabledNetworks:e})},checkIfSmartAccountEnabled(){var e;const t=q.caipNetworkIdToNumber(null==(e=Wt.activeCaipNetwork)?void 0:e.caipNetworkId),s=Wt.activeChain;if(!s||!t)return!1;
2const i=Ht.getNetworkProp("smartAccountEnabledNetworks",s);return Boolean(null==i?void 0:i.includes(Number(t)))},getActiveNetworkTokenAddress(){var e,t;const s=(null==(e=Wt.activeCaipNetwork)?void 0:e.chainNamespace)||"eip155";return`${s}:${(null==(t=Wt.activeCaipNetwork)?void 0:t.id)||1}:${qe.NATIVE_TOKEN_ADDRESS[s]}`},showUnsupportedChainUI(){ts.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const e=Wt.activeCaipNetwork;return Boolean((null==e?void 0:e.chainNamespace)&&qe.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(e.chainNamespace))},resetNetwork(e){Ht.setAdapterNetworkState(e,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(e){const t=e;if(!t)throw new Error("Chain is required to set account prop");Wt.activeCaipAddress=void 0,Ht.setChainAccountData(t,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol: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"}),St.removeConnectorId(t)},setIsSwitchingNamespace(e){Wt.isSwitchingNamespace=e},getFirstCaipNetworkSupportsAuthConnector(){var e,t;const s=[];let i;if(Wt.chains.forEach(e=>{L.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(t=>t===e.namespace)&&e.namespace&&s.push(e.namespace)}),s.length>0){const r=s[0];return i=r?null==(t=null==(e=Wt.chains.get(r))?void 0:e.caipNetworks)?void 0:t[0]:void 0,i}},getAccountData(e){var t;return e?null==(t=Ht.state.chains.get(e))?void 0:t.accountState:Zt.state},getNetworkData(e){var t;const s=e||Wt.activeChain;if(s)return null==(t=Ht.state.chains.get(s))?void 0:t.networkState},getCaipNetworkByNamespace(e,t){var s,i,r;if(!e)return;const n=Ht.state.chains.get(e),o=null==(s=null==n?void 0:n.caipNetworks)?void 0:s.find(e=>e.id===t);return o||((null==(i=null==n?void 0:n.networkState)?void 0:i.caipNetwork)||(null==(r=null==n?void 0:n.caipNetworks)?void 0:r[0]))},getRequestedCaipNetworkIds(){const e=St.state.filterByNamespace;return(e?[Wt.chains.get(e)]:Array.from(Wt.chains.values())).flatMap(e=>(null==e?void 0:e.caipNetworks)||[]).map(e=>e.caipNetworkId)},getCaipNetworks:e=>e?Ht.getRequestedCaipNetworks(e):Ht.getAllRequestedCaipNetworks()},Ht=et(Vt),Kt={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"}]}]},Gt=ze.getBlockchainApiUrl(),Jt=Ue({clientId:null,api:new We({baseUrl:Gt,clientId:null}),supportedChains:{http:[],ws:[]}}),Yt={state:Jt,async get(e){const{st:t,sv:s}=Yt.getSdkProperties(),i=Ke.state.projectId,r={...e.params||{},st:t,sv:s,projectId:i};return Jt.api.get({...e,params:r})},getSdkProperties(){const{sdkType:e,sdkVersion:t}=Ke.state;return{st:e||"unknown",sv:t||"unknown"}},async isNetworkSupported(e){if(!e)return!1;try{Jt.supportedChains.http.length||await Yt.getSupportedNetworks()}catch(wn){return!1}return Jt.supportedChains.http.includes(e)},async getSupportedNetworks(){try{const e=await Yt.get({path:"v1/supported-chains"});return Jt.supportedChains=e,e}catch{return Jt.supportedChains}},async fetchIdentity({address:e,caipNetworkId:t}){if(!(await Yt.isNetworkSupported(t)))return{avatar:"",name:""};const s=Be.getIdentityFromCacheForAddress(e);if(s)return s;const i=await Yt.get({path:`/v1/identity/${e}`,params:{sender:Ht.state.activeCaipAddress?ze.getPlainAddress(Ht.state.activeCaipAddress):void 0}});return Be.updateIdentityCache({address:e,identity:i,timestamp:Date.now()}),i},async fetchTransactions({account:e,cursor:t,onramp:s,signal:i,cache:r,chainId:n}){var o;return await Yt.isNetworkSupported(null==(o=Ht.state.activeCaipNetwork)?void 0:o.caipNetworkId)?Yt.get({path:`/v1/account/${e}/history`,params:{cursor:t,onramp:s,chainId:n},signal:i,cache:r}):{data:[],next:void 0}},async fetchSwapQuote({amount:e,userAddress:t,from:s,to:i,gasPrice:r}){var n;return await Yt.isNetworkSupported(null==(n=Ht.state.activeCaipNetwork)?void 0:n.caipNetworkId)?Yt.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:e,userAddress:t,from:s,to:i,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:e}){var t;return await Yt.isNetworkSupported(null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId)?Yt.get({path:"/v1/convert/tokens",params:{chainId:e}}):{tokens:[]}},async fetchTokenPrice({addresses:e}){var t;return await Yt.isNetworkSupported(null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId)?Jt.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:e,projectId:Ke.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:e,userAddress:t}){var s;return await Yt.isNetworkSupported(null==(s=Ht.state.activeCaipNetwork)?void 0:s.caipNetworkId)?Yt.get({path:"/v1/convert/allowance",params:{tokenAddress:e,userAddress:t},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:e}){var t;const{st:s,sv:i}=Yt.getSdkProperties();if(!(await Yt.isNetworkSupported(null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId)))throw new Error("Network not supported for Gas Price");return Yt.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:e,st:s,sv:i}})},async generateSwapCalldata({amount:e,from:t,to:s,userAddress:i,disableEstimate:r}){var n;if(!(await Yt.isNetworkSupported(null==(n=Ht.state.activeCaipNetwork)?void 0:n.caipNetworkId)))throw new Error("Network not supported for Swaps");return Jt.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:e,eip155:{slippage:qe.CONVERT_SLIPPAGE_TOLERANCE},projectId:Ke.state.projectId,from:t,to:s,userAddress:i,disableEstimate:r}}
2)},async generateApproveCalldata({from:e,to:t,userAddress:s}){var i;const{st:r,sv:n}=Yt.getSdkProperties();if(!(await Yt.isNetworkSupported(null==(i=Ht.state.activeCaipNetwork)?void 0:i.caipNetworkId)))throw new Error("Network not supported for Swaps");return Yt.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:e,to:t,st:r,sv:n}})},async getBalance(e,t,s){var i;const{st:r,sv:n}=Yt.getSdkProperties();if(!(await Yt.isNetworkSupported(null==(i=Ht.state.activeCaipNetwork)?void 0:i.caipNetworkId)))return Ot.showError("Token Balance Unavailable"),{balances:[]};const o=`${t}:${e}`,a=Be.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await Yt.get({path:`/v1/account/${e}/balance`,params:{currency:"usd",chainId:t,forceUpdate:s,st:r,sv:n}});return Be.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(e){var t;return await Yt.isNetworkSupported(null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId)?Yt.get({path:`/v1/profile/account/${e}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:e}){var t;return await Yt.isNetworkSupported(null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId)?Yt.get({path:`/v1/profile/reverse/${e}`,params:{sender:Zt.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(e){var t;return await Yt.isNetworkSupported(null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId)?Yt.get({path:`/v1/profile/suggestions/${e}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:e,address:t,message:s,signature:i}){var r;return await Yt.isNetworkSupported(null==(r=Ht.state.activeCaipNetwork)?void 0:r.caipNetworkId)?Jt.api.post({path:"/v1/profile/account",body:{coin_type:e,address:t,message:s,signature:i},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:e,partnerUserId:t,defaultNetwork:s,purchaseAmount:i,paymentAmount:r}){var n;if(!(await Yt.isNetworkSupported(null==(n=Ht.state.activeCaipNetwork)?void 0:n.caipNetworkId)))return"";return(await Jt.api.post({path:"/v1/generators/onrampurl",params:{projectId:Ke.state.projectId},body:{destinationWallets:e,defaultNetwork:s,partnerUserId:t,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url},async getOnrampOptions(){var e;if(!(await Yt.isNetworkSupported(null==(e=Ht.state.activeCaipNetwork)?void 0:e.caipNetworkId)))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await Yt.get({path:"/v1/onramp/options"})}catch(wn){return Kt}},async getOnrampQuote({purchaseCurrency:e,paymentCurrency:t,amount:s,network:i}){var r;try{if(!(await Yt.isNetworkSupported(null==(r=Ht.state.activeCaipNetwork)?void 0:r.caipNetworkId)))return null;return await Jt.api.post({path:"/v1/onramp/quote",params:{projectId:Ke.state.projectId},body:{purchaseCurrency:e,paymentCurrency:t,amount:s,network:i}})}catch(wn){return{coinbaseFee:{amount:s,currency:t.id},networkFee:{amount:s,currency:t.id},paymentSubtotal:{amount:s,currency:t.id},paymentTotal:{amount:s,currency:t.id},purchaseAmount:{amount:s,currency:t.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(e){var t;return await Yt.isNetworkSupported(null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId)?Yt.get({path:`/v1/sessions/${e}`}):[]},async revokeSmartSession(e,t,s){var i;return await Yt.isNetworkSupported(null==(i=Ht.state.activeCaipNetwork)?void 0:i.caipNetworkId)?Jt.api.post({path:`/v1/sessions/${e}/revoke`,params:{projectId:Ke.state.projectId},body:{pci:t,signature:s}}):{success:!1}},setClientId(e){Jt.clientId=e,Jt.api=new We({baseUrl:Gt,clientId:e})}},Xt=Ue({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),Zt=et({state:Xt,replaceState(e){e&&Object.assign(Xt,Me(e))},subscribe:e=>Ht.subscribeChainProp("accountState",t=>{if(t)return e(t)}),subscribeKey(e,t,s){let i;return Ht.subscribeChainProp("accountState",s=>{if(s){const r=s[e];i!==r&&(i=r,t(r))}},s)},setStatus(e,t){Ht.setAccountProp("status",e,t)},getCaipAddress:e=>Ht.getAccountProp("caipAddress",e),setCaipAddress(e,t){const s=e?ze.getPlainAddress(e):void 0;t===Ht.state.activeChain&&(Ht.state.activeCaipAddress=e),Ht.setAccountProp("caipAddress",e,t),Ht.setAccountProp("address",s,t)},setBalance(e,t,s){Ht.setAccountProp("balance",e,s),Ht.setAccountProp("balanceSymbol",t,s)},setProfileName(e,t){Ht.setAccountProp("profileName",e,t)},setProfileImage(e,t){Ht.setAccountProp("profileImage",e,t)},setUser(e,t){Ht.setAccountProp("user",e,t)},setAddressExplorerUrl(e,t){Ht.setAccountProp("addressExplorerUrl",e,t)},setSmartAccountDeployed(e,t){Ht.setAccountProp("smartAccountDeployed",e,t)},setCurrentTab(e){Ht.setAccountProp("currentTab",e,Ht.state.activeChain)},setTokenBalance(e,t){e&&Ht.setAccountProp("tokenBalance",e,t)},setShouldUpdateToAddress(e,t){Ht.setAccountProp("shouldUpdateToAddress",e,t)},setAllAccounts(e,t){Ht.setAccountProp("allAccounts",e,t)}
2,addAddressLabel(e,t,s){const i=Ht.getAccountProp("addressLabels",s)||new Map;i.set(e,t),Ht.setAccountProp("addressLabels",i,s)},removeAddressLabel(e,t){const s=Ht.getAccountProp("addressLabels",t)||new Map;s.delete(e),Ht.setAccountProp("addressLabels",s,t)},setConnectedWalletInfo(e,t){Ht.setAccountProp("connectedWalletInfo",e,t,!1)},setPreferredAccountType(e,t){Ht.setAccountProp("preferredAccountTypes",{...Xt.preferredAccountTypes,[t]:e},t)},setPreferredAccountTypes(e){Xt.preferredAccountTypes=e},setSocialProvider(e,t){e&&Ht.setAccountProp("socialProvider",e,t)},setSocialWindow(e,t){Ht.setAccountProp("socialWindow",e?Me(e):void 0,t)},setFarcasterUrl(e,t){Ht.setAccountProp("farcasterUrl",e,t)},async fetchTokenBalance(e){var t,s;Xt.balanceLoading=!0;const i=null==(t=Ht.state.activeCaipNetwork)?void 0:t.caipNetworkId,r=null==(s=Ht.state.activeCaipNetwork)?void 0:s.chainNamespace,n=Ht.state.activeCaipAddress,o=n?ze.getPlainAddress(n):void 0;if(Xt.lastRetry&&!ze.isAllowedRetry(Xt.lastRetry,30*qe.ONE_SEC_MS))return Xt.balanceLoading=!1,[];try{if(o&&i&&r){const e=(await Yt.getBalance(o,i)).balances.filter(e=>"0"!==e.quantity.decimals);return Zt.setTokenBalance(e,r),Xt.lastRetry=void 0,Xt.balanceLoading=!1,e}}catch(a){Xt.lastRetry=Date.now(),null==e||e(a),Ot.showError("Token Balance Unavailable")}finally{Xt.balanceLoading=!1}return[]},resetAccount(e){Ht.resetAccount(e)}}),Qt={onSwitchNetwork({network:e,ignoreSwitchConfirmation:t=!1}){const s=Ht.state.activeCaipNetwork,i=bt.state.data;if(e.id===(null==s?void 0:s.id))return;const r=Zt.getCaipAddress(Ht.state.activeChain),n=e.chainNamespace!==Ht.state.activeChain,o=Zt.getCaipAddress(e.chainNamespace),a=St.getConnectorId(Ht.state.activeChain)===L.CONNECTOR_ID.AUTH,c=L.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(t=>t===e.chainNamespace);t||a&&c?bt.push("SwitchNetwork",{...i,network:e}):r&&n&&!o?bt.push("SwitchActiveChain",{switchToChain:e.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:e}):bt.push("SwitchNetwork",{...i,network:e})}},es=Ue({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),ts=et({state:es,subscribe:e=>$e(es,()=>e(es)),subscribeKey:(e,t)=>je(es,e,t),async open(e){var t,s;const i="connected"===Zt.state.status,r=null==e?void 0:e.namespace,n=Ht.state.activeChain,o=r&&r!==n,a=null==(t=Ht.getAccountData(null==e?void 0:e.namespace))?void 0:t.caipAddress;if($t.state.wcBasic?vt.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await vt.prefetch({fetchConnectorImages:!i,fetchFeaturedWallets:!i,fetchRecommendedWallets:!i}),St.setFilterByNamespace(null==e?void 0:e.namespace),ts.setLoading(!0,r),r&&o){const e=(null==(s=Ht.getNetworkData(r))?void 0:s.caipNetwork)||Ht.getRequestedCaipNetworks(r)[0];e&&Qt.onSwitchNetwork({network:e,ignoreSwitchConfirmation:!0})}else{const t=Ht.state.noAdapters;Ke.state.manualWCControl||t&&!a?ze.isMobile()?bt.reset("AllWallets"):bt.reset("ConnectingWalletConnectBasic"):(null==e?void 0:e.view)?bt.reset(e.view,e.data):a?bt.reset("Account"):bt.reset("Connect")}es.open=!0,Mt.set({open:!0}),gt.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:Boolean(a)}})},close(){const e=Ke.state.enableEmbedded,t=Boolean(Ht.state.activeCaipAddress);es.open&>.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:t}}),es.open=!1,bt.reset("Connect"),ts.clearLoading(),e?t?bt.replace("Account"):bt.push("Connect"):Mt.set({open:!1}),$t.resetUri()},setLoading(e,t){t&&es.loadingNamespaceMap.set(t,e),es.loading=e,Mt.set({loading:e})},clearLoading(){es.loadingNamespaceMap.clear(),es.loading=!1},shake(){es.shake||(es.shake=!0,setTimeout(()=>{es.shake=!1},500))}}),ss={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"}]},is={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},rs=Ue({providers:Le,selectedProvider:null,error:null,purchaseCurrency:ss,paymentCurrency:is,purchaseCurrencies:[ss],paymentCurrencies:[],quotesLoading:!1}),ns=et({state:rs,subscribe:e=>$e(rs,()=>e(rs)),subscribeKey:(e,t)=>je(rs,e,t),setSelectedProvider(e){if(e&&"meld"===e.name){const t=Ht.state.activeChain===L.CHAIN.SOLANA?"SOL":"USDC",s=Zt.state.address??"",i=new URL(e.url);i.searchParams.append("publicKey","WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU"),i.searchParams.append("destinationCurrencyCode",t),i.searchParams.append("walletAddress",s),i.searchParams.append("externalCustomerId",Ke.state.projectId),r
2s.selectedProvider={...e,url:i.toString()}}else rs.selectedProvider=e},setOnrampProviders(e){if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=e,s=Le.filter(e=>t.includes(e.name));rs.providers=s}else rs.providers=[]},setPurchaseCurrency(e){rs.purchaseCurrency=e},setPaymentCurrency(e){rs.paymentCurrency=e},setPurchaseAmount(e){ns.state.purchaseAmount=e},setPaymentAmount(e){ns.state.paymentAmount=e},async getAvailableCurrencies(){const e=await Yt.getOnrampOptions();rs.purchaseCurrencies=e.purchaseCurrencies,rs.paymentCurrencies=e.paymentCurrencies,rs.paymentCurrency=e.paymentCurrencies[0]||is,rs.purchaseCurrency=e.purchaseCurrencies[0]||ss,await vt.fetchCurrencyImages(e.paymentCurrencies.map(e=>e.id)),await vt.fetchTokenImages(e.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){var e,t;rs.quotesLoading=!0;try{const s=await Yt.getOnrampQuote({purchaseCurrency:rs.purchaseCurrency,paymentCurrency:rs.paymentCurrency,amount:(null==(e=rs.paymentAmount)?void 0:e.toString())||"0",network:null==(t=rs.purchaseCurrency)?void 0:t.symbol});return rs.quotesLoading=!1,rs.purchaseAmount=Number(null==s?void 0:s.purchaseAmount.amount),s}catch(s){return rs.error=s.message,rs.quotesLoading=!1,null}finally{rs.quotesLoading=!1}},resetState(){rs.selectedProvider=null,rs.error=null,rs.purchaseCurrency=ss,rs.paymentCurrency=is,rs.purchaseCurrencies=[ss],rs.paymentCurrencies=[],rs.paymentAmount=void 0,rs.purchaseAmount=void 0,rs.quotesLoading=!1}}),os=2147483648,as={convertEVMChainIdToCoinType(e){if(e>=os)throw new Error("Invalid chainId");return(os|e)>>>0}},cs=Ue({suggestions:[],loading:!1}),ls={state:cs,subscribe:e=>$e(cs,()=>e(cs)),subscribeKey:(e,t)=>je(cs,e,t),async resolveName(e){var t,s;try{return await Yt.lookupEnsName(e)}catch(wn){throw new Error((null==(s=null==(t=null==wn?void 0:wn.reasons)?void 0:t[0])?void 0:s.description)||"Error resolving name")}},async isNameRegistered(e){try{return await Yt.lookupEnsName(e),!0}catch{return!1}},async getSuggestions(e){try{cs.loading=!0,cs.suggestions=[];const t=await Yt.getEnsNameSuggestions(e);return cs.suggestions=t.suggestions.map(e=>({...e,name:e.name}))||[],cs.suggestions}catch(wn){const t=ds.parseEnsApiError(wn,"Error fetching name suggestions");throw new Error(t)}finally{cs.loading=!1}},async getNamesForAddress(e){try{if(!Ht.state.activeCaipNetwork)return[];const t=Be.getEnsFromCacheForAddress(e);if(t)return t;const s=await Yt.reverseLookupEnsName({address:e});return Be.updateEnsCache({address:e,ens:s,timestamp:Date.now()}),s}catch(wn){const t=ds.parseEnsApiError(wn,"Error fetching names for address");throw new Error(t)}},async registerName(e){const t=Ht.state.activeCaipNetwork;if(!t)throw new Error("Network not found");const s=Zt.state.address,i=St.getAuthConnector();if(!s||!i)throw new Error("Address or auth connector not found");cs.loading=!0;try{const i=JSON.stringify({name:e,attributes:{},timestamp:Math.floor(Date.now()/1e3)});bt.pushTransactionStack({onCancel(){bt.replace("RegisterAccountName")}});const r=await $t.signMessage(i);cs.loading=!1;const n=t.id;if(!n)throw new Error("Network not found");const o=as.convertEVMChainIdToCoinType(Number(n));await Yt.registerEnsName({coinType:o,address:s,signature:r,message:i}),Zt.setProfileName(e,t.chainNamespace),bt.replace("RegisterAccountNameSuccess")}catch(wn){const s=ds.parseEnsApiError(wn,`Error registering name ${e}`);throw bt.replace("RegisterAccountName"),new Error(s)}finally{cs.loading=!1}},validateName:e=>/^[a-zA-Z0-9-]{4,}$/u.test(e),parseEnsApiError(e,t){var s,i;return(null==(i=null==(s=null==e?void 0:e.reasons)?void 0:s[0])?void 0:i.description)||t}},ds=et(ls),us={getSIWX:()=>Ke.state.siwx,async initializeIfEnabled(){var e;const t=Ke.state.siwx,s=Ht.getActiveCaipAddress();if(!t||!s)return;const[i,r,n]=s.split(":");if(Ht.checkIfSupportedNetwork(i))try{if((await t.getSessions(`${i}:${r}`,n)).length)return;await ts.open({view:"SIWXSignMessage"})}catch(o){gt.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await(null==(e=$t._getClient())?void 0:e.disconnect().catch(console.error)),bt.reset("Connect"),Ot.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const e=Ke.state.siwx,t=ze.getPlainAddress(Ht.getActiveCaipAddress()),s=Ht.getActiveCaipNetwork(),i=$t._getClient();if(!e)throw new Error("SIWX is not enabled");if(!t)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!i)throw new Error("No ConnectionController client found");try{const r=await e.createMessage({chainId:s.caipNetworkId,accountAddress:t}),n=r.toString();St.getConnectorId(s.chainNamespace)===L.CONNECTOR_ID.AUTH&&bt.pushTransactionStack({});const o=await i.signMessage(n);await e.addSession({data:r,message:n,signature:o}),ts.close(),gt.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){const e=this.getSIWXEventProperties();ts.state.open&&"ApproveTransaction"!==bt.state.view||await ts.open({view:"SIWXSignMessage"}),e.isSmartAccount?Ot.showError("This application might not support Smart Accounts"):Ot.showError("Signature declined"),gt.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:e})}},async cancelSignMessage(){var e;try{const t=this.getSIWX();(null==(e=null==t?void 0:t.getRequired)?void 0:e.call(t))?await $t.disconnect():ts.close(),bt.reset("Connect"),gt.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){}},async getSessions(){const e=Ke.state.siwx,t=ze.getPlainAddress(Ht.getActiveCaipAddress()),s=Ht.getActiveCaipNetwork();return e&&t&&s?e.getSessions(s.caipNetworkId,t):[]},async isSIWXCloseDisabled(){var e;const t=this.getSIWX();if(t){const s="ApproveTransaction"===bt.state.view,i="SIWXSignMessage"===bt.state.view;if(s||i)return(null==(e=t.getRequired)?void 0:e.call(t))&&0===(await this.get
2Sessions()).length}return!1},async universalProviderAuthenticate({universalProvider:e,chains:t,methods:s}){var i,r,n;const o=us.getSIWX(),a=new Set(t.map(e=>e.split(":")[0]));if(!o||1!==a.size||!a.has("eip155"))return!1;const c=await o.createMessage({chainId:(null==(i=Ht.getActiveCaipNetwork())?void 0:i.caipNetworkId)||"",accountAddress:""}),l=await e.authenticate({nonce:c.nonce,domain:c.domain,uri:c.uri,exp:c.expirationTime,iat:c.issuedAt,nbf:c.notBefore,requestId:c.requestId,version:c.version,resources:c.resources,statement:c.statement,chainId:c.chainId,methods:s,chains:[c.chainId,...t.filter(e=>e!==c.chainId)]});if(Ot.showLoading("Authenticating...",{autoClose:!1}),Zt.setConnectedWalletInfo({...l.session.peer.metadata,name:l.session.peer.metadata.name,icon:null==(r=l.session.peer.metadata.icons)?void 0:r[0],type:"WALLET_CONNECT"},Array.from(a)[0]),null==(n=null==l?void 0:l.auths)?void 0:n.length){const t=l.auths.map(t=>{const s=e.client.formatAuthMessage({request:t.p,iss:t.p.iss});return{data:{...t.p,accountAddress:t.p.iss.split(":").slice(-1).join(""),chainId:t.p.iss.split(":").slice(2,4).join(":"),uri:t.p.aud,version:t.p.version||c.version,expirationTime:t.p.exp,issuedAt:t.p.iat,notBefore:t.p.nbf},message:s,signature:t.s.s,cacao:t}});try{await o.setSessions(t),gt.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:us.getSIWXEventProperties()})}catch(d){throw gt.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:us.getSIWXEventProperties()}),await e.disconnect().catch(console.error),d}finally{Ot.hide()}}return!0},getSIWXEventProperties(){var e,t;const s=Ht.state.activeChain;return{network:(null==(e=Ht.state.activeCaipNetwork)?void 0:e.caipNetworkId)||"",isSmartAccount:(null==(t=Zt.state.preferredAccountTypes)?void 0:t[s])===Pt.SMART_ACCOUNT}},async clearSessions(){const e=this.getSIWX();e&&await e.setSessions([])}};var hs=Object.defineProperty,ps=(e,t,s)=>((e,t,s)=>t in e?hs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let gs=class extends s{constructor(e){super(),this.opts=e,ps(this,"protocol","wc"),ps(this,"version",2)}};var fs=Object.defineProperty,ms=(e,t,s)=>((e,t,s)=>t in e?fs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,t+"",s);let ws=class extends s{constructor(e,t){super(),this.core=e,this.logger=t,ms(this,"records",new Map)}},vs=class{constructor(e,t){this.logger=e,this.core=t}},ys=class extends s{constructor(e,t){super(),this.relayer=e,this.logger=t}},bs=class extends s{constructor(e){super()}},Es=class{constructor(e,t,s,i){this.core=e,this.logger=t,this.name=s}},Cs=class extends s{constructor(e,t){super(),this.relayer=e,this.logger=t}},Is=class extends s{constructor(e,t){super(),this.core=e,this.logger=t}},Ns=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},As=class{constructor(e,t){this.projectId=e,this.logger=t}},Ss=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var Ps=Object.defineProperty,ks=(e,t,s)=>((e,t,s)=>t in e?Ps(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let _s=class{constructor(e){this.opts=e,ks(this,"protocol","wc"),ks(this,"version",2)}},Os=class{constructor(e){this.client=e}};function xs(e,{strict:t=!0}={}){return!!e&&("string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")))}function Ts(e){return xs(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const Rs="2.23.2";let Us={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:s})=>t?`${e??"https://viem.sh"}${t}${s?`#${s}`:""}`:void 0,version:`viem@${Rs}`},$s=class e extends Error{constructor(t,s={}){var i;const r=s.cause instanceof e?s.cause.details:(null==(n=s.cause)?void 0:n.message)?s.cause.message:s.details;var n;const o=s.cause instanceof e&&s.cause.docsPath||s.docsPath,a=null==(i=Us.getDocsUrl)?void 0:i.call(Us,{...s,docsPath:o});super([t||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...a?[`Docs: ${a}`]:[],...r?[`Details: ${r}`]:[],...Us.version?[`Version: ${Us.version}`]:[]].join("\n"),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=o,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=t,this.version=Rs}walk(e){return Ds(this,e)}};function Ds(e,t){return(null==t?void 0:t(e))?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?Ds(e.cause,t):t?null:e}let Ms=class extends $s{constructor({size:e,targetSize:t,type:s}){super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};function js(e,{dir:t,size:s=32}={}){return"string"==typeof e?function(e,{dir:t,size:s=32}={}){if(null===s)return e;const i=e.replace("0x","");if(i.length>2*s)throw new Ms({size:Math.ceil(i.length/2),targetSize:s,type:"hex"});return`0x${i["right"===t?"padEnd":"padStart"](2*s,"0")}`}(e,{dir:t,size:s}):function(e,{dir:t,size:s=32}={}){if(null===s)return e;if(e.length>s)throw new Ms({size:e.length,targetSize:s,type:"bytes"});const i=new Uint8Array(s);for(let r=0;r<s;r++){const n="right"===t;i[n?r:s-r-1]=e[n?r:e.length-r-1]}return i}(e,{dir:t,size:s})}let Ls=class extends $s{constructor({max:e,min:t,signed:s,size:i,value:r}){super(`Number "${r}" is not in safe ${i?`${8*i}-bit ${s?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}},qs=class extends $s{constructor({givenSize:e,maxSize:t}
vendor: 5,087 bytes, line 2
2){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function Bs(e,{size:t}){if(Ts(e)>t)throw new qs({givenSize:Ts(e),maxSize:t})}function zs(e,t={}){const{signed:s}=t;t.size&&Bs(e,{size:t.size});const i=BigInt(e);if(!s)return i;const r=(e.length-2)/2;return i<=(1n<<8n*BigInt(r)-1n)-1n?i:i-BigInt(`0x${"f".padStart(2*r,"f")}`)-1n}const Fs=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ws(e,t={}){return"number"==typeof e||"bigint"==typeof e?Hs(e,t):"string"==typeof e?function(e,t={}){const s=Ks.encode(e);return Vs(s,t)}(e,t):"boolean"==typeof e?function(e,t={}){const s=`0x${Number(e)}`;if("number"==typeof t.size)return Bs(s,{size:t.size}),js(s,{size:t.size});return s}(e,t):Vs(e,t)}function Vs(e,t={}){let s="";for(let r=0;r<e.length;r++)s+=Fs[e[r]];const i=`0x${s}`;return"number"==typeof t.size?(Bs(i,{size:t.size}),js(i,{dir:"right",size:t.size})):i}function Hs(e,t={}){const{signed:s,size:i}=t,r=BigInt(e);let n;i?n=s?(1n<<8n*BigInt(i)-1n)-1n:2n**(8n*BigInt(i))-1n:"number"==typeof e&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof n&&s?-n-1n:0;if(n&&r>n||r<o){const t="bigint"==typeof e?"n":"";throw new Ls({max:n?`${n}${t}`:void 0,min:`${o}${t}`,signed:s,size:i,value:`${e}${t}`})}const a=`0x${(s&&r<0?(1n<<BigInt(8*i))+BigInt(r):r).toString(16)}`;return i?js(a,{size:i}):a}const Ks=new TextEncoder;const Gs=new TextEncoder;function Js(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){const s=Hs(e,t);return Zs(s)}(e,t):"boolean"==typeof e?function(e,t={}){const s=new Uint8Array(1);if(s[0]=Number(e),"number"==typeof t.size)return Bs(s,{size:t.size}),js(s,{size:t.size});return s}(e,t):xs(e)?Zs(e,t):Qs(e,t)}const Ys={zero:48,nine:57,A:65,F:70,a:97,f:102};function Xs(e){return e>=Ys.zero&&e<=Ys.nine?e-Ys.zero:e>=Ys.A&&e<=Ys.F?e-(Ys.A-10):e>=Ys.a&&e<=Ys.f?e-(Ys.a-10):void 0}function Zs(e,t={}){let s=e;t.size&&(Bs(s,{size:t.size}),s=js(s,{dir:"right",size:t.size}));let i=s.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const e=Xs(i.charCodeAt(a++)),t=Xs(i.charCodeAt(a++));if(void 0===e||void 0===t)throw new $s(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=16*e+t}return n}function Qs(e,t={}){const s=Gs.encode(e);return"number"==typeof t.size?(Bs(s,{size:t.size}),js(s,{dir:"right",size:t.size})):s}function ei(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ti(e,...t){if(!((s=e)instanceof Uint8Array||ArrayBuffer.isView(s)&&"Uint8Array"===s.constructor.name))throw new Error("Uint8Array expected");var s;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function si(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");ei(e.outputLen),ei(e.blockLen)}function ii(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ri(e,t){ti(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const ni=BigInt(2**32-1),oi=BigInt(32);function ai(e,t=!1){return t?{h:Number(e&ni),l:Number(e>>oi&ni)}:{h:0|Number(e>>oi&ni),l:0|Number(e&ni)}}function ci(e,t=!1){let s=new Uint32Array(e.length),i=new Uint32Array(e.length);for(let r=0;r<e.length;r++){const{h:n,l:o}=ai(e[r],t);[s[r],i[r]]=[n,o]}return[s,i]}const li="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function di(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ui(e,t){return e<<32-t|e>>>t}const hi=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function pi(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function gi(e){for(let t=0;t<e.length;t++)e[t]=pi(e[t])}function fi(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),ti(e),e}function mi(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];ti(s),t+=s.length}const s=new Uint8Array(t);for(let i=0,r=0;i<e.length;i++){const t=e[i];s.set(t,r),r+=t.length}return s}class wi{clone(){return this._cloneInto()}}function vi(e){const t=t=>e().update(fi(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}function yi(e=32){if(li&&"function"==typeof li.getRandomValues)return li.getRandomValues(new Uint8Array(e));if(li&&"function"==typeof li.randomBytes)return li.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}const bi=[],Ei=[],Ci=[],Ii=BigInt(0),Ni=BigInt(1),Ai=BigInt(2),Si=BigInt(7),Pi=BigInt(256),ki=BigInt(113);for(let xb=0,Tb=Ni,Rb=1,Ub=0;xb<24;xb++){[Rb,Ub]=[Ub,(2*Rb+3*Ub)%5],bi.push(2*(5*Ub+Rb)),Ei.push((xb+1)*(xb+2)/2%64);let e=Ii;for(let t=0;t<7;t++)Tb=(Tb<<Ni^(Tb>>Si)*ki)%Pi,Tb&Ai&&(e^=Ni<<(Ni<<BigInt(t))-Ni);Ci.push(e)}const[_i,Oi]=ci(Ci,!0),xi=(e,t,s)=>s>
232?((e,t,s)=>t<<s-32|e>>>64-s)(e,t,s):((e,t,s)=>e<<s|t>>>32-s)(e,t,s),Ti=(e,t,s)=>s>32?((e,t,s)=>e<<s-32|t>>>64-s)(e,t,s):((e,t,s)=>t<<s|e>>>32-s)(e,t,s);class Ri extends wi{constructor(e,t,s,i=!1,r=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=i,this.rounds=r,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ei(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function"); 3/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ 4var n;this.state=new Uint8Array(200),this.state32=(n=this.state,new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)))}keccak(){hi||gi(this.state32),function(e,t=24){const s=new Uint32Array(10);for(let i=24-t;i<24;i++){for(let i=0;i<10;i++)s[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){const t=(i+8)%10,r=(i+2)%10,n=s[r],o=s[r+1],a=xi(n,o,1)^s[t],c=Ti(n,o,1)^s[t+1];for(let s=0;s<50;s+=10)e[i+s]^=a,e[i+s+1]^=c}let t=e[2],r=e[3];for(let s=0;s<24;s++){const i=Ei[s],n=xi(t,r,i),o=Ti(t,r,i),a=bi[s];t=e[a],r=e[a+1],e[a]=n,e[a+1]=o}for(let i=0;i<50;i+=10){for(let t=0;t<10;t++)s[t]=e[i+t];for(let t=0;t<10;t++)e[i+t]^=~s[(t+2)%10]&s[(t+4)%10]}e[0]^=_i[i],e[1]^=Oi[i]}s.fill(0)}(this.state32,this.rounds),hi||gi(this.state32),this.posOut=0,this.pos=0}update(e){ii(this);const{blockLen:t,state:s}=this,i=(e=fi(e)).length;for(let r=0;r<i;){const n=Math.min(t-this.pos,i-r);for(let t=0;t<n;t++)s[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:s,blockLen:i}=this;e[s]^=t,128&t&&s===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){ii(this,!1),ti(e),this.finish();const t=this.state,{blockLen:s}=this;for(let i=0,r=e.length;i<r;){this.posOut>=s&&this.keccak();const n=Math.min(s-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+n),i),this.posOut+=n,i+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ei(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ri(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:t,suffix:s,outputLen:i,rounds:r,enableXOF:n}=this;return e||(e=new Ri(t,s,i,n,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=s,e.outputLen=i,e.enableXOF=n,e.destroyed=this.destroyed,e}}const Ui=((e,t,s)=>vi(()=>new Ri(t,e,s)))(1,136,32);function $i(e,t){const s=t||"hex",i=Ui(xs(e,{strict:!1})?Js(e):e);return"bytes"===s?i:Ws(i)}const Di=new 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 t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}(8192);function Mi(e){return function(e,t){if(Di.has(`${e}.${t}`))return Di.get(`${e}.${t}`);const s=e.substring(2).toLowerCase(),i=$i(Qs(s),"bytes"),r=s.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(15&i[o>>1])>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Di.set(`${e}.${t}`,n),n}(`0x${$i(`0x${e.substring(4)}`).substring(26)}`)}async function ji({hash:e,signature:s}){const i=xs(e)?e:Ws(e),{secp256k1:r}=await t(async()=>{const{secp256k1:e}=await import("./secp256k1.js-Cwel67ap.js");return{secp256k1:e}},__vite__mapDeps([0,1,2,3,4]));return`0x${(()=>{if("object"==typeof s&&"r"in s&&"s"in s){const{r:e,s:t,v:i,yParity:n}=s,o=Li(Number(n??i));return new r.Signature(zs(e),zs(t)).addRecoveryBit(o)}const e=xs(s)?s:Ws(s),t=Li(function(e,t={}){return Number(zs(e,t))}(`0x${e.slice(130)}`));return r.Signature.fromCompact(e.substring(2,130)).addRecoveryBit(t)})().recoverPublicKey(i.substring(2)).toHex(!1)}`}function Li(e){if(0===e||1===e)return e;if(27===e)return 0;if(28===e)return 1;throw new Error("Invalid yParityOrV value")}function qi(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?globalThis.Buffer.allocUnsafe(e):new Uint8Array(e)}function Bi(e,t){t||(t=e.reduce((e,t)=>
4e+t.length,0));const s=qi(t);let i=0;for(const r of e)s.set(r,i),i+=r.length;return s}function zi(e,t,s,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:s},decoder:{decode:i}}}const Fi=zi("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),Wi=zi("ascii","a",e=>{let t="a";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return t},e=>{const t=qi((e=e.substring(1)).length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}),Vi={utf8:Fi,"utf-8":Fi,hex:i.base16,latin1:Wi,ascii:Wi,binary:Wi,...i};function Hi(e,t="utf8"){const s=Vi[t];if(!s)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?s.decoder.decode(`${s.prefix}${e}`):globalThis.Buffer.from(e,"utf8")}function Ki(e,t="utf8"){const s=Vi[t];if(!s)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?s.encoder.encode(e).substring(1):globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}var Gi={};function Ji(e){const[t,s]=e.split(":");return{namespace:t,reference:s}}function Yi(e,t){return e.includes(":")?[e]:t.chains||[]}var Xi=Object.defineProperty,Zi=Object.defineProperties,Qi=Object.getOwnPropertyDescriptors,er=Object.getOwnPropertySymbols,tr=Object.prototype.hasOwnProperty,sr=Object.prototype.propertyIsEnumerable,ir=(e,t,s)=>t in e?Xi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,rr=(e,t)=>{for(var s in t||(t={}))tr.call(t,s)&&ir(e,s,t[s]);if(er)for(var s of er(t))sr.call(t,s)&&ir(e,s,t[s]);return e};const nr="react-native",or="node",ar="browser",cr="unknown",lr="js";function dr(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function ur(){return!o.getDocument()&&!!o.getNavigator()&&"ReactNative"===navigator.product}function hr(){return!dr()&&!!o.getNavigator()&&!!o.getDocument()}function pr(){return ur()?nr:dr()?or:hr()?ar:cr}function gr(){var e;try{return ur()&&typeof global<"u"&&typeof(null==global?void 0:global.Application)<"u"?null==(e=global.Application)?void 0:e.applicationId:void 0}catch{return}}function fr(e){var t,s;const i=mr();try{return null!=e&&e.url&&i.url&&new URL(e.url).host!==new URL(i.url).host&&(e.url=i.url),null!=(t=null==e?void 0:e.icons)&&t.length&&e.icons.length>0&&(e.icons=e.icons.filter(e=>""!==e)),((e,t)=>Zi(e,Qi(t)))(rr(rr({},i),e),{url:(null==e?void 0:e.url)||i.url,name:(null==e?void 0:e.name)||i.name,description:(null==e?void 0:e.description)||i.description,icons:null!=(s=null==e?void 0:e.icons)&&s.length&&e.icons.length>0?e.icons:i.icons})}catch(r){return e||i}}function mr(){return r.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function wr(e,t,s){const i=function(){if(pr()===nr&&typeof global<"u"&&typeof(null==global?void 0:global.Platform)<"u"){const{OS:e,Version:t}=global.Platform;return[e,t].join("-")}const e=c();if(null===e)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[t,e.name,e.version].join("-"):[t,e.version].join("-")}(),r=function(){var e;const t=pr();return t===ar?[t,(null==(e=o.getLocation())?void 0:e.host)||"unknown"].join(":"):t}();return[[e,t].join("-"),[lr,s].join("-"),i,r].join("/")}function vr({protocol:e,version:t,relayUrl:s,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d={auth:r,ua:wr(e,t,i),projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},u=function(e,t){const s=new URLSearchParams(e);for(const i of Object.keys(t).sort())if(t.hasOwnProperty(i)){const e=t[i];void 0!==e&&s.set(i,e)}return s.toString()}(l[1]||"",d);return l[0]+"?"+u}function yr(e,t){return e.filter(e=>t.includes(e)).length===e.length}function br(e){return Object.fromEntries(e.entries())}function Er(e){return new Map(Object.entries(e))}function Cr(e=n.FIVE_MINUTES,t){const s=n.toMiliseconds(e||n.FIVE_MINUTES);let i,r,o,a;return{resolve:e=>{o&&i&&(clearTimeout(o),i(e),a=Promise.resolve(e))},reject:e=>{o&&r&&(clearTimeout(o),r(e))},done:()=>
4new Promise((e,n)=>{if(a)return e(a);o=setTimeout(()=>{const e=new Error(t);a=Promise.reject(e),n(e)},s),i=e,r=n})}}function Ir(e,t,s){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(s)),t);try{i(await e)}catch(o){r(o)}clearTimeout(n)})}function Nr(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function Ar(e){const[t,s]=e.split(":"),i={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof s)i.topic=s;else{if("id"!==t||!Number.isInteger(Number(s)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${s}`);i.id=Number(s)}return i}function Sr(e,t){return n.fromMiliseconds(Date.now()+n.toMiliseconds(e))}function Pr(e){return Date.now()>=n.toMiliseconds(e)}function kr(e,t){return`${e}${t?`:${t}`:""}`}function _r(e=[],t=[]){return[...new Set([...e,...t])]}async function Or({id:e,topic:t,wcDeepLink:s}){var i;try{if(!s)return;const r="string"==typeof s?JSON.parse(s):s,n=null==r?void 0:r.href;if("string"!=typeof n)return;const a=function(e,t,s){const i=`requestId=${t}&sessionTopic=${s}`;e.endsWith("/")&&(e=e.slice(0,-1));let r=`${e}`;if(e.startsWith("https://t.me")){r=`${r}${e.includes("?")?"&startapp=":"?startapp="}${function(e,t=!1){const s=Buffer.from(e).toString("base64");return t?s.replace(/[=]/g,""):s}(i,!0)}`}else r=`${r}/wc?${i}`;return r}(n,e,t),c=pr();if(c===ar){if(null==(i=o.getDocument())||!i.hasFocus())return;!function(e){let t="_self";!function(){try{return window.self!==window.top}catch{return!1}}()?(typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"):t="_top",window.open(e,t,"noreferrer noopener")}(a)}else c===nr&&typeof(null==global?void 0:global.Linking)<"u"&&await global.Linking.openURL(a)}catch(r){}}function xr(e,t){if(!e.includes(t))return null;const s=e.split(/([&,?,=])/),i=s.indexOf(t);return s[i+2]}function Tr(){return typeof crypto<"u"&&null!=crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function Rr(){return typeof process<"u"&&"true"===Gi.IS_VITEST}function Ur(e){return Buffer.from(e,"base64").toString("utf-8")}function $r(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Dr(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Mr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");$r(e.outputLen),$r(e.blockLen)}function jr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Lr(e,t){Dr(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const qr=BigInt(2**32-1),Br=BigInt(32);function zr(e,t=!1){return t?{h:Number(e&qr),l:Number(e>>Br&qr)}:{h:0|Number(e>>Br&qr),l:0|Number(e&qr)}}const Fr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Wr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Vr(e,t){return e<<32-t|e>>>t}const Hr=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function Kr(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Gr(e){for(let t=0;t<e.length;t++)e[t]=Kr(e[t])}function Jr(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),Dr(e),e}let Yr=class{clone(){return this._cloneInto()}};function Xr(e){const t=t=>e().update(Jr(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}function Zr(e=32){if(Fr&&"function"==typeof Fr.getRandomValues)return Fr.getRandomValues(new Uint8Array(e));if(Fr&&"function"==typeof Fr.randomBytes)return Fr.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}const Qr=[],en=[],tn=[],sn=BigInt(0),rn=BigInt(1),nn=BigInt(2),on=BigInt(7),an=BigInt(256),cn=BigInt(113);for(let xb=0,Tb=rn,Rb=1,Ub=0;xb<24;xb++){[Rb,Ub]=[Ub,(2*Rb+3*Ub)%5],Qr.push(2*(5*Ub+Rb)),en.push((xb+1)*(xb+2)/2%64);let e=sn;for(let t=0;t<7;t++)Tb=(Tb<<rn^(Tb>>on)*cn)%an,Tb&nn&&(e^=rn<<(rn<<BigInt(t))-rn);tn.push(e)}const[ln,dn]=function(e,t=!1){let s=new Uint32Array(e.length),i=new Uint32Array(e.length);for(let r=0;r<e.length;r++){const{h:n,l:o}=zr(e[r],t);[s[r],i[r]]=[n,o]}return[s,i]}(tn,!0),un=(e,t,s)=>s>
432?((e,t,s)=>t<<s-32|e>>>64-s)(e,t,s):((e,t,s)=>e<<s|t>>>32-s)(e,t,s),hn=(e,t,s)=>s>32?((e,t,s)=>e<<s-32|t>>>64-s)(e,t,s):((e,t,s)=>t<<s|e>>>32-s)(e,t,s);let pn=class e extends Yr{constructor(e,t,s,i=!1,r=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=i,this.rounds=r,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,$r(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");var n;this.state=new Uint8Array(200),this.state32=(n=this.state,new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)))}keccak(){Hr||Gr(this.state32),function(e,t=24){const s=new Uint32Array(10);for(let i=24-t;i<24;i++){for(let i=0;i<10;i++)s[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){const t=(i+8)%10,r=(i+2)%10,n=s[r],o=s[r+1],a=un(n,o,1)^s[t],c=hn(n,o,1)^s[t+1];for(let s=0;s<50;s+=10)e[i+s]^=a,e[i+s+1]^=c}let t=e[2],r=e[3];for(let s=0;s<24;s++){const i=en[s],n=un(t,r,i),o=hn(t,r,i),a=Qr[s];t=e[a],r=e[a+1],e[a]=n,e[a+1]=o}for(let i=0;i<50;i+=10){for(let t=0;t<10;t++)s[t]=e[i+t];for(let t=0;t<10;t++)e[i+t]^=~s[(t+2)%10]&s[(t+4)%10]}e[0]^=ln[i],e[1]^=dn[i]}s.fill(0)}(this.state32,this.rounds),Hr||Gr(this.state32),this.posOut=0,this.pos=0}update(e){jr(this);const{blockLen:t,state:s}=this,i=(e=Jr(e)).length;for(let r=0;r<i;){const n=Math.min(t-this.pos,i-r);for(let t=0;t<n;t++)s[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:s,blockLen:i}=this;e[s]^=t,!!(128&t)&&s===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){jr(this,!1),Dr(e),this.finish();const t=this.state,{blockLen:s}=this;for(let i=0,r=e.length;i<r;){this.posOut>=s&&this.keccak();const n=Math.min(s-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+n),i),this.posOut+=n,i+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return $r(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Lr(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(t){const{blockLen:s,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return t||(t=new e(s,i,r,o,n)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=n,t.suffix=i,t.outputLen=r,t.enableXOF=o,t.destroyed=this.destroyed,t}};const gn=(mn=1,wn=136,vn=32,Xr(()=>new pn(wn,mn,vn))),fn="https://rpc.walletconnect.org/v1";var mn,wn,vn;function yn(e){const t=`�Ethereum Signed Message:\n${e.length}`,s=(new TextEncoder).encode(t+e);return"0x"+Buffer.from(gn(s)).toString("hex")}async function bn(e,t,s,i,r,n){switch(s.t){case"eip191":return await async function(e,t,s){return(await async function({hash:e,signature:t}){return Mi(await ji({hash:e,signature:t}))}({hash:yn(t),signature:s})).toLowerCase()===e.toLowerCase()}(e,t,s.s);case"eip1271":return await async function(e,t,s,i,r,n){const o=Ji(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const o="0x1626ba7e",a="0000000000000000000000000000000000000000000000000000000000000040",c="0000000000000000000000000000000000000000000000000000000000000041",l=s.substring(2),d=o+yn(t).substring(2)+a+c+l,u=await fetch(`${n||fn}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:En(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:d},"latest"]})}),{result:h}=await u.json();return!!h&&h.slice(0,o.length).toLowerCase()===o.toLowerCase()}catch(a){return!1}}(e,t,s.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}function En(){return Date.now()+Math.floor(1e3*Math.random())}var Cn=Object.defineProperty,In=Object.defineProperties,Nn=Object.getOwnPropertyDescriptors,An=Object.getOwnPropertySymbols,Sn=Object.prototype.hasOwnProperty,Pn=Object.prototype.propertyIsEnumerable,kn=(e,t,s)=>t in e?Cn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;const _n=e=>null==e?void 0:e.split(":"),On=e=>{const t=e&&_n(e);if(t)return t[2]+":"+t[3]},xn=e=>{const t=e&&_n(e);if(t)return t.pop()};async function Tn(e){const{cacao:t,projectId:s}=e,{s:i,p:r}=t,n=Rn(r,r.iss),o=xn(r.iss);return await bn(o,n,i,On(r.iss),s)}const Rn=(e,t)=>{const s=`${e.domain} wants you to sign in with your Ethereum account:`,i=xn(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=e.statement||void 0;const n=`URI: ${e.aud||e.uri}
4`,o=`Version: ${e.version}`,a=`Chain ID: ${(e=>{const t=e&&_n(e);if(t)return e.includes("did:pkh:")?t[3]:t[1]})(t)}`,c=`Nonce: ${e.nonce}`,l=`Issued At: ${e.iat}`,d=e.exp?`Expiration Time: ${e.exp}`:void 0,u=e.nbf?`Not Before: ${e.nbf}`:void 0,h=e.requestId?`Request ID: ${e.requestId}`:void 0,p=e.resources?`Resources:${e.resources.map(e=>`\n- ${e}`).join("")}`:void 0,g=zn(e.resources);if(g){r=function(e="",t){Un(t);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(s))return e;const i=[];let r=0;Object.keys(t.att).forEach(e=>{const s=Object.keys(t.att[e]).map(e=>({ability:e.split("/")[0],action:e.split("/")[1]}));s.sort((e,t)=>e.action.localeCompare(t.action));const n={};s.forEach(e=>{n[e.ability]||(n[e.ability]=[]),n[e.ability].push(e.action)});const o=Object.keys(n).map(t=>(r++,`(${r}) '${t}': '${n[t].join("', '")}' for '${e}'.`));i.push(o.join(", ").replace(".,","."))});const n=i.join(" "),o=`${s}${n}`;return`${e?e+" ":""}${o}`}(r,Mn(g))}return[s,i,"",r,"",n,o,a,c,l,d,u,h,p].filter(e=>null!=e).join("\n")};function Un(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(null==t||!t.length)throw new Error("No resources found in `att` property");t.forEach(t=>{const s=e.att[t];if(Array.isArray(s))throw new Error(`Resource must be an object: ${t}`);if("object"!=typeof s)throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(s).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(s).forEach(e=>{const t=s[e];if(!Array.isArray(t))throw new Error(`Ability limits ${e} must be an array of objects, found: ${t}`);if(!t.length)throw new Error(`Value of ${e} is empty array, must be an array with objects`);t.forEach(t=>{if("object"!=typeof t)throw new Error(`Ability limits (${e}) must be an array of objects, found: ${t}`)})})})}function $n(e,t,s={}){const i=(t=null==t?void 0:t.sort((e,t)=>e.localeCompare(t))).map(t=>({[`${e}/${t}`]:[s]}));return Object.assign({},...i)}function Dn(e){return Un(e),`urn:recap:${function(e){return Buffer.from(JSON.stringify(e)).toString("base64")}(e).replace(/=/g,"")}`}function Mn(e){const t=function(e){return JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}(e.replace("urn:recap:",""));return Un(t),t}function jn(e,t,s){const i=function(e,t,s,i={}){return null==s||s.sort((e,t)=>e.localeCompare(t)),{att:{[e]:$n(t,s,i)}}}(e,t,s);return Dn(i)}function Ln(e,t){const s=function(e,t){Un(e),Un(t);const s=Object.keys(e.att).concat(Object.keys(t.att)).sort((e,t)=>e.localeCompare(t)),i={att:{}};return s.forEach(s=>{var r,n;Object.keys((null==(r=e.att)?void 0:r[s])||{}).concat(Object.keys((null==(n=t.att)?void 0:n[s])||{})).sort((e,t)=>e.localeCompare(t)).forEach(r=>{var n,o;i.att[s]=((e,t)=>In(e,Nn(t)))(((e,t)=>{for(var s in t||(t={}))Sn.call(t,s)&&kn(e,s,t[s]);if(An)for(var s of An(t))Pn.call(t,s)&&kn(e,s,t[s]);return e})({},i.att[s]),{[r]:(null==(n=e.att[s])?void 0:n[r])||(null==(o=t.att[s])?void 0:o[r])})})}),i}(Mn(e),Mn(t));return Dn(s)}function qn(e){var t;const s=Mn(e);Un(s);const i=null==(t=s.att)?void 0:t.eip155;return i?Object.keys(i).map(e=>e.split("/")[1]):[]}function Bn(e){const t=Mn(e);Un(t);const s=[];return Object.values(t.att).forEach(e=>{Object.values(e).forEach(e=>{var t;null!=(t=null==e?void 0:e[0])&&t.chains&&s.push(e[0].chains)})}),[...new Set(s.flat())]}function zn(e){if(!e)return;const t=null==e?void 0:e[e.length-1];return function(e){return e&&e.includes("urn:recap:")}(t)?t:void 0}function Fn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Wn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Vn(e,...t){if(!Wn(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Hn(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Kn(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}const Gn=e=>
4new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw new Error("Non little-endian hardware is not supported");function Jn(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Wn(e))throw new Error("Uint8Array expected, got "+typeof e);e=Zn(e)}return e}function Yn(e,t,s=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(s&&!function(e){return e.byteOffset%4==0}(t))throw new Error("invalid output, must be aligned");return t}function Xn(e,t,s,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(s>>r&n),a=Number(s&n);e.setUint32(t+4,o,i),e.setUint32(t+0,a,i)}function Zn(e){return Uint8Array.from(e)}function Qn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const eo=e=>Uint8Array.from(e.split("").map(e=>e.charCodeAt(0))),to=eo("expand 16-byte k"),so=eo("expand 32-byte k"),io=Gn(to),ro=Gn(so);function no(e,t){return e<<t|e>>>32-t}function oo(e){return e.byteOffset%4==0}const ao=2**32-1,co=new Uint32Array;const lo=(e,t)=>255&e[t++]|(255&e[t++])<<8;class uo{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,Vn(e=Jn(e),32);const t=lo(e,0),s=lo(e,2),i=lo(e,4),r=lo(e,6),n=lo(e,8),o=lo(e,10),a=lo(e,12),c=lo(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|s<<3),this.r[2]=7939&(s>>>10|i<<6),this.r[3]=8191&(i>>>7|r<<9),this.r[4]=255&(r>>>4|n<<12),this.r[5]=n>>>1&8190,this.r[6]=8191&(n>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let l=0;l<8;l++)this.pad[l]=lo(e,16+2*l)}process(e,t,s=!1){const i=s?0:2048,{h:r,r:n}=this,o=n[0],a=n[1],c=n[2],l=n[3],d=n[4],u=n[5],h=n[6],p=n[7],g=n[8],f=n[9],m=lo(e,t+0),w=lo(e,t+2),v=lo(e,t+4),y=lo(e,t+6),b=lo(e,t+8),E=lo(e,t+10),C=lo(e,t+12),I=lo(e,t+14);let N=r[0]+(8191&m),A=r[1]+(8191&(m>>>13|w<<3)),S=r[2]+(8191&(w>>>10|v<<6)),P=r[3]+(8191&(v>>>7|y<<9)),k=r[4]+(8191&(y>>>4|b<<12)),_=r[5]+(b>>>1&8191),O=r[6]+(8191&(b>>>14|E<<2)),x=r[7]+(8191&(E>>>11|C<<5)),T=r[8]+(8191&(C>>>8|I<<8)),R=r[9]+(I>>>5|i),U=0,$=U+N*o+A*(5*f)+S*(5*g)+P*(5*p)+k*(5*h);U=$>>>13,$&=8191,$+=_*(5*u)+O*(5*d)+x*(5*l)+T*(5*c)+R*(5*a),U+=$>>>13,$&=8191;let D=U+N*a+A*o+S*(5*f)+P*(5*g)+k*(5*p);U=D>>>13,D&=8191,D+=_*(5*h)+O*(5*u)+x*(5*d)+T*(5*l)+R*(5*c),U+=D>>>13,D&=8191;let M=U+N*c+A*a+S*o+P*(5*f)+k*(5*g);U=M>>>13,M&=8191,M+=_*(5*p)+O*(5*h)+x*(5*u)+T*(5*d)+R*(5*l),U+=M>>>13,M&=8191;let j=U+N*l+A*c+S*a+P*o+k*(5*f);U=j>>>13,j&=8191,j+=_*(5*g)+O*(5*p)+x*(5*h)+T*(5*u)+R*(5*d),U+=j>>>13,j&=8191;let L=U+N*d+A*l+S*c+P*a+k*o;U=L>>>13,L&=8191,L+=_*(5*f)+O*(5*g)+x*(5*p)+T*(5*h)+R*(5*u),U+=L>>>13,L&=8191;let q=U+N*u+A*d+S*l+P*c+k*a;U=q>>>13,q&=8191,q+=_*o+O*(5*f)+x*(5*g)+T*(5*p)+R*(5*h),U+=q>>>13,q&=8191;let B=U+N*h+A*u+S*d+P*l+k*c;U=B>>>13,B&=8191,B+=_*a+O*o+x*(5*f)+T*(5*g)+R*(5*p),U+=B>>>13,B&=8191;let z=U+N*p+A*h+S*u+P*d+k*l;U=z>>>13,z&=8191,z+=_*c+O*a+x*o+T*(5*f)+R*(5*g),U+=z>>>13,z&=8191;let F=U+N*g+A*p+S*h+P*u+k*d;U=F>>>13,F&=8191,F+=_*l+O*c+x*a+T*o+R*(5*f),U+=F>>>13,F&=8191;let W=U+N*f+A*g+S*p+P*h+k*u;U=W>>>13,W&=8191,W+=_*d+O*l+x*c+T*a+R*o,U+=W>>>13,W&=8191,U=(U<<2)+U|0,U=U+$|0,$=8191&U,U>>>=13,D+=U,r[0]=$,r[1]=D,r[2]=M,r[3]=j,r[4]=L,r[5]=q,r[6]=B,r[7]=z,r[8]=F,r[9]=W}finalize(){const{h:e,pad:t}=this,s=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let o=2;o<10;o++)e[o]+=i,i=e[o]>>>13,e[o]&=8191;e[0]+=5*i,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,s[0]=e[0]+5,i=s[0]>>>13,s[0]&=8191;for(let o=1;o<10;o++)s[o]=e[o]+i,i=s[o]>>>13,s[o]&=8191;s[9]-=8192;let r=(1^i)-1;for(let o=0;o<10;o++)s[o]&=r;r=~r;for(let o=0;o<10;o++)e[o]=e[o]&r|s[o];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let n=e[0]+t[0];e[0]=65535&n;for(let o=1;o<8;o++)n=(e[o]+t[o]|0)+(n>>>16)|0,e[o]=65535&n;Qn(s)}update(e){Hn(this);const{buffer:t,blockLen:s}=this,i=(e=Jn(e)).length;for(let r=0;r<i;){const n=Math.min(s-this.pos,i-r);if(n!==s)t.set(e.subarray(r,r+n),this.pos),this.pos+=n,r+=n,this.pos===s&&(this.process(t,0,!1),this.pos=0);else for(;s<=i-r;r+=s)this.process(e,r)}return this}destroy(){Qn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Hn(this),function(e,t){Vn(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}(e,this),this.finished=!0;const{buffer:t,h:s}=this;let{pos:i}=this;if(i){for(t[i++]=1;i<16;i++)t[i]=0;this.process(t,0,!0)}this.finalize();let r=0;for(let n=0;n<8;n++)e[r++]=s[n]>>>0,e[r++]=s[n]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}}const ho=function(e){const t=(t,s)=>e(s).update(Jn(t)).digest(),s=e(new Uint8Array(32));return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=t=>e(t),t}(e=>
4new uo(e));const po=function(e,t){const{allowShortKeys:s,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return Fn(r),Fn(o),Kn(n),Kn(s),(t,a,c,l,d=0)=>{Vn(t),Vn(a),Vn(c);const u=c.length;if(void 0===l&&(l=new Uint8Array(u)),Vn(l),Fn(d),d<0||d>=ao)throw new Error("arx: counter overflow");if(l.length<u)throw new Error(`arx: output (${l.length}) is shorter than data (${u})`);const h=[];let p,g,f=t.length;if(32===f)h.push(p=Zn(t)),g=ro;else{if(16!==f||!s)throw new Error(`arx: invalid 32-byte key, got length=${f}`);p=new Uint8Array(32),p.set(t),p.set(t,16),g=io,h.push(p)}oo(a)||h.push(a=Zn(a));const m=Gn(p);if(i){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");i(g,m,Gn(a.subarray(0,16)),m),a=a.subarray(16)}const w=16-r;if(w!==a.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(12!==w){const e=new Uint8Array(12);e.set(a,n?0:12-a.length),a=e,h.push(a)}const v=Gn(a);return function(e,t,s,i,r,n,o,a){const c=r.length,l=new Uint8Array(64),d=Gn(l),u=oo(r)&&oo(n),h=u?Gn(r):co,p=u?Gn(n):co;for(let g=0;g<c;o++){if(e(t,s,i,d,o,a),o>=ao)throw new Error("arx: counter overflow");const f=Math.min(64,c-g);if(u&&64===f){const e=g/4;if(g%4!=0)throw new Error("arx: invalid block position");for(let t,s=0;s<16;s++)t=e+s,p[t]=h[t]^d[s];g+=64;continue}for(let e,t=0;t<f;t++)e=g+t,n[e]=r[e]^l[t];g+=f}}(e,g,m,v,c,l,d,o),Qn(...h),l}}(function(e,t,s,i,r,n=20){let o=e[0],a=e[1],c=e[2],l=e[3],d=t[0],u=t[1],h=t[2],p=t[3],g=t[4],f=t[5],m=t[6],w=t[7],v=r,y=s[0],b=s[1],E=s[2],C=o,I=a,N=c,A=l,S=d,P=u,k=h,_=p,O=g,x=f,T=m,R=w,U=v,$=y,D=b,M=E;for(let L=0;L<n;L+=2)C=C+S|0,U=no(U^C,16),O=O+U|0,S=no(S^O,12),C=C+S|0,U=no(U^C,8),O=O+U|0,S=no(S^O,7),I=I+P|0,$=no($^I,16),x=x+$|0,P=no(P^x,12),I=I+P|0,$=no($^I,8),x=x+$|0,P=no(P^x,7),N=N+k|0,D=no(D^N,16),T=T+D|0,k=no(k^T,12),N=N+k|0,D=no(D^N,8),T=T+D|0,k=no(k^T,7),A=A+_|0,M=no(M^A,16),R=R+M|0,_=no(_^R,12),A=A+_|0,M=no(M^A,8),R=R+M|0,_=no(_^R,7),C=C+P|0,M=no(M^C,16),T=T+M|0,P=no(P^T,12),C=C+P|0,M=no(M^C,8),T=T+M|0,P=no(P^T,7),I=I+k|0,U=no(U^I,16),R=R+U|0,k=no(k^R,12),I=I+k|0,U=no(U^I,8),R=R+U|0,k=no(k^R,7),N=N+_|0,$=no($^N,16),O=O+$|0,_=no(_^O,12),N=N+_|0,$=no($^N,8),O=O+$|0,_=no(_^O,7),A=A+S|0,D=no(D^A,16),x=x+D|0,S=no(S^x,12),A=A+S|0,D=no(D^A,8),x=x+D|0,S=no(S^x,7);let j=0;i[j++]=o+C|0,i[j++]=a+I|0,i[j++]=c+N|0,i[j++]=l+A|0,i[j++]=d+S|0,i[j++]=u+P|0,i[j++]=h+k|0,i[j++]=p+_|0,i[j++]=g+O|0,i[j++]=f+x|0,i[j++]=m+T|0,i[j++]=w+R|0,i[j++]=v+U|0,i[j++]=y+$|0,i[j++]=b+D|0,i[j++]=E+M|0},{counterRight:!1,counterLength:4,allowShortKeys:!1}),go=new Uint8Array(16),fo=(e,t)=>{e.update(t);const s=t.length%16;s&&e.update(go.subarray(s))},mo=new Uint8Array(32);function wo(e,t,s,i,r){const n=e(t,s,mo),o=ho.create(n);r&&fo(o,r),fo(o,i);const a=new Uint8Array(16),c=(e=>
4new DataView(e.buffer,e.byteOffset,e.byteLength))(a);Xn(c,0,BigInt(r?r.length:0),!0),Xn(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return Qn(n,a),l}const vo=((e,t)=>{function s(s,...i){if(Vn(s),void 0!==e.nonceLength){const t=i[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?Vn(t):Vn(t,e.nonceLength)}const r=e.tagLength;r&&void 0!==i[1]&&Vn(i[1]);const n=t(s,...i),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Vn(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,Vn(e),o(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(Vn(e),r&&e.length<r)throw new Error("invalid ciphertext length: smaller than tagLength="+r);return o(n.decrypt.length,t),n.decrypt(e,t)}}}return Object.assign(s,e),s})({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,s,i)=>({encrypt(r,n){const o=r.length;(n=Yn(o+16,n,!1)).set(r);const a=n.subarray(0,-16);e(t,s,a,a,1);const c=wo(e,t,s,a,i);return n.set(c,o),Qn(c),n},decrypt(r,n){n=Yn(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=wo(e,t,s,o,i);if(!function(e,t){if(e.length!==t.length)return!1;let s=0;for(let i=0;i<e.length;i++)s|=e[i]^t[i];return 0===s}(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),e(t,s,n,n,1),Qn(c),n}}))(po));let yo=class extends Yr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Mr(e);const s=Jr(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)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,r=new Uint8Array(i);r.set(s.length>i?e.create().update(s).digest():s);for(let n=0;n<r.length;n++)r[n]^=54;this.iHash.update(r),this.oHash=e.create();for(let n=0;n<r.length;n++)r[n]^=106;this.oHash.update(r),r.fill(0)}update(e){return jr(this),this.iHash.update(e),this}digestInto(e){jr(this),Dr(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:t,iHash:s,finished:i,destroyed:r,blockLen:n,outputLen:o}=this;return e.finished=i,e.destroyed=r,e.blockLen=n,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const bo=(e,t,s)=>new yo(e,t).update(s).digest();bo.create=(e,t)=>new yo(e,t);const Eo=new Uint8Array([0]),Co=new Uint8Array;const Io=(e,t,s,i,r)=>function(e,t,s,i=32){if(Mr(e),$r(i),i>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/e.outputLen);void 0===s&&(s=Co);const n=new Uint8Array(r*e.outputLen),o=bo.create(e,t),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)Eo[0]=l+1,a.update(0===l?Co:c).update(s).update(Eo).digestInto(c),n.set(c,e.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Eo.fill(0),n.slice(0,i)}(e,function(e,t,s){return Mr(e),void 0===s&&(s=new Uint8Array(e.outputLen)),bo(e,Jr(s),Jr(t))}(e,t,s),i,r);function No(e,t,s){return e&t^~e&s}function Ao(e,t,s){return e&t^e&s^t&s}let So=class extends Yr{constructor(e,t,s,i){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Wr(this.buffer)}update(e){jr(this);const{view:t,buffer:s,blockLen:i}=this,r=(e=Jr(e)).length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){const t=Wr(e);for(;i<=r-n;n+=i)this.process(t,n);continue}s.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){jr(this),Lr(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:i,isLE:r}=this;let{pos:n}=this;t[n++]=128,this.buffer.subarray(n).fill(0),this.padOffset>i-n&&(this.process(s,0),n=0);for(let d=n;d<i;d++)t[d]=0;(function(e,t,s,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,s,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(s>>r&n),a=Number(s&n),c=i?4:0,l=i?0:4;e.setUint32(t+c,o,i),e.setUint32(t+l,a,i)})(s,i-8,BigInt(8*this.length),r),this.process(s,0);const o=Wr(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)o.setUint32(4*d,l[d],r)}
vendor: 11,208 bytes, lines 4-5
4digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,length:i,finished:r,destroyed:n,pos:o}=this;return e.length=i,e.pos=o,e.finished=r,e.destroyed=n,i%t&&e.buffer.set(s),e}};const Po=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]),ko=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_o=new Uint32Array(64);class Oo extends So{constructor(){super(64,32,8,!1),this.A=0|ko[0],this.B=0|ko[1],this.C=0|ko[2],this.D=0|ko[3],this.E=0|ko[4],this.F=0|ko[5],this.G=0|ko[6],this.H=0|ko[7]}get(){const{A:e,B:t,C:s,D:i,E:r,F:n,G:o,H:a}=this;return[e,t,s,i,r,n,o,a]}set(e,t,s,i,r,n,o,a){this.A=0|e,this.B=0|t,this.C=0|s,this.D=0|i,this.E=0|r,this.F=0|n,this.G=0|o,this.H=0|a}process(e,t){for(let d=0;d<16;d++,t+=4)_o[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const e=_o[d-15],t=_o[d-2],s=Vr(e,7)^Vr(e,18)^e>>>3,i=Vr(t,17)^Vr(t,19)^t>>>10;_o[d]=i+_o[d-7]+s+_o[d-16]|0}let{A:s,B:i,C:r,D:n,E:o,F:a,G:c,H:l}=this;for(let d=0;d<64;d++){const e=l+(Vr(o,6)^Vr(o,11)^Vr(o,25))+No(o,a,c)+Po[d]+_o[d]|0,t=(Vr(s,2)^Vr(s,13)^Vr(s,22))+Ao(s,i,r)|0;l=c,c=a,a=o,o=n+e|0,n=r,r=i,i=s,s=e+t|0}s=s+this.A|0,i=i+this.B|0,r=r+this.C|0,n=n+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(s,i,r,n,o,a,c,l)}roundClean(){_o.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const xo=Xr(()=>new Oo),To=BigInt(0),Ro=BigInt(1),Uo=BigInt(2); 5/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function $o(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Do(e){if(!$o(e))throw new Error("Uint8Array expected")}function Mo(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const jo=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Lo(e){Do(e);let t="";for(let s=0;s<e.length;s++)t+=jo[e[s]];return t}function qo(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Bo(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?To:BigInt("0x"+e)}const zo=48,Fo=57,Wo=65,Vo=70,Ho=97,Ko=102;function Go(e){return e>=zo&&e<=Fo?e-zo:e>=Wo&&e<=Vo?e-(Wo-10):e>=Ho&&e<=Ko?e-(Ho-10):void 0}function Jo(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,s=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const i=new Uint8Array(s);for(let r=0,n=0;r<s;r++,n+=2){const t=Go(e.charCodeAt(n)),s=Go(e.charCodeAt(n+1));if(void 0===t||void 0===s){const t=e[n]+e[n+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+n)}i[r]=16*t+s}return i}function Yo(e){return Bo(Lo(e))}function Xo(e){return Do(e),Bo(Lo(Uint8Array.from(e).reverse()))}function Zo(e,t){return Jo(e.toString(16).padStart(2*t,"0"))}function Qo(e,t){return Zo(e,t).reverse()}function ea(e,t,s){let i;if("string"==typeof t)try{i=Jo(t)}catch(n){throw new Error(e+" must be hex string or Uint8Array, cause: "+n)}else{if(!$o(t))throw new Error(e+" must be hex string or Uint8Array");i=Uint8Array.from(t)}const r=i.length;if("number"==typeof s&&r!==s)throw new Error(e+" of length "+s+" expected, got "+r);return i}function ta(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];Do(s),t+=s.length}const s=new Uint8Array(t);for(let i=0,r=0;i<e.length;i++){const t=e[i];s.set(t,r),r+=t.length}return s}const sa=e=>"bigint"==typeof e&&To<=e;function ia(e,t,s){return sa(e)&&sa(t)&&sa(s)&&t<=e&&e<s}function ra(e,t,s,i){if(!ia(t,s,i))throw new Error("expected valid "+e+": "+s+" <= n < "+i+", got "+t)}function na(e){let t;for(t=0;e>To;e>>=Ro,t+=1);return t}const oa=e=>(Uo<<BigInt(e-1))-Ro,aa=e=>new Uint8Array(e),ca=e=>Uint8Array.from(e);function la(e,t,s){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof s)throw new Error("hmacFn must be a function");let i=aa(e),r=aa(e),n=0;const o=()=>{i.fill(1),r.fill(0),n=0},a=(...e)=>s(r,i,...e),c=(e=aa())=>{r=a(ca([0]),e),i=a(),0!==e.length&&(r=a(ca([1]),e),i=a())},l=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const s=[];for(;e<t;){i=a();const t=i.slice();s.push(t),e+=i.length}return ta(...s)};return(e,t)=>{let s;for(o(),c(e);!(s=t(l()));)c();return o(),s}}const da={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||$o(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function ua(e,t,s={}){const i=(t,s,i)=>{const r=da[s];if("function"!=typeof r)throw new Error("invalid validator function");const n=e[t];if(!(i&&void 0===n||r(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+s+", got "+n)};for(const[r,n]of Object.entries(t))i(r,n,!1);for(const[r,n]of Object.entries(s))i(r,n,!0);return e}function ha(e){const t=new WeakMap;return(s,...i)=>{const r=t.get(s);if(void 0!==r)return r;const n=e(s,...i);return t.set(s,n),n}}var pa=Object.freeze({__proto__:null,isBytes:$o,abytes:Do,abool:Mo,bytesToHex:Lo,numberToHexUnpadded:qo,hexToNumber:Bo,hexToBytes:Jo,bytesToNumberBE:Yo,bytesToNumberLE:Xo,numberToBytesBE:Zo,numberToBytesLE:Qo,numberToVarBytesBE:function(e){return Jo(qo(e))},ensureBytes:ea,concatBytes:ta,equalBytes:function(e,t){if(e.length!==t.length)return!1;let s=0;for(let i=0;i<e.length;i++)s|=e[i]^t[i];return 0===s},utf8ToBytes:function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))},inRange:ia,aInRange:ra,bitLen:na,bitGet:function(e,t){return e>>BigInt(t)&Ro},bitSet:function(e,t,s){return e|(s?Ro:To)<<BigInt(t)},bitMask:oa,createHmacDrbg:la,validateObject:ua,notImplemented:()=>{throw new Error("not implemented")},memoized:ha});const ga=BigInt(0),fa=BigInt(1),ma=BigInt(2),wa=BigInt(3),va=BigInt(4),ya=BigInt(5),ba=BigInt(8);function Ea(e,t){const s=e%t;return s>=ga?s:t+s}function Ca(e,t,s){if(t<ga)throw new Error("invalid exponent, negatives unsupported");if(s<=ga)throw new Error("invalid modulus");if(s===fa)return ga;let i=fa;for(;t>ga;)t&fa&&(i=i*e%s),e=e*e%s,t>>=fa;return i}function Ia(e,t,s){let i=e;for(;t-- >ga;)i*=i,i%=s;return i}function Na(e,t){if(e===ga)throw new Error("invert: expected non-zero number");if(t<=ga)throw new Error("invert: expected positive modulus, got "+t);let s=Ea(e,t),i=t,r=ga,n=fa;for(;s!==ga;){const e=i%s,t=r-n*(i/s);i=s,s=e,r=n,n=t}if(i!==fa)throw new Error("invert: does not exist");return Ea(r,t)}function Aa(e){if(e%va===wa){const t=(e+fa)/va;return function(e,s){const i=e.pow(s,t);if(!e.eql(e.sqr(i),s))throw new Error("Cannot find square root");return i}}if(e%ba===ya){const t=(e-ya)/ba;return function(e,s){const i=e.mul(s,ma),r=e.pow(i,t),n=e.mul(s,r),o=e.mul(e.mul(n,ma),r),a=e.mul(n,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),s))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-fa)/ma;let s,i,r;for(s=e-fa,i=0;s%ma===ga;s/=ma,i++);for(r=ma;r<e&&Ca(r,t,e)!==e-fa;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===i){const t=(e+fa)/va;return function(e,s){const i=e.pow(s,t);if(!e.eql(e.sqr(i),s))throw new Error("Cannot find square root");return i}}const n=(s+fa)/ma;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=i,c=e.pow(e.mul(e.ONE,r),s),l=e.pow(o,n),d=e.pow(o,s);for(;!e.eql(d,e.ONE);){if(e.eql(d,e.ZERO))return e.ZERO;let t=1;for(let i=e.sqr(d);t<a&&!e.eql(i,e.ONE);t++)i=e.sqr(i);const s=e.pow(c,fa<<BigInt(a-t-1));c=e.sqr(s),l=e.mul(l,s),d=e.mul(d,c),a=t}return l}}(e)}const Sa=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Pa(e,t){const s=void 0!==t?t:e.toString(2).length;return{nBitLength:s,nByteLength:Math.ceil(s/8)}}function ka(e,t,s=!1,i={}){if(e<=ga)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:n}=Pa(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:s,BITS:r,BYTES:n,MASK:oa(r),ZERO:ga,ONE:fa,create:t=>Ea(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return ga<=t&&t<e},is0:e=>e===ga,isOdd:e=>(e&fa)===fa,neg:t=>Ea(-t,e),eql:(e,t)=>e===t,sqr:t=>Ea(t*t,e),add:(t,s)=>Ea(t+s,e),sub:(t,s)=>Ea(t-s,e),mul:(t,s)=>Ea(t*s,e),pow:(e,t)=>function(e,t,s){if(s<ga)throw new Error("invalid exponent, negatives unsupported");if(s===ga)return e.ONE;if(s===fa)return t;let i=e.ONE,r=t;for(;s>ga;)s&fa&&(i=e.mul(i,r)),r=e.sqr(r),s>>=fa;return i}(a,e,t),div:(t,s)=>Ea(t*Na(s,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Na(t,e),sqrt:i.sqrt||(t=>(o||(o=Aa(e)),o(a,t))),invertBatch:e=>function(e,t){const s=new Array(t.length),i=t.reduce((t,i,r)=>e.is0(i)?t:(s[r]=t,e.mul(t,i)),e.ONE),r=e.inv(i);return t.reduceRight((t,i,r)=>e.is0(i)?t:(s[r]=e.mul(t,s[r]),e.mul(t,i)),r),s}(a,e),cmov:(e,t,s)=>s?t:e,toBytes:e=>s?Qo(e,n):Zo(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return s?Xo(e):Yo(e)}});return Object.freeze(a)}function _a(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Oa(e){const t=_a(e);return t+Math.ceil(t/2)}const xa=BigInt(0),Ta=BigInt(1);function Ra(e,t){const s=t.negate();return e?s:t}function Ua(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function $a(e,t){Ua(e,t);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Da=new WeakMap,Ma=new WeakMap;function ja(e){return Ma.get(e)||1}function La(e,t,s,i){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,s)=>{if(!(e instanceof t))throw new Error("invalid point at index "+s)})}(s,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,s)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+s)})}(i,t),s.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const r=e.ZERO,n=na(BigInt(s.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r);let l=r;
5for(let d=Math.floor((t.BITS-1)/o)*o;d>=0;d-=o){c.fill(r);for(let t=0;t<i.length;t++){const e=i[t],r=Number(e>>BigInt(d)&BigInt(a));c[r]=c[r].add(s[t])}let e=r;for(let t=c.length-1,s=r;t>0;t--)s=s.add(c[t]),e=e.add(s);if(l=l.add(e),0!==d)for(let t=0;t<o;t++)l=l.double()}return l}function qa(e){return function(e){ua(e,Sa.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}))}(e.Fp),ua(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Pa(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Ba=BigInt(0),za=BigInt(1);const Fa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Wa=BigInt(1),Va=BigInt(2),Ha=BigInt(3),Ka=BigInt(5);BigInt(8);const Ga=function(e){const t=function(e){return ua(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})}(e),{P:s}=t,i=e=>Ea(e,s),r=t.montgomeryBits,n=Math.ceil(r/8),o=t.nByteLength,a=t.adjustScalarBytes||(e=>e),c=t.powPminus2||(e=>Ca(e,s-BigInt(2),s));function l(e,t,s){const r=i(e*(t-s));return[t=i(t-r),s=i(s+r)]}const d=(t.a-BigInt(2))/BigInt(4);function u(e){return Qo(i(e),n)}function h(e,t){const h=function(e){const t=ea("u coordinate",e,n);return 32===o&&(t[31]&=127),Xo(t)}(t),p=function(e){const t=ea("scalar",e),s=t.length;if(s!==n&&s!==o)throw new Error("invalid scalar, expected "+n+" or "+o+" bytes, got "+s);return Xo(a(t))}(e),g=function(e,t){ra("u",e,Ba,s),ra("scalar",t,Ba,s);const n=t,o=e;let a,u=za,h=Ba,p=e,g=za,f=Ba;for(let s=BigInt(r-1);s>=Ba;s--){const e=n>>s&za;f^=e,a=l(f,u,p),u=a[0],p=a[1],a=l(f,h,g),h=a[0],g=a[1],f=e;const t=u+h,r=i(t*t),c=u-h,m=i(c*c),w=r-m,v=p+g,y=i((p-g)*t),b=i(v*c),E=y+b,C=y-b;p=i(E*E),g=i(o*i(C*C)),u=i(r*m),h=i(w*(r+i(d*w)))}a=l(f,u,p),u=a[0],p=a[1],a=l(f,h,g),h=a[0],g=a[1];const m=c(h);return i(u*m)}(h,p);if(g===Ba)throw new Error("invalid private or public key received");return u(g)}const p=u(t.Gu);function g(e){return h(e,p)}return{scalarMult:h,scalarMultBase:g,getSharedSecret:(e,t)=>h(e,t),getPublicKey:e=>g(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:p}}({P:Fa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=Fa,{pow_p_5_8:s,b2:i}=function(e){const t=BigInt(10),s=BigInt(20),i=BigInt(40),r=BigInt(80),n=Fa,o=e*e%n*e%n,a=Ia(o,Va,n)*o%n,c=Ia(a,Wa,n)*e%n,l=Ia(c,Ka,n)*c%n,d=Ia(l,t,n)*l%n,u=Ia(d,s,n)*d%n,h=Ia(u,i,n)*u%n,p=Ia(h,r,n)*h%n,g=Ia(p,r,n)*h%n,f=Ia(g,t,n)*l%n;return{pow_p_5_8:Ia(f,Va,n)*e%n,b2:o}}(e);return Ea(Ia(s,Ha,t)*i,t)},adjustScalarBytes:function(e){return e[0]&=248,e[31]&=127,e[31]|=64,e},randomBytes:Zr});function Ja(e){void 0!==e.lowS&&Mo("lowS",e.lowS),void 0!==e.prehash&&Mo("prehash",e.prehash)}const{bytesToNumberBE:Ya,hexToBytes:Xa}=pa;class Za extends Error{constructor(e=""){super(e)}}const Qa={Err:Za,_tlv:{encode:(e,t)=>{const{Err:s}=Qa;if(e<0||e>256)throw new s("tlv.encode: wrong tag");if(1&t.length)throw new s("tlv.encode: unpadded data");const i=t.length/2,r=qo(i);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const n=i>127?qo(r.length/2|128):"";return qo(e)+n+r+t},decode(e,t){const{Err:s}=Qa;let i=0;if(e<0||e>256)throw new s("tlv.encode: wrong tag");if(t.length<2||t[i++]!==e)throw new s("tlv.decode: wrong tlv");const r=t[i++];let n=0;if(!!(128&r)){const e=127&r;if(!e)throw new s("tlv.decode(long): indefinite length not supported");if(e>4)throw new s("tlv.decode(long): byte length is too big");const o=t.subarray(i,i+e);if(o.length!==e)throw new s("tlv.decode: length bytes not complete");if(0===o[0])throw new s("tlv.decode(long): zero leftmost byte");for(const t of o)n=n<<8|t;if(i+=e,n<128)throw new s("tlv.decode(long): not minimal encoding")}else n=r;const o=t.subarray(i,i+n);if(o.length!==n)throw new s("tlv.decode: wrong value length");return{v:o,l:t.subarray(i+n)}}},_int:{encode(e){const{Err:t}=Qa;if(e<ec)throw new t("integer: negative integers are not allowed");let s=qo(e);if(8&Number.parseInt(s[0],16)&&(s="00"+s),1&s.length)throw new t("unexpected DER parsing assertion: unpadded hex");return s},decode(e){const{Err:t}=Qa;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Ya(e)}},toSig(e){const{Err:t,_int:s,_tlv:i}=Qa,r="string"==typeof e?Xa(e):e;Do(r);const{v:n,l:o}=i.decode(48,r);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:l,l:d}=i.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(e){const{_tlv:t,_int:s}=Qa,i=t.encode(2,s.encode(e.r))+t.encode(2,s.encode(e.s));return t.encode(48,i)}},ec=BigInt(0),tc=BigInt(1);BigInt(2);const sc=BigInt(3);function ic(e){const t=function(e){const t=qa(e);ua(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});
vendor: 12,348 bytes, line 5
5const{endo:s,Fp:i,a:r}=t;if(s){if(!i.eql(r,i.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if("object"!=typeof s||"bigint"!=typeof s.beta||"function"!=typeof s.splitScalar)throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:s}=t,i=ka(t.n,t.nBitLength),r=t.toBytes||((e,t,i)=>{const r=t.toAffine();return ta(Uint8Array.from([4]),s.toBytes(r.x),s.toBytes(r.y))}),n=t.fromBytes||(e=>{const t=e.subarray(1);return{x:s.fromBytes(t.subarray(0,s.BYTES)),y:s.fromBytes(t.subarray(s.BYTES,2*s.BYTES))}});function o(e){const{a:i,b:r}=t,n=s.sqr(e),o=s.mul(n,e);return s.add(s.add(o,s.mul(e,i)),r)}if(!s.eql(s.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function a(e){const{allowedPrivateKeyLengths:s,nByteLength:i,wrapPrivateKey:r,n:n}=t;if(s&&"bigint"!=typeof e){if($o(e)&&(e=Lo(e)),"string"!=typeof e||!s.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*i,"0")}let o;try{o="bigint"==typeof e?e:Yo(ea("private key",e,i))}catch{throw new Error("invalid private key, expected hex or "+i+" bytes, got "+typeof e)}return r&&(o=Ea(o,n)),ra("private key",o,tc,n),o}function c(e){if(!(e instanceof u))throw new Error("ProjectivePoint expected")}const l=ha((e,t)=>{const{px:i,py:r,pz:n}=e;if(s.eql(n,s.ONE))return{x:i,y:r};const o=e.is0();null==t&&(t=o?s.ONE:s.inv(n));const a=s.mul(i,t),c=s.mul(r,t),l=s.mul(n,t);if(o)return{x:s.ZERO,y:s.ZERO};if(!s.eql(l,s.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),d=ha(e=>{if(e.is0()){if(t.allowInfinityPoint&&!s.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:i,y:r}=e.toAffine();if(!s.isValid(i)||!s.isValid(r))throw new Error("bad point: x or y not FE");const n=s.sqr(r),a=o(i);if(!s.eql(n,a))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class u{constructor(e,t,i){if(this.px=e,this.py=t,this.pz=i,null==e||!s.isValid(e))throw new Error("x required");if(null==t||!s.isValid(t))throw new Error("y required");if(null==i||!s.isValid(i))throw new Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:i}=e||{};if(!e||!s.isValid(t)||!s.isValid(i))throw new Error("invalid affine point");if(e instanceof u)throw new Error("projective point not allowed");const r=e=>s.eql(e,s.ZERO);return r(t)&&r(i)?u.ZERO:new u(t,i,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=s.invertBatch(e.map(e=>e.pz));return e.map((e,s)=>e.toAffine(t[s])).map(u.fromAffine)}static fromHex(e){const t=u.fromAffine(n(ea("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return u.BASE.multiply(a(e))}static msm(e,t){return La(u,i,e,t)}_setWindowSize(e){p.setWindowSize(this,e)}assertValidity(){d(this)}hasEvenY(){const{y:e}=this.toAffine();if(s.isOdd)return!s.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:i,pz:r}=this,{px:n,py:o,pz:a}=e,l=s.eql(s.mul(t,a),s.mul(n,r)),d=s.eql(s.mul(i,a),s.mul(o,r));return l&&d}negate(){return new u(this.px,s.neg(this.py),this.pz)}double(){const{a:e,b:i}=t,r=s.mul(i,sc),{px:n,py:o,pz:a}=this;let c=s.ZERO,l=s.ZERO,d=s.ZERO,h=s.mul(n,n),p=s.mul(o,o),g=s.mul(a,a),f=s.mul(n,o);return f=s.add(f,f),d=s.mul(n,a),d=s.add(d,d),c=s.mul(e,d),l=s.mul(r,g),l=s.add(c,l),c=s.sub(p,l),l=s.add(p,l),l=s.mul(c,l),c=s.mul(f,c),d=s.mul(r,d),g=s.mul(e,g),f=s.sub(h,g),f=s.mul(e,f),f=s.add(f,d),d=s.add(h,h),h=s.add(d,h),h=s.add(h,g),h=s.mul(h,f),l=s.add(l,h),g=s.mul(o,a),g=s.add(g,g),h=s.mul(g,f),c=s.sub(c,h),d=s.mul(g,p),d=s.add(d,d),d=s.add(d,d),new u(c,l,d)}add(e){c(e);const{px:i,py:r,pz:n}=this,{px:o,py:a,pz:l}=e;let d=s.ZERO,h=s.ZERO,p=s.ZERO;const g=t.a,f=s.mul(t.b,sc);let m=s.mul(i,o),w=s.mul(r,a),v=s.mul(n,l),y=s.add(i,r),b=s.add(o,a);y=s.mul(y,b),b=s.add(m,w),y=s.sub(y,b),b=s.add(i,n);let E=s.add(o,l);return b=s.mul(b,E),E=s.add(m,v),b=s.sub(b,E),E=s.add(r,n),d=s.add(a,l),E=s.mul(E,d),d=s.add(w,v),E=s.sub(E,d),p=s.mul(g,b),d=s.mul(f,v),p=s.add(d,p),d=s.sub(w,p),p=s.add(w,p),h=s.mul(d,p),w=s.add(m,m),w=s.add(w,m),v=s.mul(g,v),b=s.mul(f,b),w=s.add(w,v),v=s.sub(m,v),v=s.mul(g,v),b=s.add(b,v),m=s.mul(w,b),h=s.add(h,m),m=s.mul(E,b),d=s.mul(y,d),d=s.sub(d,m),m=s.mul(y,w),p=s.mul(E,p),p=s.add(p,m),new u(d,h,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(u.ZERO)}wNAF(e){return p.wNAFCached(this,e,u.normalizeZ)}multiplyUnsafe(e){const{endo:i,n:r}=t;ra("scalar",e,ec,r);const n=u.ZERO;if(e===ec)return n;if(this.is0()||e===tc)return this;if(!i||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,e,u.normalizeZ);let{k1neg:o,k1:a,k2neg:c,k2:l}=i.splitScalar(e),d=n,h=n,g=this;for(;a>ec||l>ec;)a&tc&&(d=d.add(g)),l&tc&&(h=h.add(g)),g=g.double(),a>>=tc,l>>=tc;return o&&(d=d.negate()),c&&(h=h.negate()),h=new u(s.mul(h.px,i.beta),h.py,h.pz),d.add(h)}multiply(e){const{endo:i,n:r}=t;let n,o;if(ra("scalar",e,tc,r),i){const{k1neg:t,k1:r,k2neg:a,k2:c}=i.splitScalar(e);let{p:l,f:d}=this.wNAF(r),{p:h,f:g}=this.wNAF(c);l=p.constTimeNegate(t,l),h=p.constTimeNegate(a,h),h=new u(s.mul(h.px,i.beta),h.py,h.pz),n=l.add(h),o=d.add(g)}else{const{p:t,f:s}=this.wNAF(e);n=t,o=s}return u.normalizeZ([n,o])[0]}multiplyAndAddUnsafe(e,t,s){const i=u.BASE,r=(e,t)=>t!==ec&&t!==tc&&e.equals(i)?e.multiply(t):e.multiplyUnsafe(t),n=r(this,t).add(r(e,s));return n.is0()?void 0:n}toAffine(e){return l(this,e)}isTorsionFree(){const{h:e,isTorsionFree:s}=t;if(e===tc)return!0;if(s)return s(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:s}=t;return e===tc?this:s?s(u,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return Mo("isCompressed",e),this.assertValidity(),r(u,this,e)}toHex(e=!0){return Mo("isCompressed",e),Lo(this.toRawBytes(e))}}u.BASE=new u(t.Gx,t.Gy,s.ONE),u.ZERO=new u(s.ZERO,s.ONE,s.ZERO);const h=t.nBitLength,p=function(e,t){return{constTimeNegate:Ra,hasPrecomputes:e=>1!==ja(e),unsafeLadder(t,s,i=e.ZERO){let r=t;for(;s>xa;)s&Ta&&(i=i.add(r)),r=r.double(),s>>=Ta;return i},precomputeWindow(e,s){const{windows:i,windowSize:r}=$a(s,t),n=[];let o=e,a=o;for(let t=0;t<i;t++){a=o,n.push(a);for(let e=1;e<r;e++)a=a.add(o),n.push(a);o=a.double()}return n},wNAF(s,i,r){const{windows:n,windowSize:o}=$a(s,t);let a=e.ZERO,c=e.BASE;const l=BigInt(2**s-1),d=2**s,u=BigInt(s);for(let e=0;e<n;e++){const t=e*o;let s=Number(r&l);r>>=u,s>o&&(s-=d,r+=Ta);const n=t,h=t+Math.abs(s)-1,p=e%2!=0,g=s<0;0===s?c=c.add(Ra(p,i[n])):a=a.add(Ra(g,i[h]))}return{p:a,f:c}},wNAFUnsafe(s,i,r,n=e.ZERO){const{windows:o,windowSize:a}=$a(s,t),c=BigInt(2**s-1),l=2**s,d=BigInt(s);for(let e=0;e<o;e++){const t=e*a;if(r===xa)break;let s=Number(r&c);if(r>>=d,s>a&&(s-=l,r+=Ta),0===s)continue;let o=i[t+Math.abs(s)-1];s<0&&(o=o.negate()),n=n.add(o)}return n},getPrecomputes(e,t,s){let i=Da.get(t);return i||(i=this.precomputeWindow(t,e),1!==e&&Da.set(t,s(i))),i},wNAFCached(e,t,s){const i=ja(e);return this.wNAF(i,this.getPrecomputes(i,e,s),t)},wNAFCachedUnsafe(e,t,s,i){const r=ja(e);return 1===r?this.unsafeLadder(e,t,i):this.wNAFUnsafe(r,this.getPrecomputes(r,e,s),t,i)},setWindowSize(e,s){Ua(s,t),Ma.set(e,s),Da.delete(e)}}}(u,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:u,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:function(e){return ia(e,tc,t.n)}}}function rc(e){const t=function(e){const t=qa(e);return ua(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:s,n:i}=t,r=s.BYTES+1,n=2*s.BYTES+1;function o(e){return Ea(e,i)}function a(e){return Na(e,i)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:d,isWithinCurveOrder:u}=ic({...t,toBytes(e,t,i){const r=t.toAffine(),n=s.toBytes(r.x),o=ta;return Mo("isCompressed",i),i?o(Uint8Array.from([t.hasEvenY()?2:3]),n):o(Uint8Array.from([4]),n,s.toBytes(r.y))},fromBytes(e){const t=e.length,i=e[0],o=e.subarray(1);if(t!==r||2!==i&&3!==i){if(t===n&&4===i){return{x:s.fromBytes(o.subarray(0,s.BYTES)),y:s.fromBytes(o.subarray(s.BYTES,2*s.BYTES))}}throw new Error("invalid Point, expected length of "+r+", or uncompressed "+n+", got "+t)}{const e=Yo(o);if(!ia(e,tc,s.ORDER))throw new Error("Point is not on curve");const t=d(e);let r;try{r=s.sqrt(t)}catch(a){const e=a instanceof Error?": "+a.message:"";throw new Error("Point is not on curve"+e)}return!(1&~i)!==((r&tc)===tc)&&(r=s.neg(r)),{x:e,y:r}}}}),h=e=>Lo(Zo(e,t.nByteLength));function p(e){return e>i>>tc}const g=(e,t,s)=>Yo(e.slice(t,s));class f{constructor(e,t,s){this.r=e,this.s=t,this.recovery=s,this.assertValidity()}static fromCompact(e){const s=t.nByteLength;return e=ea("compactSignature",e,2*s),new f(g(e,0,s),g(e,s,2*s))}static fromDER(e){const{r:t,s:s}=Qa.toSig(ea("DER",e));return new f(t,s)}assertValidity(){ra("r",this.r,tc,i),ra("s",this.s,tc,i)}addRecoveryBit(e){return new f(this.r,this.s,e)}recoverPublicKey(e){const{r:i,s:r,recovery:n}=this,l=y(ea("msgHash",e));if(null==n||![0,1,2,3].includes(n))throw new Error("recovery id invalid");const d=2===n||3===n?i+t.n:i;if(d>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const u=1&n?"03":"02",p=c.fromHex(u+h(d)),g=a(d),f=o(-l*g),m=o(r*g),w=c.BASE.multiplyAndAddUnsafe(p,f,m);if(!w)throw new Error("point at infinify");return w.assertValidity(),w}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Jo(this.toDERHex())}toDERHex(){return Qa.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Jo(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}const m={isValidPrivateKey(e){try{return l(e),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=Oa(t.n);return function(e,t,s=!1){const i=e.length,r=_a(t),n=Oa(t);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=Ea(s?Xo(e):Yo(e),t-fa)+fa;return s?Qo(o,r):Zo(o,r)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function w(e){const t=$o(e),s="string"==typeof e,i=(t||s)&&e.length;return t?i===r||i===n:s?i===2*r||i===2*n:e instanceof c}const v=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const s=Yo(e),i=8*e.length-t.nBitLength;return i>0?s>>BigInt(i):s},y=t.bits2int_modN||function(e){return o(v(e))},b=oa(t.nBitLength);function E(e){return ra("num < 2^"+t.nBitLength,e,ec,b),Zo(e,t.nByteLength)}function C(e,i,r=I){if(["recovered","canonical"].some(e=>e in r))throw new Error("sign() legacy options not supported");const{hash:n,randomBytes:d}=t;let{lowS:h,prehash:g,extraEntropy:m}=r;null==h&&(h=!0),e=ea("msgHash",e),Ja(r),g&&(e=ea("prehashed msgHash",n(e)));const w=y(e),b=l(i),C=[E(b),E(w)];if(null!=m&&!1!==m){const e=!0===m?d(s.BYTES):m;C.push(ea("extraEntropy",e))}const N=ta(...C),A=w;return{seed:N,k2sig:function(e){const t=v(e);if(!u(t))return;const s=a(t),i=c.BASE.multiply(t).toAffine(),r=o(i.x);if(r===ec)return;const n=o(s*o(A+r*b));if(n===ec)return;let l=(i.x===r?0:2)|Number(i.y&tc),d=n;return h&&p(n)&&(d=function(e){return p(e)?o(-e):e}(n),l^=1),new f(r,d,l)}}}const I={lowS:t.lowS,prehash:!1},N={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,s=!0){if(w(e))throw new Error("first arg must be private key");if(!w(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(s)},sign:function(e,s,i=I){const{seed:r,k2sig:n}=C(e,s,i),o=t;return la(o.hash.outputLen,o.nByteLength,o.hmac)(r,n)},verify:function(e,s,i,r=N){var n;const l=e;s=ea("msgHash",s),i=ea("publicKey",i);const{lowS:d,prehash:u,format:h}=r;if(Ja(r),"strict"in r)throw new Error("options.strict was renamed to lowS");if(void 0!==h&&"compact"!==h&&"der"!==h)throw new Error("format must be compact or der");const p="string"==typeof l||$o(l),g=!p&&!h&&"object"==typeof l&&null!==l&&"bigint"==typeof l.r&&"bigint"==typeof l.s;if(!p&&!g)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let m,w;try{if(g&&(m=new f(l.r,l.s)),p){try{"compact"!==h&&(m=f.fromDER(l))}catch(P){if(!(P instanceof Qa.Err))throw P}
5!m&&"der"!==h&&(m=f.fromCompact(l))}w=c.fromHex(i)}catch{return!1}if(!m||d&&m.hasHighS())return!1;u&&(s=t.hash(s));const{r:v,s:b}=m,E=y(s),C=a(b),I=o(E*C),A=o(v*C),S=null==(n=c.BASE.multiplyAndAddUnsafe(w,I,A))?void 0:n.toAffine();return!!S&&o(S.x)===v},ProjectivePoint:c,Signature:f,utils:m}}function nc(e){return{hash:e,hmac:(t,...s)=>bo(e,t,function(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];Dr(s),t+=s.length}const s=new Uint8Array(t);for(let i=0,r=0;i<e.length;i++){const t=e[i];s.set(t,r),r+=t.length}return s}(...s)),randomBytes:Zr}}BigInt(4);const oc=ka(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),ac=function(e,t){const s=t=>rc({...e,...nc(t)});return{...s(t),create:s}}({a:oc.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:oc,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},xo),cc="base10",lc="base16",dc="base64pad",uc="base64url",hc="utf8";function pc(){return Ki(Zr(32),lc)}function gc(e){return Ki(xo(Hi(e,lc)),lc)}function fc(e){return Ki(xo(Hi(e,hc)),lc)}function mc(e){return Hi(`${e}`,cc)}function wc(e){return Number(Ki(e,cc))}function vc(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function yc(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=(4-t.length%4)%4;return t+"=".repeat(s)}function bc(e){if(2===wc(e.type))return Ki(Bi([e.type,e.sealed]),dc);if(1===wc(e.type)){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ki(Bi([e.type,e.senderPublicKey,e.iv,e.sealed]),dc)}return Ki(Bi([e.type,e.iv,e.sealed]),dc)}function Ec(e){const t=Hi((e.encoding||dc)===uc?yc(e.encoded):e.encoded,dc),s=t.slice(0,1);if(1===wc(s)){const e=33,i=e+12,r=t.slice(1,e),n=t.slice(e,i);return{type:s,sealed:t.slice(i),iv:n,senderPublicKey:r}}if(2===wc(s)){return{type:s,sealed:t.slice(1),iv:Zr(12)}}const i=t.slice(1,13);return{type:s,sealed:t.slice(13),iv:i}}function Cc(e){const t=(null==e?void 0:e.type)||0;if(1===t){if(typeof(null==e?void 0:e.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(null==e?void 0:e.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:null==e?void 0:e.senderPublicKey,receiverPublicKey:null==e?void 0:e.receiverPublicKey}}function Ic(e){return 1===e.type&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function Nc(e){return 2===e.type}function Ac(e,t){const[s,i,r]=e.split("."),n=Buffer.from(yc(r),"base64");if(64!==n.length)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=xo(`${s}.${i}`),d=function(e){const t=Buffer.from(e.x,"base64"),s=Buffer.from(e.y,"base64");return Bi([new Uint8Array([4]),t,s])}(t);if(!ac.verify(Bi([o,a]),c,d))throw new Error("Invalid signature");return l(e).payload}function Sc(e){return(null==e?void 0:e.relay)||{protocol:"irn"}}function Pc(e){const t=a[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function kc(e,t="-"){const s={},i="relay"+t;return Object.keys(e).forEach(t=>{if(t.startsWith(i)){const r=t.replace(i,""),n=e[t];s[r]=n}}),s}function _c(e){if(!e.includes("wc:")){const t=Ur(e);null!=t&&t.includes("wc:")&&(e=t)}const t=(e=(e=e.includes("wc://")?e.replace("wc://",""):e).includes("wc:")?e.replace("wc:",""):e).indexOf(":"),s=-1!==e.indexOf("?")?e.indexOf("?"):void 0,i=e.substring(0,t),r=e.substring(t+1,s).split("@"),n=typeof s<"u"?e.substring(s):"",o=new URLSearchParams(n),a={};o.forEach((e,t)=>{a[t]=e});const c="string"==typeof a.methods?a.methods.split(","):void 0;return{protocol:i,topic:Oc(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:kc(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Oc(e){return e.startsWith("//")?e.substring(2):e}function xc(e){const t=new URLSearchParams,s=function(e,t="-"){const s={};return Object.keys(e).forEach(i=>
5{const r=i,n="relay"+t+r;e[r]&&(s[n]=e[r])}),s}(e.relay);Object.keys(s).sort().forEach(e=>{t.set(e,s[e])}),t.set("symKey",e.symKey),e.expiryTimestamp&&t.set("expiryTimestamp",e.expiryTimestamp.toString()),e.methods&&t.set("methods",e.methods.join(","));const i=t.toString();return`${e.protocol}:${e.topic}@${e.version}?${i}`}function Tc(e,t,s){return`${e}?wc_ev=${s}&topic=${t}`}var Rc=Object.defineProperty,Uc=Object.defineProperties,$c=Object.getOwnPropertyDescriptors,Dc=Object.getOwnPropertySymbols,Mc=Object.prototype.hasOwnProperty,jc=Object.prototype.propertyIsEnumerable,Lc=(e,t,s)=>t in e?Rc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,qc=(e,t)=>{for(var s in t||(t={}))Mc.call(t,s)&&Lc(e,s,t[s]);if(Dc)for(var s of Dc(t))jc.call(t,s)&&Lc(e,s,t[s]);return e},Bc=(e,t)=>Uc(e,$c(t));function zc(e){const t=[];return e.forEach(e=>{const[s,i]=e.split(":");t.push(`${s}:${i}`)}),t}function Fc(e){return e.includes(":")}function Wc(e){return Fc(e)?e.split(":")[0]:e}function Vc(e){var t,s,i;const r={};if(!Zc(e))return r;for(const[n,o]of Object.entries(e)){const e=Fc(n)?[n]:o.chains,a=o.methods||[],c=o.events||[],l=Wc(n);r[l]=Bc(qc({},r[l]),{chains:_r(e,null==(t=r[l])?void 0:t.chains),methods:_r(a,null==(s=r[l])?void 0:s.methods),events:_r(c,null==(i=r[l])?void 0:i.events)})}return r}function Hc(e,t){const s=function(e){const t={};return null==e||e.forEach(e=>{var s;const[i,r]=e.split(":");t[i]||(t[i]={accounts:[],chains:[],events:[],methods:[]}),t[i].accounts.push(e),null==(s=t[i].chains)||s.push(`${i}:${r}`)}),t}(t=t.map(e=>e.replace("did:pkh:","")));for(const[i,r]of Object.entries(s))r.methods?r.methods=_r(r.methods,e):r.methods=e,r.events=["chainChanged","accountsChanged"];return s}const Kc={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}},Gc={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 Jc(e,t){const{message:s,code:i}=Gc[e];return{message:t?`${s} ${t}`:s,code:i}}function Yc(e,t){const{message:s,code:i}=Kc[e];return{message:t?`${s} ${t}`:s,code:i}}function Xc(e,t){return!!Array.isArray(e)}function Zc(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Qc(e){return typeof e>"u"}function el(e,t){return!(!t||!Qc(e))||"string"==typeof e&&!!e.trim().length}function tl(e,t){return!(!t||!Qc(e))||"number"==typeof e&&!isNaN(e)}
5function sl(e){return!(!el(e,!1)||!e.includes(":"))&&2===e.split(":").length}function il(e){let t=!0;return Xc(e)?e.length&&(t=e.every(e=>el(e,!1))):t=!1,t}function rl(e,t,s){let i=null;return Object.entries(e).forEach(([e,r])=>{if(i)return;const n=function(e,t,s){let i=null;return Xc(t)&&t.length?t.forEach(e=>{i||sl(e)||(i=Yc("UNSUPPORTED_CHAINS",`${s}, chain ${e} should be a string and conform to "namespace:chainId" format`))}):sl(e)||(i=Yc("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}(e,Yi(e,r),`${t} ${s}`);n&&(i=n)}),i}function nl(e,t){let s=null;return Xc(e)?e.forEach(e=>{s||function(e){if(el(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&sl(e)}}return!1}(e)||(s=Yc("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))}):s=Yc("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function ol(e,t){let s=null;return Object.values(e).forEach(e=>{if(s)return;const i=function(e,t){let s=null;return il(null==e?void 0:e.methods)?il(null==e?void 0:e.events)||(s=Yc("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):s=Yc("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),s}(e,`${t}, namespace`);i&&(s=i)}),s}function al(e,t){let s=null;if(e&&Zc(e)){const i=ol(e,t);i&&(s=i);const r=function(e,t){let s=null;return Object.values(e).forEach(e=>{if(s)return;const i=nl(null==e?void 0:e.accounts,`${t} namespace`);i&&(s=i)}),s}(e,t);r&&(s=r)}else s=Jc("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return s}function cl(e){return el(e.protocol,!0)}function ll(e){return typeof e<"u"&&null!==typeof e}function dl(e,t){return!(!sl(t)||!function(e){const t=[];return Object.values(e).forEach(e=>{t.push(...zc(e.accounts))}),t}(e).includes(t))}function ul(e,t,s){return!!el(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach(e=>{zc(e.accounts).includes(t)&&s.push(...e.methods)}),s}(e,t).includes(s)}function hl(e,t,s){return!!el(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach(e=>{zc(e.accounts).includes(t)&&s.push(...e.events)}),s}(e,t).includes(s)}function pl(e,t,s){let i=null;const r=function(e){const t={};return Object.keys(e).forEach(s=>{var i;s.includes(":")?t[s]=e[s]:null==(i=e[s].chains)||i.forEach(i=>{t[i]={methods:e[s].methods,events:e[s].events}})}),t}(e),n=function(e){const t={};return Object.keys(e).forEach(s=>{if(s.includes(":"))t[s]=e[s];else{const i=zc(e[s].accounts);null==i||i.forEach(i=>{t[i]={accounts:e[s].accounts.filter(e=>e.includes(`${i}:`)),methods:e[s].methods,events:e[s].events}})}}),t}(t),o=Object.keys(r),a=Object.keys(n),c=gl(Object.keys(e)),l=gl(Object.keys(t)),d=c.filter(e=>!l.includes(e));return d.length&&(i=Jc("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.\n Required: ${d.toString()}\n Received: ${Object.keys(t).toString()}`)),yr(o,a)||(i=Jc("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach(e=>{if(!e.includes(":")||i)return;const r=zc(t[e].accounts);r.includes(e)||(i=Jc("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${r.toString()}`))}),o.forEach(e=>{i||(yr(r[e].methods,n[e].methods)?yr(r[e].events,n[e].events)||(i=Jc("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${e}`)):i=Jc("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${e}`))}),i}function gl(e){return[...new Set(e.map(e=>e.includes(":")?e.split(":")[0]:e))]}function fl(){const e=pr();return new Promise(t=>{switch(e){case ar:t(hr()&&(null==navigator?void 0:navigator.onLine));break;case nr:t(async function(){if(ur()&&typeof global<"u"&&null!=global&&global.NetInfo){const e=await(null==global?void 0:global.NetInfo.fetch());return null==e?void 0:e.isConnected}return!0}());break;default:t(!0)}})}
5function ml(e){switch(pr()){case ar:!function(e){!ur()&&hr()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}(e);break;case nr:!function(e){ur()&&typeof global<"u"&&null!=global&&global.NetInfo&&(null==global||global.NetInfo.addEventListener(t=>e(null==t?void 0:t.isConnected)))}(e)}}const wl={};class vl{static get(e){return wl[e]}static set(e,t){wl[e]=t}static delete(e){delete wl[e]}}var yl={};const bl="core",El=`wc@2:${bl}:`,Cl="error",Il={database:":memory:"},Nl="client_ed25519_seed",Al=n.ONE_DAY,Sl=n.SIX_HOURS,Pl="wss://relay.walletconnect.org",kl="relayer_message",_l="relayer_message_ack",Ol="relayer_connect",xl="relayer_disconnect",Tl="relayer_error",Rl="relayer_connection_stalled",Ul="relayer_publish",$l="payload",Dl="connect",Ml="disconnect",jl="error",Ll="2.21.0",ql={link_mode:"link_mode",relay:"relay"},Bl="inbound",zl="outbound",Fl="WALLETCONNECT_LINK_MODE_APPS",Wl="subscription_created",Vl="subscription_deleted",Hl="subscription_sync",Kl="subscription_resubscribed",Gl={wc_pairingDelete:{req:{ttl:n.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:n.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:n.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:n.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:n.ONE_DAY,prompt:!1,tag:0},res:{ttl:n.ONE_DAY,prompt:!1,tag:0}}},Jl="pairing_create",Yl="pairing_expire",Xl="pairing_delete",Zl="pairing_ping",Ql="history_created",ed="history_updated",td="history_deleted",sd="history_sync",id="expirer_created",rd="expirer_deleted",nd="expirer_expired",od="expirer_sync",ad="https://verify.walletconnect.org",cd=ad,ld=`${cd}/v3`,dd=["https://verify.walletconnect.com",ad],ud="pairing_started",hd="pairing_uri_validation_success",pd="pairing_uri_not_expired",gd="store_new_pairing",fd="subscribing_pairing_topic",md="subscribe_pairing_topic_success",wd="existing_pairing",vd="pairing_not_expired",yd="emit_inactive_pairing",bd="emit_session_proposal",Ed="no_internet_connection",Cd="malformed_pairing_uri",Id="active_pairing_already_exists",Nd="subscribe_pairing_topic_failure",Ad="pairing_expired",Sd="proposal_listener_not_found",Pd="session_approve_started",kd="session_namespaces_validation_success",_d="subscribing_session_topic",Od="subscribe_session_topic_success",xd="publishing_session_approve",Td="session_approve_publish_success",Rd="store_session",Ud="publishing_session_settle",$d="session_settle_publish_success",Dd="no_internet_connection",Md="proposal_expired",jd="subscribe_session_topic_failure",Ld="session_approve_publish_failure",qd="session_settle_publish_failure",Bd="session_approve_namespace_validation_failure",zd="proposal_not_found",Fd="authenticated_session_approve_started",Wd="create_authenticated_session_topic",Vd="cacaos_verified",Hd="store_authenticated_session",Kd="subscribing_authenticated_session_topic",Gd="subscribe_authenticated_session_topic_success",Jd="publishing_authenticated_session_approve",Yd="no_internet_connection",Xd="invalid_cacao",Zd="subscribe_authenticated_session_topic_failure",Qd="authenticated_session_approve_publish_failure",eu="authenticated_session_pending_request_not_found";var tu=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),i=0;i<s.length;i++)s[i]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==s[o])throw new TypeError(n+" is ambiguous");s[o]=r}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var i=0,r=0;e[t]===c;)i++,t++;for(var n=(e.length-t)*l+1>>>0,o=new Uint8Array(n);e[t];){var d=s[e.charCodeAt(t)];if(255===d)return;for(var u=0,h=n-1;(0!==d||u<r)&&-1!==h;h--,u++)d+=a*o[h]>>>0,o[h]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");r=u,t++}if(" "!==e[t]){for(var p=n-r;p!==n&&0===o[p];)p++;for(var g=new Uint8Array(i+(n-p)),f=i;p!==n;)g[f++]=o[p++];return g}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var s=0,i=0,r=0,n=t.length;r!==n&&0===t[r];)r++,s++;for(var o=(n-r)*d+1>>>0,l=new Uint8Array(o);r!==n;){for(var u=t[r],h=0,p=o-1;(0!==u||h<i)&&-1!==p;p--,h++)u+=256*l[p]>>>0,l[p]=u%a>>>0,u=u/a>>>0;if(0!==u)throw new Error("Non-zero carry");i=h,r++}for(var g=o-i;g!==o&&0===l[g];)g++;for(var f=c.repeat(s);g<o;++g)f+=e.charAt(l[g]);return f},decodeUnsafe:u,decode:function(e){var s=u(e);if(s)return s;throw new Error(`Non-${t} character`)}}},su=tu;const iu=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class ru{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class nu{constructor(e,t,s){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=s}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name}
5 decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return au(this,e)}}class ou{constructor(e){this.decoders=e}or(e){return au(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const au=(e,t)=>new ou({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class cu{constructor(e,t,s,i){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=i,this.encoder=new ru(e,t,s),this.decoder=new nu(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const lu=({name:e,prefix:t,encode:s,decode:i})=>new cu(e,t,s,i),du=({prefix:e,name:t,alphabet:s})=>{const{encode:i,decode:r}=su(s,t);return lu({prefix:e,name:t,encode:i,decode:e=>iu(r(e))})},uu=({name:e,prefix:t,bitsPerChar:s,alphabet:i})=>lu({prefix:t,name:e,encode:e=>((e,t,s)=>{const i="="===t[t.length-1],r=(1<<s)-1;let n="",o=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],o+=8;o>s;)o-=s,n+=t[r&a>>o];if(o&&(n+=t[r&a<<s-o]),i)for(;n.length*s&7;)n+="=";return n})(e,i,s),decode:t=>((e,t,s,i)=>{const r={};for(let d=0;d<t.length;++d)r[t[d]]=d;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*s/8|0);let a=0,c=0,l=0;for(let d=0;d<n;++d){const t=r[e[d]];if(void 0===t)throw new SyntaxError(`Non-${i} character`);c=c<<s|t,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})(t,i,s,e)}),hu=lu({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var pu=Object.freeze({__proto__:null,identity:hu});const gu=uu({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var fu=Object.freeze({__proto__:null,base2:gu});const mu=uu({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var wu=Object.freeze({__proto__:null,base8:mu});const vu=du({prefix:"9",name:"base10",alphabet:"0123456789"});var yu=Object.freeze({__proto__:null,base10:vu});const bu=uu({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Eu=uu({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Cu=Object.freeze({__proto__:null,base16:bu,base16upper:Eu});const Iu=uu({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Nu=uu({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Au=uu({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Su=uu({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Pu=uu({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ku=uu({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),_u=uu({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ou=uu({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xu=uu({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Tu=Object.freeze({__proto__:null,base32:Iu,base32upper:Nu,base32pad:Au,base32padupper:Su,base32hex:Pu,base32hexupper:ku,base32hexpad:_u,base32hexpadupper:Ou,base32z:xu});const Ru=du({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Uu=du({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $u=Object.freeze({__proto__:null,base36:Ru,base36upper:Uu});const Du=du({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mu=du({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ju=Object.freeze({__proto__:null,base58btc:Du,base58flickr:Mu});const Lu=uu({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qu=uu({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
5+/=",bitsPerChar:6}),Bu=uu({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zu=uu({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Fu=Object.freeze({__proto__:null,base64:Lu,base64pad:qu,base64url:Bu,base64urlpad:zu});const Wu=Array.from("ððªâð°ðððððððððððððâð»ð¥ð¾ð¿ðâ¤ðð¤£ððððððð
ððð¥ð¥°ðððð¢ð¤ðððªðâºðð¤ððððð¹ð¤¦ððââ¨ð¤·ð±ðð¸ððððððððð¤©ððð¤ðð¯ððð¶ðð¤â£ððððªðð¥ððð©ð¡ð¤ªðð¥³ð¥ð¤¤ððð³âððð´ðð¬ððð·ð»ðââ
ð¥ºððð¤ð¦âð£ððâ¹ððð âððºðð»ððððð¹ð£ð«ðððµð¤ðð´ð¤ð¼ð«â½ð¤âðð¤«ðð®ðð»ðð¶ðð²ð¿ð§¡ðâ¡ððââðð°ð¤¨ð¶ð¤ð¶ð°ðð¢ð¤ðð¨ð¨ð¤¬âððºð¤ððð±ðð¶ð¥´â¶â¡âðð¸â¬ð¨ðð¦ð·ðºâ ð
ððµðð¤²ð¤ ð¤§ððµð
ð§ð¾ððð¤ðð¤¯ð·âð§ð¯ððð¤ððâð´ð£ð¸ððð¥ð¤¢ð
ð¡ð©ðð¸ð»ð¤ð¤®ð¼ð¥µð©ððð¼ðð£ð¥"),Vu=Wu.reduce((e,t,s)=>(e[s]=t,e),[]),Hu=Wu.reduce((e,t,s)=>(e[t.codePointAt(0)]=s,e),[]);const Ku=lu({prefix:"ð",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+=Vu[t],"")},decode:function(e){const t=[];for(const s of e){const e=Hu[s.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${s}`);t.push(e)}return new Uint8Array(t)}});var Gu=Object.freeze({__proto__:null,base256emoji:Ku}),Ju=function e(t,s,i){s=s||[];for(var r=i=i||0;t>=Zu;)s[i++]=255&t|Yu,t/=128;for(;t&Xu;)s[i++]=255&t|Yu,t>>>=7;return s[i]=0|t,e.bytes=i-r+1,s},Yu=128,Xu=-128,Zu=Math.pow(2,31);var Qu=function e(t,s){var i,r=0,n=0,o=s=s||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");i=t[o++],r+=n<28?(i&th)<<n:(i&th)*Math.pow(2,n),n+=7}while(i>=eh);return e.bytes=o-s,r},eh=128,th=127;var sh=Math.pow(2,7),ih=Math.pow(2,14),rh=Math.pow(2,21),nh=Math.pow(2,28),oh=Math.pow(2,35),ah=Math.pow(2,42),ch=Math.pow(2,49),lh=Math.pow(2,56),dh=Math.pow(2,63),uh={encode:Ju,decode:Qu,encodingLength:function(e){return e<sh?1:e<ih?2:e<rh?3:e<nh?4:e<oh?5:e<ah?6:e<ch?7:e<lh?8:e<dh?9:10}};const hh=(e,t,s=0)=>(uh.encode(e,t,s),t),ph=e=>uh.encodingLength(e),gh=(e,t)=>{const s=t.byteLength,i=ph(e),r=i+ph(s),n=new Uint8Array(r+s);return hh(e,n,0),hh(s,n,i),n.set(t,r),new fh(e,s,t,n)};class fh{constructor(e,t,s,i){this.code=e,this.size=t,this.digest=s,this.bytes=i}}const mh=({name:e,code:t,encode:s})=>new wh(e,t,s);class wh{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?gh(this.code,t):t.then(e=>gh(this.code,e))}throw Error("Unknown type, must be binary type")}}const vh=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),yh=mh({name:"sha2-256",code:18,encode:vh("SHA-256")}),bh=mh({name:"sha2-512",code:19,encode:vh("SHA-512")});Object.freeze({__proto__:null,sha256:yh,sha512:bh});const Eh=iu,Ch={code:0,name:"identity",encode:Eh,digest:e=>gh(0,Eh(e))};Object.freeze({__proto__:null,identity:Ch});new TextEncoder,new TextDecoder;const Ih={...pu,...fu,...wu,...yu,...Cu,...Tu,...$u,...ju,...Fu,...Gu};function Nh(e,t,s,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:s},decoder:{decode:i}}}const Ah=Nh("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),Sh=Nh("ascii","a",e=>{let t="a";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return t},e=>{const t=function(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?globalThis.Buffer.allocUnsafe(e):new Uint8Array(e)}((e=e.substring(1)).length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}),Ph={utf8:Ah,"utf-8":Ah,hex:Ih.base16,latin1:Sh,ascii:Sh,binary:Sh,...Ih};var kh=Object.defineProperty,_h=(e,t,s)=>((e,t,s)=>t in e?kh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Oh{constructor(e,t){this.core=e,this.logger=t,_h(this,"keychain",new Map),_h(this,"name","keychain"),_h(this,"version","0.3"),_h(this,"initialized",!1),_h(this,"storagePrefix",El),_h(this,"init",async()=>
5{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}}),_h(this,"has",e=>(this.isInitialized(),this.keychain.has(e))),_h(this,"set",async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()}),_h(this,"get",e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=Jc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}),_h(this,"del",async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()}),this.core=e,this.logger=g(t,this.name)}get context(){return w(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,br(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Er(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Jc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xh=Object.defineProperty,Th=(e,t,s)=>((e,t,s)=>t in e?xh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Rh{constructor(e,t,s){this.core=e,this.logger=t,Th(this,"name","crypto"),Th(this,"keychain"),Th(this,"randomSessionIdentifier",pc()),Th(this,"initialized",!1),Th(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Th(this,"hasKeys",e=>(this.isInitialized(),this.keychain.has(e))),Th(this,"getClientId",async()=>{this.isInitialized();const e=await this.getClientSeed(),t=P(e);return k(t.publicKey)}),Th(this,"generateKeyPair",()=>{this.isInitialized();const e=function(){const e=Ga.utils.randomPrivateKey(),t=Ga.getPublicKey(e);return{privateKey:Ki(e,lc),publicKey:Ki(t,lc)}}();return this.setPrivateKey(e.publicKey,e.privateKey)}),Th(this,"signJWT",async e=>{this.isInitialized();const t=await this.getClientSeed(),s=P(t),i=this.randomSessionIdentifier,r=Al;return await _(i,e,r,s)}),Th(this,"generateSharedKey",(e,t,s)=>{this.isInitialized();const i=function(e,t){const s=Ga.getSharedSecret(Hi(e,lc),Hi(t,lc));return Ki(Io(xo,s,void 0,void 0,32),lc)}(this.getPrivateKey(e),t);return this.setSymKey(i,s)}),Th(this,"setSymKey",async(e,t)=>{this.isInitialized();const s=t||gc(e);return await this.keychain.set(s,e),s}),Th(this,"deleteKeyPair",async e=>{this.isInitialized(),await this.keychain.del(e)}),Th(this,"deleteSymKey",async e=>{this.isInitialized(),await this.keychain.del(e)}),Th(this,"encode",async(e,t,s)=>{this.isInitialized();const i=Cc(s),r=O(t);if(Nc(i))return function(e,t){const s=mc(2),i=Zr(12),r=bc({type:s,sealed:Hi(e,hc),iv:i});return t===uc?vc(r):r}(r,null==s?void 0:s.encoding);if(Ic(i)){const t=i.senderPublicKey,s=i.receiverPublicKey;e=await this.generateSharedKey(t,s)}const n=this.getSymKey(e),{type:o,senderPublicKey:a}=i;return function(e){const t=mc(typeof e.type<"u"?e.type:0);if(1===wc(t)&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof e.senderPublicKey<"u"?Hi(e.senderPublicKey,lc):void 0,i=typeof e.iv<"u"?Hi(e.iv,lc):Zr(12),r=Hi(e.symKey,lc),n=bc({type:t,sealed:vo(r,i).encrypt(Hi(e.message,hc)),iv:i,senderPublicKey:s});return e.encoding===uc?vc(n):n}({type:o,symKey:n,message:r,senderPublicKey:a,encoding:null==s?void 0:s.encoding})}),Th(this,"decode",async(e,t,s)=>{this.isInitialized();const i=function(e,t){const s=Ec({encoded:e,encoding:null==t?void 0:t.encoding});return Cc({type:wc(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?Ki(s.senderPublicKey,lc):void 0,receiverPublicKey:null==t?void 0:t.receiverPublicKey})}(t,s);if(Nc(i)){const e=function(e,t){const{sealed:s}=Ec({encoded:e,encoding:t});return Ki(s,hc)}(t,null==s?void 0:s.encoding);return x(e)}if(Ic(i)){const t=i.receiverPublicKey,s=i.senderPublicKey;e=await this.generateSharedKey(t,s)}try{const i=function(e){const t=Hi(e.symKey,lc),{sealed:s,iv:i}=Ec({encoded:e.encoded,encoding:e.encoding}),r=vo(t,i).decrypt(s);if(null===r)throw new Error("Failed to decrypt");return Ki(r,hc)}({symKey:this.getSymKey(e),encoded:t,encoding:null==s?void 0:s.encoding});return x(i)}catch(r){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(r)}}),Th(this,"getPayloadType",(e,t=dc)=>wc(Ec({encoded:e,encoding:t}).type)),Th(this,"getPayloadSenderPublicKey",(e,t=dc)=>{const s=Ec({encoded:e,encoding:t});return s.senderPublicKey?Ki(s.senderPublicKey,lc):void 0}),this.core=e,this.logger=g(t,this.name),this.keychain=s||new Oh(this.core,this.logger)}get context(){return w(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Nl)}catch{e=pc(),await this.keychain.set(Nl,e)}return function(e,t="utf8"){const s=Ph[t];if(!s)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?s.decoder.decode(`${s.prefix}${e}`):globalThis.Buffer.from(e,"utf8")}(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Jc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Uh=Object.defineProperty,$h=Object.defineProperties,Dh=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,jh=Object.prototype.hasOwnProperty,Lh=Object.prototype.propertyIsEnumerable,qh=(e,t,s)=>t in e?Uh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Bh=(e,t,s)=>qh(e,"symbol"!=typeof t?t+"":t,s);class zh extends vs{constructor(e,t){super(e,t),this.logger=e,this.core=t,Bh(this,"messages",new Map),Bh(this,"messagesWithoutClientAck",new Map),Bh(this,"name","messages"),Bh(this,"version","0.3"),Bh(this,"initialized",!1),Bh(this,"storagePrefix",El),Bh(this,"init",async()=>
5{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e);const t=await this.getRelayerMessagesWithoutClientAck();typeof t<"u"&&(this.messagesWithoutClientAck=t),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}}),Bh(this,"set",async(e,t,s)=>{this.isInitialized();const i=fc(t);let r=this.messages.get(e);if(typeof r>"u"&&(r={}),typeof r[i]<"u")return i;if(r[i]=t,this.messages.set(e,r),s===Bl){const s=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,((e,t)=>$h(e,Dh(t)))(((e,t)=>{for(var s in t||(t={}))jh.call(t,s)&&qh(e,s,t[s]);if(Mh)for(var s of Mh(t))Lh.call(t,s)&&qh(e,s,t[s]);return e})({},s),{[i]:t}))}return await this.persist(),i}),Bh(this,"get",e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t}),Bh(this,"getWithoutAck",e=>{this.isInitialized();const t={};for(const s of e){const e=this.messagesWithoutClientAck.get(s)||{};t[s]=Object.values(e)}return t}),Bh(this,"has",(e,t)=>{this.isInitialized();return typeof this.get(e)[fc(t)]<"u"}),Bh(this,"ack",async(e,t)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(e);if(typeof s>"u")return;delete s[fc(t)],0===Object.keys(s).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,s),await this.persist()}),Bh(this,"del",async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()}),this.logger=g(e,this.name),this.core=t}get context(){return w(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,br(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,br(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Er(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Er(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=Jc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Fh=Object.defineProperty,Wh=Object.defineProperties,Vh=Object.getOwnPropertyDescriptors,Hh=Object.getOwnPropertySymbols,Kh=Object.prototype.hasOwnProperty,Gh=Object.prototype.propertyIsEnumerable,Jh=(e,t,s)=>t in e?Fh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Yh=(e,t)=>{for(var s in t||(t={}))Kh.call(t,s)&&Jh(e,s,t[s]);if(Hh)for(var s of Hh(t))Gh.call(t,s)&&Jh(e,s,t[s]);return e},Xh=(e,t)=>Wh(e,Vh(t)),Zh=(e,t,s)=>Jh(e,"symbol"!=typeof t?t+"":t,s);class Qh extends ys{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Zh(this,"events",new u.EventEmitter),Zh(this,"name","publisher"),Zh(this,"queue",new Map),Zh(this,"publishTimeout",n.toMiliseconds(n.ONE_MINUTE)),Zh(this,"initialPublishTimeout",n.toMiliseconds(15*n.ONE_SECOND)),Zh(this,"needsTransportRestart",!1),Zh(this,"publish",async(e,t,s)=>{var i;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:s}});const r=(null==s?void 0:s.ttl)||Sl,n=Sc(s),o=(null==s?void 0:s.prompt)||!1,a=(null==s?void 0:s.tag)||0,c=(null==s?void 0:s.id)||T().toString(),l={topic:e,message:t,opts:{ttl:r,relay:n,prompt:o,tag:a,id:c,attestation:null==s?void 0:s.attestation,tvf:null==s?void 0:s.tvf}},d=`Failed to publish payload, please try again. id:${c} tag:${a}`;try{const i=new Promise(async i=>{const n=({id:e})=>{l.opts.id===e&&(this.removeRequestFromQueue(e),this.relayer.events.removeListener(Ul,n),i(l))};this.relayer.events.on(Ul,n);const d=Ir(new Promise((i,n)=>{this.rpcPublish({topic:e,message:t,ttl:r,prompt:o,tag:a,id:c,attestation:null==s?void 0:s.attestation,tvf:null==s?void 0:s.tvf}).then(i).catch(e=>{this.logger.warn(e,null==e?void 0:e.message),n(e)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${c} tag:${a}`);try{await d,this.events.removeListener(Ul,n)}catch(u){this.queue.set(c,Xh(Yh({},l),{attempt:1})),this.logger.warn(u,null==u?void 0:u.message)}});this.logger.trace({type:"method",method:"publish",params:{id:c,topic:e,message:t,opts:s}}),await Ir(i,this.publishTimeout,d)}catch(u){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(u),null!=(i=null==s?void 0:s.internal)&&i.throwOnFailedPublish)throw u}finally{this.queue.delete(c)}}),Zh(this,"on",(e,t)=>{this.events.on(e,t)}),Zh(this,"once",(e,t)=>{this.events.once(e,t)}),Zh(this,"off",(e,t)=>{this.events.off(e,t)}),Zh(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.relayer=e,this.logger=g(t,this.name),this.registerEventListeners()}get context(){return w(this.logger)}async rpcPublish(e){var t,s,i,r;const{topic:n,message:o,ttl:a=Sl,prompt:c,tag:l,id:d,attestation:u,tvf:h}=e,p={method:Pc(Sc().protocol).publish,params:Yh({topic:n,message:o,ttl:a,prompt:c,tag:l,attestation:u},h),id:d};Qc(null==(t=p.params)?void 0:t.prompt)&&(null==(s=p.params)||delete s.prompt),Qc(null==(i=p.params)?void 0:i.tag)&&(null==(r=p.params)||delete r.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:p});const g=await this.relayer.request(p);return this.relayer.events.emit(Ul,e),this.logger.debug("Successfully Published Payload"),g}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,Xh(Yh({},e),{attempt:s}));const{topic:i,message:r,opts:n,attestation:o}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${s}`),await this.rpcPublish(Xh(Yh({},e),{topic:i,message:r,ttl:n.ttl,prompt:n.prompt,tag:n.tag,id:n.id,attestation:o,tvf:n.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(y.pulse,()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(Rl);this.checkQueue()}),this.relayer.on(_l,e=>{this.removeRequestFromQueue(e.id.toString())})}}var ep=Object.defineProperty,tp=(e,t,s)=>((e,t,s)=>t in e?ep(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class sp{constructor(){tp(this,"map",new Map),tp(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),tp(this,"get",e=>this.map.get(e)||[]),tp(this,"exists",(e,t)=>this.get(e).includes(t)),tp(this,"delete",(e,t)=>{if(typeof t>"u")return void this.map.delete(e);
5if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const i=s.filter(e=>e!==t);i.length?this.map.set(e,i):this.map.delete(e)}),tp(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var ip=Object.defineProperty,rp=Object.defineProperties,np=Object.getOwnPropertyDescriptors,op=Object.getOwnPropertySymbols,ap=Object.prototype.hasOwnProperty,cp=Object.prototype.propertyIsEnumerable,lp=(e,t,s)=>t in e?ip(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,dp=(e,t)=>{for(var s in t||(t={}))ap.call(t,s)&&lp(e,s,t[s]);if(op)for(var s of op(t))cp.call(t,s)&&lp(e,s,t[s]);return e},up=(e,t)=>rp(e,np(t)),hp=(e,t,s)=>lp(e,"symbol"!=typeof t?t+"":t,s);class pp extends Cs{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,hp(this,"subscriptions",new Map),hp(this,"topicMap",new sp),hp(this,"events",new u.EventEmitter),hp(this,"name","subscription"),hp(this,"version","0.3"),hp(this,"pending",new Map),hp(this,"cached",[]),hp(this,"initialized",!1),hp(this,"storagePrefix",El),hp(this,"subscribeTimeout",n.toMiliseconds(n.ONE_MINUTE)),hp(this,"initialSubscribeTimeout",n.toMiliseconds(15*n.ONE_SECOND)),hp(this,"clientId"),hp(this,"batchSubscribeTopicsLimit",500),hp(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),hp(this,"subscribe",async(e,t)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const s=Sc(t),i={topic:e,relay:s,transportType:null==t?void 0:t.transportType};this.pending.set(e,i);const r=await this.rpcSubscribe(e,s,t);return"string"==typeof r&&(this.onSubscribe(r,i),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),r}catch(vn){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(vn),vn}}),hp(this,"unsubscribe",async(e,t)=>{this.isInitialized(),typeof(null==t?void 0:t.id)<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)}),hp(this,"isSubscribed",e=>new Promise(t=>{t(this.topicMap.topics.includes(e))})),hp(this,"isKnownTopic",e=>new Promise(t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some(t=>t.topic===e))})),hp(this,"on",(e,t)=>{this.events.on(e,t)}),hp(this,"once",(e,t)=>{this.events.once(e,t)}),hp(this,"off",(e,t)=>{this.events.off(e,t)}),hp(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),hp(this,"start",async()=>{await this.onConnect()}),hp(this,"stop",async()=>{await this.onDisconnect()}),hp(this,"restart",async()=>{await this.restore(),await this.onRestart()}),hp(this,"checkPending",async()=>{if(!(0!==this.pending.size||this.initialized&&this.relayer.connected))return;const e=[];this.pending.forEach(t=>{e.push(t)}),await this.batchSubscribe(e)}),hp(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(y.pulse,async()=>{await this.checkPending()}),this.events.on(Wl,async e=>{const t=Wl;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(Vl,async e=>{const t=Vl;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})}),this.relayer=e,this.logger=g(t,this.name),this.clientId=""}get context(){return w(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,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async s=>await this.unsubscribeById(e,s,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const i=Sc(s);await this.restartToComplete({topic:e,id:t,relay:i}),await this.rpcUnsubscribe(e,t,i);const r=Yc("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}
5async rpcSubscribe(e,t,s){var i;(!s||(null==s?void 0:s.transportType)===ql.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const r={method:Pc(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});const o=null==(i=null==s?void 0:s.internal)?void 0:i.throwOnFailedPublish;try{const t=await this.getSubscriptionId(e);if((null==s?void 0:s.transportType)===ql.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch(e=>this.logger.warn(e))},n.toMiliseconds(n.ONE_SECOND)),t;const i=new Promise(async t=>{const s=i=>{i.topic===e&&(this.events.removeListener(Wl,s),t(i.id))};this.events.on(Wl,s);try{const i=await Ir(new Promise((e,t)=>{this.relayer.request(r).catch(e=>{this.logger.warn(e,null==e?void 0:e.message),t(e)}).then(e)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Wl,s),t(i)}catch{}}),a=await Ir(i,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!a&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return a?t:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Rl),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t={method:Pc(e[0].relay.protocol).batchSubscribe,params:{topics:e.map(e=>e.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{await await Ir(new Promise(e=>{this.relayer.request(t).catch(e=>this.logger.warn(e)).then(e)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Rl)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t={method:Pc(e[0].relay.protocol).batchFetchMessages,params:{topics:e.map(e=>e.topic)}};let s;this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{s=await await Ir(new Promise((e,s)=>{this.relayer.request(t).catch(e=>{this.logger.warn(e),s(e)}).then(e)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Rl)}return s}rpcUnsubscribe(e,t,s){const i={method:Pc(s.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,t){this.setSubscription(e,up(dp({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(e=>{this.setSubscription(e.id,dp({},e)),this.pending.delete(e.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),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,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,dp({},t)),this.topicMap.set(t.topic,e),this.events.emit(Wl,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:t}=Jc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(Vl,up(dp({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Hl)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s<t;s++){const t=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(t)}}this.events.emit(Kl)}
5async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:e}=Jc("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(wn){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(wn)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async e=>up(dp({},e),{id:await this.getSubscriptionId(e.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await function(e){return new Promise(t=>setTimeout(t,e))}(n.toMiliseconds(n.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=Jc("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 fc(e+await this.getClientId())}}var gp=Object.defineProperty,fp=Object.getOwnPropertySymbols,mp=Object.prototype.hasOwnProperty,wp=Object.prototype.propertyIsEnumerable,vp=(e,t,s)=>t in e?gp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,yp=(e,t)=>{for(var s in t||(t={}))mp.call(t,s)&&vp(e,s,t[s]);if(fp)for(var s of fp(t))wp.call(t,s)&&vp(e,s,t[s]);return e},bp=(e,t,s)=>vp(e,"symbol"!=typeof t?t+"":t,s);class Ep extends bs{constructor(e){super(e),bp(this,"protocol","wc"),bp(this,"version",2),bp(this,"core"),bp(this,"logger"),bp(this,"events",new u.EventEmitter),bp(this,"provider"),bp(this,"messages"),bp(this,"subscriber"),bp(this,"publisher"),bp(this,"name","relayer"),bp(this,"transportExplicitlyClosed",!1),bp(this,"initialized",!1),bp(this,"connectionAttemptInProgress",!1),bp(this,"relayUrl"),bp(this,"projectId"),bp(this,"packageName"),bp(this,"bundleId"),bp(this,"hasExperiencedNetworkDisruption",!1),bp(this,"pingTimeout"),bp(this,"heartBeatTimeout",n.toMiliseconds(n.THIRTY_SECONDS+n.FIVE_SECONDS)),bp(this,"reconnectTimeout"),bp(this,"connectPromise"),bp(this,"reconnectInProgress",!1),bp(this,"requestsInFlight",[]),bp(this,"connectTimeout",n.toMiliseconds(15*n.ONE_SECOND)),bp(this,"request",async e=>{var t,s;this.logger.debug("Publishing Request Payload");const i=e.id||T().toString();await this.toEstablishConnection();try{this.logger.trace({id:i,method:e.method,topic:null==(t=e.params)?void 0:t.topic},"relayer.request - publishing...");const r=`${i}:${(null==(s=e.params)?void 0:s.tag)||""}`;this.requestsInFlight.push(r);const n=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter(e=>e!==r),n}catch(r){throw this.logger.debug(`Failed to Publish Request: ${i}`),r}}),bp(this,"resetPingTimeout",()=>{dr()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var e,t,s,i;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),null==(i=null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.terminate)||i.call(s)}catch(r){this.logger.warn(r,null==r?void 0:r.message)}},this.heartBeatTimeout))}),bp(this,"onPayloadHandler",e=>{this.onProviderPayload(e),this.resetPingTimeout()}),bp(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected ð"),this.startPingTimeout(),this.events.emit(Ol)}),bp(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected ð"),this.requestsInFlight=[],this.onProviderDisconnect()}),bp(this,"onProviderErrorHandler",e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(Tl,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),bp(this,"registerProviderListeners",()=>{this.provider.on($l,this.onPayloadHandler),this.provider.on(Dl,this.onConnectHandler),this.provider.on(Ml,this.onDisconnectHandler),this.provider.on(jl,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&"string"!=typeof e.logger?g(e.logger,this.name):b(h({level:e.logger||"error"})),this.messages=new zh(this.logger,e.core),this.subscriber=new pp(this,this.logger),this.publisher=new Qh(this,this.logger),this.relayUrl=(null==e?void 0:e.relayUrl)||Pl,this.projectId=e.projectId,ur()&&typeof global<"u"&&typeof(null==global?void 0:global.Platform)<"u"&&"android"===(null==global?void 0:global.Platform.OS)?this.packageName=gr():ur()&&typeof global<"u"&&typeof(null==global?void 0:global.Platform)<"u"&&"ios"===(null==global?void 0:global.Platform.OS)&&(this.bundleId=gr()),this.provider={}}
5async 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(wn){this.logger.warn(wn,null==wn?void 0:wn.message)}}get context(){return w(this.logger)}get connected(){var e,t,s;return 1===(null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.readyState)||!1}get connecting(){var e,t,s;return 0===(null==(s=null==(t=null==(e=this.provider)?void 0:e.connection)?void 0:t.socket)?void 0:s.readyState)||void 0!==this.connectPromise||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:ql.relay},zl)}async subscribe(e,t){var s,i,r;this.isInitialized(),(null==t||!t.transportType||"relay"===(null==t?void 0:t.transportType))&&await this.toEstablishConnection();const n=typeof(null==(s=null==t?void 0:t.internal)?void 0:s.throwOnFailedPublish)>"u"||(null==(i=null==t?void 0:t.internal)?void 0:i.throwOnFailedPublish);let o,a=(null==(r=this.subscriber.topicMap.get(e))?void 0:r[0])||"";const c=t=>{t.topic===e&&(this.subscriber.off(Wl,c),o())};return await Promise.all([new Promise(e=>{o=e,this.subscriber.on(Wl,c)}),new Promise(async(s,i)=>{a=await this.subscriber.subscribe(e,yp({internal:{throwOnFailedPublish:n}},t)).catch(e=>{n&&i(e)})||a,s()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Ir(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){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(t,s)=>{await this.connect(e).then(t).catch(s).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}else this.logger.warn("Starting WS connection skipped because the client has no topics to work with.")}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 fl()))throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(0===(null==e?void 0:e.length))return void this.logger.trace("Batch message events is empty. Ignoring...");const t=e.sort((e,t)=>e.publishedAt-t.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+(null==s?void 0:s.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:s}=e;if(!t.sessionExists){const e={topic:s,expiry:Sr(n.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,e)}this.events.emit(kl,e),await this.recordMessageEvent(e,Bl)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(e,t)=>{const s=()=>
5{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ml,s),await Ir(new Promise((e,t)=>{this.provider.connect().then(e).catch(t)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(e=>{t(e)}).finally(()=>{this.provider.off(Ml,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(e,t)=>{const s=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ml,s),await this.subscriber.start().then(e).catch(t).finally(()=>{this.provider.off(Ml,s)})}),this.hasExperiencedNetworkDisruption=!1,e()})}catch(s){await this.subscriber.stop();const e=s;this.logger.warn({},e.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(e=>setTimeout(e,n.toMiliseconds(1*t))),t++}}startPingTimeout(){var e,t,s,i,r;if(dr())try{null!=(t=null==(e=this.provider)?void 0:e.connection)&&t.socket&&(null==(r=null==(i=null==(s=this.provider)?void 0:s.connection)?void 0:i.socket)||r.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(n){this.logger.warn(n,null==n?void 0:n.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new E(new C(vr({sdkVersion:Ll,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,t){const{topic:s,message:i}=e;await this.messages.set(s,i,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||0===s.length)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!(await this.subscriber.isKnownTopic(t)))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const i=this.messages.has(t,s);return i&&this.logger.warn(`Ignoring duplicate message: ${s}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),I(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:s,message:i,publishedAt:r,attestation:n}=t.data,o={topic:s,message:i,publishedAt:r,transportType:ql.relay,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(yp({type:"event",event:t.id},o)),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else N(e)&&this.events.emit(_l,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Bl),this.events.emit(kl,e))}async acknowledgePayload(e){const t=A(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off($l,this.onPayloadHandler),this.provider.off(Dl,this.onConnectHandler),this.provider.off(Ml,this.onDisconnectHandler),this.provider.off(jl,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await fl();ml(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(e=>this.logger.error(e,null==e?void 0:e.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(y.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&function(){var e;return!hr()||!o.getDocument()||"visible"===(null==(e=o.getDocument())?void 0:e.visibilityState)}())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(mn){this.logger.warn(mn,null==mn?void 0:mn.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(xl),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,null==e?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},n.toMiliseconds(.1)))))}isInitialized(){if(!this.initialized){const{message:e}=Jc("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise)return void(await this.connectPromise);await this.connect()}}}function Cp(){}function Ip(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&"[object Object]"===Object.prototype.toString.call(e)}function Np(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}
5function Ap(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Sp="[object Arguments]",Pp="[object Object]";function kp(e,t,s,i,r,n,o){const a=o(e,t,s,i,r,n);if(void 0!==a)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":case"function":return e===t;case"number":return e===t||Object.is(e,t);case"object":return _p(e,t,n,o)}return _p(e,t,n,o)}function _p(e,t,s,i){if(Object.is(e,t))return!0;let r=Ap(e),n=Ap(t);if(r===Sp&&(r=Pp),n===Sp&&(n=Pp),r!==n)return!1;switch(r){case"[object String]":return e.toString()===t.toString();case"[object Number]":return function(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}(e.valueOf(),t.valueOf());case"[object Boolean]":case"[object Date]":case"[object Symbol]":return Object.is(e.valueOf(),t.valueOf());case"[object RegExp]":return e.source===t.source&&e.flags===t.flags;case"[object Function]":return e===t}const o=(s=s??new Map).get(e),a=s.get(t);if(null!=o&&null!=a)return o===t;s.set(e,t),s.set(t,e);try{switch(r){case"[object Map]":if(e.size!==t.size)return!1;for(const[r,n]of e.entries())if(!t.has(r)||!kp(n,t.get(r),r,e,t,s,i))return!1;return!0;case"[object Set]":{if(e.size!==t.size)return!1;const r=Array.from(e.values()),n=Array.from(t.values());for(let o=0;o<r.length;o++){const a=r[o],c=n.findIndex(r=>kp(a,r,void 0,e,t,s,i));if(-1===c)return!1;n.splice(c,1)}return!0}case"[object Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":case"[object BigUint64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object BigInt64Array]":case"[object Float32Array]":case"[object Float64Array]":if(typeof Buffer<"u"&&Buffer.isBuffer(e)!==Buffer.isBuffer(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!kp(e[r],t[r],r,e,t,s,i))return!1;return!0;case"[object ArrayBuffer]":return e.byteLength===t.byteLength&&_p(new Uint8Array(e),new Uint8Array(t),s,i);case"[object DataView]":return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&_p(new Uint8Array(e),new Uint8Array(t),s,i);case"[object Error]":return e.name===t.name&&e.message===t.message;case Pp:{if(!(_p(e.constructor,t.constructor,s,i)||Ip(e)&&Ip(t)))return!1;const r=[...Object.keys(e),...Np(e)],n=[...Object.keys(t),...Np(t)];if(r.length!==n.length)return!1;for(let o=0;o<r.length;o++){const n=r[o],a=e[n];if(!Object.hasOwn(t,n))return!1;if(!kp(a,t[n],n,e,t,s,i))return!1}return!0}default:return!1}}finally{s.delete(e),s.delete(t)}}function Op(e,t){return function(e,t,s){return kp(e,t,void 0,void 0,void 0,void 0,s)}(e,t,Cp)}var xp=Object.defineProperty,Tp=Object.getOwnPropertySymbols,Rp=Object.prototype.hasOwnProperty,Up=Object.prototype.propertyIsEnumerable,$p=(e,t,s)=>t in e?xp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Dp=(e,t)=>{for(var s in t||(t={}))Rp.call(t,s)&&$p(e,s,t[s]);if(Tp)for(var s of Tp(t))Up.call(t,s)&&$p(e,s,t[s]);return e},Mp=(e,t,s)=>$p(e,"symbol"!=typeof t?t+"":t,s);class jp extends Es{constructor(e,t,s,i=El,r=void 0){super(e,t,s,i),this.core=e,this.logger=t,this.name=s,Mp(this,"map",new Map),Mp(this,"version","0.3"),Mp(this,"cached",[]),Mp(this,"initialized",!1),Mp(this,"getKey"),Mp(this,"storagePrefix",El),Mp(this,"recentlyDeleted",[]),Mp(this,"recentlyDeletedLimit",200),Mp(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>{this.getKey&&null!==e&&!Qc(e)?this.map.set(this.getKey(e),e):function(e){var t;return null==(t=null==e?void 0:e.proposer)?void 0:t.publicKey}(e)?this.map.set(e.id,e):function(e){return null==e?void 0:e.topic}(e)&&this.map.set(e.topic,e)}),this.cached=[],this.initialized=!0)}),Mp(this,"set",async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())}),Mp(this,"get",e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e))),Mp(this,"getAll",e=>(this.isInitialized(),e?this.values.filter(t=>Object.keys(e).every(s=>Op(t[s],e[s]))):this.values)),Mp(this,"update",async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const s=Dp(Dp({},this.getData(e)),t);this.map.set(e,s),await this.persist()}),Mp(this,"delete",async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",ke
5y:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())}),this.logger=g(t,this.name),this.storagePrefix=i,this.getKey=r}get context(){return w(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 t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:t}=Jc("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=Jc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}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:e}=Jc("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(wn){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(wn)}}isInitialized(){if(!this.initialized){const{message:e}=Jc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Lp=Object.defineProperty,qp=(e,t,s)=>((e,t,s)=>t in e?Lp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Bp{constructor(e,t){this.core=e,this.logger=t,qp(this,"name","pairing"),qp(this,"version","0.3"),qp(this,"events",new S),qp(this,"pairings"),qp(this,"initialized",!1),qp(this,"storagePrefix",El),qp(this,"ignoredPayloadTypes",[1]),qp(this,"registeredMethods",[]),qp(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),qp(this,"register",({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]}),qp(this,"create",async e=>{this.isInitialized();const t=pc(),s=await this.core.crypto.setSymKey(t),i=Sr(n.FIVE_MINUTES),r={protocol:"irn"},o={topic:s,expiry:i,relay:r,active:!1,methods:null==e?void 0:e.methods},a=xc({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:t,relay:r,expiryTimestamp:i,methods:null==e?void 0:e.methods});return this.events.emit(Jl,o),this.core.expirer.set(s,i),await this.pairings.set(s,o),await this.core.relayer.subscribe(s,{transportType:null==e?void 0:e.transportType}),{topic:s,uri:a}}),qp(this,"pair",async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:null==e?void 0:e.uri,trace:[ud]}});this.isValidPair(e,t);const{topic:s,symKey:i,relay:r,expiryTimestamp:o,methods:a}=_c(e.uri);let c;if(t.props.properties.topic=s,t.addTrace(hd),t.addTrace(pd),this.pairings.keys.includes(s)){if(c=this.pairings.get(s),t.addTrace(wd),c.active)throw t.setError(Id),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);t.addTrace(vd)}const l=o||Sr(n.FIVE_MINUTES),d={topic:s,relay:r,expiry:l,active:!1,methods:a};this.core.expirer.set(s,l),await this.pairings.set(s,d),t.addTrace(gd),e.activatePairing&&await this.activate({topic:s}),this.events.emit(Jl,d),t.addTrace(yd),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),t.addTrace(fd);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(Ed)}try{await this.core.relayer.subscribe(s,{relay:r})}catch(u){throw t.setError(Nd),u}return t.addTrace(md),d}),qp(this,"activate",async({topic:e})=>{this.isInitialized();const t=Sr(n.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})}),qp(this,"ping",async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:s,resolve:i,reject:r}=Cr();this.events.once(kr("pairing_ping",e),({error:e})=>{e?r(e):i()}),await s()}}),qp(this,"updateExpiry",async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})}),qp(this,"updateMetadata",async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})}),qp(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),qp(this,"disconnect",async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",Yc("USER_DISCONNECTED")),await this.deletePairing(t))}),qp(this,"formatUriFromPairing",e=>{this.isInitialized();const{topic:t,relay:s,expiry:i,methods:r}=e,n=this.core.crypto.keychain.get(t);return xc({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:n,relay:s,expiryTimestamp:i,methods:r})}),qp(this,"sendRequest",async(e,t,s)=>{const i=v(t,s),r=await this.core.crypto.encode(e,i),n=Gl[t].req;return this.core.history.set(e,i),this.core.relayer.publish(e,r,n),i.id}),qp(this,"sendResult",async(e,t,s)=>{const i=A(e,s),r=await this.core.crypto.encode(t,i),n=(await this.core.history.get(t,e)).request.method,o=Gl[n].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(i)}),qp(this,"sendError",async(e,t,s)=>{const i=R(e,s),r=await this.core.crypto.encode(t,i),n=(await this.core.history.get(t,e)).request.method,o=Gl[n]?Gl[n].res:Gl.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(i)}),qp(this,"deletePairing",async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Yc("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])}),qp(this,"cleanup",async()=>{const e=this.pairings.getAll().filter(e=>Pr(e.expiry));await Promise.all(e.map(e=>this.deletePairing(e.topic)))}),qp(this,"onRelayEventRequest",async e=>{const{topic:t,payload:s}=e;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(t,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(t,s);default:return await this.onUnknownRpcMethodRequest(t,s)}}),qp(this,"onRelayEventResponse",async e=>{const{topic:t,payload:s}=e,i=(await this.core.history.get(t,s.id)).request.method;return"wc_pairingPing"===i?this.onPairingPingResponse(t,s):this.onUnknownRpcMethodResponse(i)}),qp(this,"onPairingPingRequest",async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.events.emit(Zl,{id:s,topic:e})}catch(i){await this.sendError(s,e,i),this.logger.error(i)}}),qp(this,"onPairingPingResponse",(e,t)=>{const{id:s}=t;setTimeout(()=>{U(t)?this.events.emit(kr("pairing_ping",s),{}):$(t)&&this.events.emit(kr("pairing_ping",s),{error:t.error})},500)}),qp(this,"onPairingDeleteRequest",async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(Xl,{id:s,topic:e})}catch(i){await this.sendError(s,e,i),this.logger.error(i)}}),qp(this,"onUnknownRpcMethodRequest",async(e,t)=>{const{id:s,method:i}=t;try{if(this.registeredMethods.includes(i))return;const t=Yc("WC_METHOD_UNSUPPORTED",i);await this.sendError(s,e,t),this.logger.error(t)}catch(r){await this.sendError(s,e,r),this.logger.error(r)}}),qp(this,"onUnknownRpcMethodResponse",e=>{this.registeredMethods.includes(e)||this.logger.error(Yc("WC_METHOD_UNSUPPORTED",e))}),qp(this,"isValidPair",(e,t)=>{var s;if(!ll(e)){const{message:s}=Jc("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(Cd),new Error(s)}if(!function(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if(el(e,!1))return!!t(e)||t(Ur(e))}catch{}return!1}(e.uri)){const{message:s}=Jc("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(Cd),new Error(s)}const i=_c(null==e?void 0:e.uri);if(null==(s=null==i?void 0:i.relay)||!s.protocol){const{message:e}=Jc("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(Cd),new Error(e)}if(null==i||!i.symKey){const{message:e}=Jc("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(Cd),new Error(e)}if(null!=i&&i.expiryTimestamp&&n.toMiliseconds(null==i?void 0:i.expiryTimestamp)<Date.now()){t.setError(Ad);const{message:e}=Jc("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}}),qp(this,"isValidPing",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)}),qp(this,"isValidDisconnect",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)}),qp(this,"isValidPairingTopic",async e=>{if(!el(e,!1)){const{message:t}=Jc("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=Jc("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Pr(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=Jc("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}),this.core=e,this.logger=g(t,this.name),this.pairings=new jp(this.core,this.logger,this.name,this.storagePrefix)}get context(){return w(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Jc("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(kl,async e=>{const{topic:t,message:s,transportType:i}=e;if(this.pairings.keys.includes(t)&&i!==ql.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const e=await this.core.crypto.decode(t,s);I(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):N(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e}),this.core.history.delete(t,e.id)),await this.core.relayer.messages.ack(t,s)}catch(vn){this.logger.error(vn)}})}registerExpirerEvents(){this.core.expirer.on(nd,async e=>{const{topic:t}=Ar(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Yl,{topic:t}))})}}var zp=Object.defineProperty,Fp=(e,t,s)=>((e,t,s)=>t in e?zp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Wp extends ws{constructor(e,t){super(e,t),this.core=e,this.logger=t,Fp(this,"records",new Map),Fp(this,"events",new u.EventEmitter),Fp(this,"name","history"),Fp(this,"version","0.3"),Fp(this,"cac
5hed",[]),Fp(this,"initialized",!1),Fp(this,"storagePrefix",El),Fp(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.records.set(e.id,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Fp(this,"set",(e,t,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:s}),this.records.has(t.id))return;const i={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:s,expiry:Sr(n.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(Ql,i)}),Fp(this,"resolve",async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response>"u"&&(t.response=$(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(ed,t))}),Fp(this,"get",async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t))),Fp(this,"delete",(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach(s=>{if(s.topic===e){if(typeof t<"u"&&s.id!==t)return;this.records.delete(s.id),this.events.emit(td,s)}}),this.persist()}),Fp(this,"exists",async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e)),Fp(this,"on",(e,t)=>{this.events.on(e,t)}),Fp(this,"once",(e,t)=>{this.events.once(e,t)}),Fp(this,"off",(e,t)=>{this.events.off(e,t)}),Fp(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=g(t,this.name)}get context(){return w(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(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:v(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),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 t=this.records.get(e);if(!t){const{message:t}=Jc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(sd)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=Jc("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(wn){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(wn)}}registerEventListeners(){this.events.on(Ql,e=>{const t=Ql;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(ed,e=>{const t=ed;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(td,e=>{const t=td;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(y.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{n.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(td,t,!1),e=!0)}),e&&this.persist()}catch(wn){this.logger.warn(wn)}}isInitialized(){if(!this.initialized){const{message:e}=Jc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Vp=Object.defineProperty,Hp=(e,t,s)=>((e,t,s)=>t in e?Vp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Kp extends Is{constructor(e,t){super(e,t),this.core=e,this.logger=t,Hp(this,"expirations",new Map),Hp(this,"events",new u.EventEmitter),Hp(this,"name","expirer"),Hp(this,"version","0.3"),Hp(this,"cac
5hed",[]),Hp(this,"initialized",!1),Hp(this,"storagePrefix",El),Hp(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>this.expirations.set(e.target,e)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Hp(this,"has",e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}}),Hp(this,"set",(e,t)=>{this.isInitialized();const s=this.formatTarget(e),i={target:s,expiry:t};this.expirations.set(s,i),this.checkExpiry(s,i),this.events.emit(id,{target:s,expiration:i})}),Hp(this,"get",e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)}),Hp(this,"del",e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),s=this.getExpiration(t);this.expirations.delete(t),this.events.emit(rd,{target:t,expiration:s})}}),Hp(this,"on",(e,t)=>{this.events.on(e,t)}),Hp(this,"once",(e,t)=>{this.events.once(e,t)}),Hp(this,"off",(e,t)=>{this.events.off(e,t)}),Hp(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=g(t,this.name)}get context(){return w(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("string"==typeof e)return function(e){return Nr("topic",e)}(e);if("number"==typeof e)return function(e){return Nr("id",e)}(e);const{message:t}=Jc("UNKNOWN_TYPE","Target type: "+typeof e);throw new Error(t)}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(od)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=Jc("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(wn){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(wn)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:t}=Jc("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:s}=t;n.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(nd,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(y.pulse,()=>this.checkExpirations()),this.events.on(id,e=>{const t=id;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(nd,e=>{const t=nd;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(rd,e=>{const t=rd;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Jc("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Gp=Object.defineProperty,Jp=(e,t,s)=>((e,t,s)=>t in e?Gp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Yp extends Ns{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,Jp(this,"name","verify-api"),Jp(this,"abortController"),Jp(this,"isDevEnv"),Jp(this,"verifyUrlV3",ld),Jp(this,"storagePrefix",El),Jp(this,"version",2),Jp(this,"publicKey"),Jp(this,"fetchPromise"),Jp(this,"init",async()=>{var e;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&n.toMiliseconds(null==(e=this.publicKey)?void 0:e.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Jp(this,"register",async e=>
5{if(!hr()||this.isDevEnv)return;const t=window.location.origin,{id:s,decryptedId:i}=e,r=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${s}&decryptedId=${i}`;try{const e=o.getDocument(),t=this.startAbortTimer(5*n.ONE_SECOND),i=await new Promise((i,n)=>{const o=()=>{window.removeEventListener("message",c),e.body.removeChild(a),n("attestation aborted")};this.abortController.signal.addEventListener("abort",o);const a=e.createElement("iframe");a.src=r,a.style.display="none",a.addEventListener("error",o,{signal:this.abortController.signal});const c=r=>{if(r.data&&"string"==typeof r.data)try{const n=JSON.parse(r.data);if("verify_attestation"===n.type){if(l(n.attestation).payload.id!==s)return;clearInterval(t),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",c),i(null===n.attestation?"":n.attestation)}}catch(n){this.logger.warn(n)}};e.body.appendChild(a),window.addEventListener("message",c,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",i),i}catch(a){this.logger.warn(a)}return""}),Jp(this,"resolve",async e=>{if(this.isDevEnv)return"";const{attestationId:t,hash:s,encryptedId:i}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if(l(t).payload.id!==i)return;const e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!s)return;const r=this.getVerifyUrl(null==e?void 0:e.verifyUrl);return this.fetchAttestation(s,r)}),Jp(this,"fetchAttestation",async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const s=this.startAbortTimer(5*n.ONE_SECOND),i=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(s),200===i.status?await i.json():void 0}),Jp(this,"getVerifyUrl",e=>{let t=e||cd;return dd.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${cd}`),t=cd),t}),Jp(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(n.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}}),Jp(this,"persistPublicKey",async e=>{this.logger.debug("persisting public key to local storage",e),await this.store.setItem(this.storeKey,e),this.publicKey=e}),Jp(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Jp(this,"isValidJwtAttestation",async e=>{const t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(i){this.logger.error(i),this.logger.warn("error validating attestation")}const s=await this.fetchAndPersistPublicKey();try{if(s)return this.validateAttestation(e,s)}catch(i){this.logger.error(i),this.logger.warn("error validating attestation")}}),Jp(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Jp(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async e=>{const t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))});const e=await this.fetchPromise;return this.fetchPromise=void 0,e}),Jp(this,"validateAttestation",(e,t)=>{const s=Ac(e,t.publicKey),i={hasExpired:n.toMiliseconds(s.exp)<Date.now(),payload:s};if(i.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:i.payload.origin,isScam:i.payload.isScam,isVerified:i.payload.isVerified}}),this.logger=g(t,this.name),this.abortController=new AbortController,this.isDevEnv=Rr(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return w(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),n.toMiliseconds(e))}}var Xp=Object.defineProperty,Zp=(e,t,s)=>((e,t,s)=>t in e?Xp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Qp extends As{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Zp(this,"context","echo"),Zp(this,"registerDeviceToken",async e=>{const{clientId:t,token:s,notificationType:i,enableEncrypted:r=!1}=e,n=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:i,token:s,always_raw:r})})}),this.logger=g(t,this.context)}}var eg=Object.defineProperty,tg=Object.getOwnPropertySymbols,sg=Object.prototype.hasOwnProperty,ig=Object.prototype.propertyIsEnumerable,rg=(e,t,s)=>t in e?eg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ng=(e,t)=>
5{for(var s in t||(t={}))sg.call(t,s)&&rg(e,s,t[s]);if(tg)for(var s of tg(t))ig.call(t,s)&&rg(e,s,t[s]);return e},og=(e,t,s)=>rg(e,"symbol"!=typeof t?t+"":t,s);class ag extends Ss{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,og(this,"context","event-client"),og(this,"storagePrefix",El),og(this,"storageVersion",.1),og(this,"events",new Map),og(this,"shouldPersist",!1),og(this,"init",async()=>{if(!Rr())try{const e={eventId:Tr(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:wr(this.core.relayer.protocol,this.core.relayer.version,Ll)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}}),og(this,"createEvent",e=>{const{event:t="ERROR",type:s="",properties:{topic:i,trace:r}}=e,n=Tr(),o=this.core.projectId||"",a=Date.now(),c=ng({eventId:n,timestamp:a,props:{event:t,type:s,properties:{topic:i,trace:r}},bundleId:o,domain:this.getAppDomain()},this.setMethods(n));return this.telemetryEnabled&&(this.events.set(n,c),this.shouldPersist=!0),c}),og(this,"getEvent",e=>{const{eventId:t,topic:s}=e;if(t)return this.events.get(t);const i=Array.from(this.events.values()).find(e=>e.props.properties.topic===s);return i?ng(ng({},i),this.setMethods(i.eventId)):void 0}),og(this,"deleteEvent",e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0}),og(this,"setEventListeners",()=>{this.core.heartbeat.on(y.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(e=>{n.fromMiliseconds(Date.now())-n.fromMiliseconds(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)})})}),og(this,"setMethods",e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)})),og(this,"addTrace",(e,t)=>{const s=this.events.get(e);s&&(s.props.properties.trace.push(t),this.events.set(e,s),this.shouldPersist=!0)}),og(this,"setError",(e,t)=>{const s=this.events.get(e);s&&(s.props.type=t,s.timestamp=Date.now(),this.events.set(e,s),this.shouldPersist=!0)}),og(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),og(this,"restore",async()=>{try{const e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach(e=>{this.events.set(e.eventId,ng(ng({},e),this.setMethods(e.eventId)))})}catch(e){this.logger.warn(e)}}),og(this,"submit",async()=>{if(!this.telemetryEnabled||0===this.events.size)return;const e=[];for(const[t,s]of this.events)s.props.type&&e.push(s);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(const t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(vn){this.logger.warn(vn)}}),og(this,"sendEvent",async e=>{const t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ll}${t}`,{method:"POST",body:JSON.stringify(e)})}),og(this,"getAppDomain",()=>mr().url),this.logger=g(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var cg=Object.defineProperty,lg=Object.getOwnPropertySymbols,dg=Object.prototype.hasOwnProperty,ug=Object.prototype.propertyIsEnumerable,hg=(e,t,s)=>t in e?cg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,pg=(e,t)=>
5{for(var s in t||(t={}))dg.call(t,s)&&hg(e,s,t[s]);if(lg)for(var s of lg(t))ug.call(t,s)&&hg(e,s,t[s]);return e},gg=(e,t,s)=>hg(e,"symbol"!=typeof t?t+"":t,s);const fg=class e extends gs{constructor(e){var t;super(e),gg(this,"protocol","wc"),gg(this,"version",2),gg(this,"name",bl),gg(this,"relayUrl"),gg(this,"projectId"),gg(this,"customStoragePrefix"),gg(this,"events",new u.EventEmitter),gg(this,"logger"),gg(this,"heartbeat"),gg(this,"relayer"),gg(this,"crypto"),gg(this,"storage"),gg(this,"history"),gg(this,"expirer"),gg(this,"pairing"),gg(this,"verify"),gg(this,"echoClient"),gg(this,"linkModeSupportedApps"),gg(this,"eventClient"),gg(this,"initialized",!1),gg(this,"logChunkController"),gg(this,"on",(e,t)=>this.events.on(e,t)),gg(this,"once",(e,t)=>this.events.once(e,t)),gg(this,"off",(e,t)=>this.events.off(e,t)),gg(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),gg(this,"dispatchEnvelope",({topic:e,message:t,sessionExists:s})=>{if(!e||!t)return;const i={topic:e,message:t,publishedAt:Date.now(),transportType:ql.link_mode};this.relayer.onLinkMessageEvent(i,{sessionExists:s})});const s=this.getGlobalCore(null==e?void 0:e.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(o){}this.projectId=null==e?void 0:e.projectId,this.relayUrl=(null==e?void 0:e.relayUrl)||Pl,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=h({level:"string"==typeof(null==e?void 0:e.logger)&&e.logger?e.logger:Cl,name:bl}),{logger:r,chunkLoggerController:n}=p({opts:i,maxSizeInBytes:null==e?void 0:e.maxLogBlobSizeInBytes,loggerOverride:null==e?void 0:e.logger});this.logChunkController=n,null!=(t=this.logChunkController)&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var e,t;null!=(e=this.logChunkController)&&e.downloadLogsBlobInBrowser&&(null==(t=this.logChunkController)||t.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=g(r,this.name),this.heartbeat=new f,this.crypto=new Rh(this,this.logger,null==e?void 0:e.keychain),this.history=new Wp(this,this.logger),this.expirer=new Kp(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new m(pg(pg({},Il),null==e?void 0:e.storageOptions)),this.relayer=new Ep({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Bp(this,this.logger),this.verify=new Yp(this,this.logger,this.storage),this.echoClient=new Qp(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new ag(this,this.logger,null==e?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const s=new e(t);await s.initialize();const i=await s.crypto.getClientId();return await s.storage.setItem("WALLETCONNECT_CLIENT_ID",i),s}get context(){return w(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return null==(e=this.logChunkController)?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Fl,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(Fl)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(wn){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,wn),this.logger.error(wn.message),wn}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,s=`${t}_count`;return globalThis[s]=(globalThis[s]||0)+1,globalThis[s],globalThis[t]}catch(mn){return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${(null==(t=e.opts)?void 0:t.customStoragePrefix)||""}`;globalThis[s]=e}catch(s){}}isGlobalCoreDisabled(){try{return typeof process<"u"&&"true"===yl.DISABLE_GLOBAL_CORE}catch{return!0}}},mg="client",wg=`wc@2:${mg}:`,vg=mg,yg="error",bg="WALLETCONNECT_DEEPLINK_CHOICE",Eg="Proposal expired",Cg=n.SEVEN_DAYS,Ig={wc_sessionPropose:{req:{ttl:n.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:n.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:n.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:n.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:n.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:n.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:n.ONE_DAY,prompt:!1,tag:1104},res:{ttl:n.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:n.ONE_DAY,prompt:!1,tag:1106},res:{ttl:n.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:n.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:n.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:n.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:n.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:n.ONE_DAY,prompt:!1,tag:1112},res:{ttl:n.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:n.ONE_DAY,prompt:!1,tag:1114},res:{ttl:n.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:n.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:n.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:n.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:n.FIVE_MINUTES,prompt:!1,tag:1119}}},Ng={min:n.FIVE_MINUTES,max:n.SEVEN_DAYS},Ag="IDLE",Sg="ACTIVE",Pg={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},kg=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],_g="[email protected]:auth:",Og=`${_g}:PUB_KEY`;var xg=Object.defineProperty,Tg=Object.defineProperties,Rg=Object.getOwnPropertyDescriptors,Ug=Object.getOwnPropertySymbols,$g=Object.prototype.hasOwnProperty,Dg=Object.prototype.propertyIsEnumerable,Mg=(e,t,s)=>t in e?xg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,jg=(e,t)=>
5{for(var s in t||(t={}))$g.call(t,s)&&Mg(e,s,t[s]);if(Ug)for(var s of Ug(t))Dg.call(t,s)&&Mg(e,s,t[s]);return e},Lg=(e,t)=>Tg(e,Rg(t)),qg=(e,t,s)=>Mg(e,"symbol"!=typeof t?t+"":t,s);class Bg extends Os{constructor(e){super(e),qg(this,"name","engine"),qg(this,"events",new S),qg(this,"initialized",!1),qg(this,"requestQueue",{state:Ag,queue:[]}),qg(this,"sessionRequestQueue",{state:Ag,queue:[]}),qg(this,"requestQueueDelay",n.ONE_SECOND),qg(this,"expectedPairingMethodMap",new Map),qg(this,"recentlyDeletedMap",new Map),qg(this,"recentlyDeletedLimit",200),qg(this,"relayMessageCache",[]),qg(this,"pendingSessions",new Map),qg(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(Ig)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},n.toMiliseconds(this.requestQueueDelay)))}),qg(this,"connect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t=Lg(jg({},e),{requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}});await this.isValidConnect(t),t.optionalNamespaces=function(e,t){var s,i,r,n,o,a;const c=Vc(e),l=Vc(t),d={},u=Object.keys(c).concat(Object.keys(l));for(const h of u)d[h]={chains:_r(null==(s=c[h])?void 0:s.chains,null==(i=l[h])?void 0:i.chains),methods:_r(null==(r=c[h])?void 0:r.methods,null==(n=l[h])?void 0:n.methods),events:_r(null==(o=c[h])?void 0:o.events,null==(a=l[h])?void 0:a.events)};return d}(t.requiredNamespaces,t.optionalNamespaces),t.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:r,sessionProperties:o,scopedProperties:a,relays:c}=t;let l,d=s,u=!1;try{if(d){const e=this.client.core.pairing.pairings.get(d);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),u=e.active}}catch(E){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),E}if(!d||!u){const{topic:e,uri:t}=await this.client.core.pairing.create();d=e,l=t}if(!d){const{message:e}=Jc("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(e)}const h=await this.client.core.crypto.generateKeyPair(),p=Ig.wc_sessionPropose.req.ttl||n.FIVE_MINUTES,g=Sr(p),f=Lg(jg(jg({requiredNamespaces:i,optionalNamespaces:r,relays:c??[{protocol:"irn"}],proposer:{publicKey:h,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:d},o&&{sessionProperties:o}),a&&{scopedProperties:a}),{id:D()}),m=kr("session_connect",f.id),{reject:w,resolve:v,done:y}=Cr(p,Eg),b=({id:e})=>{e===f.id&&(this.client.events.off("proposal_expire",b),this.pendingSessions.delete(f.id),this.events.emit(m,{error:{message:Eg,code:0}}))};return this.client.events.on("proposal_expire",b),this.events.once(m,({error:e,session:t})=>{this.client.events.off("proposal_expire",b),e?w(e):t&&v(t)}),await this.sendRequest({topic:d,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:l,approval:y}}),qg(this,"pair",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(mn){throw this.client.logger.error("pair() failed"),mn}}),qg(this,"approve",async e=>{var t,s,i;const r=this.client.core.eventClient.createEvent({properties:{topic:null==(t=null==e?void 0:e.id)?void 0:t.toString(),trace:[Pd]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(I){throw r.setError(Dd),I}try{await this.isValidProposalId(null==e?void 0:e.id)}catch(I){throw this.client.logger.error(`approve() -> proposal.get(${null==e?void 0:e.id}) failed`),r.setError(zd),I}try{await this.isValidApprove(e)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(Bd),I}const{id:n,relayProtocol:o,namespaces:a,sessionProperties:c,scopedProperties:l,sessionConfig:d}=e,u=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:r.eventId});const{pairingTopic:h,proposer:p,requiredNamespaces:g,optionalNamespaces:f}=u;let m=null==(s=this.client.core.eventClient)?void 0:s.getEvent({topic:h});m||(m=null==(i=this.client.core.eventClient)?void 0:i.createEvent({type:Pd,properties:{topic:h,trace:[Pd,kd]}}));const w=await this.client.core.crypto.generateKeyPair(),v=p.publicKey,y=await this.client.core.crypto.generateSharedKey(w,v),b=jg(jg(jg({relay:{protocol:o??"irn"},namespaces:a,controller:{publicKey:w,metadata:this.client.metadata},expiry:Sr(Cg)},c&&{sessionProperties:c}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),E=ql.relay;m.addTrace(_d);try{await this.client.core.relayer.subscribe(y,{transportType:E})}catch(I){throw m.setError(jd),I}m.addTrace(Od);const C=Lg(jg({},b),{topic:y,requiredNamespaces:g,optionalNamespaces:f,pairingTopic:h,acknowledged:!1,self:b.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:w,transportType:ql.relay});await this.client.session.set(y,C),m.addTrace(Rd);try{m.addTrace(Ud),await this.sendRequest({topic:y,method:"wc_sessionSettle",params:b,throwOnFailedPublish:!0}).catch(e=>{throw null==m||m.setError(qd),e}),m.addTrace($d),m.addTrace(xd),await this.sendResult({id:n,topic:h,result:{relay:{protocol:o??"irn"},responderPublicKey:w},throwOnFailedPublish:!0}).catch(e=>{throw null==m||m.setError(Ld),e}),m.addTrace(Td)}catch(I){throw this.client.logger.error(I),this.client.session.delete(y,Yc("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(y),I}
5return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:h,metadata:p.metadata}),await this.client.proposal.delete(n,Yc("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:h}),await this.setExpiry(y,Sr(Cg)),{topic:y,acknowledged:()=>Promise.resolve(this.client.session.get(y))}}),qg(this,"reject",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(r){throw this.client.logger.error("reject() -> isValidReject() failed"),r}const{id:t,reason:s}=e;let i;try{i=this.client.proposal.get(t).pairingTopic}catch(r){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),r}i&&(await this.sendError({id:t,topic:i,error:s,rpcOpts:Ig.wc_sessionPropose.reject}),await this.client.proposal.delete(t,Yc("USER_DISCONNECTED")))}),qg(this,"update",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(l){throw this.client.logger.error("update() -> isValidUpdate() failed"),l}const{topic:t,namespaces:s}=e,{done:i,resolve:r,reject:n}=Cr(),o=D(),a=T().toString(),c=this.client.session.get(t).namespaces;return this.events.once(kr("session_update",o),({error:e})=>{e?n(e):r()}),await this.client.session.update(t,{namespaces:s}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:o,relayRpcId:a}).catch(e=>{this.client.logger.error(e),this.client.session.update(t,{namespaces:c}),n(e)}),{acknowledged:i}}),qg(this,"extend",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(o){throw this.client.logger.error("extend() -> isValidExtend() failed"),o}const{topic:t}=e,s=D(),{done:i,resolve:r,reject:n}=Cr();return this.events.once(kr("session_extend",s),({error:e})=>{e?n(e):r()}),await this.setExpiry(t,Sr(Cg)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(e=>{n(e)}),{acknowledged:i}}),qg(this,"request",async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(f){throw this.client.logger.error("request() -> isValidRequest() failed"),f}const{chainId:t,request:s,topic:i,expiry:r=Ig.wc_sessionRequest.req.ttl}=e,n=this.client.session.get(i);(null==n?void 0:n.transportType)===ql.relay&&await this.confirmOnlineStateOrThrow();const o=D(),a=T().toString(),{done:c,resolve:l,reject:d}=Cr(r,"Request expired. Please try again.");this.events.once(kr("session_request",o),({error:e,result:t})=>{e?d(e):l(t)});const u="wc_sessionRequest",h=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);if(h)return await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:i,method:u,params:{request:Lg(jg({},s),{expiryTimestamp:Sr(r)}),chainId:t},expiry:r,throwOnFailedPublish:!0,appLink:h}).catch(e=>d(e)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:t,id:o}),await c();const p={request:Lg(jg({},s),{expiryTimestamp:Sr(r)}),chainId:t},g=this.shouldSetTVF(u,p);return await Promise.all([new Promise(async e=>{await this.sendRequest(jg({clientRpcId:o,relayRpcId:a,topic:i,method:u,params:p,expiry:r,throwOnFailedPublish:!0},g&&{tvf:this.getTVFParams(o,p)})).catch(e=>d(e)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:t,id:o}),e()}),new Promise(async e=>{var t;if(null==(t=n.sessionConfig)||!t.disableDeepLink){const e=await async function(e,t){let s="";try{if(hr()&&(s=localStorage.getItem(t),s))return s;s=await e.getItem(t)}catch(r){}return s}(this.client.core.storage,bg);await Or({id:o,topic:i,wcDeepLink:e})}e()}),c()]).then(e=>e[2])}),qg(this,"respond",async e=>{this.isInitialized(),await this.isValidRespond(e);const{topic:t,response:s}=e,{id:i}=s,r=this.client.session.get(t);r.transportType===ql.relay&&await this.confirmOnlineStateOrThrow();const n=this.getAppLinkIfEnabled(r.peer.metadata,r.transportType);U(s)?await this.sendResult({id:i,topic:t,result:s.result,throwOnFailedPublish:!0,appLink:n}):$(s)&&await this.sendError({id:i,topic:t,error:s.error,appLink:n}),this.cleanupAfterResponse(e)}),qg(this,"ping",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=D(),s=T().toString(),{done:i,resolve:r,reject:n}=Cr();this.events.once(kr("session_ping",e),({error:e})=>{e?n(e):r()}),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:s}),i()])}else this.client.core.pairing.pairings.keys.includes(t)&&(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:t}))}),qg(this,"emit",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:s,chainId:i}=e,r=T().toString(),n=D();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:r,clientRpcId:n})}),qg(this,"disconnect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:Yc("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=Jc("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}
5await this.client.core.pairing.disconnect({topic:t})}}),qg(this,"find",e=>(this.isInitialized(),this.client.session.getAll().filter(t=>function(e,t){const{requiredNamespaces:s}=t,i=Object.keys(e.namespaces),r=Object.keys(s);let n=!0;return!!yr(r,i)&&(i.forEach(t=>{const{accounts:i,methods:r,events:o}=e.namespaces[t],a=zc(i),c=s[t];yr(Yi(t,c),a)&&yr(c.methods,r)&&yr(c.events,o)||(n=!1)}),n)}(t,e)))),qg(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),qg(this,"authenticate",async(e,t)=>{var s;this.isInitialized(),this.isValidAuthenticate(e);const i=t&&this.client.core.linkModeSupportedApps.includes(t)&&(null==(s=this.client.metadata.redirect)?void 0:s.linkMode),r=i?ql.link_mode:ql.relay;r===ql.relay&&await this.confirmOnlineStateOrThrow();const{chains:n,statement:o="",uri:a,domain:c,nonce:l,type:d,exp:u,nbf:h,methods:p=[],expiry:g}=e,f=[...e.resources||[]],{topic:m,uri:w}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:w}});const y=await this.client.core.crypto.generateKeyPair(),b=gc(y);if(await Promise.all([this.client.auth.authKeys.set(Og,{responseTopic:b,publicKey:y}),this.client.auth.pairingTopics.set(b,{topic:b,pairingTopic:m})]),await this.client.core.relayer.subscribe(b,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${m}`),p.length>0){const{namespace:e}=Ji(n[0]);let t=jn(e,"request",p);zn(f)&&(t=Ln(t,f.pop())),f.push(t)}const E=g&&g>Ig.wc_sessionAuthenticate.req.ttl?g:Ig.wc_sessionAuthenticate.req.ttl,C={authPayload:{type:d??"caip122",chains:n,statement:o,aud:a,domain:c,version:"1",nonce:l,iat:(new Date).toISOString(),exp:u,nbf:h,resources:f},requester:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:Sr(E)},I={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:n,methods:[...new Set(["personal_sign",...p])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:Sr(Ig.wc_sessionPropose.req.ttl),id:D()},{done:N,resolve:A,reject:S}=Cr(E,"Request expired"),P=D(),k=kr("session_connect",I.id),_=kr("session_request",P),O=async({error:e,session:t})=>{this.events.off(_,x),e?S(e):t&&A({session:t})},x=async e=>{var s,i,n;if(await this.deletePendingAuthRequest(P,{message:"fulfilled",code:0}),e.error){const t=Yc("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(k,O),S(e.error.message))}await this.deleteProposal(I.id),this.events.off(k,O);const{cacaos:o,responder:a}=e.result,c=[],l=[];for(const t of o){await Tn({cacao:t,projectId:this.client.core.projectId})||(this.client.logger.error(t,"Signature verification failed"),S(Yc("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:e}=t,s=zn(e.resources),i=[On(e.iss)],r=xn(e.iss);if(s){const e=qn(s),t=Bn(s);c.push(...e),i.push(...t)}for(const t of i)l.push(`${t}:${r}`)}const d=await this.client.core.crypto.generateSharedKey(y,a.publicKey);let u;c.length>0&&(u={topic:d,acknowledged:!0,self:{publicKey:y,metadata:this.client.metadata},peer:a,controller:a.publicKey,expiry:Sr(Cg),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:Hc([...new Set(c)],[...new Set(l)]),transportType:r},await this.client.core.relayer.subscribe(d,{transportType:r}),await this.client.session.set(d,u),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:a.metadata}),u=this.client.session.get(d)),null!=(s=this.client.metadata.redirect)&&s.linkMode&&null!=(i=a.metadata.redirect)&&i.linkMode&&null!=(n=a.metadata.redirect)&&n.universal&&t&&(this.client.core.addLinkModeSupportedApp(a.metadata.redirect.universal),this.client.session.update(d,{transportType:ql.link_mode})),A({auths:o,session:u})};let T;this.events.once(k,O),this.events.once(_,x);try{if(i){const e=v("wc_sessionAuthenticate",C,P);this.client.core.history.set(m,e);const s=await this.client.core.crypto.encode("",e,{type:2,encoding:uc});T=Tc(t,m,s)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:C,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:P}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:I,expiry:Ig.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:I.id})])}catch(R){throw this.events.off(k,O),this.events.off(_,x),R}return await this.setProposal(I.id,I),await this.setAuthRequest(P,{request:Lg(jg({},C),{verifyContext:{}}),pairingTopic:m,transportType:r}),{uri:T??w,response:N}}),qg(this,"approveSessionAuthenticate",async e=>{const{id:t,auths:s}=e,i=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[Fd]}});try{this.isInitialized()}catch(g){throw i.setError(Yd),g}const r=this.getPendingAuthRequest(t);if(!r)throw i.setError(eu),new Error(`Could not find pending auth request with id ${t}`);const n=r.transportType||ql.relay;n===ql.relay&&await this.confirmOnlineStateOrThrow();const o=r.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=gc(o),l={type:1,receiverPublicKey:o,senderPublicKey:a},d=[],u=[];for(const f of s){if(!(await Tn({cacao:f,projectId:this.client.core.projectId}))){i.setError(Xd);const e=Yc("SESSION_SETTLEMENT_FAILED","Signature verification failed");
5throw await this.sendError({id:t,topic:c,error:e,encodeOpts:l}),new Error(e.message)}i.addTrace(Vd);const{p:e}=f,s=zn(e.resources),r=[On(e.iss)],n=xn(e.iss);if(s){const e=qn(s),t=Bn(s);d.push(...e),r.push(...t)}for(const t of r)u.push(`${t}:${n}`)}const h=await this.client.core.crypto.generateSharedKey(a,o);let p;if(i.addTrace(Wd),(null==d?void 0:d.length)>0){p={topic:h,acknowledged:!0,self:{publicKey:a,metadata:this.client.metadata},peer:{publicKey:o,metadata:r.requester.metadata},controller:o,expiry:Sr(Cg),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:Hc([...new Set(d)],[...new Set(u)]),transportType:n},i.addTrace(Kd);try{await this.client.core.relayer.subscribe(h,{transportType:n})}catch(g){throw i.setError(Zd),g}i.addTrace(Gd),await this.client.session.set(h,p),i.addTrace(Hd),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}i.addTrace(Jd);try{await this.sendResult({topic:c,id:t,result:{cacaos:s,responder:{publicKey:a,metadata:this.client.metadata}},encodeOpts:l,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(r.requester.metadata,n)})}catch(g){throw i.setError(Qd),g}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:r.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:p}}),qg(this,"rejectSessionAuthenticate",async e=>{this.isInitialized();const{id:t,reason:s}=e,i=this.getPendingAuthRequest(t);if(!i)throw new Error(`Could not find pending auth request with id ${t}`);i.transportType===ql.relay&&await this.confirmOnlineStateOrThrow();const r=i.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),o=gc(r),a={type:1,receiverPublicKey:r,senderPublicKey:n};await this.sendError({id:t,topic:o,error:s,encodeOpts:a,rpcOpts:Ig.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.client.proposal.delete(t,Yc("USER_DISCONNECTED"))}),qg(this,"formatAuthMessage",e=>{this.isInitialized();const{request:t,iss:s}=e;return Rn(t,s)}),qg(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(0!==this.relayMessageCache.length)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(wn){this.client.logger.error(wn)}},50)}),qg(this,"cleanupDuplicatePairings",async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(s=>{var i,r;return(null==(i=s.peerMetadata)?void 0:i.url)&&(null==(r=s.peerMetadata)?void 0:r.url)===e.peer.metadata.url&&s.topic&&s.topic!==t.topic});if(0===s.length)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(e=>this.client.core.pairing.disconnect({topic:e.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(mn){this.client.logger.error(mn)}}),qg(this,"deleteSession",async e=>{var t;const{topic:s,expirerHasDeleted:i=!1,emitEvent:r=!0,id:n=0}=e,{self:o}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,Yc("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(o.publicKey)&&await this.client.core.crypto.deleteKeyPair(o.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),i||this.client.core.expirer.del(s),this.client.core.storage.removeItem(bg).catch(e=>this.client.logger.warn(e)),this.getPendingSessionRequests().forEach(e=>{e.topic===s&&this.deletePendingSessionRequest(e.id,Yc("USER_DISCONNECTED"))}),s===(null==(t=this.sessionRequestQueue.queue[0])?void 0:t.topic)&&(this.sessionRequestQueue.state=Ag),r&&this.client.events.emit("session_delete",{id:n,topic:s})}),qg(this,"deleteProposal",async(e,t)=>{if(t)try{const t=this.client.proposal.get(e),s=this.client.core.eventClient.getEvent({topic:t.pairingTopic});null==s||s.setError(Md)}catch{}await Promise.all([this.client.proposal.delete(e,Yc("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")}),qg(this,"deletePendingSessionRequest",async(e,t,s=!1)=>
5{await Promise.all([this.client.pendingRequest.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(t=>t.id!==e),s&&(this.sessionRequestQueue.state=Ag,this.client.events.emit("session_request_expire",{id:e}))}),qg(this,"deletePendingAuthRequest",async(e,t,s=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),s?Promise.resolve():this.client.core.expirer.del(e)])}),qg(this,"setExpiry",async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))}),qg(this,"setProposal",async(e,t)=>{this.client.core.expirer.set(e,Sr(Ig.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)}),qg(this,"setAuthRequest",async(e,t)=>{const{request:s,pairingTopic:i,transportType:r=ql.relay}=t;this.client.core.expirer.set(e,s.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:e,pairingTopic:i,verifyContext:s.verifyContext,transportType:r})}),qg(this,"setPendingSessionRequest",async e=>{const{id:t,topic:s,params:i,verifyContext:r}=e,n=i.request.expiryTimestamp||Sr(Ig.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:s,params:i,verifyContext:r})}),qg(this,"sendRequest",async e=>{const{topic:t,method:s,params:i,expiry:r,relayRpcId:n,clientRpcId:o,throwOnFailedPublish:a,appLink:c,tvf:l}=e,d=v(s,i,o);let u;const h=!!c;try{const e=h?uc:dc;u=await this.client.core.crypto.encode(t,d,{encoding:e})}catch(f){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),f}let p;if(kg.includes(s)){const e=fc(JSON.stringify(d)),t=fc(u);p=await this.client.core.verify.register({id:t,decryptedId:e})}const g=Ig[s].req;if(g.attestation=p,r&&(g.ttl=r),n&&(g.id=n),this.client.core.history.set(t,d),h){const e=Tc(c,t,u);await global.Linking.openURL(e,this.client.name)}else{const e=Ig[s].req;r&&(e.ttl=r),n&&(e.id=n),e.tvf=Lg(jg({},l),{correlationId:d.id}),a?(e.internal=Lg(jg({},e.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(t,u,e)):this.client.core.relayer.publish(t,u,e).catch(e=>this.client.logger.error(e))}return d.id}),qg(this,"sendResult",async e=>{const{id:t,topic:s,result:i,throwOnFailedPublish:r,encodeOpts:n,appLink:o}=e,a=A(t,i);let c;const l=o&&typeof(null==global?void 0:global.Linking)<"u";try{const e=l?uc:dc;c=await this.client.core.crypto.encode(s,a,Lg(jg({},n||{}),{encoding:e}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),h}let d,u;try{d=await this.client.core.history.get(s,t);const e=d.request;try{this.shouldSetTVF(e.method,e.params)&&(u=this.getTVFParams(t,e.params,i))}catch(p){this.client.logger.warn("sendResult() -> getTVFParams() failed",p)}}catch(h){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${t}) failed`),h}if(l){const e=Tc(o,s,c);await global.Linking.openURL(e,this.client.name)}else{const e=d.request.method,i=Ig[e].res;i.tvf=Lg(jg({},u),{correlationId:t}),r?(i.internal=Lg(jg({},i.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,c,i)):this.client.core.relayer.publish(s,c,i).catch(e=>this.client.logger.error(e))}await this.client.core.history.resolve(a)}),qg(this,"sendError",async e=>{const{id:t,topic:s,error:i,encodeOpts:r,rpcOpts:n,appLink:o}=e,a=R(t,i);let c;const l=o&&typeof(null==global?void 0:global.Linking)<"u";try{const e=l?uc:dc;c=await this.client.core.crypto.encode(s,a,Lg(jg({},r||{}),{encoding:e}))}catch(u){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),u}let d;try{d=await this.client.core.history.get(s,t)}catch(u){throw this.client.logger.error(`sendError() -> history.get(${s}, ${t}) failed`),u}if(l){const e=Tc(o,s,c);await global.Linking.openURL(e,this.client.name)}else{const e=d.request.method,t=n||Ig[e].res;this.client.core.relayer.publish(s,c,t)}await this.client.core.history.resolve(a)}),qg(this,"cleanup",async()=>{const e=[],t=[];
5this.client.session.getAll().forEach(t=>{let s=!1;Pr(t.expiry)&&(s=!0),this.client.core.crypto.keychain.has(t.topic)||(s=!0),s&&e.push(t.topic)}),this.client.proposal.getAll().forEach(e=>{Pr(e.expiryTimestamp)&&t.push(e.id)}),await Promise.all([...e.map(e=>this.deleteSession({topic:e})),...t.map(e=>this.deleteProposal(e))])}),qg(this,"onProviderMessageEvent",async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)}),qg(this,"onRelayEventRequest",async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()}),qg(this,"processRequestsQueue",async()=>{if(this.requestQueue.state!==Sg){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Sg;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(mn){this.client.logger.warn(mn)}}this.requestQueue.state=Ag}else this.client.logger.info("Request queue already active, skipping...")}),qg(this,"processRequest",async e=>{const{topic:t,payload:s,attestation:i,transportType:r,encryptedId:n}=e,o=s.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:o}))switch(o){case"wc_sessionPropose":return await this.onSessionProposeRequest
5({topic:t,payload:s,attestation:i,encryptedId:n});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,s);case"wc_sessionPing":return await this.onSessionPingRequest(t,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});case"wc_sessionEvent":return await this.onSessionEventRequest(t,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:s,attestation:i,encryptedId:n,transportType:r});default:return this.client.logger.info(`Unsupported request method ${o}`)}}),qg(this,"onRelayEventResponse",async e=>{const{topic:t,payload:s,transportType:i}=e,r=(await this.client.core.history.get(t,s.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(t,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,s);case"wc_sessionExtend":return this.onSessionExtendResponse(t,s);case"wc_sessionPing":return this.onSessionPingResponse(t,s);case"wc_sessionRequest":return this.onSessionRequestResponse(t,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,s);default:return this.client.logger.info(`Unsupported response method ${r}`)}}),qg(this,"onRelayEventUnknownPayload",e=>{const{topic:t}=e,{message:s}=Jc("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),qg(this,"shouldIgnorePairingRequest",e=>{const{topic:t,requestMethod:s}=e,i=this.expectedPairingMethodMap.get(t);return!(!i||i.includes(s))&&!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),qg(this,"onSessionProposeRequest",async e=>{const{topic:t,payload:s,attestation:i,encryptedId:r}=e,{params:n,id:o}=s;try{const e=this.client.core.eventClient.getEvent({topic:t});0===this.client.events.listenerCount("session_proposal")&&(null==e||e.setError(Sd)),this.isValidConnect(jg({},s.params));const a=n.expiryTimestamp||Sr(Ig.wc_sessionPropose.req.ttl),c=jg({id:o,pairingTopic:t,expiryTimestamp:a},n);await this.setProposal(o,c);const l=await this.getVerifyContext({attestationId:i,hash:fc(JSON.stringify(s)),encryptedId:r,metadata:c.proposer.metadata});null==e||e.addTrace(bd),this.client.events.emit("session_proposal",{id:o,params:c,verifyContext:l})}catch(a){await this.sendError({id:o,topic:t,error:a,rpcOpts:Ig.wc_sessionPropose.autoReject}),this.client.logger.error(a)}}),qg(this,"onSessionProposeResponse",async(e,t,s)=>{const{id:i}=t;if(U(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const o=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:o});const a=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});const c=await this.client.core.crypto.generateSharedKey(o,a);this.pendingSessions.set(i,{sessionTopic:c,pairingTopic:e,proposalId:i,publicKey:o});const l=await this.client.core.relayer.subscribe(c,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:e})}else if($(t)){await this.client.proposal.delete(i,Yc("USER_DISCONNECTED"));const e=kr("session_connect",i);if(0===this.events.listenerCount(e))throw new Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}}),qg(this,"onSessionSettleRequest",async(e,t)=>{const{id:s,params:i}=t;try{this.isValidSessionSettleRequest(i);const{relay:s,controller:r,expiry:n,namespaces:o,sessionProperties:a,scopedProperties:c,sessionConfig:l}=t.params,d=[...this.pendingSessions.values()].find(t=>t.sessionTopic===e);if(!d)return this.client.logger.error(`Pending session not found for topic ${e}`);const u=this.client.proposal.get(d.proposalId),h=Lg(jg(jg(jg({topic:e,relay:s,expiry:n,namespaces:o,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:u.requiredNamespaces,optionalNamespaces:u.optionalNamespaces,controller:r.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:r.publicKey,metadata:r.metadata}},a&&{sessionProperties:a}),c&&{scopedProperties:c}),l&&{sessionConfig:l}),{transportType:ql.relay});await this.client.session.set(h.topic,h),await this.setExpiry(h.topic,h.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:h.peer.metadata}),this.client.events.emit("session_connect",{session:h}),this.events.emit(kr("session_connect",d.proposalId),{session:h}
5),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(h),await this.sendResult({id:t.id,topic:e,result:!0,throwOnFailedPublish:!0})}catch(r){await this.sendError({id:s,topic:e,error:r}),this.client.logger.error(r)}}),qg(this,"onSessionSettleResponse",async(e,t)=>{const{id:s}=t;U(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(kr("session_approve",s),{})):$(t)&&(await this.client.session.delete(e,Yc("USER_DISCONNECTED")),this.events.emit(kr("session_approve",s),{error:t.error}))}),qg(this,"onSessionUpdateRequest",async(e,t)=>{const{params:s,id:i}=t;try{const t=`${e}_session_update`,n=vl.get(t);if(n&&this.isRequestOutOfSync(n,i))return this.client.logger.warn(`Discarding out of sync request - ${i}`),void this.sendError({id:i,topic:e,error:Yc("INVALID_UPDATE_REQUEST")});this.isValidUpdate(jg({topic:e},s));try{vl.set(t,i),await this.client.session.update(e,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:e,result:!0,throwOnFailedPublish:!0})}catch(r){throw vl.delete(t),r}this.client.events.emit("session_update",{id:i,topic:e,params:s})}catch(n){await this.sendError({id:i,topic:e,error:n}),this.client.logger.error(n)}}),qg(this,"isRequestOutOfSync",(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3)),qg(this,"onSessionUpdateResponse",(e,t)=>{const{id:s}=t,i=kr("session_update",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);U(t)?this.events.emit(kr("session_update",s),{}):$(t)&&this.events.emit(kr("session_update",s),{error:t.error})}),qg(this,"onSessionExtendRequest",async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,Sr(Cg)),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:e})}catch(i){await this.sendError({id:s,topic:e,error:i}),this.client.logger.error(i)}}),qg(this,"onSessionExtendResponse",(e,t)=>{const{id:s}=t,i=kr("session_extend",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);U(t)?this.events.emit(kr("session_extend",s),{}):$(t)&&this.events.emit(kr("session_extend",s),{error:t.error})}),qg(this,"onSessionPingRequest",async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:e})}catch(i){await this.sendError({id:s,topic:e,error:i}),this.client.logger.error(i)}}),qg(this,"onSessionPingResponse",(e,t)=>{const{id:s}=t,i=kr("session_ping",s);setTimeout(()=>{if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners 2176`);U(t)?this.events.emit(kr("session_ping",s),{}):$(t)&&this.events.emit(kr("session_ping",s),{error:t.error})},500)}),qg(this,"onSessionDeleteRequest",async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e,reason:t.params}),Promise.all([new Promise(t=>{this.client.core.relayer.once(Ul,async()=>{t(await this.deleteSession({topic:e,id:s}))})}),this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:e,error:Yc("USER_DISCONNECTED")})]).catch(e=>this.client.logger.error(e))}catch(i){this.client.logger.error(i)}}),qg(this,"onSessionRequest",async e=>{var t,s,i;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:c}=e,{id:l,params:d}=n;try{await this.isValidRequest(jg({topic:r},d));const e=this.client.session.get(r),n={id:l,topic:r,params:d,verifyContext:await this.getVerifyContext({attestationId:o,hash:fc(JSON.stringify(v("wc_sessionRequest",d,l))),encryptedId:a,metadata:e.peer.metadata,transportType:c})};await this.setPendingSessionRequest(n),c===ql.link_mode&&null!=(t=e.peer.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(null==(s=e.peer.metadata.redirect)?void 0:s.universal),null!=(i=this.client.signConfig)&&i.disableRequestQueue?this.emitSessionRequest(n):(this.addSessionRequestToSessionRequestQueue(n),this.processSessionRequestQueue())}
5catch(u){await this.sendError({id:l,topic:r,error:u}),this.client.logger.error(u)}}),qg(this,"onSessionRequestResponse",(e,t)=>{const{id:s}=t,i=kr("session_request",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);U(t)?this.events.emit(kr("session_request",s),{result:t.result}):$(t)&&this.events.emit(kr("session_request",s),{error:t.error})}),qg(this,"onSessionEventRequest",async(e,t)=>{const{id:s,params:i}=t;try{const t=`${e}_session_event_${i.event.name}`,r=vl.get(t);if(r&&this.isRequestOutOfSync(r,s))return void this.client.logger.info(`Discarding out of sync request - ${s}`);this.isValidEmit(jg({topic:e},i)),this.client.events.emit("session_event",{id:s,topic:e,params:i}),vl.set(t,s)}catch(r){await this.sendError({id:s,topic:e,error:r}),this.client.logger.error(r)}}),qg(this,"onSessionAuthenticateResponse",(e,t)=>{const{id:s}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),U(t)?this.events.emit(kr("session_request",s),{result:t.result}):$(t)&&this.events.emit(kr("session_request",s),{error:t.error})}),qg(this,"onSessionAuthenticateRequest",async e=>{var t;const{topic:s,payload:i,attestation:r,encryptedId:n,transportType:o}=e;try{const{requester:e,authPayload:a,expiryTimestamp:c}=i.params,l=await this.getVerifyContext({attestationId:r,hash:fc(JSON.stringify(i)),encryptedId:n,metadata:e.metadata,transportType:o}),d={requester:e,pairingTopic:s,id:i.id,authPayload:a,verifyContext:l,expiryTimestamp:c};await this.setAuthRequest(i.id,{request:d,pairingTopic:s,transportType:o}),o===ql.link_mode&&null!=(t=e.metadata.redirect)&&t.universal&&this.client.core.addLinkModeSupportedApp(e.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:i.params,id:i.id,verifyContext:l})}catch(a){this.client.logger.error(a);const e=i.params.requester.publicKey,t=await this.client.core.crypto.generateKeyPair(),r=this.getAppLinkIfEnabled(i.params.requester.metadata,o),n={type:1,receiverPublicKey:e,senderPublicKey:t};await this.sendError({id:i.id,topic:s,error:a,encodeOpts:n,rpcOpts:Ig.wc_sessionAuthenticate.autoReject,appLink:r})}}),qg(this,"addSessionRequestToSessionRequestQueue",e=>{this.sessionRequestQueue.queue.push(e)}),qg(this,"cleanupAfterResponse",e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ag,this.processSessionRequestQueue()},n.toMiliseconds(this.requestQueueDelay))}),qg(this,"cleanupPendingSentRequestsForTopic",({topic:e,error:t})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(t=>t.topic===e&&"wc_sessionRequest"===t.request.method).forEach(e=>{const s=kr("session_request",e.request.id);if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners`);this.events.emit(kr("session_request",e.request.id),{error:t})})}),qg(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Sg)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.sessionRequestQueue.state=Sg,this.emitSessionRequest(e)}catch(mn){this.client.logger.error(mn)}else this.client.logger.info("session request queue is empty.")}),qg(this,"emitSessionRequest",e=>{this.client.events.emit("session_request",e)}),qg(this,"onPairingCreated",e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find(t=>t.pairingTopic===e.topic);
5t&&this.onSessionProposeRequest({topic:e.topic,payload:v("wc_sessionPropose",Lg(jg({},t),{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties}),t.id)})}),qg(this,"isValidConnect",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:r,scopedProperties:n,relays:o}=e;if(Qc(t)||await this.isValidPairingTopic(t),!function(e){let t=!1;return e?e&&Xc(e)&&e.length&&e.forEach(e=>{t=cl(e)}):t=!0,t}(o)){const{message:e}=Jc("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(!Qc(s)&&0!==Zc(s)){const e="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)||this.client.logger.warn(e),this.validateNamespaces(s,"requiredNamespaces")}if(!Qc(i)&&0!==Zc(i)&&this.validateNamespaces(i,"optionalNamespaces"),Qc(r)||this.validateSessionProps(r,"sessionProperties"),!Qc(n)){this.validateSessionProps(n,"scopedProperties");const e=Object.keys(s||{}).concat(Object.keys(i||{}));if(!Object.keys(n).every(t=>e.includes(t)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(n)}, required/optional namespaces: ${JSON.stringify(e)}`)}}),qg(this,"validateNamespaces",(e,t)=>{const s=function(e,t,s){let i=null;if(e&&Zc(e)){const r=ol(e,t);r&&(i=r);const n=rl(e,t,s);n&&(i=n)}else i=Jc("MISSING_OR_INVALID",`${t}, ${s} should be an object with data`);return i}(e,"connect()",t);if(s)throw new Error(s.message)}),qg(this,"isValidApprove",async e=>{if(!ll(e))throw new Error(Jc("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:s,relayProtocol:i,sessionProperties:r,scopedProperties:n}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const o=this.client.proposal.get(t),a=al(s,"approve()");if(a)throw new Error(a.message);const c=pl(o.requiredNamespaces,s,"approve()");if(c)throw new Error(c.message);if(!el(i,!0)){const{message:e}=Jc("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(e)}if(Qc(r)||this.validateSessionProps(r,"sessionProperties"),!Qc(n)){this.validateSessionProps(n,"scopedProperties");const e=new Set(Object.keys(s));if(!Object.keys(n).every(t=>e.has(t)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(n)}, approved namespaces: ${Array.from(e).join(", ")}`)}}),qg(this,"isValidReject",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:s}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!function(e){return!!(e&&"object"==typeof e&&e.code&&tl(e.code,!1)&&e.message&&el(e.message,!1))}(s)){const{message:e}=Jc("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(e)}}),qg(this,"isValidSessionSettleRequest",e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:s,namespaces:i,expiry:r}=e;if(!cl(t)){const{message:e}=Jc("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const n=function(e,t){let s=null;return el(null==e?void 0:e.publicKey,!1)||(s=Jc("MISSING_OR_INVALID",`${t} controller public key should be a string`)),s}(s,"onSessionSettleRequest()");if(n)throw new Error(n.message);const o=al(i,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(Pr(r)){const{message:e}=Jc("EXPIRED","onSessionSettleRequest()");throw new Error(e)}}),qg(this,"isValidUpdate",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:s}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const i=this.client.session.get(t),r=al(s,"update()");if(r)throw new Error(r.message);
5const n=pl(i.requiredNamespaces,s,"update()");if(n)throw new Error(n.message)}),qg(this,"isValidExtend",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)}),qg(this,"isValidRequest",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:s,chainId:i,expiry:r}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!dl(n,i)){const{message:e}=Jc("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(e)}if(!function(e){return!(Qc(e)||!el(e.method,!1))}(s)){const{message:e}=Jc("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(e)}if(!ul(n,i,s.method)){const{message:e}=Jc("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(e)}if(r&&!function(e,t){return tl(e,!1)&&e<=t.max&&e>=t.min}(r,Ng)){const{message:e}=Jc("MISSING_OR_INVALID",`request() expiry: ${r}. Expiry must be a number (in seconds) between ${Ng.min} and ${Ng.max}`);throw new Error(e)}}),qg(this,"isValidRespond",async e=>{var t;if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:s,response:i}=e;try{await this.isValidSessionTopic(s)}catch(r){throw null!=(t=null==e?void 0:e.response)&&t.id&&this.cleanupAfterResponse(e),r}if(!function(e){return!(Qc(e)||Qc(e.result)&&Qc(e.error)||!tl(e.id,!1)||!el(e.jsonrpc,!1))}(i)){const{message:e}=Jc("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(e)}}),qg(this,"isValidPing",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),qg(this,"isValidEmit",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:s,chainId:i}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!dl(r,i)){const{message:e}=Jc("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(e)}if(!function(e){return!(Qc(e)||!el(e.name,!1))}(s)){const{message:e}=Jc("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}if(!hl(r,i,s.name)){const{message:e}=Jc("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}}),qg(this,"isValidDisconnect",async e=>{if(!ll(e)){const{message:t}=Jc("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),qg(this,"isValidAuthenticate",e=>{const{chains:t,uri:s,domain:i,nonce:r}=e;if(!Array.isArray(t)||0===t.length)throw new Error("chains is required and must be a non-empty array");if(!el(s,!1))throw new Error("uri is required parameter");if(!el(i,!1))throw new Error("domain is required parameter");if(!el(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map(e=>Ji(e).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:n}=Ji(t[0]);if("eip155"!==n)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),qg(this,"getVerifyContext",async e=>{const{attestationId:t,hash:s,encryptedId:i,metadata:r,transportType:n}=e,o={verified:{verifyUrl:r.verifyUrl||cd,validation:"UNKNOWN",origin:r.url||""}};try{if(n===ql.link_mode){const e=this.getAppLinkIfEnabled(r,n);return o.verified.validation=e&&new URL(e).origin===new URL(r.url).origin?"VALID":"INVALID",o}const e=await this.client.core.verify.resolve({attestationId:t,hash:s,encryptedId:i,verifyUrl:r.verifyUrl});e&&(o.verified.origin=e.origin,o.verified.isScam=e.isScam,o.verified.validation=e.origin===new URL(r.url).origin?"VALID":"INVALID")}catch(a){this.client.logger.warn(a)}return this.client.logger.debug(`Verify context: ${JSON.stringify(o)}`),o}),qg(this,"validateSessionProps",(e,t)=>{Object.values(e).forEach((s,i)=>{if(null==s){const{message:r}=Jc("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${s} for key ${Object.keys(e)[i]}`);throw new Error(r)}})}),qg(this,"getPendingAuthRequest",e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0}),qg(this,"addToRecentlyDeleted",(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0;const t=this.recentlyDeletedLimit/2;
5for(const s of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(s)}}}),qg(this,"checkRecentlyDeleted",e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:s}=Jc("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(s)}}),qg(this,"isLinkModeEnabled",(e,t)=>{var s,i,r,n,o,a,c,l,d;return!(!e||t!==ql.link_mode)&&(!0===(null==(i=null==(s=this.client.metadata)?void 0:s.redirect)?void 0:i.linkMode)&&void 0!==(null==(n=null==(r=this.client.metadata)?void 0:r.redirect)?void 0:n.universal)&&""!==(null==(a=null==(o=this.client.metadata)?void 0:o.redirect)?void 0:a.universal)&&void 0!==(null==(c=null==e?void 0:e.redirect)?void 0:c.universal)&&""!==(null==(l=null==e?void 0:e.redirect)?void 0:l.universal)&&!0===(null==(d=null==e?void 0:e.redirect)?void 0:d.linkMode)&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof(null==global?void 0:global.Linking)<"u")}),qg(this,"getAppLinkIfEnabled",(e,t)=>{var s;return this.isLinkModeEnabled(e,t)?null==(s=null==e?void 0:e.redirect)?void 0:s.universal:void 0}),qg(this,"handleLinkModeMessage",({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=xr(e,"topic")||"",s=decodeURIComponent(xr(e,"wc_ev")||""),i=this.client.session.keys.includes(t);i&&this.client.session.update(t,{transportType:ql.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:s,sessionExists:i})}),qg(this,"registerLinkModeListeners",async()=>{var e;if(Rr()||ur()&&null!=(e=this.client.metadata.redirect)&&e.linkMode){const e=null==global?void 0:global.Linking;if(typeof e<"u"){e.addEventListener("url",this.handleLinkModeMessage,this.client.name);const t=await e.getInitialURL();t&&setTimeout(()=>{this.handleLinkModeMessage({url:t})},50)}}}),qg(this,"shouldSetTVF",(e,t)=>{if(!t||"wc_sessionRequest"!==e)return!1;const{request:s}=t;return Object.keys(Pg).includes(s.method)}),qg(this,"getTVFParams",(e,t,s)=>{var i,r;try{const n=t.request.method,o=this.extractTxHashesFromResult(n,s);return Lg(jg({correlationId:e,rpcMethods:[n],chainId:t.chainId},this.isValidContractData(t.request.params)&&{contractAddresses:[null==(r=null==(i=t.request.params)?void 0:i[0])?void 0:r.to]}),{txHashes:o})}catch(n){this.client.logger.warn("Error getting TVF params",n)}return{}}),qg(this,"isValidContractData",e=>{var t;if(!e)return!1;try{const s=(null==e?void 0:e.data)||(null==(t=null==e?void 0:e[0])?void 0:t.data);if(!s.startsWith("0x"))return!1;const i=s.slice(2);return!!/^[0-9a-fA-F]*$/.test(i)&&i.length%2==0}catch{}return!1}),qg(this,"extractTxHashesFromResult",(e,t)=>{try{if("string"==typeof t)return[t];const s=t[Pg[e].key];if(Xc(s))return"solana_signAllTransactions"===e?s.map(e=>function(e){const t=atob(e),s=new Uint8Array(t.length);for(let o=0;o<t.length;o++)s[o]=t.charCodeAt(o);const i=s[0];if(0===i)throw new Error("No signatures found");const r=1+64*i;if(s.length<r)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const n=Buffer.from(e,"base64").slice(1,65);return d.encode(n)}(e)):s;if("string"==typeof s)return[s]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[s,i]of Object.entries(t))for(const e of i)try{await this.onProviderMessageEvent({topic:s,message:e,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${s}, message: ${e}`)}}catch(vn){this.client.logger.warn("processPendingMessageEvents failed",vn)}}isInitialized(){if(!this.initialized){const{message:e}=Jc("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(kl,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:i,transportType:r}=e,{publicKey:n}=this.client.auth.authKeys.keys.includes(Og)?this.client.auth.authKeys.get(Og):{publicKey:void 0};try{const e=await this.client.core.crypto.decode(t,s,{receiverPublicKey:n,encoding:r===ql.link_mode?uc:dc});I(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:i,transportType:r,encryptedId:fc(s)})):N(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e,transportType:r}),this.client.core.history.delete(t,e.id)):await this.onRelayEventUnknownPayload({topic:t,payload:e,transportType:r}),await this.client.core.relayer.messages.ack(t,s)}catch(o){this.client.logger.error(o)}}registerExpirerEvents(){this.client.core.expirer.on(nd,async e=>
5{const{topic:t,id:s}=Ar(e.target);return s&&this.client.pendingRequest.keys.includes(s)?await this.deletePendingSessionRequest(s,Jc("EXPIRED"),!0):s&&this.client.auth.requests.keys.includes(s)?await this.deletePendingAuthRequest(s,Jc("EXPIRED"),!0):void(t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s})))})}registerPairingEvents(){this.client.core.pairing.events.on(Jl,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Xl,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!el(e,!1)){const{message:t}=Jc("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=Jc("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Pr(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=Jc("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!el(e,!1)){const{message:t}=Jc("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=Jc("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Pr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=Jc("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=Jc("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}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)){if(el(e,!1)){const{message:t}=Jc("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=Jc("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if(!function(e){return"number"==typeof e}(e)){const{message:t}=Jc("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=Jc("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Pr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=Jc("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class zg extends jp{constructor(e,t){super(e,t,"proposal",wg),this.core=e,this.logger=t}}let Fg=class extends jp{constructor(e,t){super(e,t,"session",wg),this.core=e,this.logger=t}};class Wg extends jp{constructor(e,t){super(e,t,"request",wg,e=>e.id),this.core=e,this.logger=t}}class Vg extends jp{constructor(e,t){super(e,t,"authKeys",_g,()=>Og),this.core=e,this.logger=t}}class Hg extends jp{constructor(e,t){super(e,t,"pairingTopics",_g),this.core=e,this.logger=t}}class Kg extends jp{constructor(e,t){super(e,t,"requests",_g,e=>e.id),this.core=e,this.logger=t}}var Gg=Object.defineProperty,Jg=(e,t,s)=>((e,t,s)=>t in e?Gg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Yg{constructor(e,t){this.core=e,this.logger=t,Jg(this,"authKeys"),Jg(this,"pairingTopics"),Jg(this,"requests"),this.authKeys=new Vg(this.core,this.logger),this.pairingTopics=new Hg(this.core,this.logger),this.requests=new Kg(this.core,this.logger)}
5async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Xg=Object.defineProperty,Zg=(e,t,s)=>((e,t,s)=>t in e?Xg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let Qg=class e extends _s{constructor(e){super(e),Zg(this,"protocol","wc"),Zg(this,"version",2),Zg(this,"name",vg),Zg(this,"metadata"),Zg(this,"core"),Zg(this,"logger"),Zg(this,"events",new u.EventEmitter),Zg(this,"engine"),Zg(this,"session"),Zg(this,"proposal"),Zg(this,"pendingRequest"),Zg(this,"auth"),Zg(this,"signConfig"),Zg(this,"on",(e,t)=>this.events.on(e,t)),Zg(this,"once",(e,t)=>this.events.once(e,t)),Zg(this,"off",(e,t)=>this.events.off(e,t)),Zg(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),Zg(this,"removeAllListeners",e=>this.events.removeAllListeners(e)),Zg(this,"connect",async e=>{try{return await this.engine.connect(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"pair",async e=>{try{return await this.engine.pair(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"approve",async e=>{try{return await this.engine.approve(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"reject",async e=>{try{return await this.engine.reject(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"update",async e=>{try{return await this.engine.update(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"extend",async e=>{try{return await this.engine.extend(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"request",async e=>{try{return await this.engine.request(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"respond",async e=>{try{return await this.engine.respond(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"ping",async e=>{try{return await this.engine.ping(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"emit",async e=>{try{return await this.engine.emit(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"disconnect",async e=>{try{return await this.engine.disconnect(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"find",e=>{try{return this.engine.find(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(mn){throw this.logger.error(mn.message),mn}}),Zg(this,"authenticate",async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(s){throw this.logger.error(s.message),s}}),Zg(this,"formatAuthMessage",e=>{try{return this.engine.formatAuthMessage(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"approveSessionAuthenticate",async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(t){throw this.logger.error(t.message),t}}),Zg(this,"rejectSessionAuthenticate",async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(t){throw this.logger.error(t.message),t}}),this.name=(null==e?void 0:e.name)||vg,this.metadata=fr(null==e?void 0:e.metadata),this.signConfig=null==e?void 0:e.signConfig;const t=typeof(null==e?void 0:e.logger)<"u"&&"string"!=typeof(null==e?void 0:e.logger)?e.logger:b(h({level:(null==e?void 0:e.logger)||yg}));this.core=(null==e?void 0:e.core)||new fg(e),this.logger=g(t,this.name),this.session=new Fg(this.core,this.logger),this.proposal=new zg(this.core,this.logger),this.pendingRequest=new Wg(this.core,this.logger),this.engine=new Bg(this),this.auth=new Yg(this.core,this.logger)}static async init(t){const s=new e(t);return await s.initialize(),s}get context(){return w(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()},n.toMiliseconds(n.ONE_SECOND))}catch(vn){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(vn.message),vn}}};const ef="error",tf="wc@2:universal_provider:",sf="https://rpc.walletconnect.org/v1/",rf="generic",nf=`${sf}bundler`,of="default_chain_changed";function af(){}function cf(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function lf(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function df(e){return"object"==typeof e&&null!==e}function uf(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}
5function hf(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const pf="[object RegExp]",gf="[object String]",ff="[object Number]",mf="[object Boolean]",wf="[object Arguments]",vf="[object Symbol]",yf="[object Date]",bf="[object Map]",Ef="[object Set]",Cf="[object Array]",If="[object ArrayBuffer]",Nf="[object Object]",Af="[object DataView]",Sf="[object Uint8Array]",Pf="[object Uint8ClampedArray]",kf="[object Uint16Array]",_f="[object Uint32Array]",Of="[object Int8Array]",xf="[object Int16Array]",Tf="[object Int32Array]",Rf="[object Float32Array]",Uf="[object Float64Array]";function $f(e,t,s,i=new Map,r=void 0){const n=null==r?void 0:r(e,t,s,i);if(null!=n)return n;if(cf(e))return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){const t=new Array(e.length);i.set(e,t);for(let n=0;n<e.length;n++)t[n]=$f(e[n],n,s,i,r);return Object.hasOwn(e,"index")&&(t.index=e.index),Object.hasOwn(e,"input")&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){const t=new Map;i.set(e,t);for(const[n,o]of e)t.set(n,$f(o,n,s,i,r));return t}if(e instanceof Set){const t=new Set;i.set(e,t);for(const n of e)t.add($f(n,void 0,s,i,r));return t}if(typeof Buffer<"u"&&Buffer.isBuffer(e))return e.subarray();if(lf(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);i.set(e,t);for(let n=0;n<e.length;n++)t[n]=$f(e[n],n,s,i,r);return t}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return i.set(e,t),Df(t,e,s,i,r),t}if(typeof File<"u"&&e instanceof File){const t=new File([e],e.name,{type:e.type});return i.set(e,t),Df(t,e,s,i,r),t}if(e instanceof Blob){const t=new Blob([e],{type:e.type});return i.set(e,t),Df(t,e,s,i,r),t}if(e instanceof Error){const t=new e.constructor;return i.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,Df(t,e,s,i,r),t}if("object"==typeof e&&function(e){switch(hf(e)){case wf:case Cf:case If:case Af:case mf:case yf:case Rf:case Uf:case Of:case xf:case Tf:case bf:case ff:case Nf:case pf:case Ef:case gf:case vf:case Sf:case Pf:case kf:case _f:return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return i.set(e,t),Df(t,e,s,i,r),t}return e}function Df(e,t,s=e,i,r){const n=[...Object.keys(t),...uf(t)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=$f(t[a],a,s,i,r))}}function Mf(e,t){return function(e,t){return $f(e,void 0,e,new Map,t)}(e,(t,s,i,r)=>{if("object"==typeof e)switch(Object.prototype.toString.call(e)){case ff:case gf:case mf:{const t=new e.constructor(null==e?void 0:e.valueOf());return Df(t,e),t}case wf:{const t={};return Df(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}})}function jf(e){return Mf(e)}function Lf(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===hf(e)}function qf(e){return lf(e)}function Bf(e){var t;if("object"!=typeof e||null==e)return!1;if(null===Object.getPrototypeOf(e))return!0;if("[object Object]"!==Object.prototype.toString.call(e)){const s=e[Symbol.toStringTag];return!(null==s||!(null==(t=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag))?void 0:t.writable))&&e.toString()===`[object ${s}]`}let s=e;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return Object.getPrototypeOf(e)===s}function zf(e,t,s,i){if(cf(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(i.has(t))return function(e){if(cf(e))return e;if(Array.isArray(e)||lf(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e),s=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new s(e);if(e instanceof RegExp){const t=new s(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new s(e.buffer.slice(0));if(e instanceof Error){const t=new s(e.message);return t.stack=e.stack,t.name=e.name,t.cause=e.cause,t}if(typeof File<"u"&&e instanceof File)return new s([e],e.name,{type:e.type,lastModified:e.lastModified});if("object"==typeof e){const s=Object.create(t);return Object.assign(s,e)}return e}(i.get(t));if(i.set(t,e),Array.isArray(t)){t=t.slice();for(let e=0;e<t.length;e++)t[e]=t[e]??void 0}const r=[...Object.keys(t),...uf(t)];for(let n=0;n<r.length;n++){const o=r[n];let a=t[o],c=e[o];
5if(Lf(a)&&(a={...a}),Lf(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=jf(a)),Array.isArray(a))if("object"==typeof c&&null!=c){const e=[],t=Reflect.ownKeys(c);for(let s=0;s<t.length;s++){const i=t[s];e[i]=c[i]}c=e}else c=[];const l=s(c,a,o,e,t,i);null!=l?e[o]=l:Array.isArray(a)||df(c)&&df(a)?e[o]=zf(c,a,s,i):null==c&&Bf(a)?e[o]=zf({},a,s,i):null==c&&qf(a)?e[o]=jf(a):(void 0===c||void 0!==a)&&(e[o]=a)}return e}function Ff(e,...t){return function(e,...t){const s=t.slice(0,-1),i=t[t.length-1];let r=e;for(let n=0;n<s.length;n++)r=zf(r,s[n],i,new Map);return r}(e,...t,af)}var Wf=Object.defineProperty,Vf=Object.defineProperties,Hf=Object.getOwnPropertyDescriptors,Kf=Object.getOwnPropertySymbols,Gf=Object.prototype.hasOwnProperty,Jf=Object.prototype.propertyIsEnumerable,Yf=(e,t,s)=>t in e?Wf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Xf=(e,t)=>{for(var s in t||(t={}))Gf.call(t,s)&&Yf(e,s,t[s]);if(Kf)for(var s of Kf(t))Jf.call(t,s)&&Yf(e,s,t[s]);return e},Zf=(e,t)=>Vf(e,Hf(t));function Qf(e,t,s){var i;const r=Ji(e);return(null==(i=t.rpcMap)?void 0:i[r.reference])||`${sf}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function em(e){return e.includes(":")?e.split(":")[1]:e}function tm(e){return e.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function sm(e={},t={}){return Ff(im(e),im(t))}function im(e){var t,s,i,r,n;const o={};if(!Zc(e))return o;for(const[a,c]of Object.entries(e)){const e=Fc(a)?[a]:c.chains,l=c.methods||[],d=c.events||[],u=c.rpcMap||{},h=Wc(a);o[h]=Zf(Xf(Xf({},o[h]),c),{chains:_r(e,null==(t=o[h])?void 0:t.chains),methods:_r(l,null==(s=o[h])?void 0:s.methods),events:_r(d,null==(i=o[h])?void 0:i.events)}),(Zc(u)||Zc((null==(r=o[h])?void 0:r.rpcMap)||{}))&&(o[h].rpcMap=Xf(Xf({},u),null==(n=o[h])?void 0:n.rpcMap))}return o}function rm(e){return e.includes(":")?e.split(":")[2]:e}function nm(e){const t={};for(const[s,i]of Object.entries(e)){const e=i.methods||[],r=i.events||[],n=i.accounts||[],o=Fc(s)?[s]:i.chains?i.chains:tm(i.accounts);t[s]={chains:o,methods:e,events:r,accounts:n}}return t}function om(e){return"number"==typeof e?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}const am={},cm=e=>am[e],lm=(e,t)=>{am[e]=t};var dm=Object.defineProperty,um=(e,t,s)=>((e,t,s)=>t in e?dm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class hm{constructor(e){um(this,"name","polkadot"),um(this,"client"),um(this,"httpProviders"),um(this,"events"),um(this,"namespace"),um(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(of,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e&&e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=em(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qf(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new E(new M(s,cm("disableProviderPing")))}}var pm=Object.defineProperty,gm=Object.defineProperties,fm=Object.getOwnPropertyDescriptors,mm=Object.getOwnPropertySymbols,wm=Object.prototype.hasOwnProperty,vm=Object.prototype.propertyIsEnumerable,ym=(e,t,s)=>t in e?pm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,bm=(e,t)=>
5{for(var s in t||(t={}))wm.call(t,s)&&ym(e,s,t[s]);if(mm)for(var s of mm(t))vm.call(t,s)&&ym(e,s,t[s]);return e},Em=(e,t)=>gm(e,fm(t)),Cm=(e,t,s)=>ym(e,"symbol"!=typeof t?t+"":t,s);class Im{constructor(e){Cm(this,"name","eip155"),Cm(this,"client"),Cm(this,"chainId"),Cm(this,"namespace"),Cm(this,"httpProviders"),Cm(this,"events"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":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,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(of,`${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,t){const s=t||Qf(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new E(new M(s,cm("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=parseInt(em(t));e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,s;let i=e.request.params?null==(t=e.request.params[0])?void 0:t.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const r=parseInt(i,16);if(this.isChainApproved(r))this.setDefaultChain(`${r}`);else{if(!this.namespace.methods.includes("wallet_switchEthereumChain"))throw new Error(`Failed to switch to chain 'eip155:${r}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:null==(s=this.namespace.chains)?void 0:s[0]}),this.setDefaultChain(`${r}`)}return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,s,i,r,n;const o=null==(s=null==(t=e.request)?void 0:t.params)?void 0:s[0],a=`${o}${((null==(r=null==(i=e.request)?void 0:i.params)?void 0:r[1])||[]).join(",")}`;if(!o)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const c=this.client.session.get(e.topic),l=(null==(n=null==c?void 0:c.sessionProperties)?void 0:n.capabilities)||{};if(null!=l&&l[a])return null==l?void 0:l[a];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Em(bm({},c.sessionProperties||{}),{capabilities:Em(bm({},l||{}),{[a]:d})})})}catch(u){}return d}async getCallStatus(e){var t,s;const i=this.client.session.get(e.topic),r=null==(t=i.sessionProperties)?void 0:t.bundler_name;if(r){const t=this.getBundlerUrl(e.chainId,r);try{return await this.getUserOperationReceipt(t,e)}catch(o){}}const n=null==(s=i.sessionProperties)?void 0:s.bundler_url;if(n)try{return await this.getUserOperationReceipt(n,e)}catch(a){}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,t){var s;const i=new URL(e),r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v("eth_getUserOperationReceipt",[null==(s=t.request.params)?void 0:s[0]]))});if(!r.ok)throw new Error(`Failed to fetch user operation receipt - ${r.status}`);return await r.json()}
5getBundlerUrl(e,t){return`${nf}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var Nm=Object.defineProperty,Am=(e,t,s)=>((e,t,s)=>t in e?Nm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Sm{constructor(e){Am(this,"name","solana"),Am(this,"client"),Am(this,"httpProviders"),Am(this,"events"),Am(this,"namespace"),Am(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(of,`${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(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=em(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qf(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new E(new M(s,cm("disableProviderPing")))}}var Pm=Object.defineProperty,km=(e,t,s)=>((e,t,s)=>t in e?Pm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class _m{constructor(e){km(this,"name","cosmos"),km(this,"client"),km(this,"httpProviders"),km(this,"events"),km(this,"namespace"),km(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(of,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=em(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qf(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new E(new M(s,cm("disableProviderPing")))}}var Om=Object.defineProperty,xm=(e,t,s)=>((e,t,s)=>t in e?Om(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Tm{constructor(e){xm(this,"name","algorand"),xm(this,"client"),xm(this,"httpProviders"),xm(this,"events"),xm(this,"namespace"),xm(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){if(!this.httpProviders[e]){const s=t||Qf(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.chainId=e,this.events.emit(of,`${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(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qf(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new E(new M(s,cm("disableProviderPing")))}}var Rm=Object.defineProperty,Um=(e,t,s)=>((e,t,s)=>t in e?Rm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class $m{constructor(e){Um(this,"name","cip34"),Um(this,"client"),Um(this,"httpProviders"),Um(this,"events"),Um(this,"namespace"),Um(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(of,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const s=this.getCardanoRPCUrl(t),i=em(t);e[i]=this.createHttpProvider(i,s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new E(new M(s,cm("disableProviderPing")))}}var Dm=Object.defineProperty,Mm=(e,t,s)=>((e,t,s)=>t in e?Dm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);
5class jm{constructor(e){Mm(this,"name","elrond"),Mm(this,"client"),Mm(this,"httpProviders"),Mm(this,"events"),Mm(this,"namespace"),Mm(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(of,`${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(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=em(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qf(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new E(new M(s,cm("disableProviderPing")))}}var Lm=Object.defineProperty,qm=(e,t,s)=>((e,t,s)=>t in e?Lm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Bm{constructor(e){qm(this,"name","multiversx"),qm(this,"client"),qm(this,"httpProviders"),qm(this,"events"),qm(this,"namespace"),qm(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(of,`${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(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const i=em(t);e[i]=this.createHttpProvider(i,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qf(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new E(new M(s,cm("disableProviderPing")))}}var zm=Object.defineProperty,Fm=(e,t,s)=>((e,t,s)=>t in e?zm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Wm{constructor(e){Fm(this,"name","near"),Fm(this,"client"),Fm(this,"httpProviders"),Fm(this,"events"),Fm(this,"namespace"),Fm(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||Qf(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(of,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e&&e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;e[t]=this.createHttpProvider(t,null==(s=this.namespace.rpcMap)?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qf(e,this.namespace);return typeof s>"u"?void 0:new E(new M(s,cm("disableProviderPing")))}}var Vm=Object.defineProperty,Hm=(e,t,s)=>((e,t,s)=>t in e?Vm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Km{constructor(e){Hm(this,"name","tezos"),Hm(this,"client"),Hm(this,"httpProviders"),Hm(this,"events"),Hm(this,"namespace"),Hm(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||Qf(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(of,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e&&e.filter(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2])||[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qf(e,this.namespace);return typeof s>"u"?void 0:new E(new M(s))}}var Gm=Object.defineProperty,Jm=(e,t,s)=>((e,t,s)=>t in e?Gm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Ym{constructor(e){Jm(this,"name",rf),Jm(this,"client"),Jm(this,"httpProviders"),Jm(this,"events"),Jm(this,"namespace"),Jm(this,"chainId"),this.namespace=e.namespace,this.events=cm("events"),this.client=cm("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,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(of,`${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(e=>e.split(":")[1]===this.chainId.toString()).map(e=>e.split(":")[2]))]:[]}createHttpProviders(){var e,t;const s={};return null==(t=null==(e=this.namespace)?void 0:e.accounts)||t.forEach(e
5=>{const t=Ji(e);s[`${t.namespace}:${t.reference}`]=this.createHttpProvider(e)}),s}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Qf(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new E(new M(s,cm("disableProviderPing")))}}var Xm=Object.defineProperty,Zm=Object.defineProperties,Qm=Object.getOwnPropertyDescriptors,ew=Object.getOwnPropertySymbols,tw=Object.prototype.hasOwnProperty,sw=Object.prototype.propertyIsEnumerable,iw=(e,t,s)=>t in e?Xm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,rw=(e,t)=>{for(var s in t||(t={}))tw.call(t,s)&&iw(e,s,t[s]);if(ew)for(var s of ew(t))sw.call(t,s)&&iw(e,s,t[s]);return e},nw=(e,t)=>Zm(e,Qm(t)),ow=(e,t,s)=>iw(e,"symbol"!=typeof t?t+"":t,s);let aw=class e{constructor(e){ow(this,"client"),ow(this,"namespaces"),ow(this,"optionalNamespaces"),ow(this,"sessionProperties"),ow(this,"scopedProperties"),ow(this,"events",new S),ow(this,"rpcProviders",{}),ow(this,"session"),ow(this,"providerOpts"),ow(this,"logger"),ow(this,"uri"),ow(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(null==e?void 0:e.logger)<"u"&&"string"!=typeof(null==e?void 0:e.logger)?e.logger:b(h({level:(null==e?void 0:e.logger)||ef})),this.disableProviderPing=(null==e?void 0:e.disableProviderPing)||!1}static async init(t){const s=new e(t);return await s.initialize(),s}async request(e,t,s){const[i,r]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:rw({},e),chainId:`${i}:${r}`,topic:this.session.topic,expiry:s})}sendAsync(e,t,s,i){const r=(new Date).getTime();this.request(e,s,i).then(e=>t(null,A(r,e))).catch(e=>t(e,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:null==(e=this.session)?void 0:e.topic,reason:Yc("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,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:s,response:i}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const r=await i();if(this.session=r.session,this.session){const e=nm(this.session.namespaces);this.namespaces=sm(this.namespaces,e),await this.persist("namespaces",this.namespaces),this.onConnect()}return r}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const i=await s();this.session=i;const r=nm(i.namespaces);return this.namespaces=sm(this.namespaces,r),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[s,i]=this.validateChain(e),r=this.getProvider(s);r.name===rf?r.setDefaultChain(`${s}:${i}`,t):r.setDefaultChain(i,t)}catch(s){if(!/Please call connect/.test(s.message))throw s}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(Xc(t)){for(const s of t)e.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${t.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,t;if(this.client=this.providerOpts.client||await Qg.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ef,relayUrl:this.providerOpts.relayUrl||"wss://relay.walletconnect.org",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(s){throw this.logger.error("Failed to get session",s),new Error(`The provided session: ${null==(t=null==(e=this.providerOpts)?void 0:e.session)?void 0:t.topic} doesn't exist in the Sign client`)}else{const e=this.client.session.getAll();this.session=e[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(e=>Wc(e)))];lm("client",this.client),lm("events",this.events),lm("disableProviderPing",this.disableProviderPing),e.forEach(e
5=>{if(!this.session)return;const t=function(e,t){const s=Object.keys(t.namespaces).filter(t=>t.includes(e));if(!s.length)return[];const i=[];return s.forEach(e=>{const s=t.namespaces[e].accounts;i.push(...s)}),i}(e,this.session),s=tm(t),i=sm(this.namespaces,this.optionalNamespaces),r=nw(rw({},i[e]),{accounts:t,chains:s});switch(e){case"eip155":this.rpcProviders[e]=new Im({namespace:r});break;case"algorand":this.rpcProviders[e]=new Tm({namespace:r});break;case"solana":this.rpcProviders[e]=new Sm({namespace:r});break;case"cosmos":this.rpcProviders[e]=new _m({namespace:r});break;case"polkadot":this.rpcProviders[e]=new hm({namespace:r});break;case"cip34":this.rpcProviders[e]=new $m({namespace:r});break;case"elrond":this.rpcProviders[e]=new jm({namespace:r});break;case"multiversx":this.rpcProviders[e]=new Bm({namespace:r});break;case"near":this.rpcProviders[e]=new Wm({namespace:r});break;case"tezos":this.rpcProviders[e]=new Km({namespace:r});break;default:this.rpcProviders[rf]?this.rpcProviders[rf].updateNamespace(r):this.rpcProviders[rf]=new Ym({namespace:r})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:s}=e;s===(null==(t=this.session)?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:s,topic:i}=e;if(i!==(null==(t=this.session)?void 0:t.topic))return;const{event:r}=s;if("accountsChanged"===r.name){const e=r.data;e&&Xc(e)&&this.events.emit("accountsChanged",e.map(rm))}else if("chainChanged"===r.name){const e=s.chainId,t=s.event.data,i=Wc(e),r=om(e)!==om(t)?`${i}:${om(t)}`:e;this.onChainChanged(r)}else this.events.emit(r.name,r.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,i;if(e!==(null==(s=this.session)?void 0:s.topic))return;const{namespaces:r}=t,n=null==(i=this.client)?void 0:i.session.get(e);this.session=nw(rw({},n),{namespaces:r}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===(null==(t=this.session)?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",nw(rw({},Yc("USER_DISCONNECTED")),{data:e.topic})))}),this.on(of,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[rf]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace(null==(t=this.session)?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t={},optionalNamespaces:s={},sessionProperties:i,scopedProperties:r}=e;this.optionalNamespaces=sm(t,s),this.sessionProperties=i,this.scopedProperties=r}validateChain(e){const[t,s]=(null==e?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(e=>Wc(e)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&s)return[t,s];const i=Wc(Object.keys(this.namespaces)[0]);return[i,this.rpcProviders[i].getDefaultChain()]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[s,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(s,i),this.events.emit("chainChanged",i);const r=this.getProvider(s).getDefaultChain();t||this.getProvider(s).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:s,previousChainId:r,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:s}){var i,r;try{if(t===s)return;const n=null==(r=null==(i=this.session)?void 0:i.namespaces[e])?void 0:r.accounts;if(!n)return;const o=n.filter(e=>e.includes(`${s}:`)).map(rm);if(!Xc(o))return;this.events.emit("accountsChanged",o)}catch(n){this.logger.warn("Failed to emit accountsChanged on chain change",n)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const s=this.namespaces[e]?e:`${e}:${t}`,i={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[s]?this.namespaces[s]&&(this.namespaces[s].defaultChain=t):this.namespaces[s]=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,t){var s;const i=(null==(s=this.session)?void 0:s.topic)||"";await this.client.core.storage.setItem(`${tf}/${e}${i}`,t)}async getFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${tf}/${e}${s}`)}async deleteFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${tf}/${e}${s}`)}async cleanupStorage(){var e;try{if((null==(e=this.client)?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const e of t)e.startsWith(tf)&&await this.client.core.storage.removeItem(e)}catch(wn){this.logger.warn("Failed to cleanup storage",wn)}}};function cw(e,t){return St.getConnectorId(e)===t}const lw="eip155",dw="WALLET_CONNECT",uw="INJECTED",hw="ANNOUNCED",pw={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:{[L.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[L.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[L.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[L.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[L.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[L.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-454
50-9e6a2b9cae00"},ConnectorNamesMap:{[L.CONNECTOR_ID.INJECTED]:"Browser Wallet",[L.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[L.CONNECTOR_ID.COINBASE]:"Coinbase",[L.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[L.CONNECTOR_ID.LEDGER]:"Ledger",[L.CONNECTOR_ID.SAFE]:"Safe"}},gw={getCaipTokens(e){if(!e)return;const t={};return Object.entries(e).forEach(([e,s])=>{t[`${lw}:${e}`]=s}),t},isLowerCaseMatch:(e,t)=>(null==e?void 0:e.toLowerCase())===(null==t?void 0:t.toLowerCase())};new AbortController;const fw={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 ${"undefined"!=typeof window?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"}}};const mw={createLogger(e,t="error"){const s=h({level:t}),{logger:i}=p({opts:s});return i.error=(...t)=>{for(const s of t)if(s instanceof Error)return void e(s,...t);e(void 0,...t)},i}};function ww(e){return function(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const vw="2.33.2";let yw={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:s})=>t?`${e??"https://viem.sh"}${t}${s?`#${s}`:""}`:void 0,version:`viem@${vw}`},bw=class e extends Error{constructor(t,s={}){var i;const r=s.cause instanceof e?s.cause.details:(null==(n=s.cause)?void 0:n.message)?s.cause.message:s.details;var n;const o=s.cause instanceof e&&s.cause.docsPath||s.docsPath,a=null==(i=yw.getDocsUrl)?void 0:i.call(yw,{...s,docsPath:o});super([t||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...a?[`Docs: ${a}`]:[],...r?[`Details: ${r}`]:[],...yw.version?[`Version: ${yw.version}`]:[]].join("\n"),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=o,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=t,this.version=vw}walk(e){return Ew(this,e)}};function Ew(e,t){return(null==t?void 0:t(e))?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?Ew(e.cause,t):t?null:e}let Cw=class extends bw{constructor({size:e,targetSize:t,type:s}){super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};function Iw(e,{dir:t,size:s=32}={}){return"string"==typeof e?function(e,{dir:t,size:s=32}={}){if(null===s)return e;const i=e.replace("0x","");if(i.length>2*s)throw new Cw({size:Math.ceil(i.length/2),targetSize:s,type:"hex"});return`0x${i["right"===t?"padEnd":"padStart"](2*s,"0")}`}(e,{dir:t,size:s}):function(e,{dir:t,size:s=32}={}){if(null===s)return e;if(e.length>s)throw new Cw({size:e.length,targetSize:s,type:"bytes"});const i=new Uint8Array(s);for(let r=0;r<s;r++){const n="right"===t;i[n?r:s-r-1]=e[n?r:e.length-r-1]}return i}(e,{dir:t,size:s})}let Nw=class extends bw{constructor({givenSize:e,maxSize:t}
5){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};const Aw=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Sw(e,t={}){let s="";for(let r=0;r<e.length;r++)s+=Aw[e[r]];const i=`0x${s}`;return"number"==typeof t.size?(function(e,{size:t}){if(ww(e)>t)throw new Nw({givenSize:ww(e),maxSize:t})}(i,{size:t.size}),Iw(i,{dir:"right",size:t.size})):i}const Pw=new TextEncoder;class kw extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const _w=(e,t,s)=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t,s);class Ow extends bw{constructor({body:e,cause:t,details:s,headers:i,status:r,url:n}){super("HTTP request failed.",{cause:t,details:s,metaMessages:[r&&`Status: ${r}`,`URL: ${n}`,e&&`Request body: ${_w(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=r,this.url=n}}class xw extends bw{constructor({body:e,error:t,url:s}){super("RPC Request failed.",{cause:t,details:t.message,metaMessages:[`URL: ${s}`,`Request body: ${_w(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=t.code,this.data=t.data}}class Tw extends bw{constructor({body:e,url:t}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${t}`,`Request body: ${_w(e)}`],name:"TimeoutError"})}}class Rw extends bw{constructor(e,{code:t,docsPath:s,metaMessages:i,name:r,shortMessage:n}){super(n,{cause:e,docsPath:s,metaMessages:i||(null==e?void 0:e.metaMessages),name:r||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r||e.name,this.code=e instanceof xw?e.code:t??-1}}class Uw extends Rw{constructor(e,t){super(e,t),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=t.data}}class $w extends Rw{constructor(e){super(e,{code:$w.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty($w,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Dw extends Rw{constructor(e){super(e,{code:Dw.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Dw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Mw extends Rw{constructor(e,{method:t}={}){super(e,{code:Mw.code,name:"MethodNotFoundRpcError",shortMessage:`The method${t?` "${t}"`:""} does not exist / is not available.`})}}Object.defineProperty(Mw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class jw extends Rw{constructor(e){super(e,{code:jw.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join("\n")})}}Object.defineProperty(jw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class Lw extends Rw{constructor(e){super(e,{code:Lw.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(Lw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class qw extends Rw{constructor(e){super(e,{code:qw.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join("\n")})}}Object.defineProperty(qw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Bw extends Rw{constructor(e){super(e,{code:Bw.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Bw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class zw extends Rw{constructor(e){super(e,{code:zw.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(zw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Fw extends Rw{constructor(e){super(e,{code:Fw.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Fw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Ww extends Rw{constructor(e,{method:t}={}){super(e,{code:Ww.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${t?` "${t}"`:""} is not supported.`})}}Object.defineProperty(Ww,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});
5class Vw extends Rw{constructor(e){super(e,{code:Vw.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(Vw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Hw extends Rw{constructor(e){super(e,{code:Hw.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Hw,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Kw extends Uw{constructor(e){super(e,{code:Kw.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Kw,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class Gw extends Uw{constructor(e){super(e,{code:Gw.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(Gw,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Jw extends Uw{constructor(e,{method:t}={}){super(e,{code:Jw.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${t?` " ${t}"`:""}.`})}}Object.defineProperty(Jw,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class Yw extends Uw{constructor(e){super(e,{code:Yw.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(Yw,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Xw extends Uw{constructor(e){super(e,{code:Xw.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Xw,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class Zw extends Uw{constructor(e){super(e,{code:Zw.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(Zw,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class Qw extends Uw{constructor(e){super(e,{code:Qw.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(Qw,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class ev extends Uw{constructor(e){super(e,{code:ev.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(ev,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class tv extends Uw{constructor(e){super(e,{code:tv.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(tv,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class sv extends Uw{constructor(e){super(e,{code:sv.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(sv,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class iv extends Uw{constructor(e){super(e,{code:iv.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(iv,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class rv extends Uw{constructor(e){super(e,{code:rv.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(rv,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class nv extends Uw{constructor(e){super(e,{code:nv.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(nv,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class ov extends Rw{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}class av extends bw{constructor({cause:e,message:t}={}){var s;const i=null==(s=null==t?void 0:t.replace("execution reverted: ",""))?void 0:s.replace("execution reverted","");super(`Execution reverted ${i?`with reason: ${i}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(av,"code",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(av,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});const cv=new Map;function lv({fn:e,id:t,shouldSplitBatch:s,wait:i=0,sort:r}){const n=async()=>{const t=a();o();const s=t.map(({args:e})=>e);0!==s.length&&e(s).then(e=>{r&&Array.isArray(e)&&e.sort(r);for(let s=0;s<t.length;s++){const{resolve:i}=t[s];null==i||i([e[s],e])}}).catch(e=>{for(let s=0;s<t.length;s++){const{reject:i}=t[s];null==i||i(e)}})},o=()=>cv.delete(t),a=()=>cv.get(t)||[],c=e=>cv.set(t,[...a(),e]);return{flush:o,async schedule(e){const{promise:t,resolve:r,reject:o}=function(){let e=()=>{},t=()=>{};return{promise:new Promise((s,i)=>{e=s,t=i}),resolve:e,reject:t}}();(null==s?void 0:s([...a().map(({args:e})=>e),e]))&&n();return a().length>0?(c({args:e,resolve:r,reject:o}),t):(c({args:e,resolve:r,reject:o}),setTimeout(n,i),t)}}}async function dv(e){return new Promise(t=>setTimeout(t,e))}function uv(e,{delay:t=100,retryCount:s=2,shouldRetry:i=()=>!0}={}){return new Promise((r,n)=>{const o=async({count:a=0}={})=>{try{const t=await e();r(t)}catch(c){if(a<s&&await i({count:a,error:c}))return(async({error:e})=>{const s="function"==typeof t?t({count:a,error:e}):t;s&&await dv(s),o({count:a+1})})({error:c});n(c)}};o()})}let hv,pv=256;const gv=new kw(8192);
5function fv(e,t={}){return async(s,i={})=>{var r;const{dedupe:n=!1,methods:o,retryDelay:a=150,retryCount:c=3,uid:l}={...t,...i},{method:d}=s;if(null==(r=null==o?void 0:o.exclude)?void 0:r.includes(d))throw new Ww(new Error("method not supported"),{method:d});if((null==o?void 0:o.include)&&!o.include.includes(d))throw new Ww(new Error("method not supported"),{method:d});return function(e,{enabled:t=!0,id:s}){if(!t||!s)return e();if(gv.get(s))return gv.get(s);const i=e().finally(()=>gv.delete(s));return gv.set(s,i),i}(()=>uv(async()=>{try{return await e(s)}catch(t){const e=t;switch(e.code){case $w.code:throw new $w(e);case Dw.code:throw new Dw(e);case Mw.code:throw new Mw(e,{method:s.method});case jw.code:throw new jw(e);case Lw.code:throw new Lw(e);case qw.code:throw new qw(e);case Bw.code:throw new Bw(e);case zw.code:throw new zw(e);case Fw.code:throw new Fw(e);case Ww.code:throw new Ww(e,{method:s.method});case Vw.code:throw new Vw(e);case Hw.code:throw new Hw(e);case Kw.code:throw new Kw(e);case Gw.code:throw new Gw(e);case Jw.code:throw new Jw(e);case Yw.code:throw new Yw(e);case Xw.code:throw new Xw(e);case Zw.code:throw new Zw(e);case Qw.code:throw new Qw(e);case ev.code:throw new ev(e);case tv.code:throw new tv(e);case sv.code:throw new sv(e);case iv.code:throw new iv(e);case rv.code:throw new rv(e);case nv.code:throw new nv(e);case 5e3:throw new Kw(e);default:if(t instanceof bw)throw t;throw new ov(e)}}},{delay:({count:e,error:t})=>{var s;if(t&&t instanceof Ow){const e=null==(s=null==t?void 0:t.headers)?void 0:s.get("Retry-After");if(null==e?void 0:e.match(/\d/))return 1e3*Number.parseInt(e)}return(1<<e)*a},retryCount:c,shouldRetry:({error:e})=>function(e){if("code"in e&&"number"==typeof e.code)return-1===e.code||(e.code===Vw.code||e.code===Lw.co
5de);if(e instanceof Ow&&e.status)return 403===e.status||(408===e.status||(413===e.status||(429===e.status||(500===e.status||(502===e.status||(503===e.status||504===e.status))))));return!0}(e)}),{enabled:n,id:n?function(e,t={}){return Sw(Pw.encode(e),t)}(`${l}.${_w(s)}`):void 0})}}function mv({key:e,methods:t,name:s,request:i,retryCount:r=3,retryDelay:n=150,timeout:o,type:a},c){return{config:{key:e,methods:t,name:s,request:i,retryCount:r,retryDelay:n,timeout:o,type:a},request:fv(i,{methods:t,retryCount:r,retryDelay:n,uid:function(e=11){if(!hv||pv+e>512){hv="",pv=0;for(let e=0;e<256;e++)hv+=(256+256*Math.random()|0).toString(16).substring(1)}return hv.substring(pv,pv+++e)}()}),value:c}}function wv(e,t={}){const{key:s="fallback",name:i="Fallback",rank:r=!1,shouldThrow:n=vv,retryCount:o,retryDelay:a}=t;return({chain:t,pollingInterval:c=4e3,timeout:l,...d})=>{let u=e,h=()=>{};const p=mv({key:s,name:i,async request({method:e,params:s}){let i;const r=async(o=0)=>{const a=u[o]({...d,chain:t,retryCount:0,timeout:l});try{const t=await a.request({method:e,params:s});return h({method:e,params:s,response:t,transport:a,status:"success"}),t}catch(c){if(h({error:c,method:e,params:s,transport:a,status:"error"}),n(c))throw c;if(o===u.length-1)throw c;if(i??(i=u.slice(o+1).some(s=>{const{include:i,exclude:r}=s({chain:t}).config.methods||{};return i?i.includes(e):!r||!r.includes(e)})),!i)throw c;return r(o+1)}};return r()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:e=>h=e,transports:u.map(e=>e({chain:t,retryCount:0}))});if(r){const e="object"==typeof r?r:{};!function({chain:e,interval:t=4e3,onTransports:s,ping:i,sampleCount:r=10,timeout:n=1e3,transports:o,weights:a={}}){const{stability:c=.7,latency:l=.3}=a,d=[],u=async()=>{const a=await Promise.all(o.map(async t=>{const s=t({chain:e,retryCount:0,timeout:n}),r=Date.now();let o,a;try{await(i?i({transport:s}):s.request({method:"net_listening"})),a=1}catch{a=0}finally{o=Date.now()}return{latency:o-r,success:a}}));d.push(a),d.length>r&&d.shift();const h=Math.max(...d.map(e=>Math.max(...e.map(({latency:e})=>e)))),p=o.map((e,t)=>{const s=d.map(e=>e[t].latency),i=1-s.reduce((e,t)=>e+t,0)/s.length/h,r=d.map(e=>e[t].success),n=r.reduce((e,t)=>e+t,0)/r.length;return 0===n?[0,t]:[l*i+c*n,t]}).sort((e,t)=>t[0]-e[0]);s(p.map(([,e])=>
5o[e])),await dv(t),u()};u()}({chain:t,interval:e.interval??c,onTransports:e=>u=e,ping:e.ping,sampleCount:e.sampleCount,timeout:e.timeout,transports:u,weights:e.weights})}return p}}function vv(e){return!(!("code"in e)||"number"!=typeof e.code||e.code!==Fw.code&&e.code!==Kw.code&&!av.nodeMessage.test(e.message)&&5e3!==e.code)}class yv extends bw{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 bv(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const Ev=bv();function Cv(e,t={}){return{async request(s){var i;const{body:r,onRequest:n=t.onRequest,onResponse:o=t.onResponse,timeout:a=t.timeout??1e4}=s,c={...t.fetchOptions??{},...s.fetchOptions??{}},{headers:l,method:d,signal:u}=c;try{const t=await function(e,{errorInstance:t=new Error("timed out"),timeout:s,signal:i}){return new Promise((r,n)=>{(async()=>{let o;try{const t=new AbortController;s>0&&(o=setTimeout(()=>{i&&t.abort()},s)),r(await e({signal:(null==t?void 0:t.signal)||null}))}catch(a){"AbortError"===(null==a?void 0:a.name)&&n(t),n(a)}finally{clearTimeout(o)}})()})}(async({signal:t})=>{const s={...c,body:Array.isArray(r)?_w(r.map(e=>({jsonrpc:"2.0",id:e.id??Ev.take(),...e}))):_w({jsonrpc:"2.0",id:r.id??Ev.take(),...r}),headers:{"Content-Type":"application/json",...l},method:d||"POST",signal:u||(a>0?t:null)},i=new Request(e,s),o=await(null==n?void 0:n(i,s))??{...s,url:e};return await fetch(o.url??e,o)},{errorInstance:new Tw({body:r,url:e}),timeout:a,signal:!0});let s;if(o&&await o(t),null==(i=t.headers.get("Content-Type"))?void 0:i.startsWith("application/json"))s=await t.json();else{s=await t.text();try{s=JSON.parse(s||"{}")}catch(h){if(t.ok)throw h;s={error:s}}}if(!t.ok)throw new Ow({body:r,details:_w(s.error)||t.statusText,headers:t.headers,status:t.status,url:e});return s}catch(h){if(h instanceof Ow)throw h;if(h instanceof Tw)throw h;throw new Ow({body:r,cause:h,url:e})}}}}function Iv(e,t={}){const{batch:s,fetchOptions:i,key:r="http",methods:n,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:l,raw:d}=t;return({chain:u,retryCount:h,timeout:p})=>{const{batchSize:g=1e3,wait:f=0}="object"==typeof s?s:{},m=t.retryCount??h,w=p??t.timeout??1e4,v=e||(null==u?void 0:u.rpcUrls.default.http[0]);if(!v)throw new yv;const y=Cv(v,{fetchOptions:i,onRequest:a,onResponse:c,timeout:w});return mv({key:r,methods:n,name:o,async request({method:e,params:t}){const i={method:e,params:t},{schedule:r}=lv({id:v,wait:f,shouldSplitBatch:e=>e.length>g,fn:e=>y.request({body:e}),sort:(e,t)=>e.id-t.id}),[{error:n,result:o}]=await(async e=>s?r(e):[await y.request({body:e})])(i);if(d)return{error:n,result:o};if(n)throw new xw({body:i,error:n,url:v});return o},retryCount:m,retryDelay:l,timeout:w,type:"http"},{fetchOptions:i,url:v})}}function Nv(e,t){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",e),s.searchParams.set("projectId",t),s.toString()}const Av=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],Sv={extendRpcUrlWithProjectId(e,t){let s=!1;try{s="rpc.walletconnect.org"===new URL(e).host}catch(wn){s=!1}if(s){const s=new URL(e);return s.searchParams.has("projectId")||s.searchParams.set("projectId",t),s.toString()}return e},isCaipNetwork:e=>"chainNamespace"in e&&"caipNetworkId"in e,getChainNamespace(e){return this.isCaipNetwork(e)?e.chainNamespace:L.CHAIN.EVM},getCaipNetworkId(e){return this.isCaipNetwork(e)?e.caipNetworkId:`${L.CHAIN.EVM}:${e.id}`}
5,getDefaultRpcUrl(e,t,s){var i,r,n;const o=null==(n=null==(r=null==(i=e.rpcUrls)?void 0:i.default)?void 0:r.http)?void 0:n[0];return Av.includes(t)?Nv(t,s):o||""},extendCaipNetwork(e,{customNetworkImageUrls:t,projectId:s,customRpcUrls:i}){var r,n,o,a,c;const l=this.getChainNamespace(e),d=this.getCaipNetworkId(e),u=null==(r=e.rpcUrls.default.http)?void 0:r[0],h=this.getDefaultRpcUrl(e,d,s),p=(null==(a=null==(o=null==(n=null==e?void 0:e.rpcUrls)?void 0:n.chainDefault)?void 0:o.http)?void 0:a[0])||u,g=(null==(c=null==i?void 0:i[d])?void 0:c.map(e=>e.url))||[],f=[...g,h],m=[...g];return p&&!m.includes(p)&&m.push(p),{...e,chainNamespace:l,caipNetworkId:d,assets:{imageId:pw.NetworkImageIds[e.id],imageUrl:null==t?void 0:t[e.id]},rpcUrls:{...e.rpcUrls,default:{http:f},chainDefault:{http:m}}}},extendCaipNetworks:(e,{customNetworkImageUrls:t,projectId:s,customRpcUrls:i})=>e.map(e=>Sv.extendCaipNetwork(e,{customNetworkImageUrls:t,customRpcUrls:i,projectId:s})),getViemTransport(e,t,s){var i,r,n;const o=[];return null==s||s.forEach(e=>{o.push(Iv(e.url,e.config))}),Av.includes(e.caipNetworkId)&&o.push(Iv(Nv(e.caipNetworkId,t),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),null==(n=null==(r=null==(i=null==e?void 0:e.rpcUrls)?void 0:i.default)?void 0:r.http)||n.forEach(e=>{o.push(Iv(e))}),wv(o)},extendWagmiTransports(e,t,s){if(Av.includes(e.caipNetworkId)){return wv([s,Iv(this.getDefaultRpcUrl(e,e.caipNetworkId,t))])}return s},getUnsupportedNetwork:e=>({id:e.split(":")[1],caipNetworkId:e,name:L.UNSUPPORTED_NETWORK_NAME,chainNamespace:e.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}),getCaipNetworkFromStorage(e){var t;const s=Be.getActiveCaipNetworkId(),i=Ht.getAllRequestedCaipNetworks(),r=Array.from((null==(t=Ht.state.chains)?void 0:t.keys())||[]),n=null==s?void 0:s.split(":")[0],o=!!n&&r.includes(n),a=null==i?void 0:i.find(e=>e.caipNetworkId===s);return o&&!a&&s?this.getUnsupportedNetwork(s):a||(e||(null==i?void 0:i[0]))}},Pv={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},kv=Ue({providers:{...Pv},providerIds:{...Pv}}),_v={state:kv,subscribeKey:(e,t)=>je(kv,e,t),subscribe:e=>$e(kv,()=>{e(kv)}),subscribeProviders:e=>$e(kv.providers,()=>e(kv.providers)),setProvider(e,t){t&&(kv.providers[e]=Me(t))},getProvider:e=>kv.providers[e],setProviderId(e,t){t&&(kv.providerIds[e]=t)},getProviderId(e){if(e)return kv.providerIds[e]},reset(){kv.providers={...Pv},kv.providerIds={...Pv}},resetChain(e){kv.providers[e]=void 0,kv.providerIds[e]=void 0}},Ov={VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},xv={filterOutDuplicatesByRDNS(e){const t=Ke.state.enableEIP6963?St.state.connectors:[],s=Be.getRecentWallets(),i=t.map(e=>{var t;return null==(t=e.info)?void 0:t.rdns}).filter(Boolean),r=s.map(e=>
5e.rdns).filter(Boolean),n=i.concat(r);if(n.includes("io.metamask.mobile")&&ze.isMobile()){const e=n.indexOf("io.metamask.mobile");n[e]="io.metamask"}return e.filter(e=>!n.includes(String(null==e?void 0:e.rdns)))},filterOutDuplicatesByIds(e){const t=St.state.connectors.filter(e=>"ANNOUNCED"===e.type||"INJECTED"===e.type),s=Be.getRecentWallets(),i=t.map(e=>e.explorerId),r=s.map(e=>e.id),n=i.concat(r);return e.filter(e=>!n.includes(null==e?void 0:e.id))},filterOutDuplicateWallets(e){const t=this.filterOutDuplicatesByRDNS(e);return this.filterOutDuplicatesByIds(t)},markWalletsAsInstalled(e){const{connectors:t}=St.state,{featuredWalletIds:s}=Ke.state,i=t.filter(e=>"ANNOUNCED"===e.type).reduce((e,t)=>{var s;return(null==(s=t.info)?void 0:s.rdns)?(e[t.info.rdns]=!0,e):e},{});return e.map(e=>({...e,installed:Boolean(e.rdns)&&Boolean(i[e.rdns??""])})).sort((e,t)=>{const i=Number(t.installed)-Number(e.installed);if(0!==i)return i;if(null==s?void 0:s.length){const i=s.indexOf(e.id),r=s.indexOf(t.id);if(-1!==i&&-1!==r)return i-r;if(-1!==i)return-1;if(-1!==r)return 1}return 0})},getConnectOrderMethod(e,t){var s;const i=(null==e?void 0:e.connectMethodsOrder)||(null==(s=Ke.state.features)?void 0:s.connectMethodsOrder),r=t||St.
5state.connectors;if(i)return i;const{injected:n,announced:o}=Tv.getConnectorsByType(r,vt.state.recommended,vt.state.featured),a=n.filter(Tv.showConnector),c=o.filter(Tv.showConnector);return a.length||c.length?["wallet","email","social"]:Ov.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(e){const t=Boolean(e.rdns)&&vt.state.excludedWallets.some(t=>t.rdns===e.rdns),s=Boolean(e.name)&&vt.state.excludedWallets.some(t=>gw.isLowerCaseMatch(t.name,e.name));return t||s}},Tv={getConnectorsByType(e,t,s){const{customWallets:i}=Ke.state,r=Be.getRecentWallets(),n=xv.filterOutDuplicateWallets(t),o=xv.filterOutDuplicateWallets(s),a=e.filter(e=>"MULTI_CHAIN"===e.type),c=e.filter(e=>"ANNOUNCED"===e.type),l=e.filter(e=>"INJECTED"===e.type);return{custom:i,recent:r,external:e.filter(e=>"EXTERNAL"===e.type),multiChain:a,announced:c,injected:l,recommended:n,featured:o}},showConnector(e){var t;const s=null==(t=e.info)?void 0:t.rdns,i=Boolean(s)&&vt.state.excludedWallets.some(e=>Boolean(e.rdns)&&e.rdns===s),r=Boolean(e.name)&&vt.state.excludedWallets.some(t=>gw.isLowerCaseMatch(t.name,e.name));if("INJECTED"===e.type){if("Browser Wallet"===e.name){if(!ze.isMobile())return!1;if(ze.isMobile()&&!s&&!$t.checkInstalled())return!1}if(i||r)return!1}return"ANNOUNCED"!==e.type&&"EXTERNAL"!==e.type||!i&&!r},getIsConnectedWithWC:()=>Array.from(Ht.state.chains.values()).some(e=>St.getConnectorId(e.namespace)===L.CONNECTOR_ID.WALLET_CONNECT),getConnectorTypeOrder({recommended:e,featured:t,custom:s,recent:i,announced:r,injected:n,multiChain:o,external:a,overriddenConnectors:c=(e=>null==(e=Ke.state.features)?void 0:e.connectorTypeOrder)()??[]}){const l=Tv.getIsConnectedWithWC(),d=[{type:"walletConnect",isEnabled:Ke.state.enableWalletConnect&&!l},{type:"recent",isEnabled:i.length>0},{type:"injected",isEnabled:[...n,...r,...o].length>0},{type:"featured",isEnabled:t.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:e.length>0}].filter(e=>e.isEnabled),u=new Set(d.map(e=>e.type)),h=c.filter(e=>u.has(e)).map(e=>({type:e,isEnabled:!0})),p=d.filter(({type:e})=>!h.some(({type:t})=>t===e));return Array.from(new Set([...h,...p].map(({type:e})=>e)))}},Rv=globalThis,Uv=Rv.ShadowRoot&&(void 0===Rv.ShadyCSS||Rv.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,$v=Symbol(),Dv=new WeakMap;let Mv=class{constructor(e,t,s){if(this._$cssResult$=!0,s!==$v)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Uv&&void 0===e){const s=void 0!==t&&1===t.length;s&&(e=Dv.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),s&&Dv.set(t,e))}return e}toString(){return this.cssText}};const jv=e=>new Mv("string"==typeof e?e:e+"",void 0,$v),Lv=(e,...t)=>{const s=1===e.length?e[0]:t.reduce((t,s,i)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[i+1],e[0]);return new Mv(s,e,$v)},qv=Uv?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const s of e.cssRules)t+=s.cssText;return jv(t)})(e):e,{is:Bv,defineProperty:zv,getOwnPropertyDescriptor:Fv,getOwnPropertyNames:Wv,getOwnPropertySymbols:Vv,getPrototypeOf:Hv}=Object,Kv=globalThis,Gv=Kv.trustedTypes,Jv=Gv?Gv.emptyScript:"",Yv=Kv.reactiveElementPolyfillSupport,Xv=(e,t)=>e,Zv={toAttribute(e,t){switch(t){case Boolean:e=e?Jv:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let s=e;switch(t){case Boolean:s=null!==e;break;case Number:s=null===e?null:Number(e);break;case Object:case Array:try{s=JSON.parse(e)}catch(i){s=null}}return s}},Qv=(e,t)=>!Bv(e,t),ey={attribute:!0,type:String,converter:Zv,reflect:!1,useDefault:!1,hasChanged:Qv}; 6/** 7 * @license 8 * Copyright 2017 Google LLC 9 * SPDX-License-Identifier: BSD-3-Clause 10 */Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Kv.litPropertyMetadata??(Kv.litPropertyMetadata=new WeakMap);let ty=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,t=ey){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const s=Symbol(),i=this.getPropertyDescriptor(e,s,t);void 0!==i&&zv(this.prototype,e,i)}}static getPropertyDescriptor(e,t,s){const{get:i,set:r}=Fv(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:i,set(t){const n=null==i?void 0:i.call(this);null==r||r.call(this,t),this.requestUpdate(e,n,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??ey}static _$Ei(){if(this.hasOwnProperty(Xv("elementProperties")))return;const e=Hv(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Xv("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Xv("properties"))){const e=this.properties,t=[...Wv(e),...Vv(e)];for(const s of t)this.createProperty(s,e[s])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,s]of t)this.elementProperties.set(e,s)}this._$Eh=new Map;for(const[t,s]of this.elementProperties){const e=this._$Eu(t,s);void 0!==e&&this._$Eh.set(e,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const s=new Set(e.flat(1/0).reverse());for(const e of s)t.unshift(qv(e))}else void 0!==e&&t.push(qv(e));return t}static _$Eu(e,t){const s=t.attribute;return!1===s?void 0:"string"==typeof s?s:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),null==(e=this.constructor.l)||e.forEach(e
10=>e(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),void 0!==this.renderRoot&&this.isConnected&&(null==(t=e.hostConnected)||t.call(e))}removeController(e){var t;null==(t=this._$EO)||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const s of t.keys())this.hasOwnProperty(s)&&(e.set(s,this[s]),delete this[s]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(Uv)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const s of t){const t=document.createElement("style"),i=Rv.litNonce;void 0!==i&&t.setAttribute("nonce",i),t.textContent=s.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),null==(e=this._$EO)||e.forEach(e=>{var t;return null==(t=e.hostConnected)?void 0:t.call(e)})}enableUpdating(e){}disconnectedCallback(){var e;null==(e=this._$EO)||e.forEach(e=>{var t;return null==(t=e.hostDisconnected)?void 0:t.call(e)})}attributeChangedCallback(e,t,s){this._$AK(e,s)}_$ET(e,t){var s;const i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(void 0!==r&&!0===i.reflect){const n=(void 0!==(null==(s=i.converter)?void 0:s.toAttribute)?i.converter:Zv).toAttribute(t,i.type);this._$Em=e,null==n?this.removeAttribute(r):this.setAttribute(r,n),this._$Em=null}}_$AK(e,t){var s,i;const r=this.constructor,n=r._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=r.getPropertyOptions(n),o="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==(null==(s=e.converter)?void 0:s.fromAttribute)?e.converter:Zv;this._$Em=n;const a=o.fromAttribute(t,e.type);this[n]=a??(null==(i=this._$Ej)?void 0:i.get(n))??a,this._$Em=null}}requestUpdate(e,t,s){var i;if(void 0!==e){const r=this.constructor,n=this[e];if(s??(s=r.getPropertyOptions(e)),!((s.hasChanged??Qv)(n,t)||s.useDefault&&s.reflect&&n===(null==(i=this._$Ej)?void 0:i.get(e))&&!this.hasAttribute(r._$Eu(e,s))))return;this.C(e,t,s)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:s,reflect:i,wrapped:r},n){s&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,n??t??this[e]),!0!==r||void 0!==n)||(this._$AL.has(e)||(this.hasUpdated||s||(t=void 0),this._$AL.set(e,t)),!0===i&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var e;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,s]of e){const{wrapped:e}=s,i=this[t];!0!==e||this._$AL.has(t)||void 0===i||this.C(t,void 0,s,i)}}let t=!1;const s=this._$AL;try{t=this.shouldUpdate(s),t?(this.willUpdate(s),null==(e=this._$EO)||e.forEach(e=>{var t;return null==(t=e.hostUpdate)?void 0:t.call(e)}),this.update(s)):this._$EM()}catch(i){throw t=!1,this._$EM(),i}t&&this._$AE(s)}willUpdate(e){}_$AE(e){var t;null==(t=this._$EO)||t.forEach(e=>{var t;return null==(t=e.hostUpdated)?void 0:t.call(e)}),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(e=>this._$ET(e,this[e]))),this._$EM()}updated(e){}firstUpdated(e){}};ty.elementStyles=[],ty.shadowRootOptions={mode:"open"},ty[Xv("elementProperties")]=new Map,ty[Xv("finalized")]=new Map,null==Yv||Yv({ReactiveElement:ty}),(Kv.reactiveElementVersions??(Kv.reactiveElementVersions=[])).push("2.1.1"); 11/** 12 * @license 13 * Copyright 2017 Google LLC 14 * SPDX-License-Identifier: BSD-3-Clause 15 */ 16const sy=globalThis,iy=sy.trustedTypes,ry=iy?iy.createPolicy("lit-html",{createHTML:e=>e}):void 0,ny="$lit$",oy=`lit$${Math.random().toFixed(9).slice(2)}
16$`,ay="?"+oy,cy=`<${ay}>`,ly=document,dy=()=>ly.createComment(""),uy=e=>null===e||"object"!=typeof e&&"function"!=typeof e,hy=Array.isArray,py="[ \t\n\f\r]",gy=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,fy=/-->/g,my=/>/g,wy=RegExp(`>|${py}(?:([^\\s"'>=/]+)(${py}*=${py}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),vy=/'/g,yy=/"/g,by=/^(?:script|style|textarea|title)$/i,Ey=e=>(t,...s)=>({_$litType$:e,strings:t,values:s}),Cy=Ey(1),Iy=Ey(2),Ny=Symbol.for("lit-noChange"),Ay=Symbol.for("lit-nothing"),Sy=new WeakMap,Py=ly.createTreeWalker(ly,129);function ky(e,t){if(!hy(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==ry?ry.createHTML(t):t}class _y{constructor({strings:e,_$litType$:t},s){let i;this.parts=[];let r=0,n=0;const o=e.length-1,a=this.parts,[c,l]=((e,t)=>{const s=e.length-1,i=[];let r,n=2===t?"<svg>":3===t?"<math>":"",o=gy;for(let a=0;a<s;a++){const t=e[a];let s,c,l=-1,d=0;for(;d<t.length&&(o.lastIndex=d,c=o.exec(t),null!==c);)d=o.lastIndex,o===gy?"!--"===c[1]?o=fy:void 0!==c[1]?o=my:void 0!==c[2]?(by.test(c[2])&&(r=RegExp("</"+c[2],"g")),o=wy):void 0!==c[3]&&(o=wy):o===wy?">"===c[0]?(o=r??gy,l=-1):void 0===c[1]?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=void 0===c[3]?wy:'"'===c[3]?yy:vy):o===yy||o===vy?o=wy:o===fy||o===my?o=gy:(o=wy,r=void 0);const u=o===wy&&e[a+1].startsWith("/>")?" ":"";n+=o===gy?t+cy:l>=0?(i.push(s),t.slice(0,l)+ny+t.slice(l)+oy+u):t+oy+(-2===l?a:u)}return[ky(e,n+(e[s]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),i]})(e,t);if(this.el=_y.createElement(c,s),Py.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(i=Py.nextNode())&&a.length<o;){if(1===i.nodeType){if(i.hasAttributes())for(const e of i.getAttributeNames())if(e.endsWith(ny)){const t=l[n++],s=i.getAttribute(e).split(oy),o=/([.?@])?(.*)/.exec(t);a.push({type:1,index:r,name:o[2],strings:s,ctor:"."===o[1]?Uy:"?"===o[1]?$y:"@"===o[1]?Dy:Ry}),i.removeAttribute(e)}else e.startsWith(oy)&&(a.push({type:6,index:r}),i.removeAttribute(e));if(by.test(i.tagName)){const e=i.textContent.split(oy),t=e.length-1;if(t>0){i.textContent=iy?iy.emptyScript:"";for(let s=0;s<t;s++)i.append(e[s],dy()),Py.nextNode(),a.push({type:2,index:++r});i.append(e[t],dy())}}}else if(8===i.nodeType)if(i.data===ay)a.push({type:2,index:r});else{let e=-1;for(;-1!==(e=i.data.indexOf(oy,e+1));)a.push({type:7,index:r}),e+=oy.length-1}r++}}static createElement(e,t){const s=ly.createElement("template");return s.innerHTML=e,s}}function Oy(e,t,s=e,i){var r,n;if(t===Ny)return t;let o=void 0!==i?null==(r=s._$Co)?void 0:r[i]:s._$Cl;const a=uy(t)?void 0:t._$litDirective$;return(null==o?void 0:o.constructor)!==a&&(null==(n=null==o?void 0:o._$AO)||n.call(o,!1),void 0===a?o=void 0:(o=new a(e),o._$AT(e,s,i)),void 0!==i?(s._$Co??(s._$Co=[]))[i]=o:s._$Cl=o),void 0!==o&&(t=Oy(e,o._$AS(e,t.values),o,i)),t}class xy{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:s}=this._$AD,i=((null==e?void 0:e.creationScope)??ly).importNode(t,!0);Py.currentNode=i;let r=Py.nextNode(),n=0,o=0,a=s[0];for(;void 0!==a;){if(n===a.index){let t;2===a.type?t=new Ty(r,r.nextSibling,this,e):1===a.type?t=new a.ctor(r,a.name,a.strings,this,e):6===a.type&&(t=new My(r,this,e)),this._$AV.push(t),a=s[++o]}n!==(null==a?void 0:a.index)&&(r=Py.nextNode(),n++)}return Py.currentNode=ly,i}p(e){let t=0;for(const s of this._$AV)void 0!==s&&(void 0!==s.strings?(s._$AI(e,s,t),t+=s.strings.length-2):s._$AI(e[t])),t++}}class Ty{get _$AU(){var e;return(null==(e=this._$AM)?void 0:e._$AU)??this._$Cv}constructor(e,t,s,i){this.type=2,this._$AH=Ay,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=s,this.options=i,this._$Cv=(null==i?void 0:i.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===(null==e?void 0:e.nodeType)&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Oy(this,e,t),uy(e)?e===Ay||null==e||""===e?(this._$AH!==Ay&&this._$AR(),this._$AH=Ay):e!==this._$AH&&e!==Ny&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>hy(e)||"function"==typeof(null==e?void 0:e[Symbol.iterator]))(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!==Ay&&uy(this._$AH)?this._$AA.nextSibling.data=e:this.T(ly.createTextNode(e)),this._$AH=e}$(e){var t;const{values:s,_$litType$:i}=e,r="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=_y.createElement(ky(i.h,i.h[0]),this.options)),i);if((null==(t=this._$AH)?void 0:t._$AD)===r)this._$AH.p(s);else{const e=new xy(r,this),t=e.u(this.options);e.p(s),this.T(t),this._$AH=e}}_$AC(e){let t=Sy.get(e.strings);return void 0===t&&Sy.set(e.strings,t=new _y(e)),t}k(e){hy(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let s,i=0;for(const r of e)i===t.length?t.push(s=new Ty(this.O(dy()),this.O(dy()),this,this.options)):s=t[i],s._$AI(r),i++;i<t.length&&(this._$AR(s&&s._$AB.nextSibling,i),t.length=i)}_$AR(e=this._$AA.nextSibling,t){var s;
16for(null==(s=this._$AP)||s.call(this,!1,!0,t);e!==this._$AB;){const t=e.nextSibling;e.remove(),e=t}}setConnected(e){var t;void 0===this._$AM&&(this._$Cv=e,null==(t=this._$AP)||t.call(this,e))}}class Ry{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,s,i,r){this.type=1,this._$AH=Ay,this._$AN=void 0,this.element=e,this.name=t,this._$AM=i,this.options=r,s.length>2||""!==s[0]||""!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=Ay}_$AI(e,t=this,s,i){const r=this.strings;let n=!1;if(void 0===r)e=Oy(this,e,t,0),n=!uy(e)||e!==this._$AH&&e!==Ny,n&&(this._$AH=e);else{const i=e;let o,a;for(e=r[0],o=0;o<r.length-1;o++)a=Oy(this,i[s+o],t,o),a===Ny&&(a=this._$AH[o]),n||(n=!uy(a)||a!==this._$AH[o]),a===Ay?e=Ay:e!==Ay&&(e+=(a??"")+r[o+1]),this._$AH[o]=a}n&&!i&&this.j(e)}j(e){e===Ay?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Uy extends Ry{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Ay?void 0:e}}class $y extends Ry{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Ay)}}class Dy extends Ry{constructor(e,t,s,i,r){super(e,t,s,i,r),this.type=5}
16_$AI(e,t=this){if((e=Oy(this,e,t,0)??Ay)===Ny)return;const s=this._$AH,i=e===Ay&&s!==Ay||e.capture!==s.capture||e.once!==s.once||e.passive!==s.passive,r=e!==Ay&&(s===Ay||i);i&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;"function"==typeof this._$AH?this._$AH.call((null==(t=this.options)?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class My{constructor(e,t,s){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(e){Oy(this,e)}}const jy=sy.litHtmlPolyfillSupport;null==jy||jy(_y,Ty),(sy.litHtmlVersions??(sy.litHtmlVersions=[])).push("3.3.1");const Ly=globalThis; 17/** 18 * @license 19 * Copyright 2017 Google LLC 20 * SPDX-License-Identifier: BSD-3-Clause 21 */class qy extends ty{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;const t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,s)=>{const i=(null==s?void 0:s.renderBefore)??t;let r=i._$litPart$;if(void 0===r){const e=(null==s?void 0:s.renderBefore)??null;i._$litPart$=r=new Ty(t.insertBefore(dy(),e),e,void 0,s??{})}return r._$AI(e),r})(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),null==(e=this._$Do)||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),null==(e=this._$Do)||e.setConnected(!1)}render(){return Ny}}qy._$litElement$=!0,qy.finalized=!0,null==(e=Ly.litElementHydrateSupport)||e.call(Ly,{LitElement:qy});const By=Ly.litElementPolyfillSupport;let zy,Fy,Wy;function Vy(e,t){zy=document.createElement("style"),Fy=document.createElement("style"),Wy=document.createElement("style"),zy.textContent=Ky(e).core.cssText,Fy.textContent=Ky(e).dark.cssText,Wy.textContent=Ky(e).light.cssText,document.head.appendChild(zy),document.head.appendChild(Fy),document.head.appendChild(Wy),Hy(t)}function Hy(e){Fy&&Wy&&("light"===e?(Fy.removeAttribute("media"),Wy.media="enabled"):(Wy.removeAttribute("media"),Fy.media="enabled"))}function Ky(e){return{core:Lv` 22 @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap'); 23 @keyframes w3m-shake { 24 0% { 25 transform: scale(1) rotate(0deg); 26 } 27 20% { 28 transform: scale(1) rotate(-1deg); 29 } 30 40% { 31 transform: scale(1) rotate(1.5deg); 32 } 33 60% { 34 transform: scale(1) rotate(-1.5deg); 35 } 36 80% { 37 transform: scale(1) rotate(1deg); 38 } 39 100% { 40 transform: scale(1) rotate(0deg); 41 } 42 } 43 @keyframes w3m-iframe-fade-out { 44 0% { 45 opacity: 1; 46 } 47 100% { 48 opacity: 0; 49 } 50 } 51 @keyframes w3m-iframe-zoom-in { 52 0% { 53 transform: translateY(50px); 54 opacity: 0; 55 } 56 100% { 57 transform: translateY(0px); 58 opacity: 1; 59 } 60 } 61 @keyframes w3m-iframe-zoom-in-mobile { 62 0% { 63 transform: scale(0.95); 64 opacity: 0; 65 } 66 100% { 67 transform: scale(1); 68 opacity: 1; 69 } 70 } 71 :root { 72 --w3m-modal-width: 360px; 73 --w3m-color-mix-strength: ${jv((null==e?void 0:e["--w3m-color-mix-strength"])?`${e["--w3m-color-mix-strength"]}%`:"0%")}; 74 --w3m-font-family: ${jv((null==e?void 0:e["--w3m-font-family"])||"Inter, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;")}; 75 --w3m-font-size-master: ${jv((null==e?void 0:e["--w3m-font-size-master"])||"10px")}; 76 --w3m-border-radius-master: ${jv((null==e?void 0:e["--w3m-border-radius-master"])||"4px")}; 77 --w3m-z-index: ${jv((null==e?void 0:e["--w3m-z-index"])||
vendor: 15,824 bytes, lines 77-503
77999)}; 78 79 --wui-font-family: var(--w3m-font-family); 80 81 --wui-font-size-mini: calc(var(--w3m-font-size-master) * 0.8); 82 --wui-font-size-micro: var(--w3m-font-size-master); 83 --wui-font-size-tiny: calc(var(--w3m-font-size-master) * 1.2); 84 --wui-font-size-small: calc(var(--w3m-font-size-master) * 1.4); 85 --wui-font-size-paragraph: calc(var(--w3m-font-size-master) * 1.6); 86 --wui-font-size-medium: calc(var(--w3m-font-size-master) * 1.8); 87 --wui-font-size-large: calc(var(--w3m-font-size-master) * 2); 88 --wui-font-size-title-6: calc(var(--w3m-font-size-master) * 2.2); 89 --wui-font-size-medium-title: calc(var(--w3m-font-size-master) * 2.4); 90 --wui-font-size-2xl: calc(var(--w3m-font-size-master) * 4); 91 92 --wui-border-radius-5xs: var(--w3m-border-radius-master); 93 --wui-border-radius-4xs: calc(var(--w3m-border-radius-master) * 1.5); 94 --wui-border-radius-3xs: calc(var(--w3m-border-radius-master) * 2); 95 --wui-border-radius-xxs: calc(var(--w3m-border-radius-master) * 3); 96 --wui-border-radius-xs: calc(var(--w3m-border-radius-master) * 4); 97 --wui-border-radius-s: calc(var(--w3m-border-radius-master) * 5); 98 --wui-border-radius-m: calc(var(--w3m-border-radius-master) * 7); 99 --wui-border-radius-l: calc(var(--w3m-border-radius-master) * 9); 100 --wui-border-radius-3xl: calc(var(--w3m-border-radius-master) * 20); 101 102 --wui-font-weight-light: 400; 103 --wui-font-weight-regular: 500; 104 --wui-font-weight-medium: 600; 105 --wui-font-weight-bold: 700; 106 107 --wui-letter-spacing-2xl: -1.6px; 108 --wui-letter-spacing-medium-title: -0.96px; 109 --wui-letter-spacing-title-6: -0.88px; 110 --wui-letter-spacing-large: -0.8px; 111 --wui-letter-spacing-medium: -0.72px; 112 --wui-letter-spacing-paragraph: -0.64px; 113 --wui-letter-spacing-small: -0.56px; 114 --wui-letter-spacing-tiny: -0.48px; 115 --wui-letter-spacing-micro: -0.2px; 116 --wui-letter-spacing-mini: -0.16px; 117 118 --wui-spacing-0: 0px; 119 --wui-spacing-4xs: 2px; 120 --wui-spacing-3xs: 4px; 121 --wui-spacing-xxs: 6px; 122 --wui-spacing-2xs: 7px; 123 --wui-spacing-xs: 8px; 124 --wui-spacing-1xs: 10px; 125 --wui-spacing-s: 12px; 126 --wui-spacing-m: 14px; 127 --wui-spacing-l: 16px; 128 --wui-spacing-2l: 18px; 129 --wui-spacing-xl: 20px; 130 --wui-spacing-xxl: 24px; 131 --wui-spacing-2xl: 32px; 132 --wui-spacing-3xl: 40px; 133 --wui-spacing-4xl: 90px; 134 --wui-spacing-5xl: 95px; 135 136 --wui-icon-box-size-xxs: 14px; 137 --wui-icon-box-size-xs: 20px; 138 --wui-icon-box-size-sm: 24px; 139 --wui-icon-box-size-md: 32px; 140 --wui-icon-box-size-mdl: 36px; 141 --wui-icon-box-size-lg: 40px; 142 --wui-icon-box-size-2lg: 48px; 143 --wui-icon-box-size-xl: 64px; 144 145 --wui-icon-size-inherit: inherit; 146 --wui-icon-size-xxs: 10px; 147 --wui-icon-size-xs: 12px; 148 --wui-icon-size-sm: 14px; 149 --wui-icon-size-md: 16px; 150 --wui-icon-size-mdl: 18px; 151 --wui-icon-size-lg: 20px; 152 --wui-icon-size-xl: 24px; 153 --wui-icon-size-xxl: 28px; 154 155 --wui-wallet-image-size-inherit: inherit; 156 --wui-wallet-image-size-sm: 40px; 157 --wui-wallet-image-size-md: 56px; 158 --wui-wallet-image-size-lg: 80px; 159 160 --wui-visual-size-size-inherit: inherit; 161 --wui-visual-size-sm: 40px; 162 --wui-visual-size-md: 55px; 163 --wui-visual-size-lg: 80px; 164 165 --wui-box-size-md: 100px; 166 --wui-box-size-lg: 120px; 167 168 --wui-ease-out-power-2: cubic-bezier(0, 0, 0.22, 1); 169 --wui-ease-out-power-1: cubic-bezier(0, 0, 0.55, 1); 170 171 --wui-ease-in-power-3: cubic-bezier(0.66, 0, 1, 1); 172 --wui-ease-in-power-2: cubic-bezier(0.45, 0, 1, 1); 173 --wui-ease-in-power-1: cubic-bezier(0.3, 0, 1, 1); 174 175 --wui-ease-inout-power-1: cubic-bezier(0.45, 0, 0.55, 1); 176 177 --wui-duration-lg: 200ms; 178 --wui-duration-md: 125ms; 179 --wui-duration-sm: 75ms; 180 181 --wui-path-network-sm: path( 182 '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' 183 ); 184 185 --wui-path-network-md: path( 186 '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' 187 ); 188 189 --wui-path-network-lg: path( 190 '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' 191 ); 192 193 --wui-width-network-sm: 36px; 194 --wui-width-network-md: 48px; 195 --wui-width-network-lg: 86px; 196 197 --wui-height-network-sm: 40px; 198 --wui-height-network-md: 54px; 199 --wui-height-network-lg: 96px; 200 201 --wui-icon-size-network-xs: 12px; 202 --wui-icon-size-network-sm: 16px; 203 --wui-icon-size-network-md: 24px; 204 --wui-icon-size-network-lg: 42px; 205 206 --wui-color-inherit: inherit; 207 208 --wui-color-inverse-100: #fff; 209 --wui-color-inverse-000: #000; 210 211 --wui-cover: rgba(20, 20, 20, 0.8); 212 213 --wui-color-modal-bg: var(--wui-color-modal-bg-base); 214 215 --wui-color-accent-100: var(--wui-color-accent-base-100); 216 --wui-color-accent-090: var(--wui-color-accent-base-090); 217 --wui-color-accent-080: var(--wui-color-accent-base-080); 218 219 --wui-color-success-100: var(--wui-color-success-base-100); 220 --wui-color-success-125: var(--wui-color-success-base-125); 221 222 --wui-color-warning-100: var(--wui-color-warning-base-100); 223 224 --wui-color-error-100: var(--wui-color-error-base-100); 225 --wui-color-error-125: var(--wui-color-error-base-125); 226 227 --wui-color-blue-100: var(--wui-color-blue-base-100); 228 --wui-color-blue-90: var(--wui-color-blue-base-90); 229 230 --wui-icon-box-bg-error-100: var(--wui-icon-box-bg-error-base-100); 231 --wui-icon-box-bg-blue-100: var(--wui-icon-box-bg-blue-base-100); 232 --wui-icon-box-bg-success-100: var(--wui-icon-box-bg-success-base-100); 233 --wui-icon-box-bg-inverse-100: var(--wui-icon-box-bg-inverse-base-100); 234 235 --wui-all-wallets-bg-100: var(--wui-all-wallets-bg-100); 236 237 --wui-avatar-border: var(--wui-avatar-border-base); 238 239 --wui-thumbnail-border: var(--wui-thumbnail-border-base); 240 241 --wui-wallet-button-bg: var(--wui-wallet-button-bg-base); 242 243 --wui-box-shadow-blue: var(--wui-color-accent-glass-020); 244 } 245 246 @supports (background: color-mix(in srgb, white 50%, black)) { 247 :root { 248 --wui-color-modal-bg: color-mix( 249 in srgb, 250 var(--w3m-color-mix) var(--w3m-color-mix-strength), 251 var(--wui-color-modal-bg-base) 252 ); 253 254 --wui-box-shadow-blue: color-mix(in srgb, var(--wui-color-accent-100) 20%, transparent); 255 256 --wui-color-accent-100: color-mix( 257 in srgb, 258 var(--wui-color-accent-base-100) 100%, 259 transparent 260 ); 261 --wui-color-accent-090: color-mix( 262 in srgb, 263 var(--wui-color-accent-base-100) 90%, 264 transparent 265 ); 266 --wui-color-accent-080: color-mix( 267 in srgb, 268 var(--wui-color-accent-base-100) 80%, 269 transparent 270 ); 271 --wui-color-accent-glass-090: color-mix( 272 in srgb, 273 var(--wui-color-accent-base-100) 90%, 274 transparent 275 ); 276 --wui-color-accent-glass-080: color-mix( 277 in srgb, 278 var(--wui-color-accent-base-100) 80%, 279 transparent 280 ); 281 --wui-color-accent-glass-020: color-mix( 282 in srgb, 283 var(--wui-color-accent-base-100) 20%, 284 transparent 285 ); 286 --wui-color-accent-glass-015: color-mix( 287 in srgb, 288 var(--wui-color-accent-base-100) 15%, 289 transparent 290 ); 291 --wui-color-accent-glass-010: color-mix( 292 in srgb, 293 var(--wui-color-accent-base-100) 10%, 294 transparent 295 ); 296 --wui-color-accent-glass-005: color-mix( 297 in srgb, 298 var(--wui-color-accent-base-100) 5%, 299 transparent 300 ); 301 --wui-color-accent-002: color-mix( 302 in srgb, 303 var(--wui-color-accent-base-100) 2%, 304 transparent 305 ); 306 307 --wui-color-fg-100: color-mix( 308 in srgb, 309 var(--w3m-color-mix) var(--w3m-color-mix-strength), 310 var(--wui-color-fg-100) 311 ); 312 --wui-color-fg-125: color-mix( 313 in srgb, 314 var(--w3m-color-mix) var(--w3m-color-mix-strength), 315 var(--wui-color-fg-125) 316 ); 317 --wui-color-fg-150: color-mix( 318 in srgb, 319 var(--w3m-color-mix) var(--w3m-color-mix-strength), 320 var(--wui-color-fg-150) 321 ); 322 --wui-color-fg-175: color-mix( 323 in srgb, 324 var(--w3m-color-mix) var(--w3m-color-mix-strength), 325 var(--wui-color-fg-175) 326 ); 327 --wui-color-fg-200: color-mix( 328 in srgb, 329 var(--w3m-color-mix) var(--w3m-color-mix-strength), 330 var(--wui-color-fg-200) 331 ); 332 --wui-color-fg-225: color-mix( 333 in srgb, 334 var(--w3m-color-mix) var(--w3m-color-mix-strength), 335 var(--wui-color-fg-225) 336 ); 337 --wui-color-fg-250: color-mix( 338 in srgb, 339 var(--w3m-color-mix) var(--w3m-color-mix-strength), 340 var(--wui-color-fg-250) 341 ); 342 --wui-color-fg-275: color-mix( 343 in srgb, 344 var(--w3m-color-mix) var(--w3m-color-mix-strength), 345 var(--wui-color-fg-275) 346 ); 347 --wui-color-fg-300: color-mix( 348 in srgb, 349 var(--w3m-color-mix) var(--w3m-color-mix-strength), 350 var(--wui-color-fg-300) 351 ); 352 --wui-color-fg-325: color-mix( 353 in srgb, 354 var(--w3m-color-mix) var(--w3m-color-mix-strength), 355 var(--wui-color-fg-325) 356 ); 357 --wui-color-fg-350: color-mix( 358 in srgb, 359 var(--w3m-color-mix) var(--w3m-color-mix-strength), 360 var(--wui-color-fg-350) 361 ); 362 363 --wui-color-bg-100: color-mix( 364 in srgb, 365 var(--w3m-color-mix) var(--w3m-color-mix-strength), 366 var(--wui-color-bg-100) 367 ); 368 --wui-color-bg-125: color-mix( 369 in srgb, 370 var(--w3m-color-mix) var(--w3m-color-mix-strength), 371 var(--wui-color-bg-125) 372 ); 373 --wui-color-bg-150: color-mix( 374 in srgb, 375 var(--w3m-color-mix) var(--w3m-color-mix-strength), 376 var(--wui-color-bg-150) 377 ); 378 --wui-color-bg-175: color-mix( 379 in srgb, 380 var(--w3m-color-mix) var(--w3m-color-mix-strength), 381 var(--wui-color-bg-175) 382 ); 383 --wui-color-bg-200: color-mix( 384 in srgb, 385 var(--w3m-color-mix) var(--w3m-color-mix-strength), 386 var(--wui-color-bg-200) 387 ); 388 --wui-color-bg-225: color-mix( 389 in srgb, 390 var(--w3m-color-mix) var(--w3m-color-mix-strength), 391 var(--wui-color-bg-225) 392 ); 393 --wui-color-bg-250: color-mix( 394 in srgb, 395 var(--w3m-color-mix) var(--w3m-color-mix-strength), 396 var(--wui-color-bg-250) 397 ); 398 --wui-color-bg-275: color-mix( 399 in srgb, 400 var(--w3m-color-mix) var(--w3m-color-mix-strength), 401 var(--wui-color-bg-275) 402 ); 403 --wui-color-bg-300: color-mix( 404 in srgb, 405 var(--w3m-color-mix) var(--w3m-color-mix-strength), 406 var(--wui-color-bg-300) 407 ); 408 --wui-color-bg-325: color-mix( 409 in srgb, 410 var(--w3m-color-mix) var(--w3m-color-mix-strength), 411 var(--wui-color-bg-325) 412 ); 413 --wui-color-bg-350: color-mix( 414 in srgb, 415 var(--w3m-color-mix) var(--w3m-color-mix-strength), 416 var(--wui-color-bg-350) 417 ); 418 419 --wui-color-success-100: color-mix( 420 in srgb, 421 var(--w3m-color-mix) var(--w3m-color-mix-strength), 422 var(--wui-color-success-base-100) 423 ); 424 --wui-color-success-125: color-mix( 425 in srgb, 426 var(--w3m-color-mix) var(--w3m-color-mix-strength), 427 var(--wui-color-success-base-125) 428 ); 429 430 --wui-color-warning-100: color-mix( 431 in srgb, 432 var(--w3m-color-mix) var(--w3m-color-mix-strength), 433 var(--wui-color-warning-base-100) 434 ); 435 436 --wui-color-error-100: color-mix( 437 in srgb, 438 var(--w3m-color-mix) var(--w3m-color-mix-strength), 439 var(--wui-color-error-base-100) 440 ); 441 --wui-color-blue-100: color-mix( 442 in srgb, 443 var(--w3m-color-mix) var(--w3m-color-mix-strength), 444 var(--wui-color-blue-base-100) 445 ); 446 --wui-color-blue-90: color-mix( 447 in srgb, 448 var(--w3m-color-mix) var(--w3m-color-mix-strength), 449 var(--wui-color-blue-base-90) 450 ); 451 --wui-color-error-125: color-mix( 452 in srgb, 453 var(--w3m-color-mix) var(--w3m-color-mix-strength), 454 var(--wui-color-error-base-125) 455 ); 456 457 --wui-icon-box-bg-error-100: color-mix( 458 in srgb, 459 var(--w3m-color-mix) var(--w3m-color-mix-strength), 460 var(--wui-icon-box-bg-error-base-100) 461 ); 462 --wui-icon-box-bg-accent-100: color-mix( 463 in srgb, 464 var(--w3m-color-mix) var(--w3m-color-mix-strength), 465 var(--wui-icon-box-bg-blue-base-100) 466 ); 467 --wui-icon-box-bg-success-100: color-mix( 468 in srgb, 469 var(--w3m-color-mix) var(--w3m-color-mix-strength), 470 var(--wui-icon-box-bg-success-base-100) 471 ); 472 --wui-icon-box-bg-inverse-100: color-mix( 473 in srgb, 474 var(--w3m-color-mix) var(--w3m-color-mix-strength), 475 var(--wui-icon-box-bg-inverse-base-100) 476 ); 477 478 --wui-all-wallets-bg-100: color-mix( 479 in srgb, 480 var(--w3m-color-mix) var(--w3m-color-mix-strength), 481 var(--wui-all-wallets-bg-100) 482 ); 483 484 --wui-avatar-border: color-mix( 485 in srgb, 486 var(--w3m-color-mix) var(--w3m-color-mix-strength), 487 var(--wui-avatar-border-base) 488 ); 489 490 --wui-thumbnail-border: color-mix( 491 in srgb, 492 var(--w3m-color-mix) var(--w3m-color-mix-strength), 493 var(--wui-thumbnail-border-base) 494 ); 495 496 --wui-wallet-button-bg: color-mix( 497 in srgb, 498 var(--w3m-color-mix) var(--w3m-color-mix-strength), 499 var(--wui-wallet-button-bg-base) 500 ); 501 } 502 } 503 `,
503light:Lv` 504 :root { 505 --w3m-color-mix: ${jv((null==e?void 0:e["--w3m-color-mix"])||"#fff")}; 506 --w3m-accent: ${jv(Ie(e,"dark")["--w3m-accent"])}; 507 --w3m-default: #fff; 508 509 --wui-color-modal-bg-base: ${jv(Ie(e,"dark")["--w3m-background"])}; 510 --wui-color-accent-base-100: var(--w3m-accent); 511 512 --wui-color-blueberry-100: hsla(230, 100%, 67%, 1); 513 --wui-color-blueberry-090: hsla(231, 76%, 61%, 1); 514 --wui-color-blueberry-080: hsla(230, 59%, 55%, 1); 515 --wui-color-blueberry-050: hsla(231, 100%, 70%, 0.1); 516 517 --wui-color-fg-100: #e4e7e7; 518 --wui-color-fg-125: #d0d5d5; 519 --wui-color-fg-150: #a8b1b1; 520 --wui-color-fg-175: #a8b0b0; 521 --wui-color-fg-200: #949e9e; 522 --wui-color-fg-225: #868f8f; 523 --wui-color-fg-250: #788080; 524 --wui-color-fg-275: #788181; 525 --wui-color-fg-300: #6e7777; 526 --wui-color-fg-325: #9a9a9a; 527 --wui-color-fg-350: #363636; 528 529 --wui-color-bg-100: #141414; 530 --wui-color-bg-125: #191a1a; 531 --wui-color-bg-150: #1e1f1f; 532 --wui-color-bg-175: #222525; 533 --wui-color-bg-200: #272a2a; 534 --wui-color-bg-225: #2c3030; 535 --wui-color-bg-250: #313535; 536 --wui-color-bg-275: #363b3b; 537 --wui-color-bg-300: #3b4040; 538 --wui-color-bg-325: #252525; 539 --wui-color-bg-350: #ffffff; 540 541 --wui-color-success-base-100: #26d962; 542 --wui-color-success-base-125: #30a46b; 543 544 --wui-color-warning-base-100: #f3a13f; 545 546 --wui-color-error-base-100: #f25a67; 547 --wui-color-error-base-125: #df4a34; 548 549 --wui-color-blue-base-100: rgba(102, 125, 255, 1); 550 --wui-color-blue-base-90: rgba(102, 125, 255, 0.9); 551 552 --wui-color-success-glass-001: rgba(38, 217, 98, 0.01); 553 --wui-color-success-glass-002: rgba(38, 217, 98, 0.02); 554 --wui-color-success-glass-005: rgba(38, 217, 98, 0.05); 555 --wui-color-success-glass-010: rgba(38, 217, 98, 0.1); 556 --wui-color-success-glass-015: rgba(38, 217, 98, 0.15); 557 --wui-color-success-glass-020: rgba(38, 217, 98, 0.2); 558 --wui-color-success-glass-025: rgba(38, 217, 98, 0.25); 559 --wui-color-success-glass-030: rgba(38, 217, 98, 0.3); 560 --wui-color-success-glass-060: rgba(38, 217, 98, 0.6); 561 --wui-color-success-glass-080: rgba(38, 217, 98, 0.8); 562 563 --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2); 564 565 --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2); 566 567 --wui-color-error-glass-001: rgba(242, 90, 103, 0.01); 568 --wui-color-error-glass-002: rgba(242, 90, 103, 0.02); 569 --wui-color-error-glass-005: rgba(242, 90, 103, 0.05); 570 --wui-color-error-glass-010: rgba(242, 90, 103, 0.1); 571 --wui-color-error-glass-015: rgba(242, 90, 103, 0.15); 572 --wui-color-error-glass-020: rgba(242, 90, 103, 0.2); 573 --wui-color-error-glass-025: rgba(242, 90, 103, 0.25); 574 --wui-color-error-glass-030: rgba(242, 90, 103, 0.3); 575 --wui-color-error-glass-060: rgba(242, 90, 103, 0.6); 576 --wui-color-error-glass-080: rgba(242, 90, 103, 0.8); 577 578 --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2); 579 580 --wui-color-gray-glass-001: rgba(255, 255, 255, 0.01); 581 --wui-color-gray-glass-002: rgba(255, 255, 255, 0.02); 582 --wui-color-gray-glass-005: rgba(255, 255, 255, 0.05); 583 --wui-color-gray-glass-010: rgba(255, 255, 255, 0.1); 584 --wui-color-gray-glass-015: rgba(255, 255, 255, 0.15); 585 --wui-color-gray-glass-020: rgba(255, 255, 255, 0.2); 586 --wui-color-gray-glass-025: rgba(255, 255, 255, 0.25); 587 --wui-color-gray-glass-030: rgba(255, 255, 255, 0.3); 588 --wui-color-gray-glass-060: rgba(255, 255, 255, 0.6); 589 --wui-color-gray-glass-080: rgba(255, 255, 255, 0.8); 590 --wui-color-gray-glass-090: rgba(255, 255, 255, 0.9); 591 592 --wui-color-dark-glass-100: rgba(42, 42, 42, 1); 593 594 --wui-icon-box-bg-error-base-100: #3c2426; 595 --wui-icon-box-bg-blue-base-100: #20303f; 596 --wui-icon-box-bg-success-base-100: #1f3a28; 597 --wui-icon-box-bg-inverse-base-100: #243240; 598 599 --wui-all-wallets-bg-100: #222b35; 600 601 --wui-avatar-border-base: #252525; 602
603 --wui-thumbnail-border-base: #252525; 604 605 --wui-wallet-button-bg-base: var(--wui-color-bg-125); 606 607 --w3m-card-embedded-shadow-color: rgb(17 17 18 / 25%); 608 } 609 `,dark:Lv` 610 :root { 611 --w3m-color-mix: ${jv((null==e?void 0:e["--w3m-color-mix"])||"#000")}; 612 --w3m-accent: ${jv(Ie(e,"light")["--w3m-accent"])}; 613 --w3m-default: #000; 614 615 --wui-color-modal-bg-base: ${jv(Ie(e,"light")["--w3m-background"])}; 616 --wui-color-accent-base-100: var(--w3m-accent); 617 618 --wui-color-blueberry-100: hsla(231, 100%, 70%, 1); 619 --wui-color-blueberry-090: hsla(231, 97%, 72%, 1); 620 --wui-color-blueberry-080: hsla(231, 92%, 74%, 1); 621 622 --wui-color-fg-100: #141414; 623 --wui-color-fg-125: #2d3131; 624 --wui-color-fg-150: #474d4d; 625 --wui-color-fg-175: #636d6d; 626 --wui-color-fg-200: #798686; 627 --wui-color-fg-225: #828f8f; 628 --wui-color-fg-250: #8b9797; 629 --wui-color-fg-275: #95a0a0; 630 --wui-color-fg-300: #9ea9a9; 631 --wui-color-fg-325: #9a9a9a; 632 --wui-color-fg-350: #d0d0d0; 633 634 --wui-color-bg-100: #ffffff; 635 --wui-color-bg-125: #f5fafa; 636 --wui-color-bg-150: #f3f8f8; 637 --wui-color-bg-175: #eef4f4; 638 --wui-color-bg-200: #eaf1f1; 639 --wui-color-bg-225: #e5eded; 640 --wui-color-bg-250: #e1e9e9; 641 --wui-color-bg-275: #dce7e7; 642 --wui-color-bg-300: #d8e3e3; 643 --wui-color-bg-325: #f3f3f3; 644 --wui-color-bg-350: #202020; 645 646 --wui-color-success-base-100: #26b562; 647 --wui-color-success-base-125: #30a46b; 648 649 --wui-color-warning-base-100: #f3a13f; 650 651 --wui-color-error-base-100: #f05142; 652 --wui-color-error-base-125: #df4a34; 653 654 --wui-color-blue-base-100: rgba(102, 125, 255, 1); 655 --wui-color-blue-base-90: rgba(102, 125, 255, 0.9); 656 657 --wui-color-success-glass-001: rgba(38, 181, 98, 0.01); 658 --wui-color-success-glass-002: rgba(38, 181, 98, 0.02); 659 --wui-color-success-glass-005: rgba(38, 181, 98, 0.05); 660 --wui-color-success-glass-010: rgba(38, 181, 98, 0.1); 661 --wui-color-success-glass-015: rgba(38, 181, 98, 0.15); 662 --wui-color-success-glass-020: rgba(38, 181, 98, 0.2); 663 --wui-color-success-glass-025: rgba(38, 181, 98, 0.25); 664 --wui-color-success-glass-030: rgba(38, 181, 98, 0.3); 665 --wui-color-success-glass-060: rgba(38, 181, 98, 0.6); 666 --wui-color-success-glass-080: rgba(38, 181, 98, 0.8); 667 668 --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2); 669 670 --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2); 671 672 --wui-color-error-glass-001: rgba(240, 81, 66, 0.01); 673 --wui-color-error-glass-002: rgba(240, 81, 66, 0.02); 674 --wui-color-error-glass-005: rgba(240, 81, 66, 0.05); 675 --wui-color-error-glass-010: rgba(240, 81, 66, 0.1); 676 --wui-color-error-glass-015: rgba(240, 81, 66, 0.15); 677 --wui-color-error-glass-020: rgba(240, 81, 66, 0.2); 678 --wui-color-error-glass-025: rgba(240, 81, 66, 0.25); 679 --wui-color-error-glass-030: rgba(240, 81, 66, 0.3); 680 --wui-color-error-glass-060: rgba(240, 81, 66, 0.6); 681 --wui-color-error-glass-080: rgba(240, 81, 66, 0.8); 682 683 --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2); 684 685 --wui-icon-box-bg-error-base-100: #f4dfdd; 686 --wui-icon-box-bg-blue-base-100: #d9ecfb; 687 --wui-icon-box-bg-success-base-100: #daf0e4; 688 --wui-icon-box-bg-inverse-base-100: #dcecfc; 689 690 --wui-all-wallets-bg-100: #e8f1fa; 691 692 --wui-avatar-border-base: #f3f4f4; 693 694 --wui-thumbnail-border-base: #eaefef; 695 696 --wui-wallet-button-bg-base: var(--wui-color-bg-125); 697 698 --wui-color-gray-glass-001: rgba(0, 0, 0, 0.01); 699 --wui-color-gray-glass-002: rgba(0, 0, 0, 0.02); 700 --wui-color-gray-glass-005: rgba(0, 0, 0, 0.05); 701 --wui-color-gray-glass-010: rgba(0, 0, 0, 0.1); 702 --wui-color-gray-glass-015: rgba(0, 0, 0, 0.15); 703 --wui-color-gray-glass-020: rgba(0, 0, 0, 0.2); 704 --wui-color-gray-glass-025: rgba(0, 0, 0, 0.25); 705 --wui-color-gray-glass-030: rgba(0, 0, 0, 0.3); 706 --wui-color-gray-glass-060: rgba(0, 0, 0, 0.6); 707 --wui-color-gray-glass-080: rgba(0, 0, 0, 0.8); 708 --wui-color-gray-glass-090: rgba(0, 0, 0, 0.9); 709 710 --wui-color-dark-glass-100: rgba(233, 233, 233, 1); 711 712 --w3m-card-embedded-shadow-color: rgb(224 225 233 / 25%); 713 } 714 `}}null==By||By({LitElement:qy}),(Ly.litElementVersions??(Ly.litElementVersions=[])).push("4.2.1");const Gy=Lv` 715 *, 716 *::after, 717 *::before, 718 :host { 719 margin: 0; 720 padding: 0; 721 box-sizing: border-box; 722 font-style: normal; 723 text-rendering: optimizeSpeed; 724 -webkit-font-smoothing: antialiased; 725 -moz-osx-font-smoothing: grayscale; 726 -webkit-tap-highlight-color: transparent; 727 font-family: var(--wui-font-family); 728 backface-visibility: hidden; 729 } 730`,Jy=Lv` 731 button, 732 a { 733 cursor: pointer; 734 display: flex; 735 justify-content: center;
736 align-items: center; 737 position: relative; 738 transition: 739 color var(--wui-duration-lg) var(--wui-ease-out-power-1), 740 background-color var(--wui-duration-lg) var(--wui-ease-out-power-1), 741 border var(--wui-duration-lg) var(--wui-ease-out-power-1), 742 border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1), 743 box-shadow var(--wui-duration-lg) var(--wui-ease-out-power-1); 744 will-change: background-color, color, border, box-shadow, border-radius; 745 outline: none; 746 border: none; 747 column-gap: var(--wui-spacing-3xs); 748 background-color: transparent; 749 text-decoration: none; 750 } 751 752 wui-flex { 753 transition: border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1); 754 will-change: border-radius; 755 } 756 757 button:disabled > wui-wallet-image, 758 button:disabled > wui-all-wallets-image, 759 button:disabled > wui-network-image, 760 button:disabled > wui-image, 761 button:disabled > wui-transaction-visual, 762 button:disabled > wui-logo { 763 filter: grayscale(1); 764 } 765 766 @media (hover: hover) and (pointer: fine) { 767 button:hover:enabled { 768 background-color: var(--wui-color-gray-glass-005); 769 } 770 771 button:active:enabled { 772 background-color: var(--wui-color-gray-glass-010); 773 } 774 } 775 776 button:disabled > wui-icon-box { 777 opacity: 0.5; 778 } 779 780 input { 781 border: none; 782 outline: none; 783 appearance: none; 784 } 785`,Yy=Lv` 786 .wui-color-inherit { 787 color: var(--wui-color-inherit); 788 } 789 790 .wui-color-accent-100 { 791 color: var(--wui-color-accent-100); 792 } 793 794 .wui-color-error-100 { 795 color: var(--wui-color-error-100); 796 } 797 798 .wui-color-blue-100 { 799 color: var(--wui-color-blue-100); 800 } 801 802 .wui-color-blue-90 { 803 color: var(--wui-color-blue-90); 804 } 805 806 .wui-color-error-125 { 807 color: var(--wui-color-error-125); 808 } 809 810 .wui-color-success-100 { 811 color: var(--wui-color-success-100); 812 } 813 814 .wui-color-success-125 { 815 color: var(--wui-color-success-125); 816 } 817 818 .wui-color-inverse-100 { 819 color: var(--wui-color-inverse-100); 820 } 821 822 .wui-color-inverse-000 { 823 color: var(--wui-color-inverse-000); 824 } 825 826 .wui-color-fg-100 { 827 color: var(--wui-color-fg-100); 828 } 829 830 .wui-color-fg-200 { 831 color: var(--wui-color-fg-200); 832 } 833 834 .wui-color-fg-300 { 835 color: var(--wui-color-fg-300); 836 } 837 838 .wui-color-fg-325 { 839 color: var(--wui-color-fg-325); 840 } 841 842 .wui-color-fg-350 { 843 color: var(--wui-color-fg-350); 844 } 845 846 .wui-bg-color-inherit { 847 background-color: var(--wui-color-inherit); 848 } 849 850 .wui-bg-color-blue-100 { 851 background-color: var(--wui-color-accent-100); 852 } 853 854 .wui-bg-color-error-100 { 855 background-color: var(--wui-color-error-100); 856 } 857 858 .wui-bg-color-error-125 { 859 background-color: var(--wui-color-error-125); 860 } 861 862 .wui-bg-color-success-100 { 863 background-color: var(--wui-color-success-100); 864 } 865 866 .wui-bg-color-success-125 { 867 background-color: var(--wui-color-success-100); 868 } 869 870 .wui-bg-color-inverse-100 { 871 background-color: var(--wui-color-inverse-100); 872 } 873 874 .wui-bg-color-inverse-000 { 875 background-color: var(--wui-color-inverse-000); 876 } 877 878 .wui-bg-color-fg-100 { 879 background-color: var(--wui-color-fg-100); 880 } 881 882 .wui-bg-color-fg-200 { 883 background-color: var(--wui-color-fg-200); 884 } 885 886 .wui-bg-color-fg-300 { 887 background-color: var(--wui-color-fg-300); 888 } 889 890 .wui-color-fg-325 { 891 background-color: var(--wui-color-fg-325); 892 } 893 894 .wui-color-fg-350 { 895 background-color: var(--wui-color-fg-350); 896 } 897`;function Xy(e){return function(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const Zy="2.33.2";let Qy={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:s})=>t?`${e??"https://viem.sh"}${t}${s?`#${s}`:""}`:void 0,version:`viem@${Zy}`};class eb extends Error{constructor(e,t={}){var s;const i=t.cause instanceof eb?t.cause.details:(null==(r=t.cause)?void 0:r.message)?t.cause.message:t.details;var r;const n=t.cause instanceof eb&&t.cause.docsPath||t.docsPath,o=null==(s=Qy.getDocsUrl)?void 0:s.call(Qy,{...t,docsPath:n});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...i?[`Details: ${i}`]:[],...Qy.version?[`Version: ${Qy.version}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=n,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Zy}walk(e){return tb(this,e)}}function tb(e,t){return(null==t?void 0:t(e))?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?tb(e.cause,t):t?null:e}class sb extends eb{constructor({size:e,targetSize:t,type:s}){super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function ib(e,{dir:t,size:s=32}={}){return"string"==typeof e?function(e,{dir:t,size:s=32}={}){if(null===s)return e;const i=e.replace("0x","");if(i.length>2*s)throw new sb({size:Math.ceil(i.length/2),targetSize:s,type:"hex"});return`0x${i["right"===t?"padEnd":"padStart"](2*s,"0")}`}(e,{dir:t,size:s}):function(e,{dir:t,size:s=32}={}){if(null===s)return e;if(e.length>s)throw new sb({size:e.length,targetSize:s,type:"bytes"});const i=new Uint8Array(s);for(let r=0;r<s;r++){const n="right"===t;i[n?r:s-r-1]=e[n?r:e.length-r-1]}return i}(e,{dir:t,size:s})}class rb extends eb{constructor({max:e,min:t,signed:s,size:i,value:r}){super(`Number "${r}" is not in safe ${i?`${8*i}-bit ${s?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class nb extends eb{constructor({givenSize:e,maxSize:t}
897){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ob(e,{size:t}){if(Xy(e)>t)throw new nb({givenSize:Xy(e),maxSize:t})}const ab=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function cb(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t={}){const{signed:s,size:i}=t,r=BigInt(e);let n;i?n=s?(1n<<8n*BigInt(i)-1n)-1n:2n**(8n*BigInt(i))-1n:"number"==typeof e&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof n&&s?-n-1n:0;if(n&&r>n||r<o){const t="bigint"==typeof e?"n":"";throw new rb({max:n?`${n}${t}`:void 0,min:`${o}${t}`,signed:s,size:i,value:`${e}${t}`})}const a=`0x${(s&&r<0?(1n<<BigInt(8*i))+BigInt(r):r).toString(16)}`;return i?ib(a,{size:i}):a}(e,t):"string"==typeof e?function(e,t={}){const s=db.encode(e);return lb(s,t)}(e,t):"boolean"==typeof e?function(e,t={}){const s=`0x${Number(e)}`;if("number"==typeof t.size)return ob(s,{size:t.size}),ib(s,{size:t.size});return s}(e,t):lb(e,t)}function lb(e,t={}){let s="";for(let r=0;r<e.length;r++)s+=ab[e[r]];const i=`0x${s}`;return"number"==typeof t.size?(ob(i,{size:t.size}),ib(i,{dir:"right",size:t.size})):i}const db=new TextEncoder;const ub=4902,hb=5e3,pb=32603,gb=["http://localhost:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"];function fb(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const mb=fb({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"}),wb=fb({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"});fb({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"}),fb({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}}),fb({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 vb={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"]},yb={getMethodsByChainNamespace:e=>vb[e]||[],createDefaultNamespace(e){return{methods:this.getMethodsByChainNamespace(e),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(e,t){if(!t)return{...e};const s={...e},i=new Set;
897if(t.methods&&Object.keys(t.methods).forEach(e=>i.add(e)),t.chains&&Object.keys(t.chains).forEach(e=>i.add(e)),t.events&&Object.keys(t.events).forEach(e=>i.add(e)),t.rpcMap&&Object.keys(t.rpcMap).forEach(e=>{const[t]=e.split(":");t&&i.add(t)}),i.forEach(e=>{s[e]||(s[e]=this.createDefaultNamespace(e))}),t.methods&&Object.entries(t.methods).forEach(([e,t])=>{s[e]&&(s[e].methods=t)}),t.chains&&Object.entries(t.chains).forEach(([e,t])=>{s[e]&&(s[e].chains=t)}),t.events&&Object.entries(t.events).forEach(([e,t])=>{s[e]&&(s[e].events=t)}),t.rpcMap){const e=new Set;Object.entries(t.rpcMap).forEach(([t,i])=>{const[r,n]=t.split(":");r&&n&&s[r]&&(s[r].rpcMap||(s[r].rpcMap={}),e.has(r)||(s[r].rpcMap={},e.add(r)),s[r].rpcMap[n]=i)})}return s},createNamespaces(e,t){const s=e.reduce((e,t)=>{const{id:s,chainNamespace:i,rpcUrls:r}=t,n=r.default.http[0];e[i]||(e[i]=this.createDefaultNamespace(i));const o=`${i}:${s}`,a=e[i];switch(a.chains.push(o),o){case mb.caipNetworkId:a.chains.push(mb.deprecatedCaipNetworkId);break;case wb.caipNetworkId:a.chains.push(wb.deprecatedCaipNetworkId)}return(null==a?void 0:a.rpcMap)&&n&&(a.rpcMap[s]=n),e},{});return this.applyNamespaceOverrides(s,t)},resolveReownName:async e=>{var t;const s=await ds.resolveName(e);return(null==(t=(Object.values(null==s?void 0:s.addresses)||[])[0])?void 0:t.address)||!1},getChainsFromNamespaces:(e={})=>Object.values(e).flatMap(e=>{const t=e.chains||[],s=e.accounts.map(e=>{const[t,s]=e.split(":");return`${t}:${s}`});return Array.from(new Set([...t,...s]))}),isSessionEventData:e=>"object"==typeof e&&null!==e&&"id"in e&&"topic"in e&&"params"in e&&"object"==typeof e.params&&null!==e.params&&"chainId"in e.params&&"event"in e.params&&"object"==typeof e.params.event&&null!==e.params.event,isOriginAllowed(e,t,s){for(const i of[...t,...s])if(i.includes("*")){const t=`^${i.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(t,"u").test(e))return!0}else try{if(new URL(i).origin===e)return!0}catch(wn){if(i===e)return!0}return!1}};class bb{constructor({provider:e,namespace:t}){this.id=L.CONNECTOR_ID.WALLET_CONNECT,this.name=pw.ConnectorNamesMap[L.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=pw.ConnectorImageIds[L.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=Ht.getCaipNetworks.bind(Ht),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=t}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!(await this.authenticate())){const e=this.getCaipNetworks(),t=Ke.state.universalProviderConfigOverride,s=yb.createNamespaces(e,t);await this.provider.connect({optionalNamespaces:s})}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(e=>e.caipNetworkId);return us.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:Eb})}}const Eb=["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 Cb{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=e=>Ht.getCaipNetworks(e),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:L.CONNECTOR_ID.AUTH,type:"AUTH",name:L.CONNECTOR_NAMES.AUTH,provider:e,imageId:pw.ConnectorImageIds[L.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(e=>
897!t.has(e.id)&&(t.add(e.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){Zt.setStatus(e,t)}on(e,t){var s;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),null==(s=this.eventListeners.get(e))||s.add(t)}off(e,t){const s=this.eventListeners.get(e);s&&s.delete(t)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,t){const s=this.eventListeners.get(e);s&&s.forEach(e=>e(t))}async connectWalletConnect(e){const t=this.getWalletConnectConnector();return{clientId:(await t.connectWalletConnect()).clientId}}async switchNetwork(e){var t;const{caipNetwork:s,providerType:i}=e;if(!e.provider)return;const r="provider"in e.provider?e.provider.provider:e.provider;if("WALLET_CONNECT"!==i){if(r&&"AUTH"===i){const e=r,i=null==(t=Zt.state.preferredAccountTypes)?void 0:t[s.chainNamespace];await e.switchNetwork(s.caipNetworkId);const n=await e.getUser({chainId:s.caipNetworkId,preferredAccountType:i});this.emit("switchNetwork",n)}}else r.setDefaultChain(s.caipNetworkId)}getWalletConnectConnector(){const e=this.connectors.find(e=>e instanceof bb);if(!e)throw new Error("WalletConnectConnector not found");return e}}class Ib extends Cb{setUniversalProvider(e){this.addConnector(new bb({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{const e=this.getWalletConnectConnector();await e.disconnect()}catch(e){}}async getAccounts({namespace:e}){var t,s,i,r;const n=this.provider,o=(null==(r=null==(i=null==(s=null==(t=null==n?void 0:n.session)?void 0:t.namespaces)?void 0:s[e])?void 0:i.accounts)?void 0:r.map(e=>{const[,,t]=e.split(":");return t}).filter((e,t,s)=>s.indexOf(e)===t))||[];return Promise.resolve({accounts:o.map(t=>ze.createAccount(e,t,"bip122"===e?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var t,s,i,r,n;if(!(e.caipNetwork&&qe.BALANCE_SUPPORTED_CHAINS.includes(null==(t=e.caipNetwork)?void 0:t.chainNamespace))||(null==(s=e.caipNetwork)?void 0:s.testnet))return{balance:"0.00",symbol:(null==(i=e.caipNetwork)?void 0:i.nativeCurrency.symbol)||""};if(Zt.state.balanceLoading&&e.chainId===(null==(r=Ht.state.activeCaipNetwork)?void 0:r.id))return{balance:Zt.state.balance||"0.00",symbol:Zt.state.balanceSymbol||""};const o=(await Zt.fetchTokenBalance()).find(t=>{var s,i;return t.chainId===`${null==(s=e.caipNetwork)?void 0:s.chainNamespace}:${e.chainId}`&&t.symbol===(null==(i=e.caipNetwork)?void 0:i.nativeCurrency.symbol)});return{balance:(null==o?void 0:o.quantity.numeric)||"0.00",symbol:(null==o?void 0:o.symbol)||(null==(n=e.caipNetwork)?void 0:n.nativeCurrency.symbol)||""}}async signMessage(e){var t,s,i;const{provider:r,message:n,address:o}=e;if(!r)throw new Error("UniversalAdapter:signMessage - provider is undefined");let a="";if((null==(t=Ht.state.activeCaipNetwork)?void 0:t.chainNamespace)===L.CHAIN.SOLANA){a=(await r.request({method:"solana_signMessage",params:{message:d.encode((new TextEncoder).encode(n)),pubkey:o}},null==(s=Ht.state.activeCaipNetwork)?void 0:s.caipNetworkId)).signature}else a=await r.request({method:"personal_sign",params:[n,o]},null==(i=Ht.state.activeCaipNetwork)?void 0:i.caipNetworkId);return{signature:a}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var t,s,i,r,n,o;const{caipNetwork:a}=e,c=this.getWalletConnectConnector();if(a.chainNamespace===L.CHAIN.EVM)try{await(null==(t=c.provider)?void 0:t.request({method:"wallet_switchEthereumChain",params:[{chainId:cb(a.id)}]}))}catch(l){if(l.code===ub||l.code===pb||l.code===hb||(null==(i=null==(s=null==l?void 0:l.data)?void 0:s.originalError)?void 0:i.code)===ub)try{await(null==(o=c.provider)?void 0:o.request({method:"wallet_addEthereumChain",params:[{chainId:cb(a.id),rpcUrls:[null==(r=null==a?void 0:a.rpcUrls.chainDefault)?void 0:r.http],chainName:a.name,nativeCurrency:a.nativeCurrency,blockExplorerUrls:[null==(n=a.blockExplorers)?void 0:n.default.url]}]}))}catch(d){throw new Error("Chain is not supported")}}c.provider.setDefaultChain(a.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(e=>"WALLET_CONNECT"===e.type);return null==e?void 0:e.provider}}const Nb=["email","socials","swaps","onramp","activity","reownBranding"],Ab={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!(null==e?void 0:e.config))return!1;const t=e.config;return Boolean(e.isEnabled)&&t.includes("email")},processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.email:Boolean(e)},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!(null==e?void 0:e.config))return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t.filter(e=>"email"!==e)},processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.socials:"boolean"==typeof e?!!e&&qe.DEFAULT_REMOTE_FEATURES.socials:e},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!(null==e?void 0:e.config))return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t},processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.swaps:"boolean"==typeof e?!!e&&qe.DEFAULT_REMOTE_FEATURES.swaps:e},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>{if(!(null==e?void 0:e.config))return!1;const t=e.config;return!!(Boolean(e.isEnabled)&&t.length>0)&&t},processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.onramp:"boolean"==typeof e?!!e&&qe.DEFAULT_REMOTE_FEATURES.onramp:e},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.activity:Boolean(e)},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:e=>Boolean(e.isEnabled),processFallback:e=>void 0===e?qe.DEFAULT_REMOTE_FEATURES.reownBranding:Boolean(e)}},Sb={localSettingsOverridden:new Set,getApiConfig:(e,t)=>
897null==t?void 0:t.find(t=>t.id===e),addWarning(e,t){if(void 0!==e){const e=Ab[t],s=e.isLegacy?`"features.${e.localFeatureName}" (now "${t}")`:`"features.${t}"`;this.localSettingsOverridden.add(s)}},processFeature(e,t,s,i,r){const n=Ab[e],o=t[n.localFeatureName];if(r&&!n.isAvailableOnBasic)return!1;if(i){const t=this.getApiConfig(n.apiFeatureName,s);return null===(null==t?void 0:t.config)?this.processFallbackFeature(e,o):!!(null==t?void 0:t.config)&&(void 0!==o&&this.addWarning(o,e),this.processApiFeature(e,t))}return this.processFallbackFeature(e,o)},processApiFeature:(e,t)=>Ab[e].processApi(t),processFallbackFeature:(e,t)=>Ab[e].processFallback(t),async fetchRemoteFeatures(e){const t=e.basic??!1,s=e.features||{};this.localSettingsOverridden.clear();let i=null,r=!1;try{i=await vt.fetchProjectConfig(),r=null!=i}catch(wn){}const n=r&&!t?qe.DEFAULT_REMOTE_FEATURES:qe.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const e of Nb){const o=this.processFeature(e,s,i,r,t);Object.assign(n,{[e]:o})}}catch(wn){return qe.DEFAULT_REMOTE_FEATURES}if(r&&this.localSettingsOverridden.size>0){const e=`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.`;lt.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${e}`},"warning")}return n}};class Pb{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(e,t)=>{var s,i,r,n;if(e){const o=null==(i=null==(s=Ht.getNetworkData(e))?void 0:s.requestedCaipNetworks)?void 0:i.find(e=>e.id===t);if(o)return o;const a=null==(r=Ht.getNetworkData(e))?void 0:r.caipNetwork;if(a)return a;return null==(n=Ht.getRequestedCaipNetworks(e).filter(t=>t.chainNamespace===e))?void 0:n[0]}return Ht.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const e=this.getCaipNetwork();if(e)return e.id},this.getCaipNetworks=e=>Ht.getCaipNetworks(e),this.getActiveChainNamespace=()=>Ht.state.activeChain,this.setRequestedCaipNetworks=(e,t)=>{Ht.setRequestedCaipNetworks(e,t)},this.getApprovedCaipNetworkIds=()=>Ht.getAllApprovedCaipNetworkIds(),this.getCaipAddress=e=>Ht.state.activeChain!==e&&e?Ht.getAccountProp("caipAddress",e):Ht.state.activeCaipAddress,this.setClientId=e=>{Yt.setClientId(e)},this.getProvider=e=>_v.getProvider(e),this.getProviderType=e=>_v.getProviderId(e),this.getPreferredAccountType=e=>{var t;return null==(t=Zt.state.preferredAccountTypes)?void 0:t[e]},this.setCaipAddress=(e,t)=>{Zt.setCaipAddress(e,t),e&&Ke.state.enableEmbedded&&this.close()},this.setBalance=(e,t,s)=>{Zt.setBalance(e,t,s)},this.setProfileName=(e,t)=>{Zt.setProfileName(e,t)},this.setProfileImage=(e,t)=>{Zt.setProfileImage(e,t)},this.setUser=(e,t)=>{Zt.setUser(e,t)},this.resetAccount=e=>{Zt.resetAccount(e)},this.setCaipNetwork=e=>{Ht.setActiveCaipNetwork(e)},this.setCaipNetworkOfNamespace=(e,t)=>{Ht.setChainNetworkData(t,{caipNetwork:e})},this.setAllAccounts=(e,t)=>{Zt.setAllAccounts(e,t),Ke.setHasMultipleAddresses((null==e?void 0:e.length)>1)},this.setStatus=(e,t)=>{Zt.setStatus(e,t),St.isConnected()?Be.setConnectionStatus("connected"):Be.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=e=>Ht.getAccountProp("address",e),this.setConnectors=e=>{const t=[...St.state.allConnectors,...e];St.setConnectors(t)},this.setConnections=(e,t)=>{$t.setConnections(e,t)},this.fetchIdentity=e=>Yt.fetchIdentity(e),this.getReownName=e=>ds.getNamesForAddress(e),this.getConnectors=()=>St.getConnectors(),this.getConnectorImage=e=>at.getConnectorImage(e),this.setConnectedWalletInfo=(e,t)=>{const s=_v.getProviderId(t),i=e?{...e,type:s}:void 0;Zt.setConnectedWalletInfo(i,t)},this.getIsConnectedState=()=>Boolean(Ht.state.activeCaipAddress),this.addAddressLabel=(e,t,s)=>{Zt.addAddressLabel(e,t,s)},this.removeAddressLabel=(e,t)=>
897{Zt.removeAddressLabel(e,t)},this.getAddress=e=>Ht.state.activeChain!==e&&e?Ht.getAccountProp("address",e):Zt.state.address,this.setApprovedCaipNetworksData=e=>Ht.setApprovedCaipNetworksData(e),this.resetNetwork=e=>{Ht.resetNetwork(e)},this.addConnector=e=>{St.addConnector(e)},this.resetWcConnection=()=>{$t.resetWcConnection()},this.setAddressExplorerUrl=(e,t)=>{Zt.setAddressExplorerUrl(e,t)},this.setSmartAccountDeployed=(e,t)=>{Zt.setSmartAccountDeployed(e,t)},this.setSmartAccountEnabledNetworks=(e,t)=>{Ht.setSmartAccountEnabledNetworks(e,t)},this.setPreferredAccountType=(e,t)=>{Zt.setPreferredAccountType(e,t)},this.setEIP6963Enabled=e=>{Ke.setEIP6963Enabled(e)},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,t){const s=null==e?void 0:e.map(e=>e.namespace).filter(e=>Boolean(e));if(null==s?void 0:s.length)return[...new Set(s)];const i=null==t?void 0:t.map(e=>e.chainNamespace);return[...new Set(i)]}async initialize(e){var t,s,i;this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),await this.syncExistingConnection(),this.remoteFeatures=await Sb.fetchRemoteFeatures(e),Ke.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&ns.setOnrampProviders(this.remoteFeatures.onramp),((null==(t=Ke.state.remoteFeatures)?void 0:t.email)||Array.isArray(null==(s=Ke.state.remoteFeatures)?void 0:s.socials)&&(null==(i=Ke.state.remoteFeatures)?void 0:i.socials.length)>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await vt.fetchAllowedOrigins();if(e&&ze.isClient()){const t=window.location.origin;yb.isOriginAllowed(t,e,gb)||lt.open(fw.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else lt.open(fw.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){var t;const{...s}=e;delete s.adapters,delete s.universalProvider,gt.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(e=>e.id),siweConfig:{options:(null==(t=e.siweConfig)?void 0:t.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&It.setThemeMode(e.themeMode),e.themeVariables&&It.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");Ht.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&Ht.setActiveCaipNetwork(t)}initializeConnectionController(e){$t.setWcBasic(e.basic??!1)}initializeConnectorController(){St.initialize(this.chainNamespaces)}initializeProjectSettings(e){Ke.setProjectId(e.projectId),Ke.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var t;Ke.setDebug(!1!==e.debug),Ke.setEnableWalletConnect(!1!==e.enableWalletConnect),Ke.setEnableWalletGuide(!1!==e.enableWalletGuide),Ke.setEnableWallets(!1!==e.enableWallets),Ke.setEIP6963Enabled(!1!==e.enableEIP6963),Ke.setEnableNetworkSwitch(!1!==e.enableNetworkSwitch),Ke.setEnableAuthLogger(!1!==e.enableAuthLogger),Ke.setCustomRpcUrls(e.customRpcUrls),Ke.setEnableEmbedded(e.enableEmbedded),Ke.setAllWallets(e.allWallets),Ke.setIncludeWalletIds(e.includeWalletIds),Ke.setExcludeWalletIds(e.excludeWalletIds),Ke.setFeaturedWalletIds(e.featuredWalletIds),Ke.setTokens(e.tokens),Ke.setTermsConditionsUrl(e.termsConditionsUrl),Ke.setPrivacyPolicyUrl(e.privacyPolicyUrl),Ke.setCustomWallets(e.customWallets),Ke.setFeatures(e.features),Ke.setAllowUnsupportedChain(e.allowUnsupportedChain),Ke.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),Ke.setPreferUniversalLinks(e.experimental_preferUniversalLinks),Ke.setDefaultAccountTypes(e.defaultAccountTypes);const s=Be.getPreferredAccountTypes()||{},i={...Ke.state.defaultAccountTypes,...s};Zt.setPreferredAccountTypes(i);const r=this.getDefaultMetaData();if(!e.metadata&&r&&(e.metadata=r),Ke.setMetadata(e.metadata),Ke.setDisableAppend(e.disableAppend),Ke.setEnableEmbedded(e.enableEmbedded),Ke.setSIWX(e.siwx),!e.projectId)return void lt.open(fw.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");
897if((null==(t=e.adapters)?void 0:t.find(e=>e.namespace===L.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");Ke.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,t,s,i;return ze.isClient()?{name:(null==(t=null==(e=document.getElementsByTagName("title"))?void 0:e[0])?void 0:t.textContent)||"",description:(null==(s=document.querySelector('meta[property="og:description"]'))?void 0:s.content)||"",url:window.location.origin,icons:[(null==(i=document.querySelector('link[rel~="icon"]'))?void 0:i.href)||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const s=Sv.getUnsupportedNetwork(`${t}:${e}`);Ht.setActiveCaipNetwork(s)}}getDefaultNetwork(){return Sv.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return Sv.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return Sv.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find(t=>{var s;return t.id===(null==(s=e.defaultNetwork)?void 0:s.id)});return t?Sv.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e){try{const t=this.getAdapter(e),s=_v.getProvider(e),i=_v.getProviderId(e),{caipAddress:r}=Ht.getAccountData(e)||{};this.setLoading(!0,e),r&&(null==t?void 0:t.disconnect)&&await t.disconnect({provider:s,providerType:i}),Be.removeConnectedNamespace(e),_v.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),St.removeConnectorId(e),Ht.resetAccount(e),Ht.resetNetwork(e),this.setLoading(!1,e)}catch(t){throw this.setLoading(!1,e),new Error(`Failed to disconnect chain ${e}: ${t.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var e;const t=Ht.state.activeChain,s=this.getAdapter(t),i=null==(e=this.getCaipNetwork(t))?void 0:e.id;if(!s)throw new Error("Adapter not found");const r=await s.connectWalletConnect(i);this.close(),this.setClientId((null==r?void 0:r.clientId)||null),Be.setConnectedNamespaces([...Ht.state.chains.keys()]),this.chainNamespaces.forEach(e=>{St.setConnectorId(dw,e)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:s,provider:i,chain:r,caipNetwork:n,socialUri:o})=>{var a,c,l,d,u,h;const p=Ht.state.activeChain,g=r||p,f=this.getAdapter(g);if(r&&r!==p&&!n){const e=this.getCaipNetworks().find(e=>e.chainNamespace===r);e&&this.setCaipNetwork(e)}if(!f)throw new Error("Adapter not found");const m=this.getCaipNetwork(g),w=await f.connect({id:e,info:t,type:s,provider:i,socialUri:o,chainId:(null==n?void 0:n.id)||(null==m?void 0:m.id),rpcUrl:(null==(l=null==(c=null==(a=null==n?void 0:n.rpcUrls)?void 0:a.default)?void 0:c.http)?void 0:l[0])||(null==(h=null==(u=null==(d=null==m?void 0:m.rpcUrls)?void 0:d.default)?void 0:u.http)?void 0:h[0])});if(!w)return;Be.addConnectedNamespace(g),this.syncProvider({...w,chainNamespace:g});const v=Zt.state.allAccounts,{accounts:y}=(null==v?void 0:v.length)>0?{accounts:[...v]}:await f.getAccounts({namespace:g,id:e});this.setAllAccounts(y,g),this.setStatus("connected",g),this.syncConnectedWalletInfo(g)},reconnectExternal:async({id:e,info:t,type:s,provider:i})=>{var r;const n=Ht.state.activeChain,o=this.getAdapter(n);(null==o?void 0:o.reconnect)&&(await(null==o?void 0:o.reconnect({id:e,info:t,type:s,provider:i,chainId:null==(r=this.getCaipNetwork())?void 0:r.id})),Be.addConnectedNamespace(n),this.syncConnectedWalletInfo(n))},disconnect:async e=>{const t=function(e){const t=Array.from(Ht.state.chains.keys());let s=[];return e?(s.push([e,Ht.state.chains.get(e)]),cw(e,L.CONNECTOR_ID.WALLET_CONNECT)?t.forEach(t=>{t!==e&&cw(t,L.CONNECTOR_ID.WALLET_CONNECT)&&s.push([t,Ht.state.chains.get(t)])}):cw(e,L.CONNECTOR_ID.AUTH)&&t.forEach(t=>{t!==e&&cw(t,L.CONNECTOR_ID.AUTH)&&s.push([t,Ht.state.chains.get(t)])})):s=Array.from(Ht.state.chains.entries()),s}(e);try{const s=await Promise.allSettled(t.map(async([e])=>this.disconnectNamespace(e)));Bt.resetSend(),$t.resetWcConnection(),await us.clearSessions(),St.setFilterByNamespace(void 0);const i=s.filter(e=>"rejected"===e.status);if(i.length>0)throw new Error(i.map(e=>e.reason.message).join(", "));Be.deleteConnectedSocialProvider(),gt.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:e||"all"}})}catch(s){throw new Error(`Failed to disconnect chains: ${s.message}`)}},checkInstalled:e=>e?e.some(e=>{var t;return Boolean(null==(t=window.ethereum)?void 0:t[String(e)])}):Boolean(window.ethereum),signMessage:async e=>{const t=this.getAdapter(Ht.state.activeChain),s=await(null==t?void 0:t.signMessage({message:e,address:Zt.state.address,provider:_v.getProvider(Ht.state.activeChain)}));return(null==s?void 0:s.signature)||""},sendTransaction:async e=>{const t=e.chainNamespace;if(qe.SEND_SUPPORTED_NAMESPACES.includes(t)){const s=this.getAdapter(Ht.state.activeChain),i=_v.getProvider(t),r=await(null==s?void 0:s.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}));return(null==r?void 0:r.hash)||""}return""},estimateGas:async e=>{if(e.chainNamespace===L.CHAIN.EVM){const t=this.getAdapter(Ht.state.activeChain),s=_v.getProvider(Ht.state.activeChain),i=this.getCaipNetwork();if(!i)throw new Error("CaipNetwork is undefined");const r=await(null==t?void 0:t.estimateGas({...e,provider:s,caipNetwork:i}));return(null==r?void 0:r.gas)||0n}return 0n},getEnsAvatar:async()=>{var e;return await this.syncIdentity({address:Zt.state.address,chainId:Number(null==(e=this.getCaipNetwork())?void 0:e.id),chainNamespace:Ht.state.activeChain}),Zt.state.profileImage||!1},getEnsAddress:async e=>await yb.resolveReownName(e),writeContract:async e=>{const t=this.getAdapter(Ht.state.activeChain),s=this.getCaipNetwork(),i=this.getCaipAddress(),r=_v.getProvider(Ht.state.activeChain);if(!s||!i)throw new Error("CaipNetwork or CaipAddress is undefined");const n=await(null==t?void 0:t.writeContract({...e,caipNetwork:s,provider:r,caipAddress:i}));return null==n?void 0:n.hash},parseUnits:(e,t)=>{const s=this.getAdapter(Ht.state.activeChain);return(null==s?void 0:s.parseUnits({value:e,decimals:t}))??0n},formatUnits:(e,t)=>{const s=this.getAdapter(Ht.state.activeChain);return(null==s?void 0:s.formatUnits({value:e,decimals:t}))??"0"},getCapabilities:async e=>{const t=this.getAdapter(Ht.state.activeChain);return await(null==t?void 0:t.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(Ht.state.activeChain);return await(null==t?void 0:t.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(Ht.state.activeChain);return(null==t?void 0:t.revokePermissions)?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(Ht.state.activeChain);return await(null==t?void 0:t.walletGetAssets(e))??{}},updateBalance:e=>{const t=this.getCaipNetwork(e);t&&Zt.state.address&&this.updateNativeBalance(Zt.state.address,null==t?void 0:t.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},$t.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var e,t,s,i,r;if(_v.getProviderId(Ht.state.activeChain)===dw){const n=null==(t=null==(e=this.universalProvider)?void 0:e.session)?void 0:t.namespaces;return{supportsAllNetworks:"MetaMask Wallet"===(null==(r=null==(i=null==(s=this.universalProvider)?void 0:s.session)?void 0:i.peer)?void 0:r.metadata.name),approvedCaipNetworkIds:this.getChainsFromNamespaces(n)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const s=_v.getProvider(t),i=_v.getProviderId(t);if(e.chainNamespace===Ht.state.activeChain){const r=this.getAdapter(t);await(null==r?void 0:r.switchNetwork({caipNetwork:e,provider:s,providerType:i}))}else if(this.setCaipNetwork(e),i===dw)this.syncWalletConnectAccount();else{const s=this.getAddressByChainNamespace(t);s&&this.syncAccount({address:s,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}
897getChainsFromNamespaces(e={}){return Object.values(e).flatMap(e=>{const t=e.chains||[],s=e.accounts.map(e=>{const{chainId:t,chainNamespace:s}=re.parseCaipAddress(e);return`${s}:${t}`});return Array.from(new Set([...t,...s]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((t,s)=>{var i;const r=null==e?void 0:e.find(e=>e.namespace===s);return r?(r.construct({namespace:s,projectId:null==(i=this.options)?void 0:i.projectId,networks:this.getCaipNetworks()}),t[s]=r):t[s]=new Ib({namespace:s,networks:this.getCaipNetworks()}),t},{})}async initChainAdapter(e){var t;this.onConnectors(e),this.listenAdapter(e),await(null==(t=this.chainAdapters)?void 0:t[e].syncConnectors(this.options,this)),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){const t=this.getAdapter(e);null==t||t.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const s=Be.getConnectionStatus();"connected"===s?this.setStatus("connecting",e):"disconnected"===s?(Be.clearAddressCache(),this.setStatus(s,e)):this.setStatus(s,e),t.on("switchNetwork",({address:t,chainId:s})=>{const i=this.getCaipNetworks().find(e=>e.id===s||e.caipNetworkId===s),r=Ht.state.activeChain===e,n=Ht.getAccountProp("address",e);if(i){const s=r&&t?t:n;s&&this.syncAccount({address:s,chainId:i.id,chainNamespace:e})}else this.setUnsupportedNetwork(s)}),t.on("disconnect",this.disconnect.bind(this,e)),t.on("connections",t=>{this.setConnections(t,e)}),t.on("pendingTransactions",()=>{const e=Zt.state.address,t=Ht.state.activeCaipNetwork;e&&(null==t?void 0:t.id)&&this.updateNativeBalance(e,t.id,t.chainNamespace)}),t.on("accountChanged",({address:t,chainId:s})=>{var i,r;const n=Ht.state.activeChain===e;n&&s?this.syncAccount({address:t,chainId:s,chainNamespace:e}):n&&(null==(i=Ht.state.activeCaipNetwork)?void 0:i.id)?this.syncAccount({address:t,chainId:null==(r=Ht.state.activeCaipNetwork)?void 0:r.id,chainNamespace:e}):this.syncAccountInfo(t,s,e),this.syncAllAccounts(e)})}async createUniversalProviderForAdapter(e){var t,s,i;await this.getUniversalProvider(),this.universalProvider&&(null==(i=null==(s=null==(t=this.chainAdapters)?void 0:t[e])?void 0:s.setUniversalProvider)||i.call(s,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{e===L.CHAIN.EVM&&ze.isSafeApp()&&St.setConnectorId(L.CONNECTOR_ID.SAFE,e);const t=St.getConnectorId(e);switch(this.setStatus("connecting",e),t){case L.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case L.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){this.setStatus("disconnected",e)}}async syncAdapterConnection(e){var t,s,i;const r=this.getAdapter(e),n=St.getConnectorId(e),o=this.getCaipNetwork(e),a=St.getConnectors(e).find(e=>e.id===n);try{if(!r||!a)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(null==o?void 0:o.id))throw new Error("CaipNetwork not found");const n=await(null==r?void 0:r.syncConnection({namespace:e,id:a.id,chainId:o.id,rpcUrl:null==(i=null==(s=null==(t=null==o?void 0:o.rpcUrls)?void 0:t.default)?void 0:s.http)?void 0:i[0]}));if(n){const t=await(null==r?void 0:r.getAccounts({namespace:e,id:a.id}));t&&t.accounts.length>0?this.setAllAccounts(t.accounts,e):this.setAllAccounts([ze.createAccount(e,n.address,"eoa")],e),this.syncProvider({...n,chainNamespace:e}),await this.syncAccount({...n,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch(wn){this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async e=>{var t,s,i,r,n;const o=this.getAdapter(e),a=(null==(r=null==(i=null==(s=null==(t=this.universalProvider)?void 0:t.session)?void 0:s.namespaces)?void 0:i[e])?void 0:r.accounts)||[],c=null==(n=Ht.state.activeCaipNetwork)?void 0:n.id,l=a.find(e=>{const{chainId:t}=re.parseCaipAddress(e);return t===(null==c?void 0:c.toString())})||a[0];if(l){const t=re.validateCaipAddress(l),{chainId:s,address:i}=re.parseCaipAddress(t);if(_v.setProviderId(e,dw),this.caipNetworks&&Ht.state.activeCaipNetwork&&(null==o?void 0:o.namespace)!==L.CHAIN.EVM){const t=null==o?void 0:o.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:Ht.state.activeCaipNetwork});_v.setProvider(e,t)}else _v.setProvider(e,this.universalProvider);St.setConnectorId(L.CONNECTOR_ID.WALLET_CONNECT,e),Be.addConnectedNamespace(e),this.syncWalletConnectAccounts(e),await this.syncAccount({address:i,chainId:s,chainNamespace:e})}else this.setStatus("disconnected",e);this.syncConnectedWalletInfo(e),await Ht.setApprovedCaipNetworksData(e)});await Promise.all(e)}syncWalletConnectAccounts(e){var t,s,i,r,n;const o=null==(n=null==(r=null==(i=null==(s=null==(t=this.universalProvider)?void 0:t.session)?void 0:s.namespaces)?void 0:i[e])?void 0:r.accounts)?void 0:n.map(e=>{const{address:t}=re.parseCaipAddress(e);return t}).filter((e,t,s)=>s.indexOf(e)===t);o&&this.setAllAccounts(o.map(t=>ze.createAccount(e,t,"bip122"===e?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:s,chainNamespace:i}){_v.setProviderId(i,e),_v.setProvider(i,t),St.setConnectorId(s,i)}async syncAllAccounts(e){const t=St.getConnectorId(e);if(!t)return;const s=this.getAdapter(e),i=await(null==s?void 0:s.getAccounts({namespace:e,id:t}));i&&i.accounts.length>0&&this.setAllAccounts(i.accounts,e)}async syncAccount(e){var t,s;const i=e.chainNamespace===Ht.state.activeChain,r=Ht.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:n,chainId:o,chainNamespace:a}=e,{chainId:c}=Be.getActiveNetworkProps(),l=o||c,d=(null==(t=Ht.state.activeCaipNetwork)?void 0:t.name)===L.UNSUPPORTED_NETWORK_NAME,u=Ht.getNetworkProp("supportsAllNetworks",a);if(this.setStatus("connected",a),(!d||u)&&l){let e=this.getCaipNetworks().find(e=>e.id.toString()===l.toString()),t=this.getCaipNetworks().find(e=>e.chainNamespace===a);if(!u&&!e&&!t){const s=this.getApprovedCaipNetworkIds()||[],i=s.find(e=>{var t;return(null==(t=re.parseCaipNetworkId(e))?void 0:t.chainId)===l.toString()}),r=s.find(e=>{var t;return(null==(t=re.parseCaipNetworkId(e))?void 0:t.chainNamespace)===a});e=this.getCaipNetworks().find(e=>e.caipNetworkId===i),t=this.getCaipNetworks().find(e=>e.caipNetworkId===r||"deprecatedCaipNetworkId"in e&&e.deprecatedCaipNetworkId===r)}const o=e||t;(null==o?void 0:o.chainNamespace)===Ht.state.activeChain?Ke.state.enableNetworkSwitch&&!Ke.state.allowUnsupportedChain&&(null==(s=Ht.state.activeCaipNetwork)?void 0:s.name)===L.UNSUPPORTED_NETWORK_NAME?Ht.showUnsupportedChainUI():this.setCaipNetwork(o):i||r&&this.setCaipNetworkOfNamespace(r,a),this.syncConnectedWalletInfo(a),gw.isLowerCaseMatch(n,Zt.state.address)||this.syncAccountInfo(n,null==o?void 0:o.id,a),i?await this.syncBalance({address:n,chainId:null==o?void 0:o.id,chainNamespace:a}):await this.syncBalance({address:n,chainId:null==r?void 0:r.id,chainNamespace:a})}}async syncAccountInfo(e,t,s){const i=this.getCaipAddress(s),r=t||(null==i?void 0:i.split(":")[1]);if(!r)return;const n=`${s}:${r}:${e}`;this.setCaipAddress(n,s),await this.syncIdentity({address:e,chainId:r,chainNamespace:s})}async syncReownName(e,t){try{const s=await this.getReownName(e);
897if(s[0]){const e=s[0];this.setProfileName(e.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){var t;const s=St.getConnectorId(e),i=_v.getProviderId(e);if(i===hw||i===uw){if(s){const t=this.getConnectors().find(e=>e.id===s);if(t){const{info:s,name:i,imageUrl:r}=t,n=r||this.getConnectorImage(t);this.setConnectedWalletInfo({name:i,icon:n,...s},e)}}}else if(i===dw){const s=_v.getProvider(e);(null==s?void 0:s.session)&&this.setConnectedWalletInfo({...s.session.peer.metadata,name:s.session.peer.metadata.name,icon:null==(t=s.session.peer.metadata.icons)?void 0:t[0]},e)}else if(s&&s===L.CONNECTOR_ID.COINBASE){const t=this.getConnectors().find(e=>e.id===L.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(t)},e)}}async syncBalance(e){const t=q.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(t=>{var s;return t.id.toString()===(null==(s=e.chainId)?void 0:s.toString())});t&&e.chainId&&await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,t,s){const i=this.getAdapter(s),r=Ht.getCaipNetworkByNamespace(s,t);if(i){const n=await i.getBalance({address:e,chainId:t,caipNetwork:r,tokens:this.options.tokens});return this.setBalance(n.balance,n.symbol,s),n}}async initializeUniversalAdapter(){var e,t,s,i,r,n,o,a,c,l;const d=mw.createLogger((e,...t)=>{e&&this.handleAlertError(e)}),u={projectId:null==(e=this.options)?void 0:e.projectId,metadata:{name:(null==(t=this.options)?void 0:t.metadata)?null==(s=this.options)?void 0:s.metadata.name:"",description:(null==(i=this.options)?void 0:i.metadata)?null==(r=this.options)?void 0:r.metadata.description:"",url:(null==(n=this.options)?void 0:n.metadata)?null==(o=this.options)?void 0:o.metadata.url:"",icons:(null==(a=this.options)?void 0:a.metadata)?null==(c=this.options)?void 0:c.metadata.icons:[""]},logger:d};Ke.setManualWCControl(Boolean(null==(l=this.options)?void 0:l.manualWCControl)),this.universalProvider=this.options.universalProvider??await aw.init(u),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{$t.setUri(e)}),this.universalProvider.on("connect",$t.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),$t.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const t=this.getCaipNetworks().find(t=>t.id==e),s=this.getCaipNetwork();t?(null==s?void 0:s.id)!==(null==t?void 0:t.id)&&this.setCaipNetwork(t):this.setUnsupportedNetwork(e)}),this.universalProvider.on("session_event",e=>{if(yb.isSessionEventData(e)){const{name:t,data:s}=e.params.event;"accountsChanged"===t&&Array.isArray(s)&&ze.isCaipAddress(s[0])&&this.syncAccount(re.parseCaipAddress(s[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&ze.isClient()&&(null==(e=this.options)?void 0:e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}
897async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){gt.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}})}return this.universalProvider}handleAlertError(e){const t=Object.entries(fw.UniversalProviderErrors).find(([,{message:t}])=>e.message.includes(t)),[s,i]=t??[],{message:r,alertErrorKey:n}=i??{};if(s&&r&&!this.reportedAlertErrors[s]){const e=fw.ALERT_ERRORS[n];e&&(lt.open(e,"error"),this.reportedAlertErrors[s]=!0)}}getAdapter(e){var t;if(e)return null==(t=this.chainAdapters)?void 0:t[e]}createAdapter(e){var t;if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const i=e;i.namespace=s,i.construct({namespace:s,projectId:null==(t=this.options)?void 0:t.projectId,networks:this.getCaipNetworks()}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=i)}async open(e){return await this.injectModalUi(),(null==e?void 0:e.uri)&&$t.setUri(e.uri),(null==e?void 0:e.arguments)&&"Swap"===(null==e?void 0:e.view)?ts.open({...e,data:{swap:e.arguments}}):ts.open(e)}async close(){await this.injectModalUi(),ts.close()}setLoading(e,t){ts.setLoading(e,t)}async disconnect(e){await $t.disconnect(e)}getSIWX(){return Ke.state.siwx}getError(){return""}getChainId(){var e;return null==(e=Ht.state.activeCaipNetwork)?void 0:e.id}async switchNetwork(e){const t=this.getCaipNetworks().find(t=>t.id===e.id);t?await Ht.switchActiveNetwork(t):lt.open(fw.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error")}getWalletProvider(){return Ht.state.activeChain?_v.state.providers[Ht.state.activeChain]:null}getWalletProviderType(){return _v.getProviderId(Ht.state.activeChain)}subscribeProviders(e){return _v.subscribeProviders(e)}getThemeMode(){return It.state.themeMode}getThemeVariables(){return It.state.themeVariables}setThemeMode(e){It.setThemeMode(e),Hy(It.state.themeMode)}setTermsConditionsUrl(e){Ke.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){Ke.setPrivacyPolicyUrl(e)}setThemeVariables(e){It.setThemeVariables(e),function(e){zy&&Fy&&Wy&&(zy.textContent=Ky(e).core.cssText,Fy.textContent=Ky(e).dark.cssText,Wy.textContent=Ky(e).light.cssText)}(It.state.themeVariables)}subscribeTheme(e){return It.subscribe(e)}getWalletInfo(){return Zt.state.connectedWalletInfo}getAccount(e){var t;const s=St.getAuthConnector(e),i=Ht.getAccountData(e),r=Ht.state.activeChain,n=Be.getConnectedConnectorId(e||r);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:ze.getPlainAddress(i.caipAddress),isConnected:Boolean(i.caipAddress),status:i.status,embeddedWalletInfo:s&&n===L.CONNECTOR_ID.AUTH?{user:i.user?{...i.user,username:Be.getConnectedSocialUsername()}:void 0,authProvider:i.socialProvider||"email",accountType:null==(t=i.preferredAccountTypes)?void 0:t[e||r],isSmartAccountDeployed:Boolean(i.smartAccountDeployed)}:void 0}}subscribeAccount(e,t){const s=()=>{const s=this.getAccount(t);s&&e(s)};t?Ht.subscribeChainProp("accountState",s,t):Ht.subscribe(s),St.subscribe(s)}subscribeNetwork(e){return Ht.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:null==t?void 0:t.id,caipNetworkId:null==t?void 0:t.caipNetworkId})})}subscribeWalletInfo(e){return Zt.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){Zt.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){Ht.subscribeKey("activeCaipNetwork",e)}getState(){return Mt.state}subscribeState(e){return Mt.subscribe(e)}showErrorMessage(e){Ot.showError(e)}showSuccessMessage(e){Ot.showSuccess(e)}getEvent(){return{...gt.state}}subscribeEvents(e){return gt.subscribe(e)}replace(e){bt.replace(e)}redirect(e){bt.push(e)}popTransactionStack(e){bt.popTransactionStack(e)}isOpen(){return ts.state.open}isTransactionStackEmpty(){return 0===bt.state.transactionStack.length}static getInstance(){return this.instance}updateFeatures(e){Ke.setFeatures(e)}updateRemoteFeatures(e){Ke.setRemoteFeatures(e)}updateOptions(e){const t={...Ke.state||{},...e};Ke.setOptions(t)}setConnectMethodsOrder(e){Ke.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){Ke.setWalletFeaturesOrder(e)}setCollapseWallets(e){Ke.setCollapseWallets(e)}setSocialsOrder(e){Ke.setSocialsOrder(e)}getConnectMethodsOrder(){return xv.getConnectOrderMethod(Ke.state.features,St.getConnectors())}addNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const s=this.extendCaipNetwork(t,this.options);this.getCaipNetworks().find(e=>e.id===s.id)||Ht.addNetwork(s)}removeNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const s=this.getCaipNetworks().find(e=>e.id===t);s&&Ht.removeNetwork(e,t)}}let kb=!1;class _b extends Pb{async open(e){St.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&$t.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}
897async injectModalUi(){if(!kb&&ze.isClient()){await t(()=>import("./basic.js-CTBEV7tZ.js"),__vite__mapDeps([5,6,1,2,3,4])),await t(()=>import("./w3m-modal.js-Cy8msb3B.js"),__vite__mapDeps([7,6,1,2,3,4]));if(!document.querySelector("w3m-modal")){const e=document.createElement("w3m-modal");Ke.state.disableAppend||Ke.state.enableEmbedded||document.body.insertAdjacentElement("beforeend",e)}kb=!0}}}const Ob=Object.freeze(Object.defineProperty({__proto__:null,AppKit:_b,createAppKit:function(e){return new _b({...e,basic:!0,sdkVersion:"html-core-1.7.8"})}},Symbol.toStringTag,{value:"Module"}));export{vt as A,Ov as B,St as C,Zt as D,gt as E,Vy as F,di as G,wi as H,ii as I,fi as J,ri as K,vi as L,ts as M,ui as N,Ke as O,si as P,ti as Q,bt as R,Be as S,It as T,yi as U,mi as V,xv as W,Ob as X,qy as a,ze as b,Tv as c,at as d,Jy as e,$t as f,L as g,Ht as h,Lv as i,rt as j,Ot as k,qe as l,Iy as m,Ay as n,Yy as o,Qv as p,Ny as q,Gy as r,Ue as s,je as t,Zv as u,$e as v,et as w,Cy as x,us as y,lt 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.