1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/basic-BP359C7t.js","assets/index-4dXlA8_B.js","assets/index-Cq7_ZeC-.js","assets/index-DS18Fqyg.css","assets/index.es-vKaiadAv.js","assets/index-CFYEtFbK.js","assets/http-BNBGYCfA.js","assets/stringify-DWaBlQ-W.js","assets/w3m-modal-DbvUgcN5.js"])))=>i.map(i=>d[i]); 2var e;import{ft as t,hY as s,hZ as i,fQ as r,h_ as n,h$ as o,dJ as a}from"./index-Cq7_ZeC-.js";import{I as c,h as l,i as d,j as h,k as u,l as p,C as g,m,s as f,n as w,o as v,p as y,A as b,E,q as C,u as I,y as N,v as A,x as S,O as P,z as k,B as _,D as O,F as T,G as x,P as R,Q as U,J as D,K as $,L as M,M as L,N as j,R as q,S as B,T as F,U as W}from"./index.es-vKaiadAv.js";import{c as z,T as H,U as V,W as K,E as G,w as J,f as Y,h as Z}from"./http-BNBGYCfA.js";import{c as Q}from"./stringify-DWaBlQ-W.js";function X(e,t={}){const{key:s="fallback",name:i="Fallback",rank:r=!1,shouldThrow:n=ee,retryCount:o,retryDelay:a}=t;return({chain:t,pollingInterval:c=4e3,timeout:l,...d})=>{let h=e,u=()=>{};const p=z({key:s,name:i,async request({method:e,params:s}){let i;const r=async(o=0)=>{const a=h[o]({...d,chain:t,retryCount:0,timeout:l});try{const t=await a.request({method:e,params:s});return u({method:e,params:s,response:t,transport:a,status:"success"}),t}catch(c){if(u({error:c,method:e,params:s,transport:a,status:"error"}),n(c))throw c;if(o===h.length-1)throw c;if(i??(i=h.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=>u=e,transports:h.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=[],h=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 u=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/u,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])=>
2o[e])),await J(t),h()};h()}({chain:t,interval:e.interval??c,onTransports:e=>h=e,ping:e.ping,sampleCount:e.sampleCount,timeout:e.timeout,transports:h,weights:e.weights})}return p}}function ee(e){return!(!("code"in e)||"number"!=typeof e.code||e.code!==H.code&&e.code!==V.code&&e.code!==K.code&&!G.nodeMessage.test(e.message)&&5e3!==e.code)}var te={};const se={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"},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:(void 0!==t?te.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},ie={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=se.CHAIN_NAME_MAP)?void 0:s[r])||void 0}};var re=1e6,ne="[big.js] ",oe=ne+"Invalid ",ae=oe+"decimal places",ce=oe+"rounding mode",le=ne+"Division by zero",de={},he=void 0,ue=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function pe(e,t,s,i){var r=e.c;if(s===he&&(s=e.constructor.RM),0!==s&&1!==s&&2!==s&&3!==s)throw Error(ce);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]!==he))),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]!==he||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 ge(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}de.abs=function(){var e=new this.constructor(this);return e.s=1,e},de.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},de.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>re)throw Error(ae);if(!r[0])throw Error(le);if(!i[0])return e.s=n,e.c=[e.e=0],e;var a,c,l,d,h,u=r.slice(),p=a=r.length,g=i.length,m=i.slice(0,a),f=m.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,u.unshift(0);f++<a;)m.push(0);do{for(l=0;l<10;l++){if(a!=(f=m.length))d=a>f?1:-1;else for(h=-1,d=0;++h<a;)if(r[h]!=m[h]){d=r[h]>m[h]?1:-1;break}if(!(d<0))break;for(c=f==a?r:u;f;){if(m[--f]<c[f]){for(h=f;h&&!m[--h];)m[h]=9;--m[h],m[f]+=10}m[f]-=c[f]}for(;!m[0];)m.shift()}v[y++]=d?l:++l,m[0]&&d?m[f]=i[p]||0:m=[i[p]]}while((p++<g||m[0]!==he)&&n--);
vendor: 5,053 bytes, line 2
2return v[0]||1==y||(v.shift(),w.e--,b--),y>b&&pe(w,b,s.RM,m[0]!==he),w},de.eq=function(e){return 0===this.cmp(e)},de.gt=function(e){return this.cmp(e)>0},de.gte=function(e){return this.cmp(e)>-1},de.lt=function(e){return this.cmp(e)<0},de.lte=function(e){return this.cmp(e)<1},de.minus=de.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,h=e.c,u=e.e;if(!l[0]||!h[0])return h[0]?e.s=-c:l[0]?e=new o(n):e.s=1,e;if(a=d-u){for((r=a<0)?(a=-a,i=l):(u=d,i=h),i.reverse(),c=a;c--;)i.push(0);i.reverse()}else for(s=((r=l.length<h.length)?l:h).length,a=c=0;c<s;c++)if(l[c]!=h[c]){r=l[c]<h[c];break}if(r&&(i=l,l=h,h=i,e.s=-e.s),(c=(s=h.length)-(t=l.length))>0)for(;c--;)l[t++]=0;for(c=t;s>a;){if(l[--s]<h[s]){for(t=s;t&&!l[--t];)l[t]=9;--l[t],l[s]+=10}l[s]-=h[s]}for(;0===l[--c];)l.pop();for(;0===l[0];)l.shift(),--u;return l[0]||(e.s=1,l=[u=0]),e.c=l,e.e=u,e},de.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(le);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)))},de.neg=function(){var e=new this.constructor(this);return e.s=-e.s,e},de.plus=de.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},de.pow=function(e){var t=this,s=new t.constructor("1"),i=s,r=e<0;if(e!==~~e||e<-1e6||e>1e6)throw Error(oe+"exponent");for(r&&(e=-e);1&e&&(i=i.times(t)),e>>=1;)t=t.times(t);return r?s.div(i):i},de.prec=function(e,t){if(e!==~~e||e<1||e>re)throw Error(oe+"precision");return pe(new this.constructor(this),e,t)},de.round=function(e,t){if(e===he)e=0;else if(e!==~~e||e<-1e6||e>re)throw Error(ae);return pe(new this.constructor(this),e+this.e+1,t)},de.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(ne+"No square root");0===(n=Math.sqrt(+ge(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 pe(e,(r.DP-=4)+e.e+1,r.RM)},de.times=de.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},de.toExponential=function(e,t){var s=this,i=s.c[0];if(e!==he){if(e!==~~e||e<0||e>re)throw Error(ae);for(s=pe(new s.constructor(s),++e,t);s.c.length<e;)s.c.push(0)}return ge(s,!0,!!i)},de.toFixed=function(e,t){var s=this,i=s.c[0];if(e!==he){if(e!==~~e||e<0||e>re)throw Error(ae);for(e=e+(s=pe(new s.constructor(s),e+s.e+1,t)).e+1;s.c.length<e;)s.c.push(0)}return ge(s,!1,!!i)},de[Symbol.for("nodejs.util.inspect.custom")]=de.toJSON=de.toString=function(){var e=this,t=e.constructor;return ge(e,e.e<=t.NE||e.e>=t.PE,!!e.c[0])},de.toNumber=function(){var e=+ge(this,!0,!0);if(!0===this.constructor.strict&&!this.eq(e.toString()))throw Error(ne+"Imprecise conversion");return e},de.toPrecision=function(e,t){var s=this,i=s.constructor,r=s.c[0];if(e!==he){if(e!==~~e||e<1||e>re)throw Error(oe+"precision");for(s=pe(new i(s),e,t);s.c.length<e;)s.c.push(0)}return ge(s,e<=s.e||s.e<=i.NE||s.e>=i.PE,!!r)},de.valueOf=function(){var e=this,t=e.constructor;if(!0===t.strict)throw Error(ne+"valueOf disallowed");return ge(e,e.e<=t.NE||e.e>=t.PE,!0)};var me=function e(){function t(s){var i=this;if(!(i instanceof t))return s===he?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(oe+"value");s=0===s&&1/s<0?"-0":String(s)}!function(e,t){var s,i,r;if(!ue.test(t))throw Error(oe+"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=de,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 fe={bigNumber:e=>new me(e||0),multiply(e,t){if(void 0===e||void 0===t)return new me(0);const s=new me(e),i=new me(t);return s.times(i)},formatNumberToLocalString:(e,t=2)=>
2void 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,""))},we=[{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"}]}],ve=[{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"}]}],ye=e=>se.USDT_CONTRACT_ADDRESSES.includes(e)?ve:we,be={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}}},Ee="@appkit/active_caip_network_id",Ce="@appkit/connected_social",Ie="@appkit-wallet/SOCIAL_USERNAME",Ne="@appkit/recent_wallets",Ae="WALLETCONNECT_DEEPLINK_CHOICE",Se="@appkit/active_namespace",Pe="@appkit/connected_namespaces",ke="@appkit/connection_status",_e="@appkit/social_provider",Oe="@appkit/native_balance_cache",Te="@appkit/portfolio_cache",xe="@appkit/ens_cache",Re="@appkit/identity_cache",Ue="@appkit/preferred_account_types",De="@appkit/connections";function $e(e){if(!e)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${e}:connected_connector_id`}const Me={setItem(e,t){Le()&&void 0!==t&&localStorage.setItem(e,t)},getItem(e){if(Le())return localStorage.getItem(e)||void 0},removeItem(e){Le()&&localStorage.removeItem(e)},clear(){Le()&&localStorage.clear()}};function Le(){return"undefined"!=typeof window&&"undefined"!=typeof localStorage}function je(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 qe=Symbol(),Be=Object.getPrototypeOf,Fe=new WeakMap,We=e=>(e=>e&&(Fe.has(e)?Fe.get(e):Be(e)===Object.prototype||Be(e)===Array.prototype))(e)&&e[qe]||null,ze=(e,t=!0)=>{Fe.set(e,t)},He={},Ve=e=>"object"==typeof e&&null!==e,Ke=new WeakMap,Ge=new WeakSet,[Je]=((e=Object.is,t=(e,t)=>new Proxy(e,t),s=e=>Ve(e)&&!Ge.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 ze(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(Ge.has(i))ze(i,!1);else if(i instanceof Promise)delete o.value,o.get=()=>s(i);else if(Ke.has(i)){const[e,t]=Ke.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(!Ve(i))throw new Error("object required");const r=o.get(i);if(r)return r;let l=a[0];const d=new Set,h=(e,t=++a[0])=>{l!==t&&(l=t,d.forEach(s=>s(e,t)))};let u=a[1];const p=e=>(t,s)=>{const i=[...t];i[1]=[e,...i[1]],h(i,s)},g=new Map,m=e=>{var t;const s=g.get(e);s&&(g.delete(e),null==(t=s[1])||t.call(s))},f=Array.isArray(i)?[]:Object.create(Object.getPrototypeOf(i)),w=t(f,{deleteProperty(e,t){const s=Reflect.get(e,t);m(t);const i=Reflect.deleteProperty(e,t);return i&&h(["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;m(i),Ve(r)&&(r=We(r)||r);let u=r;if(r instanceof Promise)r.then(e=>{r.status="fulfilled",r.value=e,h(["resolve",[i],e])}).catch(e=>{r.status="rejected",r.reason=e,h(["reject",[i],e])});else{!Ke.has(r)&&s(r)&&(u=c(r));const e=!Ge.has(u)&&Ke.get(u);e&&((e,t)=>{if("production"!==(He?"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,u,n),h(["set",[i],r,l]),!0}});o.set(i,w);const v=[f,(e=++a[1])=>(u===e||d.size||(u=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"!==(He?"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 Ke.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(f,e,t)}),w})=>[c,Ke,Ge,e,t,s,i,r,n,o,a])();function Ye(e={}){return Je(e)}function Ze(e,t,s){const i=Ke.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 Qe(e,t){const s=Ke.get(e),[i,r,n]=s;return n(i,r(),t)}function Xe(e){return Ge.add(e),e}function et(e,t,s,i){let r=e[t];return Ze(e,()=>{const i=e[t];Object.is(r,i)||s(r=i)})}const tt=[{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"]}],st={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"}},it={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired:(e,t)=>Date.now()-e>t,getActiveNetworkProps(){const e=it.getActiveNamespace(),t=it.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{Me.setItem(Ae,JSON.stringify({href:t,name:e}))}catch{}},getWalletConnectDeepLink(){try{const e=Me.getItem(Ae);if(e)return JSON.parse(e)}catch{}},deleteWalletConnectDeepLink(){try{Me.removeItem(Ae)}catch{}},setActiveNamespace(e){try{Me.setItem(Se,e)}catch{}},setActiveCaipNetworkId(e){try{Me.setItem(Ee,e),it.setActiveNamespace(e.split(":")[0])}catch{}},getActiveCaipNetworkId(){try{return Me.getItem(Ee)}catch{return}},deleteActiveCaipNetworkId(){try{Me.removeItem(Ee)}catch{}},deleteConnectedConnectorId(e){try{const t=$e(e);Me.removeItem(t)}catch{}},setAppKitRecent(e){try{const t=it.getRecentWallets();t.find(t=>t.id===e.id)||(t.unshift(e),t.length>2&&t.pop(),Me.setItem(Ne,JSON.stringify(t)))}catch{}},getRecentWallets(){try{const e=Me.getItem(Ne);return e?JSON.parse(e):[]}catch{}return[]},setConnectedConnectorId(e,t){try{const s=$e(e);Me.setItem(s,t)}catch{}},getActiveNamespace(){try{return Me.getItem(Se)}catch{}},getConnectedConnectorId(e){if(e)try{const t=$e(e);return Me.getItem(t)}catch(gr){}},setConnectedSocialProvider(e){try{Me.setItem(Ce,e)}catch{}},getConnectedSocialProvider(){try{return Me.getItem(Ce)}catch{}},deleteConnectedSocialProvider(){try{Me.removeItem(Ce)}catch{}},getConnectedSocialUsername(){try{return Me.getItem(Ie)}catch{}},getStoredActiveCaipNetworkId(){var e;const t=Me.getItem(Ee);return null==(e=null==t?void 0:t.split(":"))?void 0:e[1]},setConnectionStatus(e){try{Me.setItem(ke,e)}catch{}},getConnectionStatus(){try{return Me.getItem(ke)}catch{return}},getConnectedNamespaces(){try{const e=Me.getItem(Pe);return(null==e?void 0:e.length)?e.split(","):[]}catch{return[]}},setConnectedNamespaces(e){try{const t=Array.from(new Set(e));Me.setItem(Pe,t.join(","))}catch{}},addConnectedNamespace(e){try{const t=it.getConnectedNamespaces();t.includes(e)||(t.push(e),it.setConnectedNamespaces(t))}catch{}},removeConnectedNamespace(e){try{const t=it.getConnectedNamespaces(),s=t.indexOf(e);s>-1&&(t.splice(s,1),it.setConnectedNamespaces(t))}catch{}},getTelegramSocialProvider(){try{return Me.getItem(_e)}catch{return null}},setTelegramSocialProvider(e){try{Me.setItem(_e,e)}catch{}},removeTelegramSocialProvider(){try{Me.removeItem(_e)}catch{}},getBalanceCache(){let e={};try{const t=Me.getItem(Te);e=t?JSON.parse(t):{}}catch{}return e},removeAddressFromBalanceCache(e){try{const t=it.getBalanceCache();Me.setItem(Te,JSON.stringify({...t,[e]:void 0}))}catch{}},getBalanceCacheForCaipAddress(e){try{const t=it.getBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;it.removeAddressFromBalanceCache(e)}catch{}},updateBalanceCache(e){try{const t=it.getBalanceCache();t[e.caipAddress]=e,Me.setItem(Te,JSON.stringify(t))}catch{}},getNativeBalanceCache(){let e={};try{const t=Me.getItem(Oe);e=t?JSON.parse(t):{}}catch{}return e},removeAddressFromNativeBalanceCache(e){try{const t=it.getBalanceCache();Me.setItem(Oe,JSON.stringify({...t,[e]:void 0}))}catch{}},getNativeBalanceCacheForCaipAddress(e){try{const t=it.getNativeBalanceCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;it.removeAddressFromBalanceCache(e)}catch{}},updateNativeBalanceCache(e){try{const t=it.getNativeBalanceCache();t[e.caipAddress]=e,Me.setItem(Oe,JSON.stringify(t))}catch{}},getEnsCache(){let e={};try{const t=Me.getItem(xe);e=t?JSON.parse(t):{}}catch{}return e}
2,getEnsFromCacheForAddress(e){try{const t=it.getEnsCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;it.removeEnsFromCache(e)}catch{}},updateEnsCache(e){try{const t=it.getEnsCache();t[e.address]=e,Me.setItem(xe,JSON.stringify(t))}catch{}},removeEnsFromCache(e){try{const t=it.getEnsCache();Me.setItem(xe,JSON.stringify({...t,[e]:void 0}))}catch{}},getIdentityCache(){let e={};try{const t=Me.getItem(Re);e=t?JSON.parse(t):{}}catch{}return e},getIdentityFromCacheForAddress(e){try{const t=it.getIdentityCache()[e];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;it.removeIdentityFromCache(e)}catch{}},updateIdentityCache(e){try{const t=it.getIdentityCache();t[e.address]={identity:e.identity,timestamp:e.timestamp},Me.setItem(Re,JSON.stringify(t))}catch{}},removeIdentityFromCache(e){try{const t=it.getIdentityCache();Me.setItem(Re,JSON.stringify({...t,[e]:void 0}))}catch{}},clearAddressCache(){try{Me.removeItem(Te),Me.removeItem(Oe),Me.removeItem(xe),Me.removeItem(Re)}catch{}},setPreferredAccountTypes(e){try{Me.setItem(Ue,JSON.stringify(e))}catch{}},getPreferredAccountTypes(){try{const e=Me.getItem(Ue);return e?JSON.parse(e):{}}catch{}return{}},setConnections(e,t){try{const s={...it.getConnections(),[t]:e};Me.setItem(De,JSON.stringify(s))}catch(s){}},getConnections(){try{const e=Me.getItem(De);return e?JSON.parse(e):{}}catch(e){return{}}}},rt={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 rt.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()<=st.TEN_SEC_MS,isAllowedRetry:(e,t=st.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(gr){return!1}},isSafeApp(){var e,t;if(rt.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()+st.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(rt.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(!rt.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()?it.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,rt.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:()=>se.W3M_API_URL,getBlockchainApiUrl:()=>se.BLOCKCHAIN_API_RPC_URL,getAnalyticsUrl:()=>se.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?st.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 se.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 nt(...e){const t=await fetch(...e);if(!t.ok){throw new Error(`HTTP status code: ${t.status}`,{cause:t})}return t}class ot{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 nt(r,{method:"GET",headers:e,signal:t,cache:s})).json()}async getBlob({headers:e,signal:t,...s}){const i=this.createUrl(s);return(await nt(i,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:s,...i}){const r=this.createUrl(i);return(await nt(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 nt(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 nt(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 at={getFeatureValue(e,t){const s=null==t?void 0:t[e];return void 0===s?st.DEFAULT_FEATURES[e]:s}
2,filterSocialsByPlatform(e){if(!e||!e.length)return e;if(rt.isTelegram()){if(rt.isIos())return e.filter(e=>"google"!==e);if(rt.isMac())return e.filter(e=>"x"!==e);if(rt.isAndroid())return e.filter(e=>!["facebook","x"].includes(e))}return e}},ct=Ye({features:st.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:st.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),lt={state:ct,subscribeKey:(e,t)=>et(ct,e,t),setOptions(e){Object.assign(ct,e)},setRemoteFeatures(e){var t;if(!e)return;const s={...ct.remoteFeatures,...e};ct.remoteFeatures=s,(null==(t=ct.remoteFeatures)?void 0:t.socials)&&(ct.remoteFeatures.socials=at.filterSocialsByPlatform(ct.remoteFeatures.socials))},setFeatures(e){if(!e)return;ct.features||(ct.features=st.DEFAULT_FEATURES);const t={...ct.features,...e};ct.features=t},setProjectId(e){ct.projectId=e},setCustomRpcUrls(e){ct.customRpcUrls=e},setAllWallets(e){ct.allWallets=e},setIncludeWalletIds(e){ct.includeWalletIds=e},setExcludeWalletIds(e){ct.excludeWalletIds=e},setFeaturedWalletIds(e){ct.featuredWalletIds=e},setTokens(e){ct.tokens=e},setTermsConditionsUrl(e){ct.termsConditionsUrl=e},setPrivacyPolicyUrl(e){ct.privacyPolicyUrl=e},setCustomWallets(e){ct.customWallets=e},setIsSiweEnabled(e){ct.isSiweEnabled=e},setIsUniversalProvider(e){ct.isUniversalProvider=e},setSdkVersion(e){ct.sdkVersion=e},setMetadata(e){ct.metadata=e},setDisableAppend(e){ct.disableAppend=e},setEIP6963Enabled(e){ct.enableEIP6963=e},setDebug(e){ct.debug=e},setEnableWalletConnect(e){ct.enableWalletConnect=e},setEnableWalletGuide(e){ct.enableWalletGuide=e},setEnableAuthLogger(e){ct.enableAuthLogger=e},setEnableWallets(e){ct.enableWallets=e},setPreferUniversalLinks(e){ct.experimental_preferUniversalLinks=e},setHasMultipleAddresses(e){ct.hasMultipleAddresses=e},setSIWX(e){ct.siwx=e},setConnectMethodsOrder(e){ct.features={...ct.features,connectMethodsOrder:e}},setWalletFeaturesOrder(e){ct.features={...ct.features,walletFeaturesOrder:e}},setSocialsOrder(e){ct.remoteFeatures={...ct.remoteFeatures,socials:e}},setCollapseWallets(e){ct.features={...ct.features,collapseWallets:e}},setEnableEmbedded(e){ct.enableEmbedded=e},setAllowUnsupportedChain(e){ct.allowUnsupportedChain=e},setManualWCControl(e){ct.manualWCControl=e},setEnableNetworkSwitch(e){ct.enableNetworkSwitch=e},setDefaultAccountTypes(e={}){Object.entries(e).forEach(([e,t])=>{t&&(ct.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(e){ct.universalProviderConfigOverride=e},getUniversalProviderConfigOverride:()=>ct.universalProviderConfigOverride,getSnapshot:()=>Qe(ct)},dt=Object.freeze({enabled:!0,events:[]}),ht=new ot({baseUrl:rt.getAnalyticsUrl(),clientId:null}),ut=Ye({...dt}),pt={state:ut,subscribeKey:(e,t)=>et(ut,e,t),async sendError(e,t){if(!ut.enabled)return;const s=Date.now();if(ut.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()}};ut.events.push(i);try{if("undefined"==typeof window)return;const{projectId:s,sdkType:i,sdkVersion:r}=lt.state;await ht.post({path:"/e",params:{projectId:s,st:i,sv:r||"html-wagmi-4.2.2"},body:{eventId:rt.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(){ut.enabled=!0},disable(){ut.enabled=!1},clearEvents(){ut.events=[]}};class gt extends Error{constructor(e,t,s){super(e),this.name="AppKitError",this.category=t,this.originalError=s,Object.setPrototypeOf(this,gt.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,gt):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function mt(e,t){const s=e instanceof gt?e:new gt(e instanceof Error?e.message:String(e),t,e);throw pt.sendError(s,s.category),s}
2function ft(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 mt(s,t)}}:(...e)=>{try{return r(...e)}catch(s){return mt(s,t)}},s[i]=e}else s[i]=r}),s}const wt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},vt={handleMobileDeeplinkRedirect(e,t){const s=window.location.href,i=encodeURIComponent(s);if(e===wt.PHANTOM.id&&!("phantom"in window)){const e=s.startsWith("https")?"https":"http",t=s.split("/")[2],r=encodeURIComponent(`${e}://${t}`);window.location.href=`${wt.PHANTOM.url}/ul/browse/${i}?ref=${r}`}e!==wt.SOLFLARE.id||"solflare"in window||(window.location.href=`${wt.SOLFLARE.url}/ul/v1/browse/${i}?ref=${i}`),t===se.CHAIN.SOLANA&&(e!==wt.COINBASE.id||"coinbaseSolana"in window||(window.location.href=`${wt.COINBASE.url}/dapp?cb_url=${i}`))}},yt=Ye({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),bt=ft({state:yt,subscribeNetworkImages:e=>Ze(yt.networkImages,()=>e(yt.networkImages)),subscribeKey:(e,t)=>et(yt,e,t),subscribe:e=>Ze(yt,()=>e(yt)),setWalletImage(e,t){yt.walletImages[e]=t},setNetworkImage(e,t){yt.networkImages[e]=t},setChainImage(e,t){yt.chainImages[e]=t},setConnectorImage(e,t){yt.connectorImages={...yt.connectorImages,[e]:t}},setTokenImage(e,t){yt.tokenImages[e]=t},setCurrencyImage(e,t){yt.currencyImages[e]=t}}),Et={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},Ct=Ye({networkImagePromises:{}}),It={async fetchWalletImage(e){if(e)return await Ut._fetchWalletImage(e),this.getWalletImageById(e)},async fetchNetworkImage(e){if(!e)return;const t=this.getNetworkImageById(e);return t||(Ct.networkImagePromises[e]||(Ct.networkImagePromises[e]=Ut._fetchNetworkImage(e)),await Ct.networkImagePromises[e],this.getNetworkImageById(e))},getWalletImageById(e){if(e)return bt.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)?bt.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)?bt.state.networkImages[e.assets.imageId]:void 0},getNetworkImageById(e){if(e)return bt.state.networkImages[e]},getConnectorImage:e=>(null==e?void 0:e.imageUrl)?e.imageUrl:(null==e?void 0:e.imageId)?bt.state.connectorImages[e.imageId]:void 0,getChainImage:e=>bt.state.networkImages[Et[e]]},Nt=Ye({message:"",variant:"info",open:!1}),At=ft({state:Nt,subscribeKey:(e,t)=>et(Nt,e,t),open(e,t){const{debug:s}=lt.state,{shortMessage:i,longMessage:r}=e;s&&(Nt.message=i,Nt.variant=t,Nt.open=!0)},close(){Nt.open=!1,Nt.message="",Nt.variant="info"}}),St=rt.getAnalyticsUrl(),Pt=new ot({baseUrl:St,clientId:null}),kt=["MODAL_CREATED"],_t=Ye({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Ot={state:_t,subscribe:e=>Ze(_t,()=>e(_t)),getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=lt.state;return{projectId:e,st:t,sv:s||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(e){try{const t=gs.state.address;if(kt.includes(e.data.event)||"undefined"==typeof window)return;await Pt.post({path:"/e",params:Ot.getSdkProperties(),body:{eventId:rt.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:e.timestamp,props:{...e.data,address:t}}}),_t.reportedErrors.FORBIDDEN=!1}catch(t){t instanceof Error&&t.cause instanceof Response&&t.cause.status===se.HTTP_STATUS_CODES.FORBIDDEN&&!_t.reportedErrors.FORBIDDEN&&(At.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${Le()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),_t.reportedErrors.FORBIDDEN=!0)}},sendEvent(e){var t;_t.timestamp=Date.now(),_t.data=e,(null==(t=lt.state.features)?void 0:t.analytics)&&Ot._sendAnalyticsEvent(_t)}},Tt=rt.getApiUrl(),xt=new ot({baseUrl:Tt,clientId:null}),Rt=Ye({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),Ut={state:Rt,subscribeKey:(e,t)=>et(Rt,e,t),_getSdkProperties(){const{projectId:e,sdkType:t,sdkVersion:s}=lt.state;return{projectId:e,st:t||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions:e=>lt.state.isUniversalProvider?e.filter(e=>Boolean(e.mobile_link||e.desktop_link||e.webapp_link)):e,async _fetchWalletImage(e){const t=`${xt.baseUrl}/getWalletImage/${e}`,s=await xt.getBlob({path:t,params:Ut._getSdkProperties()});bt.setWalletImage(e,URL.createObjectURL(s))},async _fetchNetworkImage(e){const t=`${xt.baseUrl}/public/getAssetImage/${e}`,s=await xt.getBlob({path:t,params:Ut._getSdkProperties()});bt.setNetworkImage(e,URL.createObjectURL(s))},async _fetchConnectorImage(e){const t=`${xt.baseUrl}/public/getAssetImage/${e}`,s=await xt.getBlob({path:t,params:Ut._getSdkProperties()});bt.setConnectorImage(e,URL.createObjectURL(s))},async _fetchCurrencyImage(e){const t=`${xt.baseUrl}/public/getCurrencyImage/${e}`,s=await xt.getBlob({path:t,params:Ut._getSdkProperties()});bt.setCurrencyImage(e,URL.createObjectURL(s))},async _fetchTokenImage(e){const t=`${xt.baseUrl}/public/getTokenImage/${e}`,s=await xt.getBlob({path:t,params:Ut._getSdkProperties()});bt.setTokenImage(e,URL.createObjectURL(s))},_filterWalletsByPlatform:e=>rt.isMobile()?null==e?void 0:e.filter(e=>{if(e.mobile_link)return!0;
2if(e.id===wt.COINBASE.id)return!0;return"solana"===cs.state.activeChain&&(e.id===wt.SOLFLARE.id||e.id===wt.PHANTOM.id)}):e,fetchProjectConfig:async()=>(await xt.get({path:"/appkit/v1/config",params:Ut._getSdkProperties()})).features,async fetchAllowedOrigins(){try{const{allowedOrigins:e}=await xt.get({path:"/projects/v1/origins",params:Ut._getSdkProperties()});return e}catch(e){return[]}},async fetchNetworkImages(){const e=cs.getAllRequestedCaipNetworks(),t=null==e?void 0:e.map(({assets:e})=>null==e?void 0:e.imageId).filter(Boolean).filter(e=>!It.getNetworkImageById(e));t&&await Promise.allSettled(t.map(e=>Ut._fetchNetworkImage(e)))},async fetchConnectorImages(){const{connectors:e}=Ft.state,t=e.map(({imageId:e})=>e).filter(Boolean);await Promise.allSettled(t.map(e=>Ut._fetchConnectorImage(e)))},async fetchCurrencyImages(e=[]){await Promise.allSettled(e.map(e=>Ut._fetchCurrencyImage(e)))},async fetchTokenImages(e=[]){await Promise.allSettled(e.map(e=>Ut._fetchTokenImage(e)))},async fetchWallets(e){var t;const s=e.exclude??[];Ut._getSdkProperties().sv.startsWith("html-core-")&&s.push(...Object.values(wt).map(e=>e.id));const i=await xt.get({path:"/getWallets",params:{...Ut._getSdkProperties(),...e,page:String(e.page),entries:String(e.entries),include:null==(t=e.include)?void 0:t.join(","),exclude:s.join(",")}});return{data:Ut._filterWalletsByPlatform(null==i?void 0:i.data)||[],count:null==i?void 0:i.count}},async fetchFeaturedWallets(){const{featuredWalletIds:e}=lt.state;if(null==e?void 0:e.length){const t={...Ut._getSdkProperties(),page:1,entries:(null==e?void 0:e.length)??4,include:e},{data:s}=await Ut.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=>Ut._fetchWalletImage(e))),Rt.featured=i,Rt.allFeatured=i}},async fetchRecommendedWallets(){try{Rt.isFetchingRecommendedWallets=!0;const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:s}=lt.state,i=[...t??[],...s??[]].filter(Boolean),r={page:1,entries:4,include:e,exclude:i,chains:cs.getRequestedCaipNetworkIds().join(",")},{data:n,count:o}=await Ut.fetchWallets(r),a=it.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=>Ut._fetchWalletImage(e))),Rt.recommended=n,Rt.allRecommended=n,Rt.count=o??0}catch{}finally{Rt.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:e}){const{includeWalletIds:t,excludeWalletIds:s,featuredWalletIds:i}=lt.state,r=cs.getRequestedCaipNetworkIds().join(","),n={page:e,entries:40,include:t,exclude:[...Rt.recommended.map(({id:e})=>e),...s??[],...i??[]].filter(Boolean),chains:r},{data:o,count:a}=await Ut.fetchWallets(n),c=o.slice(0,20).map(e=>e.image_id).filter(Boolean);await Promise.allSettled(c.map(e=>Ut._fetchWalletImage(e))),Rt.wallets=rt.uniqueBy([...Rt.wallets,...Ut._filterOutExtensions(o)],"id").filter(e=>{var t;return null==(t=e.chains)?void 0:t.some(e=>r.includes(e))}),Rt.count=a>Rt.count?a:Rt.count,Rt.page=e},async initializeExcludedWallets({ids:e}){const t={page:1,entries:e.length,include:e},{data:s}=await Ut.fetchWallets(t);s&&s.forEach(e=>{Rt.excludedWallets.push({rdns:e.rdns,name:e.name})})},async searchWallet({search:e,badge:t}){const{includeWalletIds:s,excludeWalletIds:i}=lt.state,r=cs.getRequestedCaipNetworkIds().join(",");Rt.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 Ut.fetchWallets(n);Ot.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=>Ut._fetchWalletImage(e)),rt.wait(300)]),Rt.search=Ut._filterOutExtensions(o)},initPromise(e,t){const s=Rt.promises[e];return s||(Rt.promises[e]=t())},prefetch({fetchConnectorImages:e=!0,fetchFeaturedWallets:t=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:i=!0}={}){const r=[e&&Ut.initPromise("connectorImages",Ut.fetchConnectorImages),t&&Ut.initPromise("featuredWallets",Ut.fetchFeaturedWallets),s&&Ut.initPromise("recommendedWallets",Ut.fetchRecommendedWallets),i&&Ut.initPromise("networkImages",Ut.fetchNetworkImages)].filter(
2Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){var e;(null==(e=lt.state.features)?void 0:e.analytics)&&Ut.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:e}=await xt.get({path:"/getAnalyticsConfig",params:Ut._getSdkProperties()});lt.setFeatures({analytics:e})}catch(e){lt.setFeatures({analytics:!1})}},filterByNamespaces(e){if(!(null==e?void 0:e.length))return Rt.featured=Rt.allFeatured,void(Rt.recommended=Rt.allRecommended);const t=cs.getRequestedCaipNetworkIds().join(",");Rt.featured=Rt.allFeatured.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))}),Rt.recommended=Rt.allRecommended.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))}),Rt.filteredWallets=Rt.wallets.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))})},clearFilterByNamespaces(){Rt.filteredWallets=[]},setFilterByNamespace(e){if(!e)return Rt.featured=Rt.allFeatured,void(Rt.recommended=Rt.allRecommended);const t=cs.getRequestedCaipNetworkIds().join(",");Rt.featured=Rt.allFeatured.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))}),Rt.recommended=Rt.allRecommended.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))}),Rt.filteredWallets=Rt.wallets.filter(e=>{var s;return null==(s=e.chains)?void 0:s.some(e=>t.includes(e))})}},Dt=Ye({view:"Connect",history:["Connect"],transactionStack:[]}),$t=ft({state:Dt,subscribeKey:(e,t)=>et(Dt,e,t),pushTransactionStack(e){Dt.transactionStack.push(e)},popTransactionStack(e){const t=Dt.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(),$t.goBack();break;case"cancel":null==r||r(),$t.goBack()}},push(e,t){e!==Dt.view&&(Dt.view=e,Dt.history.push(e),Dt.data=t)},reset(e,t){Dt.view=e,Dt.history=[e],Dt.data=t},replace(e,t){Dt.history.at(-1)===e||(Dt.view=e,Dt.history[Dt.history.length-1]=e,Dt.data=t)},goBack(){var e;const t=cs.state.activeCaipAddress,s="ConnectingFarcaster"===$t.state.view,i=!t&&s;if(Dt.history.length>1){Dt.history.pop();const[e]=Dt.history.slice(-1);if(e){const s="Connect"===e;Dt.view=t&&s?"Account":e}}else ws.close();(null==(e=Dt.data)?void 0:e.wallet)&&(Dt.data.wallet=void 0),setTimeout(()=>{var e,t,s;if(i){gs.setFarcasterUrl(void 0,cs.state.activeChain);const i=Ft.getAuthConnector();null==(e=null==i?void 0:i.provider)||e.reload();const r=Qe(lt.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(Dt.history.length>1){Dt.history=Dt.history.slice(0,e+1);const[t]=Dt.history.slice(-1);t&&(Dt.view=t)}},goBackOrCloseModal(){$t.state.history.length>1?$t.goBack():ws.close()}}),Mt=Ye({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Lt={state:Mt,subscribe:e=>Ze(Mt,()=>e(Mt)),setThemeMode(e){Mt.themeMode=e;try{const t=Ft.getAuthConnector();if(t){const s=Lt.getSnapshot().themeVariables;t.provider.syncTheme({themeMode:e,themeVariables:s,w3mThemeVariables:je(s,e)})}}catch{}},setThemeVariables(e){Mt.themeVariables={...Mt.themeVariables,...e};try{const e=Ft.getAuthConnector();if(e){const t=Lt.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:je(Mt.themeVariables,Mt.themeMode)})}}catch{}},getSnapshot:()=>Qe(Mt)},jt=ft(Lt),qt={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},Bt=Ye({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...qt},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),Ft=ft({state:Bt,subscribe:e=>Ze(Bt,()=>{e(Bt)}),subscribeKey:(e,t)=>et(Bt,e,t),initialize(e){e.forEach(e=>{const t=it.getConnectedConnectorId(e);t&&Ft.setConnectorId(t,e)})},setActiveConnector(e){e&&(Bt.activeConnector=Xe(e))},setConnectors(e){e.filter(e=>!Bt.allConnectors.some(t=>t.id===e.id&&Ft.getConnectorName(t.name)===Ft.getConnectorName(e.name)&&t.chain===e.chain)).forEach(e=>{"MULTI_CHAIN"!==e.type&&Bt.allConnectors.push(Xe(e))});const t=Ft.getEnabledNamespaces(),s=Ft.getEnabledConnectors(t);Bt.connectors=Ft.mergeMultiChainConnectors(s)},filterByNamespaces(e){Object.keys(Bt.filterByNamespaceMap).forEac
2h(e=>{Bt.filterByNamespaceMap[e]=!1}),e.forEach(e=>{Bt.filterByNamespaceMap[e]=!0}),Ft.updateConnectorsForEnabledNamespaces()},filterByNamespace(e,t){Bt.filterByNamespaceMap[e]=t,Ft.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const e=Ft.getEnabledNamespaces(),t=Ft.getEnabledConnectors(e),s=Ft.areAllNamespacesEnabled();Bt.connectors=Ft.mergeMultiChainConnectors(t),s?Ut.clearFilterByNamespaces():Ut.filterByNamespaces(e)},getEnabledNamespaces:()=>Object.entries(Bt.filterByNamespaceMap).filter(([e,t])=>t).map(([e])=>e),getEnabledConnectors:e=>Bt.allConnectors.filter(t=>e.includes(t.chain)),areAllNamespacesEnabled:()=>Object.values(Bt.filterByNamespaceMap).every(e=>e),mergeMultiChainConnectors(e){const t=Ft.generateConnectorMapByName(e),s=[];return t.forEach(e=>{const t=e[0],i=(null==t?void 0:t.id)===se.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=Ft.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===se.CONNECTOR_ID.AUTH){const r=e,n=Qe(lt.state),o=jt.getSnapshot().themeMode,a=jt.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:je(a,o)}),Ft.setConnectors([e])}else Ft.setConnectors([e])},getAuthConnector(e){var t;const s=e||cs.state.activeChain,i=Bt.connectors.find(e=>e.id===se.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:()=>Bt.connectors.filter(e=>"ANNOUNCED"===e.type).map(e=>{var t;return null==(t=e.info)?void 0:t.rdns}),getConnectorById:e=>Bt.allConnectors.find(t=>t.id===e),getConnector:(e,t)=>Bt.allConnectors.filter(e=>e.chain===cs.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=Qe(lt.state),n=jt.getSnapshot().themeMode,o=jt.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:je(o,n)})},getConnectorsByNamespace(e){const t=Bt.allConnectors.filter(t=>t.chain===e);return Ft.mergeMultiChainConnectors(t)},selectWalletConnector(e){const t=Ft.getConnector(e.id,e.rdns),s=cs.state.activeChain;vt.handleMobileDeeplinkRedirect((null==t?void 0:t.explorerId)||e.id,s),t?$t.push("ConnectingExternal",{connector:t}):$t.push("ConnectingWalletConnect",{wallet:e})},getConnectors:e=>e?Ft.getConnectorsByNamespace(e):Ft.mergeMultiChainConnectors(Bt.allConnectors),setFilterByNamespace(e){Bt.filterByNamespace=e,Bt.connectors=Ft.getConnectors(e),Ut.setFilterByNamespace(e)},setConnectorId(e,t){e&&(Bt.activeConnectorIds={...Bt.activeConnectorIds,[t]:e},it.setConnectedConnectorId(t,e))},removeConnectorId(e){Bt.activeConnectorIds={...Bt.activeConnectorIds,[e]:void 0},it.deleteConnectedConnectorId(e)},getConnectorId(e){if(e)return Bt.activeConnectorIds[e]},isConnected:e=>e?Boolean(Bt.activeConnectorIds[e]):Object.values(Bt.activeConnectorIds).some(e=>Boolean(e)),resetConnectorIds(){Bt.activeConnectorIds={...qt}}}),Wt={SMART_ACCOUNT:"smartAccount"},zt=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),Ht=Ye({...zt}),Vt={state:Ht,subscribeKey:(e,t)=>et(Ht,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=rt.parseError(e);this._showMessage({message:t,variant:"error"})},hide(){Ht.message=zt.message,Ht.variant=zt.variant,Ht.svg=zt.svg,Ht.o
2pen=zt.open,Ht.autoClose=zt.autoClose},_showMessage({message:e,svg:t,variant:s="success",autoClose:i=zt.autoClose}){Ht.open?(Ht.open=!1,setTimeout(()=>{Ht.message=e,Ht.variant=s,Ht.svg=t,Ht.open=!0,Ht.autoClose=i},150)):(Ht.message=e,Ht.variant=s,Ht.svg=t,Ht.open=!0,Ht.autoClose=i)}},Kt=Ye({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Gt=ft({state:Kt,subscribe:e=>Ze(Kt,()=>e(Kt)),setLastNetworkInView(e){Kt.lastNetworkInView=e},async fetchTransactions(e,t){var s,i;if(!e)throw new Error("Transactions can't be fetched without an accountAddress");Kt.loading=!0;try{const i=await us.fetchTransactions({account:e,cursor:Kt.next,onramp:t,cache:"coinbase"===t?"no-cache":void 0,chainId:null==(s=cs.state.activeCaipNetwork)?void 0:s.caipNetworkId}),r=Gt.filterSpamTransactions(i.data),n=Gt.filterByConnectedChain(r),o=[...Kt.transactions,...n];Kt.loading=!1,"coinbase"===t?Kt.coinbaseTransactions=Gt.groupTransactionsByYearAndMonth(Kt.coinbaseTransactions,i.data):(Kt.transactions=o,Kt.transactionsByYear=Gt.groupTransactionsByYearAndMonth(Kt.transactionsByYear,n)),Kt.empty=0===o.length,Kt.next=i.next?i.next:void 0}catch(r){const t=cs.state.activeChain;Ot.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:e,projectId:lt.state.projectId,cursor:Kt.next,isSmartAccount:(null==(i=gs.state.preferredAccountTypes)?void 0:i[t])===Wt.SMART_ACCOUNT}}),Vt.showError("Failed to fetch transactions"),Kt.loading=!1,Kt.empty=!0,Kt.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=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId;return e.filter(e=>e.metadata.chain===s)},clearCursor(){Kt.next=void 0},resetTransactions(){Kt.transactions=[],Kt.transactionsByYear={},Kt.lastNetworkInView=void 0,Kt.loading=!1,Kt.empty=!1,Kt.next=void 0}},"API_ERROR"),Jt=Ye({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let Yt;const Zt=ft({state:Jt,subscribeKey:(e,t)=>et(Jt,e,t),_getClient:()=>Jt._client,setClient(e){Jt._client=Xe(e)},async connectWalletConnect(){var e,t,s,i;if(rt.isTelegram()||rt.isSafari()&&rt.isIos()){if(Yt)return await Yt,void(Yt=void 0);if(!rt.isPairingExpired(null==Jt?void 0:Jt.wcPairingExpiry)){const e=Jt.wcUri;return void(Jt.wcUri=e)}Yt=null==(t=null==(e=Zt._getClient())?void 0:e.connectWalletConnect)?void 0:t.call(e).catch(()=>{}),Zt.state.status="connecting",await Yt,Yt=void 0,Jt.wcPairingExpiry=void 0,Zt.state.status="connected"}else await(null==(i=null==(s=Zt._getClient())?void 0:s.connectWalletConnect)?void 0:i.call(s))},async connectExternal(e,t,s=!0){var i,r;await(null==(r=null==(i=Zt._getClient())?void 0:i.connectExternal)?void 0:r.call(i,e)),s&&cs.setActiveNamespace(t)},async reconnectExternal(e){var t,s;await(null==(s=null==(t=Zt._getClient())?void 0:t.reconnectExternal)?void 0:s.call(t,e));const i=e.chain||cs.state.activeChain;i&&Ft.setConnectorId(e.id,i)},async setPreferredAccountType(e,t){var s;ws.setLoading(!0,cs.state.activeChain);const i=Ft.getAuthConnector();i&&(gs.setPreferredAccountType(e,t),await i.provider.setPreferredAccount(e),it.
2setPreferredAccountTypes(gs.state.preferredAccountTypes??{[t]:e}),await Zt.reconnectExternal(i),ws.setLoading(!1,cs.state.activeChain),Ot.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:e,network:(null==(s=cs.state.activeCaipNetwork)?void 0:s.caipNetworkId)||""}}))},async signMessage(e){var t;return null==(t=Zt._getClient())?void 0:t.signMessage(e)},parseUnits(e,t){var s;return null==(s=Zt._getClient())?void 0:s.parseUnits(e,t)},formatUnits(e,t){var s;return null==(s=Zt._getClient())?void 0:s.formatUnits(e,t)},async sendTransaction(e){var t;return null==(t=Zt._getClient())?void 0:t.sendTransaction(e)},async getCapabilities(e){var t;return null==(t=Zt._getClient())?void 0:t.getCapabilities(e)},async grantPermissions(e){var t;return null==(t=Zt._getClient())?void 0:t.grantPermissions(e)},async walletGetAssets(e){var t;return(null==(t=Zt._getClient())?void 0:t.walletGetAssets(e))??{}},async estimateGas(e){var t;return null==(t=Zt._getClient())?void 0:t.estimateGas(e)},async writeContract(e){var t;return null==(t=Zt._getClient())?void 0:t.writeContract(e)},async getEnsAddress(e){var t;return null==(t=Zt._getClient())?void 0:t.getEnsAddress(e)},async getEnsAvatar(e){var t;return null==(t=Zt._getClient())?void 0:t.getEnsAvatar(e)},checkInstalled(e){var t,s;return(null==(s=null==(t=Zt._getClient())?void 0:t.checkInstalled)?void 0:s.call(t,e))||!1},resetWcConnection(){Jt.wcUri=void 0,Jt.wcPairingExpiry=void 0,Jt.wcLinking=void 0,Jt.recentWallet=void 0,Jt.status="disconnected",Gt.resetTransactions(),it.deleteWalletConnectDeepLink()},resetUri(){Jt.wcUri=void 0,Jt.wcPairingExpiry=void 0,Yt=void 0},finalizeWcConnection(){var e,t;const{wcLinking:s,recentWallet:i}=Zt.state;s&&it.setWalletConnectDeepLink(s),i&&it.setAppKitRecent(i),Ot.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s?"mobile":"qrcode",name:(null==(t=null==(e=$t.state.data)?void 0:e.wallet)?void 0:t.name)||"Unknown"}})},setWcBasic(e){Jt.wcBasic=e},setUri(e){Jt.wcUri=e,Jt.wcPairingExpiry=rt.getPairingExpiry()},setWcLinking(e){Jt.wcLinking=e},setWcError(e){Jt.wcError=e,Jt.buffering=!1},setRecentWallet(e){Jt.recentWallet=e},setBuffering(e){Jt.buffering=e},setStatus(e){Jt.status=e},async disconnect(e){var t;try{await(null==(t=Zt._getClient())?void 0:t.disconnect(e))}catch(s){throw new gt("Failed to disconnect","INTERNAL_SDK_ERROR",s)}},setConnections(e,t){Jt.connections.set(t,e)},switchAccount({connection:e,address:t,namespace:s}){if(Ft.state.activeConnectorIds[s]===e.connectorId){const e=cs.state.activeCaipNetwork;if(e){const i=`${s}:${e.id}:${t}`;gs.setCaipAddress(i,s)}}else{const t=Ft.getConnector(e.connectorId);t&&Zt.connectExternal(t,s)}}}),Qt=Ye({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),Xt={state:Qt,subscribe:e=>Ze(Qt,()=>e(Qt)),subscribeOpen:e=>et(Qt,"open",e),set(e){Object.assign(Qt,{...Qt,...e})}},es={createBalance(e,t){const s={name:e.metadata.name||"",symbol: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})=>Y(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},ts={async getMyTokensWithBalance(e){const t=gs.state.address,s=cs.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 us.getBalance(t,s.caipNetworkId,e);return this.filterLowQualityTokens(i.balances)},async getEIP155Balances(e,t){var s,i;try{const r=es.getChainIdHexFromCAIP2ChainId(t.caipNetworkId),n=await Zt.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 Zt.walletGetAssets({account:e,chainFilter:[r]});if(!es.isWalletGetAssetsResponse(o))return null;return(o[r]||[]).map(e=>es.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:cs.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]},ss=Ye({tokenBalances:[],loading:!1}),is=ft({state:ss,subscribe:e=>Ze(ss,()=>e(ss)),subscribeKey:(e,t)=>et(ss,e,t),setToken(e){e&&(ss.token=Xe(e))},setTokenAmount(e){ss.sendTokenAmount=e},setReceiverAddress(e){ss.receiverAddress=e},setReceiverProfileImageUrl(e){ss.receiverProfileImageUrl=e},setReceiverProfileName(e){ss.receiverProfileName=e},setNetworkBalanceInUsd(e){ss.networkBalanceInUSD=e},setLoading(e){ss.loading=e},async sendToken(){var e;try{switch(is.setLoading(!0),null==(e=cs.state.activeCaipNetwork)?void 0:e.chainNamespace){case"eip155":return void(await is.sendEvmToken());case"solana":return void(await is.sendSolanaToken());default:throw new Error("Unsupported chain")}}finally{is.setLoading(!1)}},async sendEvmToken(){var e,t,s,i;const r=cs.state.activeChain,n=null==(e=gs.state.preferredAccountTypes)?void 0:e[r];if(!is.state.sendTokenAmount||!is.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!is.state.token)throw new Error("A token is required");(null==(t=is.state.token)?void 0:t.address)?(Ot.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:n===Wt.SMART_ACCOUNT,token:is.state.token.address,amount:is.state.sendTokenAmount,network:(null==(s=cs.state.activeCaipNetwork)?void 0:s.caipNetworkId)||""}}),await is.sendERC20Token({receiverAddress:is.state.receiverAddress,tokenAddress:is.state.token.address,sendTokenAmount:is.state.sendTokenAmount,decimals:is.state.token.quantity.decimals})):(Ot.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:n===Wt.SMART_ACCOUNT,token:is.state.token.symbol||"",amount:is.state.sendTokenAmount,network:(null==(i=cs.state.activeCaipNetwork)?void 0:i.caipNetworkId)||""}}),await is.sendNativeToken({receiverAddress:is.state.receiverAddress,sendTokenAmount:is.state.sendTokenAmount,decimals:is.state.token.quantity.decimals}))},async fetchTokenBalance(e){var t,s;ss.loading=!0;const i=null==(t=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId,r=null==(s=cs.state.activeCaipNetwork)?void 0:s.chainNamespace,n=cs.state.activeCaipAddress,o=n?rt.getPlainAddress(n):void 0;if(ss.lastRetry&&!rt.isAllowedRetry(ss.lastRetry,30*st.ONE_SEC_MS))return ss.loading=!1,[];try{if(o&&i&&r){const e=await ts.getMyTokensWithBalance();return ss.tokenBalances=e,ss.lastRetry=void 0,e}}catch(a){ss.lastRetry=Date.now(),null==e||e(a),Vt.showError("Token Balance Unavailable")}finally{ss.loading=!1}return[]},fetchNetworkBalance(){if(0===ss.tokenBalances.length)return;const e=ts.mapBalancesToSwapTokens(ss.tokenBalances);if(!e)return;const t=e.find(e=>e.address===cs.getActiveNetworkTokenAddress());t&&(ss.networkBalanceInUSD=t?fe.multiply(t.quantity.numeric,t.price).toString():"0")},async sendNativeToken(e){var t,s,i,r;$t.pushTransactionStack({});const n=e.receiverAddress,o=gs.state.address,a=Zt.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals));await Zt.sendTransaction({chainNamespace:"eip155",to:n,address:o,data:"0x",value:a??BigInt(0)}),Ot.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:(null==(t=gs.state.preferredAccountTypes)?void 0:t.eip155)===Wt.SMART_ACCOUNT,token:(null==(s=is.state.token)?void 0:s.symbol)||"",amount:e.sendTokenAmount,network:(null==(i=cs.state.activeCaipNetwork)?void 0:i.caipNetworkId)||""}}),null==(r=Zt._getClient())||r.updateBalance("eip155"),is.resetSend()},async sendERC20Token(e){$t.pushTransactionStack({onSuccess(){$t.replace("Account")}});const t=Zt.parseUnits(e.sendTokenAmount.toString(),Number(e.decimals));if(gs.state.address&&e.sendTokenAmount&&e.receiverAddress&&e.tokenAddress){const s=rt.getPlainAddress(e.tokenAddress);await Zt.writeContract({fromAddress:gs.state.address,tokenAddress:s,args:[e.receiverAddress,t??BigInt(0)],method:"transfer",abi:ye(s),chainNamespace:"eip155"}),is.resetSend()}},async sendSolanaToken(){var e;if(!is.state.sendTokenAmount||!is.state.receiverAddress)throw new Error("An amount and receiver address are required");$t.pushTransactionStack({onSuccess(){$t.replace("Account")}}),await Zt.sendTransaction({chainNamespace:"solana",to:is.state.receiverAddress,value:is.state.sendTokenAmount}),null==(e=Zt._getClient())||e.updateBalance("solana"),is.resetSend()},resetSend(){ss.token=void 0,ss.sendTokenAmount=void 0,ss.receiverAddress=void 0,ss.receiverProfileImageUrl=void 0,ss.receiverProfileName=void 0,ss.loading=!1,ss.tokenBalances=[]}}),rs={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},ns={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},os=Ye({chains:function(){const e=Ye({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}),as={state:os,subscribe:e=>Ze(os,()=>{e(os)}),subscribeKey:(e,t)=>et(os,e,t),subscribeChainProp(e,t,s){let i;return Ze(os.chains,()=>{var r;const n=s||os.activeChain;if(n){const s=null==(r=os.chains.get(n))?void 0:r[e];i!==s&&(i=s,t(s))}})},initialize(e,t,s){const{chainId:i,namespace:r}=it.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=lt.state.enableEmbedded?new Set([...a]):new Set([...(null==t?void 0:t.map(e=>e.chainNamespace))??[]]);0!==(null==e?void 0:e.length)&&o||(os.noAdapters=!0),os.noAdapters||(os.activeChain=null==o?void 0:o.namespace,os.activeCaipNetwork=n,cs.setChainNetworkData(null==o?void 0:o.namespace,{caipNetwork:n}),os.activeChain&&Xt.set({activeChain:null==o?void 0:o.namespace})),c.forEach(e=>{const i=null==t?void 0:t.filter(t=>t.chainNamespace===e);cs.state.chains.set(e,{namespace:e,networkState:Ye({...ns,caipNetwork:null==i?void 0:i[0]}),accountState:Ye(rs),caipNetworks:i??[],...s}),cs.setRequestedCaipNetworks(i??[],e)})},removeAdapter(e){var t,s;if(os.activeChain===e){const i=Array.from(os.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&&cs.setActiveCaipNetwork(e)}}os.chains.delete(e)},addAdapter(e,{networkControllerClient:t,connectionControllerClient:s},i){os.chains.set(e.namespace,{namespace:e.namespace,networkState:{...ns,caipNetwork:i[0]},accountState:rs,caipNetworks:i,connectionControllerClient:s,networkControllerClient:t}),cs.setRequestedCaipNetworks((null==i?void 0:i.filter(t=>t.chainNamespace===e.namespace))??[],e.namespace)},addNetwork(e){var t;const s=os.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),os.chains.set(e.chainNamespace,{...s,caipNetworks:i}),cs.setRequestedCaipNetworks(i,e.chainNamespace),Ft.filterByNamespace(e.chainNamespace,!0)}},removeNetwork(e,t){var s,i,r;const n=os.chains.get(e);if(n){const o=(null==(s=os.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])&&cs.setActiveCaipNetwork(n.caipNetworks[0]),os.chains.set(e,{...n,caipNetworks:a}),cs.setRequestedCaipNetworks(a||[],e),0===a.length&&Ft.filterByNamespace(e,!1)}},setAdapterNetworkState(e,t){const s=os.chains.get(e);s&&(s.networkState={...s.networkState||ns,...t},os.chains.set(e,s))},setChainAccountData(e,t,s=!0){if(!e)throw new Error("Chain is required to update chain account data");const i=os.chains.get(e);if(i){const s={...i.accountState||rs,...t};os.chains.set(e,{...i,accountState:s}),1!==os.chains.size&&os.activeChain!==e||(t.caipAddress&&(os.activeCaipAddress=t.caipAddress),gs.replaceState(s))}},setChainNetworkData(e,t){if(!e)return;const s=os.chains.get(e);if(s){const i={...s.networkState||ns,...t};os.chains.set(e,{...s,networkState:i})}},setAccountProp(e,t,s,i=!0){cs.setChainAccountData(s,{[e]:t},i),"status"===e&&"disconnected"===t&&s&&Ft.removeConnectorId(s)},setActiveNamespace(e){var t,s;os.activeChain=e;const i=e?os.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&&(os.activeCaipAddress=null==(s=null==i?void 0:i.accountState)?void 0:s.caipAddress,os.activeCaipNetwork=r,cs.setChainNetworkData(e,{caipNetwork:r}),it.setActiveCaipNetworkId(null==r?void 0:r.caipNetworkId),Xt.set({activeChain:e,selectedNetworkId:null==r?void 0:r.caipNetworkId}))},setActiveCaipNetwork(e){var t,s,i;if(!e)return;os.activeChain!==e.chainNamespace&&cs.setIsSwitchingNamespace(!0);const r=os.chains.get(e.chainNamespace);os.activeChain=e.chainNamespace,os.activeCaipNetwork=e,cs.setChainNetworkData(e.chainNamespace,{caipNetwork:e}),(null==(t=null==r?void 0:r.accountState)?void 0:t.address)?os.activeCaipAddress=`${e.chainNamespace}:${e.id}:${null==(s=null==r?void 0:r.accountState)?void 0:s.address}`:os.activeCaipAddress=void 0,cs.setAccountProp("caipAddress",os.activeCaipAddress,e.chainNamespace),r&&gs.replaceState(r.accountState),is.resetSend(),Xt.set({activeChain:os.activeChain,selectedNetworkId:null==(i=os.activeCaipNetwork)?void 0:i.caipNetworkId}),it.setActiveCaipNetworkId(e.caipNetworkId);cs.checkIfSupportedNetwork(e.chainNamespace)||!lt.state.enableNetworkSwitch||lt.state.allowUnsupportedChain||Zt.state.wcBasic||cs.showUnsupportedChainUI()},addCaipNetwork(e){var t;if(!e)return;const s=os.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!==cs.state.activeChain,i=null==(t=cs.getNetworkData(e))?void 0:t.caipNetwork,r=cs.getCaipNetworkByNamespace(e,null==i?void 0:i.id);s&&r&&await cs.switchActiveNetwork(r)},async switchActiveNetwork(e){var t;const s=cs.state.chains.get(cs.state.activeChain),i=!(null==(t=null==s?void 0:s.caipNetworks)?void 0:t.some(e=>{var t;return e.id===(null==(t=os.activeCaipNetwork)?void 0:t.id)})),r=cs.getNetworkControllerClient(e.chainNamespace);if(r){try{await r.switchCaipNetwork(e),i&&ws.close()}catch(n){$t.goBack()}Ot.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:e.caipNetworkId}})}},getNetworkControllerClient(e){const t=e||os.activeChain,s=os.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||os.activeChain;if(!t)throw new Error("Chain is required to get connection controller client");const s=os.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=os.activeChain;if(t&&(i=t),!i)return;const r=null==(s=os.chains.get(i))?void 0:s.accountState;return r?r[e]:void 0},getNetworkProp(e,t){var s;const i=null==(s=os.chains.get(t))?void 0:s.networkState;if(i)return i[e]},getRequestedCaipNetworks(e){const t=os.chains.get(e),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:i=[]}=(null==t?void 0:t.networkState)||{};
2return rt.sortRequestedNetworks(s,i)},getAllRequestedCaipNetworks(){const e=[];return os.chains.forEach(t=>{const s=cs.getRequestedCaipNetworks(t.namespace);e.push(...s)}),e},setRequestedCaipNetworks(e,t){cs.setAdapterNetworkState(t,{requestedCaipNetworks:e});const s=cs.getAllRequestedCaipNetworks().map(e=>e.chainNamespace),i=Array.from(new Set(s));Ft.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const e=[];return os.chains.forEach(t=>{const s=cs.getApprovedCaipNetworkIds(t.namespace);e.push(...s)}),e},getActiveCaipNetwork:()=>os.activeCaipNetwork,getActiveCaipAddress:()=>os.activeCaipAddress,getApprovedCaipNetworkIds(e){var t;const s=os.chains.get(e);return(null==(t=null==s?void 0:s.networkState)?void 0:t.approvedCaipNetworkIds)||[]},async setApprovedCaipNetworksData(e){const t=cs.getNetworkControllerClient(),s=await(null==t?void 0:t.getApprovedCaipNetworksData());cs.setAdapterNetworkState(e,{approvedCaipNetworkIds:null==s?void 0:s.approvedCaipNetworkIds,supportsAllNetworks:null==s?void 0:s.supportsAllNetworks})},checkIfSupportedNetwork(e,t){const s=t||os.activeCaipNetwork,i=cs.getRequestedCaipNetworks(e);return!i.length||(null==i?void 0:i.some(e=>e.id===(null==s?void 0:s.id)))},checkIfSupportedChainId(e){if(!os.activeChain)return!0;const t=cs.getRequestedCaipNetworks(os.activeChain);return null==t?void 0:t.some(t=>t.id===e)},setSmartAccountEnabledNetworks(e,t){cs.setAdapterNetworkState(t,{smartAccountEnabledNetworks:e})},checkIfSmartAccountEnabled(){var e;const t=ie.caipNetworkIdToNumber(null==(e=os.activeCaipNetwork)?void 0:e.caipNetworkId),s=os.activeChain;if(!s||!t)return!1;const i=cs.getNetworkProp("smartAccountEnabledNetworks",s);return Boolean(null==i?void 0:i.includes(Number(t)))},getActiveNetworkTokenAddress(){var e,t;const s=(null==(e=os.activeCaipNetwork)?void 0:e.chainNamespace)||"eip155";return`${s}:${(null==(t=os.activeCaipNetwork)?void 0:t.id)||1}:${st.NATIVE_TOKEN_ADDRESS[s]}`},showUnsupportedChainUI(){ws.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const e=os.activeCaipNetwork;return Boolean((null==e?void 0:e.chainNamespace)&&st.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(e.chainNamespace))},resetNetwork(e){cs.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");os.activeCaipAddress=void 0,cs.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"}),Ft.removeConnectorId(t)},setIsSwitchingNamespace(e){os.isSwitchingNamespace=e},getFirstCaipNetworkSupportsAuthConnector(){var e,t;const s=[];let i;if(os.chains.forEach(e=>{se.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=os.chains.get(r))?void 0:e.caipNetworks)?void 0:t[0]:void 0,i}},getAccountData(e){var t;return e?null==(t=cs.state.chains.get(e))?void 0:t.accountState:gs.state},getNetworkData(e){var t;const s=e||os.activeChain;if(s)return null==(t=cs.state.chains.get(s))?void 0:t.networkState},getCaipNetworkByNamespace(e,t){var s,i,r;if(!e)return;const n=cs.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=Ft.state.filterByNamespace;return(e?[os.chains.get(e)]:Array.from(os.chains.values())).flatMap(e=>(null==e?void 0:e.caipNetworks)||[]).map(e=>e.caipNetworkId)},getCaipNetworks:e=>e?cs.getRequestedCaipNetworks(e):cs.getAllRequestedCaipNetworks()},cs=ft(as),ls={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"}]}
2,{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"}]}]},ds=rt.getBlockchainApiUrl(),hs=Ye({clientId:null,api:new ot({baseUrl:ds,clientId:null}),supportedChains:{http:[],ws:[]}}),us={state:hs,async get(e){const{st:t,sv:s}=us.getSdkProperties(),i=lt.state.projectId,r={...e.params||{},st:t,sv:s,projectId:i};return hs.api.get({...e,params:r})},getSdkProperties(){const{sdkType:e,sdkVersion:t}=lt.state;return{st:e||"unknown",sv:t||"unknown"}},async isNetworkSupported(e){if(!e)return!1;try{hs.supportedChains.http.length||await us.getSupportedNetworks()}catch(gr){return!1}return hs.supportedChains.http.includes(e)},async getSupportedNetworks(){try{const e=await us.get({path:"v1/supported-chains"});return hs.supportedChains=e,e}catch{return hs.supportedChains}},async fetchIdentity({address:e,caipNetworkId:t}){if(!(await us.isNetworkSupported(t)))return{avatar:"",name:""};const s=it.getIdentityFromCacheForAddress(e);if(s)return s;const i=await us.get({path:`/v1/identity/${e}`,params:{sender:cs.state.activeCaipAddress?rt.getPlainAddress(cs.state.activeCaipAddress):void 0}});return it.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 us.isNetworkSupported(null==(o=cs.state.activeCaipNetwork)?void 0:o.caipNetworkId)?us.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 us.isNetworkSupported(null==(n=cs.state.activeCaipNetwork)?void 0:n.caipNetworkId)?us.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 us.isNetworkSupported(null==(t=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId)?us.get({path:"/v1/convert/tokens",params:{chainId:e}}):{tokens:[]}},async fetchTokenPrice({addresses:e}){var t;return await us.isNetworkSupported(null==(t=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId)?hs.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:e,projectId:lt.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:e,userAddress:t}){var s;return await us.isNetworkSupported(null==(s=cs.state.activeCaipNetwork)?void 0:s.caipNetworkId)?us.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}=us.getSdkProperties();if(!(await us.isNetworkSupported(null==(t=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId)))throw new Error("Network not supported for Gas Price");return us.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 us.isNetworkSupported(null==(n=cs.state.activeCaipNetwork)?void 0:n.caipNetworkId)))throw new Error("Network not supported for Swaps");return hs.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:e,eip155:{slippage:st.CONVERT_SLIPPAGE_TOLERANCE},projectId:lt.state.projectId,from:t,to:s,userAddress:i,disableEstimate:r}})},async generateApproveCalldata({from:e,to:t,userAddress:s}){var i;const{st:r,sv:n}=us.getSdkProperties();if(!(await us.isNetworkSupported(null==(i=cs.state.activeCaipNetwork)?void 0:i.caipNetworkId)))throw new Error("Network not supported for Swaps");return us.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"}
2,params:{userAddress:s,from:e,to:t,st:r,sv:n}})},async getBalance(e,t,s){var i;const{st:r,sv:n}=us.getSdkProperties();if(!(await us.isNetworkSupported(null==(i=cs.state.activeCaipNetwork)?void 0:i.caipNetworkId)))return Vt.showError("Token Balance Unavailable"),{balances:[]};const o=`${t}:${e}`,a=it.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await us.get({path:`/v1/account/${e}/balance`,params:{currency:"usd",chainId:t,forceUpdate:s,st:r,sv:n}});return it.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(e){var t;return await us.isNetworkSupported(null==(t=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId)?us.get({path:`/v1/profile/account/${e}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:e}){var t;return await us.isNetworkSupported(null==(t=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId)?us.get({path:`/v1/profile/reverse/${e}`,params:{sender:gs.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(e){var t;return await us.isNetworkSupported(null==(t=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId)?us.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 us.isNetworkSupported(null==(r=cs.state.activeCaipNetwork)?void 0:r.caipNetworkId)?hs.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 us.isNetworkSupported(null==(n=cs.state.activeCaipNetwork)?void 0:n.caipNetworkId)))return"";return(await hs.api.post({path:"/v1/generators/onrampurl",params:{projectId:lt.state.projectId},body:{destinationWallets:e,defaultNetwork:s,partnerUserId:t,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url},async getOnrampOptions(){var e;if(!(await us.isNetworkSupported(null==(e=cs.state.activeCaipNetwork)?void 0:e.caipNetworkId)))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await us.get({path:"/v1/onramp/options"})}catch(gr){return ls}},async getOnrampQuote({purchaseCurrency:e,paymentCurrency:t,amount:s,network:i}){var r;try{if(!(await us.isNetworkSupported(null==(r=cs.state.activeCaipNetwork)?void 0:r.caipNetworkId)))return null;return await hs.api.post({path:"/v1/onramp/quote",params:{projectId:lt.state.projectId},body:{purchaseCurrency:e,paymentCurrency:t,amount:s,network:i}})}catch(gr){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 us.isNetworkSupported(null==(t=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId)?us.get({path:`/v1/sessions/${e}`}):[]},async revokeSmartSession(e,t,s){var i;return await us.isNetworkSupported(null==(i=cs.state.activeCaipNetwork)?void 0:i.caipNetworkId)?hs.api.post({path:`/v1/sessions/${e}/revoke`,params:{projectId:lt.state.projectId},body:{pci:t,signature:s}}):{success:!1}},setClientId(e){hs.clientId=e,hs.api=new ot({baseUrl:ds,clientId:e})}},ps=Ye({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),gs=ft({state:ps,replaceState(e){e&&Object.assign(ps,Xe(e))},subscribe:e=>cs.subscribeChainProp("accountState",t=>{if(t)return e(t)}),subscribeKey(e,t,s){let i;return cs.subscribeChainProp("accountState",s=>{if(s){const r=s[e];i!==r&&(i=r,t(r))}},s)},setStatus(e,t){cs.setAccountProp("status",e,t)},getCaipAddress:e=>cs.getAccountProp("caipAddress",e),setCaipAddress(e,t){const s=e?rt.getPlainAddress(e):void 0;t===cs.state.activeChain&&(cs.state.activeCaipAddress=e),cs.setAccountProp("caipAddress",e,t),cs.setAccountProp("address",s,t)},setBalance(e,t,s){cs.setAccountProp("balance",e,s),cs.setAccountProp("balanceSymbol",t,s)},setProfileName(e,t){cs.setAccountProp("profileName",e,t)},setProfileImage(e,t){cs.setAccountProp("profileImage",e,t)},setUser(e,t){cs.setAccountProp("user",e,t)},setAddressExplorerUrl(e,t){cs.setAccountProp("addressExplorerUrl",e,t)},setSmartAccountDeployed(e,t){cs.setAccountProp("smartAccountDeployed",e,t)},setCurrentTab(e){cs.setAccountProp("currentTab",e,cs.state.activeChain)},setTokenBalance(e,t){e&&cs.setAccountProp("tokenBalance",e,t)},setShouldUpdateToAddress(e,t){cs.setAccountProp("shouldUpdateToAddress",e,t)},setAllAccounts(e,t){cs.setAccountProp("allAccounts",e,t)}
2,addAddressLabel(e,t,s){const i=cs.getAccountProp("addressLabels",s)||new Map;i.set(e,t),cs.setAccountProp("addressLabels",i,s)},removeAddressLabel(e,t){const s=cs.getAccountProp("addressLabels",t)||new Map;s.delete(e),cs.setAccountProp("addressLabels",s,t)},setConnectedWalletInfo(e,t){cs.setAccountProp("connectedWalletInfo",e,t,!1)},setPreferredAccountType(e,t){cs.setAccountProp("preferredAccountTypes",{...ps.preferredAccountTypes,[t]:e},t)},setPreferredAccountTypes(e){ps.preferredAccountTypes=e},setSocialProvider(e,t){e&&cs.setAccountProp("socialProvider",e,t)},setSocialWindow(e,t){cs.setAccountProp("socialWindow",e?Xe(e):void 0,t)},setFarcasterUrl(e,t){cs.setAccountProp("farcasterUrl",e,t)},async fetchTokenBalance(e){var t,s;ps.balanceLoading=!0;const i=null==(t=cs.state.activeCaipNetwork)?void 0:t.caipNetworkId,r=null==(s=cs.state.activeCaipNetwork)?void 0:s.chainNamespace,n=cs.state.activeCaipAddress,o=n?rt.getPlainAddress(n):void 0;if(ps.lastRetry&&!rt.isAllowedRetry(ps.lastRetry,30*st.ONE_SEC_MS))return ps.balanceLoading=!1,[];try{if(o&&i&&r){const e=(await us.getBalance(o,i)).balances.filter(e=>"0"!==e.quantity.decimals);return gs.setTokenBalance(e,r),ps.lastRetry=void 0,ps.balanceLoading=!1,e}}catch(a){ps.lastRetry=Date.now(),null==e||e(a),Vt.showError("Token Balance Unavailable")}finally{ps.balanceLoading=!1}return[]},resetAccount(e){cs.resetAccount(e)}}),ms={onSwitchNetwork({network:e,ignoreSwitchConfirmation:t=!1}){const s=cs.state.activeCaipNetwork,i=$t.state.data;if(e.id===(null==s?void 0:s.id))return;const r=gs.getCaipAddress(cs.state.activeChain),n=e.chainNamespace!==cs.state.activeChain,o=gs.getCaipAddress(e.chainNamespace),a=Ft.getConnectorId(cs.state.activeChain)===se.CONNECTOR_ID.AUTH,c=se.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(t=>t===e.chainNamespace);t||a&&c?$t.push("SwitchNetwork",{...i,network:e}):r&&n&&!o?$t.push("SwitchActiveChain",{switchToChain:e.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:e}):$t.push("SwitchNetwork",{...i,network:e})}},fs=Ye({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),ws=ft({state:fs,subscribe:e=>Ze(fs,()=>e(fs)),subscribeKey:(e,t)=>et(fs,e,t),async open(e){var t,s;const i="connected"===gs.state.status,r=null==e?void 0:e.namespace,n=cs.state.activeChain,o=r&&r!==n,a=null==(t=cs.getAccountData(null==e?void 0:e.namespace))?void 0:t.caipAddress;if(Zt.state.wcBasic?Ut.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await Ut.prefetch({fetchConnectorImages:!i,fetchFeaturedWallets:!i,fetchRecommendedWallets:!i}),Ft.setFilterByNamespace(null==e?void 0:e.namespace),ws.setLoading(!0,r),r&&o){const e=(null==(s=cs.getNetworkData(r))?void 0:s.caipNetwork)||cs.getRequestedCaipNetworks(r)[0];e&&ms.onSwitchNetwork({network:e,ignoreSwitchConfirmation:!0})}else{const t=cs.state.noAdapters;lt.state.manualWCControl||t&&!a?rt.isMobile()?$t.reset("AllWallets"):$t.reset("ConnectingWalletConnectBasic"):(null==e?void 0:e.view)?$t.reset(e.view,e.data):a?$t.reset("Account"):$t.reset("Connect")}fs.open=!0,Xt.set({open:!0}),Ot.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:Boolean(a)}})},close(){const e=lt.state.enableEmbedded,t=Boolean(cs.state.activeCaipAddress);fs.open&&Ot.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:t}}),fs.open=!1,$t.reset("Connect"),ws.clearLoading(),e?t?$t.replace("Account"):$t.push("Connect"):Xt.set({open:!1}),Zt.resetUri()},setLoading(e,t){t&&fs.loadingNamespaceMap.set(t,e),fs.loading=e,Xt.set({loading:e})},clearLoading(){fs.loadingNamespaceMap.clear(),fs.loading=!1},shake(){fs.shake||(fs.shake=!0,setTimeout(()=>{fs.shake=!1},500))}}),vs={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"}]},ys={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},bs=Ye({providers:tt,selectedProvider:null,error:null,purchaseCurrency:vs,paymentCurrency:ys,purchaseCurrencies:[vs],paymentCurrencies:[],quotesLoading:!1}),Es=ft({state:bs,subscribe:e=>Ze(bs,()=>e(bs)),subscribeKey:(e,t)=>et(bs,e,t),setSelectedProvider(e){if(e&&"meld"===e.name){const t=cs.state.activeChain===se.CHAIN.SOLANA?"SOL":"USDC",s=gs.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",lt.state.projectId),bs.selectedProvider={...e,url:i.toString()}}else bs.selectedProvider=e},setOnrampProviders(e){if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=e,s=tt.filter(e=>t.includes(e.name));bs.providers=s}else bs.providers=[]},setPurchaseCurrency(e){bs.purchaseCurrency=e},setPaymentCurrency(e){bs.paymentCurrency=e},setPurchaseAmount(e){Es.state.purchaseAmount=e},setPaymentAmount(e){Es.state.paymentAmount=e},async getAvailableCurrencies(){const e=await us.getOnrampOptions();bs.purchaseCurrencies=e.purchaseCurrencies,bs.paymentCurrencies=e.paymentCurrencies,bs.paymentCurrency=e.paymentCurrencies[0]||ys,bs.purchaseCurrency=e.purchaseCurrencies[0]||vs,await Ut.fetchCurrencyImages(e.paymentCurrencies.map(e=>e.id)),await Ut.fetchTokenImages(e.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){var e,t;bs.quotesLoading=!0;try{const s=await us.getOnrampQuote({purchaseCurrency:bs.purchaseCurrency,paymentCurrency:bs.paymentCurrency,amount:(null==(e=bs.paymentAmount)?void 0:e.toString())||"0",network:null==(t=bs.purchaseCurrency)?void 0:t.symbol});return bs.quotesLoading=!1,bs.purchaseAmount=Number(null==s?void 0:s.purchaseAmount.amount),s}catch(s){return bs.error=s.message,bs.quotesLoading=!1,null}finally{bs.quotesLoading=!1}},resetState(){bs.selectedProvider=null,bs.error=null,bs.purchaseCurrency=vs,bs.paymentCurrency=ys,bs.purchaseCurrencies=[vs],bs.paymentCurrencies=[],bs.paymentAmount=void 0,bs.purchaseAmount=void 0,bs.quotesLoading=!1}}),Cs=2147483648,Is={convertEVMChainIdToCoinType(e){if(e>=Cs)throw new Error("Invalid chainId");return(Cs|e)>>>0}},Ns=Ye({suggestions:[],loading:!1}),As={state:Ns,subscribe:e=>Ze(Ns,()=>e(Ns)),subscribeKey:(e,t)=>et(Ns,e,t),async resolveName(e){var t,s;try{return await us.lookupEnsName(e)}catch(gr){throw new Error((null==(s=null==(t=null==gr?void 0:gr.reasons)?void 0:t[0])?void 0:s.description)||"Error resolving name")}},async isNameRegistered(e){try{return await us.lookupEnsName(e),!0}catch{return!1}},async getSuggestions(e){try{Ns.loading=!0,Ns.suggestions=[];const t=await us.getEnsNameSuggestions(e);return Ns.suggestions=t.suggestions.map(e=>({...e,name:e.name}))||[],Ns.suggestions}catch(gr){const t=Ss.parseEnsApiError(gr,"Error fetching name suggestions");throw new Error(t)}finally{Ns.loading=!1}},async getNamesForAddress(e){try{if(!cs.state.activeCaipNetwork)return[];
2const t=it.getEnsFromCacheForAddress(e);if(t)return t;const s=await us.reverseLookupEnsName({address:e});return it.updateEnsCache({address:e,ens:s,timestamp:Date.now()}),s}catch(gr){const t=Ss.parseEnsApiError(gr,"Error fetching names for address");throw new Error(t)}},async registerName(e){const t=cs.state.activeCaipNetwork;if(!t)throw new Error("Network not found");const s=gs.state.address,i=Ft.getAuthConnector();if(!s||!i)throw new Error("Address or auth connector not found");Ns.loading=!0;try{const i=JSON.stringify({name:e,attributes:{},timestamp:Math.floor(Date.now()/1e3)});$t.pushTransactionStack({onCancel(){$t.replace("RegisterAccountName")}});const r=await Zt.signMessage(i);Ns.loading=!1;const n=t.id;if(!n)throw new Error("Network not found");const o=Is.convertEVMChainIdToCoinType(Number(n));await us.registerEnsName({coinType:o,address:s,signature:r,message:i}),gs.setProfileName(e,t.chainNamespace),$t.replace("RegisterAccountNameSuccess")}catch(gr){const s=Ss.parseEnsApiError(gr,`Error registering name ${e}`);throw $t.replace("RegisterAccountName"),new Error(s)}finally{Ns.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}},Ss=ft(As);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 extends c{constructor(e){super(),this.opts=e,ks(this,"protocol","wc"),ks(this,"version",2)}};var Os=Object.defineProperty,Ts=(e,t,s)=>((e,t,s)=>t in e?Os(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,t+"",s);let xs=class extends c{constructor(e,t){super(),this.core=e,this.logger=t,Ts(this,"records",new Map)}},Rs=class{constructor(e,t){this.logger=e,this.core=t}},Us=class extends c{constructor(e,t){super(),this.relayer=e,this.logger=t}},Ds=class extends c{constructor(e){super()}},$s=class{constructor(e,t,s,i){this.core=e,this.logger=t,this.name=s}},Ms=class extends c{constructor(e,t){super(),this.relayer=e,this.logger=t}},Ls=class extends c{constructor(e,t){super(),this.core=e,this.logger=t}},js=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},qs=class{constructor(e,t){this.projectId=e,this.logger=t}},Bs=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var Fs=Object.defineProperty,Ws=(e,t,s)=>((e,t,s)=>t in e?Fs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let zs=class{constructor(e){this.opts=e,Ws(this,"protocol","wc"),Ws(this,"version",2)}},Hs=class{constructor(e){this.client=e}};var Vs={};function Ks(e){const[t,s]=e.split(":");return{namespace:t,reference:s}}function Gs(e,t){return e.includes(":")?[e]:t.chains||[]}var Js=Object.defineProperty,Ys=Object.defineProperties,Zs=Object.getOwnPropertyDescriptors,Qs=Object.getOwnPropertySymbols,Xs=Object.prototype.hasOwnProperty,ei=Object.prototype.propertyIsEnumerable,ti=(e,t,s)=>t in e?Js(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,si=(e,t)=>{for(var s in t||(t={}))Xs.call(t,s)&&ti(e,s,t[s]);if(Qs)for(var s of Qs(t))ei.call(t,s)&&ti(e,s,t[s]);return e};const ii="react-native",ri="node",ni="browser",oi="unknown",ai="js";function ci(){return typeof t<"u"&&typeof t.versions<"u"&&typeof t.versions.node<"u"}function li(){return!p.getDocument()&&!!p.getNavigator()&&"ReactNative"===navigator.product}function di(){return!ci()&&!!p.getNavigator()&&!!p.getDocument()}function hi(){return li()?ii:ci()?ri:di()?ni:oi}function ui(){var e;try{return li()&&typeof s<"u"&&typeof(null==s?void 0:s.Application)<"u"?null==(e=s.Application)?void 0:e.applicationId:void 0}catch{return}}function pi(e){var t,s;const i=gi();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)=>Ys(e,Zs(t)))(si(si({},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}}
2function gi(){return l.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function mi(e,t,r){const n=function(){if(hi()===ii&&typeof s<"u"&&typeof(null==s?void 0:s.Platform)<"u"){const{OS:e,Version:t}=s.Platform;return[e,t].join("-")}const e=i();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("-")}(),o=function(){var e;const t=hi();return t===ni?[t,(null==(e=p.getLocation())?void 0:e.host)||"unknown"].join(":"):t}();return[[e,t].join("-"),[ai,r].join("-"),n,o].join("/")}function fi({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:mi(e,t,i),projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=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]+"?"+h}function wi(e,t){return e.filter(e=>t.includes(e)).length===e.length}function vi(e){return Object.fromEntries(e.entries())}function yi(e){return new Map(Object.entries(e))}function bi(e=u.FIVE_MINUTES,t){const s=u.toMiliseconds(e||u.FIVE_MINUTES);let i,r,n,o;return{resolve:e=>{n&&i&&(clearTimeout(n),i(e),o=Promise.resolve(e))},reject:e=>{n&&r&&(clearTimeout(n),r(e))},done:()=>new Promise((e,a)=>{if(o)return e(o);n=setTimeout(()=>{const e=new Error(t);o=Promise.reject(e),a(e)},s),i=e,r=a})}}function Ei(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 Ci(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 Ii(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 Ni(e,t){return u.fromMiliseconds(Date.now()+u.toMiliseconds(e))}function Ai(e){return Date.now()>=u.toMiliseconds(e)}function Si(e,t){return`${e}${t?`:${t}`:""}`}function Pi(e=[],t=[]){return[...new Set([...e,...t])]}async function ki({id:e,topic:t,wcDeepLink:i}){var n;try{if(!i)return;const o="string"==typeof i?JSON.parse(i):i,a=null==o?void 0:o.href;if("string"!=typeof a)return;const c=function(e,t,s){const i=`requestId=${t}&sessionTopic=${s}`;e.endsWith("/")&&(e=e.slice(0,-1));let n=`${e}`;if(e.startsWith("https://t.me")){n=`${n}${e.includes("?")?"&startapp=":"?startapp="}${function(e,t=!1){const s=r.from(e).toString("base64");return t?s.replace(/[=]/g,""):s}(i,!0)}`}else n=`${n}/wc?${i}`;return n}(a,e,t),l=hi();if(l===ni){if(null==(n=p.getDocument())||!n.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")}(c)}else l===ii&&typeof(null==s?void 0:s.Linking)<"u"&&await s.Linking.openURL(c)}catch(o){}}function _i(e,t){if(!e.includes(t))return null;const s=e.split(/([&,?,=])/),i=s.indexOf(t);return s[i+2]}function Oi(){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 Ti(){return typeof t<"u"&&"true"===Vs.IS_VITEST}function xi(e){return r.from(e,"base64").toString("utf-8")}function Ri(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Ui(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 Di(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Ri(e.outputLen),Ri(e.blockLen)}function $i(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 Mi(e,t){Ui(e);const s=t.outputLen;if(e.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const Li=BigInt(2**32-1),ji=BigInt(32);function qi(e,t=!1){return t?{h:Number(e&Li),l:Number(e>>ji&Li)}:{h:0|Number(e>>ji&Li),l:0|Number(e&Li)}}const Bi="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Fi(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Wi(e,t){return e<<32-t|e>>>t}const zi=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];function Hi(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Vi(e){for(let t=0;t<e.length;t++)e[t]=Hi(e[t])}function Ki(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)),Ui(e),e}let Gi=class{clone(){return this._cloneInto()}};function Ji(e){const t=t=>e().update(Ki(t)).digest(),s=e();return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=()=>e(),t}function Yi(e=32){if(Bi&&"function"==typeof Bi.getRandomValues)return Bi.getRandomValues(new Uint8Array(e));if(Bi&&"function"==typeof Bi.randomBytes)return Bi.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}const Zi=[],Qi=[],Xi=[],er=BigInt(0),tr=BigInt(1),sr=BigInt(2),ir=BigInt(7),rr=BigInt(256),nr=BigInt(113);for(let lv=0,dv=tr,hv=1,uv=0;lv<24;lv++){[hv,uv]=[uv,(2*hv+3*uv)%5],Zi.push(2*(5*uv+hv)),Qi.push((lv+1)*(lv+2)/2%64);let e=er;for(let t=0;t<7;t++)dv=(dv<<tr^(dv>>ir)*nr)%rr,dv&sr&&(e^=tr<<(tr<<BigInt(t))-tr);Xi.push(e)}const[or,ar]=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}=qi(e[r],t);[s[r],i[r]]=[n,o]}return[s,i]}(Xi,!0),cr=(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),lr=(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 dr=class e extends Gi{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,Ri(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(){zi||Vi(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=cr(n,o,1)^s[t],c=lr(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=Qi[s],n=cr(t,r,i),o=lr(t,r,i),a=Zi[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]^=or[i],e[1]^=ar[i]}s.fill(0)}(this.state32,this.rounds),zi||Vi(this.state32),this.posOut=0,this.pos=0}update(e){$i(this);const{blockLen:t,state:s}=this,i=(e=Ki(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){$i(this,!1),Ui(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 Ri(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Mi(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 hr=(pr=1,gr=136,mr=32,Ji(()=>new dr(gr,pr,mr))),ur="https://rpc.walletconnect.org/v1";var pr,gr,mr;function fr(e){const t=`�Ethereum Signed Message:\n${e.length}`,s=(new TextEncoder).encode(t+e);return"0x"+r.from(hr(s)).toString("hex")}async function wr(e,t,s,i,r,n){switch(s.t){case"eip191":return await async function(e,t,s){return(await v({hash:fr(t),signature:s})).toLowerCase()===e.toLowerCase()}(e,t,s.s);case"eip1271":return await async function(e,t,s,i,r,n){const o=Ks(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+fr(t).substring(2)+a+c+l,h=await fetch(`${n||ur}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:vr(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:d},"latest"]})}),{result:u}=await h.json();return!!u&&u.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 vr(){return Date.now()+Math.floor(1e3*Math.random())}var yr=Object.defineProperty,br=Object.defineProperties,Er=Object.getOwnPropertyDescriptors,Cr=Object.getOwnPropertySymbols,Ir=Object.prototype.hasOwnProperty,Nr=Object.prototype.propertyIsEnumerable,Ar=(e,t,s)=>t in e?yr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;const Sr=e=>null==e?void 0:e.split(":"),Pr=e=>{const t=e&&Sr(e);if(t)return t[2]+":"+t[3]},kr=e=>{const t=e&&Sr(e);if(t)return t.pop()};async function _r(e){const{cacao:t,projectId:s}=e,{s:i,p:r}=t,n=Or(r,r.iss),o=kr(r.iss);return await wr(o,n,i,Pr(r.iss),s)}const Or=(e,t)=>{const s=`${e.domain} wants you to sign in with your Ethereum account:`,i=kr(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}
2`,o=`Version: ${e.version}`,a=`Chain ID: ${(e=>{const t=e&&Sr(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,h=e.nbf?`Not Before: ${e.nbf}`:void 0,u=e.requestId?`Request ID: ${e.requestId}`:void 0,p=e.resources?`Resources:${e.resources.map(e=>`\n- ${e}`).join("")}`:void 0,g=jr(e.resources);if(g){r=function(e="",t){Tr(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,Ur(g))}return[s,i,"",r,"",n,o,a,c,l,d,h,u,p].filter(e=>null!=e).join("\n")};function Tr(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 xr(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 Rr(e){return Tr(e),`urn:recap:${function(e){return r.from(JSON.stringify(e)).toString("base64")}(e).replace(/=/g,"")}`}function Ur(e){const t=function(e){return JSON.parse(r.from(e,"base64").toString("utf-8"))}(e.replace("urn:recap:",""));return Tr(t),t}function Dr(e,t,s){const i=function(e,t,s,i={}){return null==s||s.sort((e,t)=>e.localeCompare(t)),{att:{[e]:xr(t,s,i)}}}(e,t,s);return Rr(i)}function $r(e,t){const s=function(e,t){Tr(e),Tr(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)=>br(e,Er(t)))(((e,t)=>{for(var s in t||(t={}))Ir.call(t,s)&&Ar(e,s,t[s]);if(Cr)for(var s of Cr(t))Nr.call(t,s)&&Ar(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}(Ur(e),Ur(t));return Rr(s)}function Mr(e){var t;const s=Ur(e);Tr(s);const i=null==(t=s.att)?void 0:t.eip155;return i?Object.keys(i).map(e=>e.split("/")[1]):[]}function Lr(e){const t=Ur(e);Tr(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 jr(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 qr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Br(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Fr(e,...t){if(!Br(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 Wr(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 zr(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}const Hr=e=>new 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 Vr(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(!Br(e))throw new Error("Uint8Array expected, got "+typeof e);e=Jr(e)}return e}function Kr(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 Gr(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 Jr(e){return Uint8Array.from(e)}function Yr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Zr=e=>Uint8Array.from(e.split("").map(e=>
2e.charCodeAt(0))),Qr=Zr("expand 16-byte k"),Xr=Zr("expand 32-byte k"),en=Hr(Qr),tn=Hr(Xr);function sn(e,t){return e<<t|e>>>32-t}function rn(e){return e.byteOffset%4==0}const nn=2**32-1,on=new Uint32Array;const an=(e,t)=>255&e[t++]|(255&e[t++])<<8;class cn{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,Fr(e=Vr(e),32);const t=an(e,0),s=an(e,2),i=an(e,4),r=an(e,6),n=an(e,8),o=an(e,10),a=an(e,12),c=an(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]=an(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],h=n[5],u=n[6],p=n[7],g=n[8],m=n[9],f=an(e,t+0),w=an(e,t+2),v=an(e,t+4),y=an(e,t+6),b=an(e,t+8),E=an(e,t+10),C=an(e,t+12),I=an(e,t+14);let N=r[0]+(8191&f),A=r[1]+(8191&(f>>>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)),T=r[7]+(8191&(E>>>11|C<<5)),x=r[8]+(8191&(C>>>8|I<<8)),R=r[9]+(I>>>5|i),U=0,D=U+N*o+A*(5*m)+S*(5*g)+P*(5*p)+k*(5*u);U=D>>>13,D&=8191,D+=_*(5*h)+O*(5*d)+T*(5*l)+x*(5*c)+R*(5*a),U+=D>>>13,D&=8191;let $=U+N*a+A*o+S*(5*m)+P*(5*g)+k*(5*p);U=$>>>13,$&=8191,$+=_*(5*u)+O*(5*h)+T*(5*d)+x*(5*l)+R*(5*c),U+=$>>>13,$&=8191;let M=U+N*c+A*a+S*o+P*(5*m)+k*(5*g);U=M>>>13,M&=8191,M+=_*(5*p)+O*(5*u)+T*(5*h)+x*(5*d)+R*(5*l),U+=M>>>13,M&=8191;let L=U+N*l+A*c+S*a+P*o+k*(5*m);U=L>>>13,L&=8191,L+=_*(5*g)+O*(5*p)+T*(5*u)+x*(5*h)+R*(5*d),U+=L>>>13,L&=8191;let j=U+N*d+A*l+S*c+P*a+k*o;U=j>>>13,j&=8191,j+=_*(5*m)+O*(5*g)+T*(5*p)+x*(5*u)+R*(5*h),U+=j>>>13,j&=8191;let q=U+N*h+A*d+S*l+P*c+k*a;U=q>>>13,q&=8191,q+=_*o+O*(5*m)+T*(5*g)+x*(5*p)+R*(5*u),U+=q>>>13,q&=8191;let B=U+N*u+A*h+S*d+P*l+k*c;U=B>>>13,B&=8191,B+=_*a+O*o+T*(5*m)+x*(5*g)+R*(5*p),U+=B>>>13,B&=8191;let F=U+N*p+A*u+S*h+P*d+k*l;U=F>>>13,F&=8191,F+=_*c+O*a+T*o+x*(5*m)+R*(5*g),U+=F>>>13,F&=8191;let W=U+N*g+A*p+S*u+P*h+k*d;U=W>>>13,W&=8191,W+=_*l+O*c+T*a+x*o+R*(5*m),U+=W>>>13,W&=8191;let z=U+N*m+A*g+S*p+P*u+k*h;U=z>>>13,z&=8191,z+=_*d+O*l+T*c+x*a+R*o,U+=z>>>13,z&=8191,U=(U<<2)+U|0,U=U+D|0,D=8191&U,U>>>=13,$+=U,r[0]=D,r[1]=$,r[2]=M,r[3]=L,r[4]=j,r[5]=q,r[6]=B,r[7]=F,r[8]=W,r[9]=z}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;Yr(s)}update(e){Wr(this);const{buffer:t,blockLen:s}=this,i=(e=Vr(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(){Yr(this.h,this.r,this.buffer,this.pad)}digestInto(e){Wr(this),function(e,t){Fr(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 ln=function(e){const t=(t,s)=>e(s).update(Vr(t)).digest(),s=e(new Uint8Array(32));return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=t=>e(t),t}(e=>
2new cn(e));const dn=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 qr(r),qr(o),zr(n),zr(s),(t,a,c,l,d=0)=>{Fr(t),Fr(a),Fr(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),Fr(l),qr(d),d<0||d>=nn)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const u=[];let p,g,m=t.length;if(32===m)u.push(p=Jr(t)),g=tn;else{if(16!==m||!s)throw new Error(`arx: invalid 32-byte key, got length=${m}`);p=new Uint8Array(32),p.set(t),p.set(t,16),g=en,u.push(p)}rn(a)||u.push(a=Jr(a));const f=Hr(p);if(i){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");i(g,f,Hr(a.subarray(0,16)),f),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,u.push(a)}const v=Hr(a);return function(e,t,s,i,r,n,o,a){const c=r.length,l=new Uint8Array(64),d=Hr(l),h=rn(r)&&rn(n),u=h?Hr(r):on,p=h?Hr(n):on;for(let g=0;g<c;o++){if(e(t,s,i,d,o,a),o>=nn)throw new Error("arx: counter overflow");const m=Math.min(64,c-g);if(h&&64===m){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]=u[t]^d[s];g+=64;continue}for(let e,t=0;t<m;t++)e=g+t,n[e]=r[e]^l[t];g+=m}}(e,g,f,v,c,l,d,o),Yr(...u),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],h=t[1],u=t[2],p=t[3],g=t[4],m=t[5],f=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=h,k=u,_=p,O=g,T=m,x=f,R=w,U=v,D=y,$=b,M=E;for(let j=0;j<n;j+=2)C=C+S|0,U=sn(U^C,16),O=O+U|0,S=sn(S^O,12),C=C+S|0,U=sn(U^C,8),O=O+U|0,S=sn(S^O,7),I=I+P|0,D=sn(D^I,16),T=T+D|0,P=sn(P^T,12),I=I+P|0,D=sn(D^I,8),T=T+D|0,P=sn(P^T,7),N=N+k|0,$=sn($^N,16),x=x+$|0,k=sn(k^x,12),N=N+k|0,$=sn($^N,8),x=x+$|0,k=sn(k^x,7),A=A+_|0,M=sn(M^A,16),R=R+M|0,_=sn(_^R,12),A=A+_|0,M=sn(M^A,8),R=R+M|0,_=sn(_^R,7),C=C+P|0,M=sn(M^C,16),x=x+M|0,P=sn(P^x,12),C=C+P|0,M=sn(M^C,8),x=x+M|0,P=sn(P^x,7),I=I+k|0,U=sn(U^I,16),R=R+U|0,k=sn(k^R,12),I=I+k|0,U=sn(U^I,8),R=R+U|0,k=sn(k^R,7),N=N+_|0,D=sn(D^N,16),O=O+D|0,_=sn(_^O,12),N=N+_|0,D=sn(D^N,8),O=O+D|0,_=sn(_^O,7),A=A+S|0,$=sn($^A,16),T=T+$|0,S=sn(S^T,12),A=A+S|0,$=sn($^A,8),T=T+$|0,S=sn(S^T,7);let L=0;i[L++]=o+C|0,i[L++]=a+I|0,i[L++]=c+N|0,i[L++]=l+A|0,i[L++]=d+S|0,i[L++]=h+P|0,i[L++]=u+k|0,i[L++]=p+_|0,i[L++]=g+O|0,i[L++]=m+T|0,i[L++]=f+x|0,i[L++]=w+R|0,i[L++]=v+U|0,i[L++]=y+D|0,i[L++]=b+$|0,i[L++]=E+M|0},{counterRight:!1,counterLength:4,allowShortKeys:!1}),hn=new Uint8Array(16),un=(e,t)=>{e.update(t);const s=t.length%16;s&&e.update(hn.subarray(s))},pn=new Uint8Array(32);function gn(e,t,s,i,r){const n=e(t,s,pn),o=ln.create(n);r&&un(o,r),un(o,i);const a=new Uint8Array(16),c=(e=>
2new DataView(e.buffer,e.byteOffset,e.byteLength))(a);Gr(c,0,BigInt(r?r.length:0),!0),Gr(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return Yr(n,a),l}const mn=((e,t)=>{function s(s,...i){if(Fr(s),void 0!==e.nonceLength){const t=i[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?Fr(t):Fr(t,e.nonceLength)}const r=e.tagLength;r&&void 0!==i[1]&&Fr(i[1]);const n=t(s,...i),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Fr(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,Fr(e),o(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(Fr(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=Kr(o+16,n,!1)).set(r);const a=n.subarray(0,-16);e(t,s,a,a,1);const c=gn(e,t,s,a,i);return n.set(c,o),Yr(c),n},decrypt(r,n){n=Kr(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=gn(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),Yr(c),n}}))(dn));let fn=class extends Gi{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Di(e);const s=Ki(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 $i(this),this.iHash.update(e),this}digestInto(e){$i(this),Ui(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 wn=(e,t,s)=>new fn(e,t).update(s).digest();wn.create=(e,t)=>new fn(e,t);const vn=new Uint8Array([0]),yn=new Uint8Array;const bn=(e,t,s,i,r)=>function(e,t,s,i=32){if(Di(e),Ri(i),i>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/e.outputLen);void 0===s&&(s=yn);const n=new Uint8Array(r*e.outputLen),o=wn.create(e,t),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)vn[0]=l+1,a.update(0===l?yn:c).update(s).update(vn).digestInto(c),n.set(c,e.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),vn.fill(0),n.slice(0,i)}(e,function(e,t,s){return Di(e),void 0===s&&(s=new Uint8Array(e.outputLen)),wn(e,Ki(s),Ki(t))}(e,t,s),i,r);function En(e,t,s){return e&t^~e&s}function Cn(e,t,s){return e&t^e&s^t&s}let In=class extends Gi{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=Fi(this.buffer)}update(e){$i(this);const{view:t,buffer:s,blockLen:i}=this,r=(e=Ki(e)).length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){const t=Fi(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){$i(this),Mi(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=Fi(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 2-3
2digest(){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 Nn=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]),An=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Sn=new Uint32Array(64);class Pn extends In{constructor(){super(64,32,8,!1),this.A=0|An[0],this.B=0|An[1],this.C=0|An[2],this.D=0|An[3],this.E=0|An[4],this.F=0|An[5],this.G=0|An[6],this.H=0|An[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)Sn[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const e=Sn[d-15],t=Sn[d-2],s=Wi(e,7)^Wi(e,18)^e>>>3,i=Wi(t,17)^Wi(t,19)^t>>>10;Sn[d]=i+Sn[d-7]+s+Sn[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+(Wi(o,6)^Wi(o,11)^Wi(o,25))+En(o,a,c)+Nn[d]+Sn[d]|0,t=(Wi(s,2)^Wi(s,13)^Wi(s,22))+Cn(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(){Sn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const kn=Ji(()=>new Pn),_n=BigInt(0),On=BigInt(1),Tn=BigInt(2); 3/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function xn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Rn(e){if(!xn(e))throw new Error("Uint8Array expected")}function Un(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const Dn=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function $n(e){Rn(e);let t="";for(let s=0;s<e.length;s++)t+=Dn[e[s]];return t}function Mn(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Ln(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?_n:BigInt("0x"+e)}const jn=48,qn=57,Bn=65,Fn=70,Wn=97,zn=102;function Hn(e){return e>=jn&&e<=qn?e-jn:e>=Bn&&e<=Fn?e-(Bn-10):e>=Wn&&e<=zn?e-(Wn-10):void 0}function Vn(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=Hn(e.charCodeAt(n)),s=Hn(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 Kn(e){return Ln($n(e))}function Gn(e){return Rn(e),Ln($n(Uint8Array.from(e).reverse()))}function Jn(e,t){return Vn(e.toString(16).padStart(2*t,"0"))}function Yn(e,t){return Jn(e,t).reverse()}function Zn(e,t,s){let i;if("string"==typeof t)try{i=Vn(t)}catch(n){throw new Error(e+" must be hex string or Uint8Array, cause: "+n)}else{if(!xn(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 Qn(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];Rn(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 Xn=e=>"bigint"==typeof e&&_n<=e;function eo(e,t,s){return Xn(e)&&Xn(t)&&Xn(s)&&t<=e&&e<s}function to(e,t,s,i){if(!eo(t,s,i))throw new Error("expected valid "+e+": "+s+" <= n < "+i+", got "+t)}function so(e){let t;for(t=0;e>_n;e>>=On,t+=1);return t}const io=e=>(Tn<<BigInt(e-1))-On,ro=e=>new Uint8Array(e),no=e=>Uint8Array.from(e);function oo(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=ro(e),r=ro(e),n=0;const o=()=>{i.fill(1),r.fill(0),n=0},a=(...e)=>s(r,i,...e),c=(e=ro())=>{r=a(no([0]),e),i=a(),0!==e.length&&(r=a(no([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 Qn(...s)};return(e,t)=>{let s;for(o(),c(e);!(s=t(l()));)c();return o(),s}}const ao={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||xn(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 co(e,t,s={}){const i=(t,s,i)=>{const r=ao[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 lo(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 ho=Object.freeze({__proto__:null,isBytes:xn,abytes:Rn,abool:Un,bytesToHex:$n,numberToHexUnpadded:Mn,hexToNumber:Ln,hexToBytes:Vn,bytesToNumberBE:Kn,bytesToNumberLE:Gn,numberToBytesBE:Jn,numberToBytesLE:Yn,numberToVarBytesBE:function(e){return Vn(Mn(e))},ensureBytes:Zn,concatBytes:Qn,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:eo,aInRange:to,bitLen:so,bitGet:function(e,t){return e>>BigInt(t)&On},bitSet:function(e,t,s){return e|(s?On:_n)<<BigInt(t)},bitMask:io,createHmacDrbg:oo,validateObject:co,notImplemented:()=>{throw new Error("not implemented")},memoized:lo});const uo=BigInt(0),po=BigInt(1),go=BigInt(2),mo=BigInt(3),fo=BigInt(4),wo=BigInt(5),vo=BigInt(8);function yo(e,t){const s=e%t;return s>=uo?s:t+s}function bo(e,t,s){if(t<uo)throw new Error("invalid exponent, negatives unsupported");if(s<=uo)throw new Error("invalid modulus");if(s===po)return uo;let i=po;for(;t>uo;)t&po&&(i=i*e%s),e=e*e%s,t>>=po;return i}function Eo(e,t,s){let i=e;for(;t-- >uo;)i*=i,i%=s;return i}function Co(e,t){if(e===uo)throw new Error("invert: expected non-zero number");if(t<=uo)throw new Error("invert: expected positive modulus, got "+t);let s=yo(e,t),i=t,r=uo,n=po;for(;s!==uo;){const e=i%s,t=r-n*(i/s);i=s,s=e,r=n,n=t}if(i!==po)throw new Error("invert: does not exist");return yo(r,t)}function Io(e){if(e%fo===mo){const t=(e+po)/fo;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%vo===wo){const t=(e-wo)/vo;return function(e,s){const i=e.mul(s,go),r=e.pow(i,t),n=e.mul(s,r),o=e.mul(e.mul(n,go),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-po)/go;let s,i,r;for(s=e-po,i=0;s%go===uo;s/=go,i++);for(r=go;r<e&&bo(r,t,e)!==e-po;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===i){const t=(e+po)/fo;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+po)/go;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,po<<BigInt(a-t-1));c=e.sqr(s),l=e.mul(l,s),d=e.mul(d,c),a=t}return l}}(e)}const No=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ao(e,t){const s=void 0!==t?t:e.toString(2).length;return{nBitLength:s,nByteLength:Math.ceil(s/8)}}function So(e,t,s=!1,i={}){if(e<=uo)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:n}=Ao(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:io(r),ZERO:uo,ONE:po,create:t=>yo(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return uo<=t&&t<e},is0:e=>e===uo,isOdd:e=>(e&po)===po,neg:t=>yo(-t,e),eql:(e,t)=>e===t,sqr:t=>yo(t*t,e),add:(t,s)=>yo(t+s,e),sub:(t,s)=>yo(t-s,e),mul:(t,s)=>yo(t*s,e),pow:(e,t)=>function(e,t,s){if(s<uo)throw new Error("invalid exponent, negatives unsupported");if(s===uo)return e.ONE;if(s===po)return t;let i=e.ONE,r=t;for(;s>uo;)s&po&&(i=e.mul(i,r)),r=e.sqr(r),s>>=po;return i}(a,e,t),div:(t,s)=>yo(t*Co(s,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Co(t,e),sqrt:i.sqrt||(t=>(o||(o=Io(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?Yn(e,n):Jn(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return s?Gn(e):Kn(e)}});return Object.freeze(a)}function Po(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 ko(e){const t=Po(e);return t+Math.ceil(t/2)}const _o=BigInt(0),Oo=BigInt(1);function To(e,t){const s=t.negate();return e?s:t}function xo(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ro(e,t){xo(e,t);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Uo=new WeakMap,Do=new WeakMap;function $o(e){return Do.get(e)||1}function Mo(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=so(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;
3for(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 Lo(e){return function(e){co(e,No.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}))}(e.Fp),co(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ao(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const jo=BigInt(0),qo=BigInt(1);const Bo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Fo=BigInt(1),Wo=BigInt(2),zo=BigInt(3),Ho=BigInt(5);BigInt(8);const Vo=function(e){const t=function(e){return co(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})}(e),{P:s}=t,i=e=>yo(e,s),r=t.montgomeryBits,n=Math.ceil(r/8),o=t.nByteLength,a=t.adjustScalarBytes||(e=>e),c=t.powPminus2||(e=>bo(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 h(e){return Yn(i(e),n)}function u(e,t){const u=function(e){const t=Zn("u coordinate",e,n);return 32===o&&(t[31]&=127),Gn(t)}(t),p=function(e){const t=Zn("scalar",e),s=t.length;if(s!==n&&s!==o)throw new Error("invalid scalar, expected "+n+" or "+o+" bytes, got "+s);return Gn(a(t))}(e),g=function(e,t){to("u",e,jo,s),to("scalar",t,jo,s);const n=t,o=e;let a,h=qo,u=jo,p=e,g=qo,m=jo;for(let s=BigInt(r-1);s>=jo;s--){const e=n>>s&qo;m^=e,a=l(m,h,p),h=a[0],p=a[1],a=l(m,u,g),u=a[0],g=a[1],m=e;const t=h+u,r=i(t*t),c=h-u,f=i(c*c),w=r-f,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)),h=i(r*f),u=i(w*(r+i(d*w)))}a=l(m,h,p),h=a[0],p=a[1],a=l(m,u,g),u=a[0],g=a[1];const f=c(u);return i(h*f)}(u,p);if(g===jo)throw new Error("invalid private or public key received");return h(g)}const p=h(t.Gu);function g(e){return u(e,p)}return{scalarMult:u,scalarMultBase:g,getSharedSecret:(e,t)=>u(e,t),getPublicKey:e=>g(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:p}}({P:Bo,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=Bo,{pow_p_5_8:s,b2:i}=function(e){const t=BigInt(10),s=BigInt(20),i=BigInt(40),r=BigInt(80),n=Bo,o=e*e%n*e%n,a=Eo(o,Wo,n)*o%n,c=Eo(a,Fo,n)*e%n,l=Eo(c,Ho,n)*c%n,d=Eo(l,t,n)*l%n,h=Eo(d,s,n)*d%n,u=Eo(h,i,n)*h%n,p=Eo(u,r,n)*u%n,g=Eo(p,r,n)*u%n,m=Eo(g,t,n)*l%n;return{pow_p_5_8:Eo(m,Wo,n)*e%n,b2:o}}(e);return yo(Eo(s,zo,t)*i,t)},adjustScalarBytes:function(e){return e[0]&=248,e[31]&=127,e[31]|=64,e},randomBytes:Yi});function Ko(e){void 0!==e.lowS&&Un("lowS",e.lowS),void 0!==e.prehash&&Un("prehash",e.prehash)}const{bytesToNumberBE:Go,hexToBytes:Jo}=ho;class Yo extends Error{constructor(e=""){super(e)}}const Zo={Err:Yo,_tlv:{encode:(e,t)=>{const{Err:s}=Zo;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=Mn(i);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const n=i>127?Mn(r.length/2|128):"";return Mn(e)+n+r+t},decode(e,t){const{Err:s}=Zo;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}=Zo;if(e<Qo)throw new t("integer: negative integers are not allowed");let s=Mn(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}=Zo;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 Go(e)}},toSig(e){const{Err:t,_int:s,_tlv:i}=Zo,r="string"==typeof e?Jo(e):e;Rn(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}=Zo,i=t.encode(2,s.encode(e.r))+t.encode(2,s.encode(e.s));return t.encode(48,i)}},Qo=BigInt(0),Xo=BigInt(1);BigInt(2);const ea=BigInt(3);function ta(e){const t=function(e){const t=Lo(e);co(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});
vendor: 12,237 bytes, line 3
3const{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=So(t.n,t.nBitLength),r=t.toBytes||((e,t,i)=>{const r=t.toAffine();return Qn(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(xn(e)&&(e=$n(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:Kn(Zn("private key",e,i))}catch{throw new Error("invalid private key, expected hex or "+i+" bytes, got "+typeof e)}return r&&(o=yo(o,n)),to("private key",o,Xo,n),o}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const l=lo((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=lo(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 h{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 h)throw new Error("projective point not allowed");const r=e=>s.eql(e,s.ZERO);return r(t)&&r(i)?h.ZERO:new h(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(h.fromAffine)}static fromHex(e){const t=h.fromAffine(n(Zn("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(a(e))}static msm(e,t){return Mo(h,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 h(this.px,s.neg(this.py),this.pz)}double(){const{a:e,b:i}=t,r=s.mul(i,ea),{px:n,py:o,pz:a}=this;let c=s.ZERO,l=s.ZERO,d=s.ZERO,u=s.mul(n,n),p=s.mul(o,o),g=s.mul(a,a),m=s.mul(n,o);return m=s.add(m,m),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(m,c),d=s.mul(r,d),g=s.mul(e,g),m=s.sub(u,g),m=s.mul(e,m),m=s.add(m,d),d=s.add(u,u),u=s.add(d,u),u=s.add(u,g),u=s.mul(u,m),l=s.add(l,u),g=s.mul(o,a),g=s.add(g,g),u=s.mul(g,m),c=s.sub(c,u),d=s.mul(g,p),d=s.add(d,d),d=s.add(d,d),new h(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,u=s.ZERO,p=s.ZERO;const g=t.a,m=s.mul(t.b,ea);let f=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(f,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(f,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(m,v),p=s.add(d,p),d=s.sub(w,p),p=s.add(w,p),u=s.mul(d,p),w=s.add(f,f),w=s.add(w,f),v=s.mul(g,v),b=s.mul(m,b),w=s.add(w,v),v=s.sub(f,v),v=s.mul(g,v),b=s.add(b,v),f=s.mul(w,b),u=s.add(u,f),f=s.mul(E,b),d=s.mul(y,d),d=s.sub(d,f),f=s.mul(y,w),p=s.mul(E,p),p=s.add(p,f),new h(d,u,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){const{endo:i,n:r}=t;to("scalar",e,Qo,r);const n=h.ZERO;if(e===Qo)return n;if(this.is0()||e===Xo)return this;if(!i||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,e,h.normalizeZ);let{k1neg:o,k1:a,k2neg:c,k2:l}=i.splitScalar(e),d=n,u=n,g=this;for(;a>Qo||l>Qo;)a&Xo&&(d=d.add(g)),l&Xo&&(u=u.add(g)),g=g.double(),a>>=Xo,l>>=Xo;return o&&(d=d.negate()),c&&(u=u.negate()),u=new h(s.mul(u.px,i.beta),u.py,u.pz),d.add(u)}multiply(e){const{endo:i,n:r}=t;let n,o;if(to("scalar",e,Xo,r),i){const{k1neg:t,k1:r,k2neg:a,k2:c}=i.splitScalar(e);let{p:l,f:d}=this.wNAF(r),{p:u,f:g}=this.wNAF(c);l=p.constTimeNegate(t,l),u=p.constTimeNegate(a,u),u=new h(s.mul(u.px,i.beta),u.py,u.pz),n=l.add(u),o=d.add(g)}else{const{p:t,f:s}=this.wNAF(e);n=t,o=s}return h.normalizeZ([n,o])[0]}multiplyAndAddUnsafe(e,t,s){const i=h.BASE,r=(e,t)=>t!==Qo&&t!==Xo&&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===Xo)return!0;if(s)return s(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:s}=t;return e===Xo?this:s?s(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return Un("isCompressed",e),this.assertValidity(),r(h,this,e)}toHex(e=!0){return Un("isCompressed",e),$n(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,s.ONE),h.ZERO=new h(s.ZERO,s.ONE,s.ZERO);const u=t.nBitLength,p=function(e,t){return{constTimeNegate:To,hasPrecomputes:e=>1!==$o(e),unsafeLadder(t,s,i=e.ZERO){let r=t;for(;s>_o;)s&Oo&&(i=i.add(r)),r=r.double(),s>>=Oo;return i},precomputeWindow(e,s){const{windows:i,windowSize:r}=Ro(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}=Ro(s,t);let a=e.ZERO,c=e.BASE;const l=BigInt(2**s-1),d=2**s,h=BigInt(s);for(let e=0;e<n;e++){const t=e*o;let s=Number(r&l);r>>=h,s>o&&(s-=d,r+=Oo);const n=t,u=t+Math.abs(s)-1,p=e%2!=0,g=s<0;0===s?c=c.add(To(p,i[n])):a=a.add(To(g,i[u]))}return{p:a,f:c}},wNAFUnsafe(s,i,r,n=e.ZERO){const{windows:o,windowSize:a}=Ro(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===_o)break;let s=Number(r&c);if(r>>=d,s>a&&(s-=l,r+=Oo),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=Uo.get(t);return i||(i=this.precomputeWindow(t,e),1!==e&&Uo.set(t,s(i))),i},wNAFCached(e,t,s){const i=$o(e);return this.wNAF(i,this.getPrecomputes(i,e,s),t)},wNAFCachedUnsafe(e,t,s,i){const r=$o(e);return 1===r?this.unsafeLadder(e,t,i):this.wNAFUnsafe(r,this.getPrecomputes(r,e,s),t,i)},setWindowSize(e,s){xo(s,t),Do.set(e,s),Uo.delete(e)}}}(h,t.endo?Math.ceil(u/2):u);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:function(e){return eo(e,Xo,t.n)}}}function sa(e){const t=function(e){const t=Lo(e);return co(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 yo(e,i)}function a(e){return Co(e,i)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:d,isWithinCurveOrder:h}=ta({...t,toBytes(e,t,i){const r=t.toAffine(),n=s.toBytes(r.x),o=Qn;return Un("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=Kn(o);if(!eo(e,Xo,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&Xo)===Xo)&&(r=s.neg(r)),{x:e,y:r}}}}),u=e=>$n(Jn(e,t.nByteLength));function p(e){return e>i>>Xo}const g=(e,t,s)=>Kn(e.slice(t,s));class m{constructor(e,t,s){this.r=e,this.s=t,this.recovery=s,this.assertValidity()}static fromCompact(e){const s=t.nByteLength;return e=Zn("compactSignature",e,2*s),new m(g(e,0,s),g(e,s,2*s))}static fromDER(e){const{r:t,s:s}=Zo.toSig(Zn("DER",e));return new m(t,s)}assertValidity(){to("r",this.r,Xo,i),to("s",this.s,Xo,i)}addRecoveryBit(e){return new m(this.r,this.s,e)}recoverPublicKey(e){const{r:i,s:r,recovery:n}=this,l=y(Zn("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 h=1&n?"03":"02",p=c.fromHex(h+u(d)),g=a(d),m=o(-l*g),f=o(r*g),w=c.BASE.multiplyAndAddUnsafe(p,m,f);if(!w)throw new Error("point at infinify");return w.assertValidity(),w}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Vn(this.toDERHex())}toDERHex(){return Zo.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Vn(this.toCompactHex())}toCompactHex(){return u(this.r)+u(this.s)}}const f={isValidPrivateKey(e){try{return l(e),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=ko(t.n);return function(e,t,s=!1){const i=e.length,r=Po(t),n=ko(t);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=yo(s?Gn(e):Kn(e),t-po)+po;return s?Yn(o,r):Jn(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=xn(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=Kn(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=io(t.nBitLength);function E(e){return to("num < 2^"+t.nBitLength,e,Qo,b),Jn(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:u,prehash:g,extraEntropy:f}=r;null==u&&(u=!0),e=Zn("msgHash",e),Ko(r),g&&(e=Zn("prehashed msgHash",n(e)));const w=y(e),b=l(i),C=[E(b),E(w)];if(null!=f&&!1!==f){const e=!0===f?d(s.BYTES):f;C.push(Zn("extraEntropy",e))}const N=Qn(...C),A=w;return{seed:N,k2sig:function(e){const t=v(e);if(!h(t))return;const s=a(t),i=c.BASE.multiply(t).toAffine(),r=o(i.x);if(r===Qo)return;const n=o(s*o(A+r*b));if(n===Qo)return;let l=(i.x===r?0:2)|Number(i.y&Xo),d=n;return u&&p(n)&&(d=function(e){return p(e)?o(-e):e}(n),l^=1),new m(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 oo(o.hash.outputLen,o.nByteLength,o.hmac)(r,n)},verify:function(e,s,i,r=N){var n;const l=e;s=Zn("msgHash",s),i=Zn("publicKey",i);const{lowS:d,prehash:h,format:u}=r;if(Ko(r),"strict"in r)throw new Error("options.strict was renamed to lowS");if(void 0!==u&&"compact"!==u&&"der"!==u)throw new Error("format must be compact or der");const p="string"==typeof l||xn(l),g=!p&&!u&&"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 f,w;
3try{if(g&&(f=new m(l.r,l.s)),p){try{"compact"!==u&&(f=m.fromDER(l))}catch(P){if(!(P instanceof Zo.Err))throw P}!f&&"der"!==u&&(f=m.fromCompact(l))}w=c.fromHex(i)}catch{return!1}if(!f||d&&f.hasHighS())return!1;h&&(s=t.hash(s));const{r:v,s:b}=f,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:m,utils:f}}function ia(e){return{hash:e,hmac:(t,...s)=>wn(e,t,function(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];Ui(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:Yi}}BigInt(4);const ra=So(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),na=function(e,t){const s=t=>sa({...e,...ia(t)});return{...s(t),create:s}}({a:ra.create(BigInt("-3")),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Fp:ra,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},kn),oa="base10",aa="base16",ca="base64pad",la="base64url",da="utf8";function ha(){const e=Yi(32);return h(e,aa)}function ua(e){const t=kn(d(e,aa));return h(t,aa)}function pa(e){const t=kn(d(e,da));return h(t,aa)}function ga(e){return d(`${e}`,oa)}function ma(e){return Number(h(e,oa))}function fa(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function wa(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=(4-t.length%4)%4;return t+"=".repeat(s)}function va(e){if(2===ma(e.type))return h(m([e.type,e.sealed]),ca);if(1===ma(e.type)){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return h(m([e.type,e.senderPublicKey,e.iv,e.sealed]),ca)}return h(m([e.type,e.iv,e.sealed]),ca)}function ya(e){const t=(e.encoding||ca)===la?wa(e.encoded):e.encoded,s=d(t,ca),i=s.slice(0,1);if(1===ma(i)){const e=33,t=e+12,r=s.slice(1,e),n=s.slice(e,t);return{type:i,sealed:s.slice(t),iv:n,senderPublicKey:r}}if(2===ma(i)){return{type:i,sealed:s.slice(1),iv:Yi(12)}}const r=s.slice(1,13);return{type:i,sealed:s.slice(13),iv:r}}function ba(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 Ea(e){return 1===e.type&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function Ca(e){return 2===e.type}function Ia(e,t){const[s,i,n]=e.split("."),o=r.from(wa(n),"base64");if(64!==o.length)throw new Error("Invalid signature length");const a=o.slice(0,32),c=o.slice(32,64),l=kn(`${s}.${i}`),d=function(e){const t=r.from(e.x,"base64"),s=r.from(e.y,"base64");return m([new Uint8Array([4]),t,s])}(t);if(!na.verify(m([a,c]),l,d))throw new Error("Invalid signature");return f(e).payload}function Na(e){return(null==e?void 0:e.relay)||{protocol:"irn"}}function Aa(e){const t=g[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function Sa(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 Pa(e){if(!e.includes("wc:")){const t=xi(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:ka(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:Sa(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function ka(e){return e.startsWith("//")?e.substring(2):e}function _a(e){const t=new URLSearchParams,s=function(e,t="-"){const s={};return Object.keys(e).forEach(i=>
3{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 Oa(e,t,s){return`${e}?wc_ev=${s}&topic=${t}`}var Ta=Object.defineProperty,xa=Object.defineProperties,Ra=Object.getOwnPropertyDescriptors,Ua=Object.getOwnPropertySymbols,Da=Object.prototype.hasOwnProperty,$a=Object.prototype.propertyIsEnumerable,Ma=(e,t,s)=>t in e?Ta(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,La=(e,t)=>{for(var s in t||(t={}))Da.call(t,s)&&Ma(e,s,t[s]);if(Ua)for(var s of Ua(t))$a.call(t,s)&&Ma(e,s,t[s]);return e},ja=(e,t)=>xa(e,Ra(t));function qa(e){const t=[];return e.forEach(e=>{const[s,i]=e.split(":");t.push(`${s}:${i}`)}),t}function Ba(e){return e.includes(":")}function Fa(e){return Ba(e)?e.split(":")[0]:e}function Wa(e){var t,s,i;const r={};if(!Ya(e))return r;for(const[n,o]of Object.entries(e)){const e=Ba(n)?[n]:o.chains,a=o.methods||[],c=o.events||[],l=Fa(n);r[l]=ja(La({},r[l]),{chains:Pi(e,null==(t=r[l])?void 0:t.chains),methods:Pi(a,null==(s=r[l])?void 0:s.methods),events:Pi(c,null==(i=r[l])?void 0:i.events)})}return r}function za(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=Pi(r.methods,e):r.methods=e,r.events=["chainChanged","accountsChanged"];return s}const Ha={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}},Va={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 Ka(e,t){const{message:s,code:i}=Va[e];return{message:t?`${s} ${t}`:s,code:i}}function Ga(e,t){const{message:s,code:i}=Ha[e];return{message:t?`${s} ${t}`:s,code:i}}function Ja(e,t){return!!Array.isArray(e)}function Ya(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Za(e){return typeof e>"u"}function Qa(e,t){return!(!t||!Za(e))||"string"==typeof e&&!!e.trim().length}function Xa(e,t){return!(!t||!Za(e))||"number"==typeof e&&!isNaN(e)}
3function ec(e){return!(!Qa(e,!1)||!e.includes(":"))&&2===e.split(":").length}function tc(e){let t=!0;return Ja(e)?e.length&&(t=e.every(e=>Qa(e,!1))):t=!1,t}function sc(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 Ja(t)&&t.length?t.forEach(e=>{i||ec(e)||(i=Ga("UNSUPPORTED_CHAINS",`${s}, chain ${e} should be a string and conform to "namespace:chainId" format`))}):ec(e)||(i=Ga("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,Gs(e,r),`${t} ${s}`);n&&(i=n)}),i}function ic(e,t){let s=null;return Ja(e)?e.forEach(e=>{s||function(e){if(Qa(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&ec(e)}}return!1}(e)||(s=Ga("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))}):s=Ga("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function rc(e,t){let s=null;return Object.values(e).forEach(e=>{if(s)return;const i=function(e,t){let s=null;return tc(null==e?void 0:e.methods)?tc(null==e?void 0:e.events)||(s=Ga("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):s=Ga("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 nc(e,t){let s=null;if(e&&Ya(e)){const i=rc(e,t);i&&(s=i);const r=function(e,t){let s=null;return Object.values(e).forEach(e=>{if(s)return;const i=ic(null==e?void 0:e.accounts,`${t} namespace`);i&&(s=i)}),s}(e,t);r&&(s=r)}else s=Ka("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return s}function oc(e){return Qa(e.protocol,!0)}function ac(e){return typeof e<"u"&&null!==typeof e}function cc(e,t){return!(!ec(t)||!function(e){const t=[];return Object.values(e).forEach(e=>{t.push(...qa(e.accounts))}),t}(e).includes(t))}function lc(e,t,s){return!!Qa(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach(e=>{qa(e.accounts).includes(t)&&s.push(...e.methods)}),s}(e,t).includes(s)}function dc(e,t,s){return!!Qa(s,!1)&&function(e,t){const s=[];return Object.values(e).forEach(e=>{qa(e.accounts).includes(t)&&s.push(...e.events)}),s}(e,t).includes(s)}function hc(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=qa(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=uc(Object.keys(e)),l=uc(Object.keys(t)),d=c.filter(e=>!l.includes(e));return d.length&&(i=Ka("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.\n Required: ${d.toString()}\n Received: ${Object.keys(t).toString()}`)),wi(o,a)||(i=Ka("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=qa(t[e].accounts);r.includes(e)||(i=Ka("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${r.toString()}`))}),o.forEach(e=>{i||(wi(r[e].methods,n[e].methods)?wi(r[e].events,n[e].events)||(i=Ka("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${e}`)):i=Ka("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${e}`))}),i}function uc(e){return[...new Set(e.map(e=>e.includes(":")?e.split(":")[0]:e))]}function pc(){const e=hi();return new Promise(t=>{switch(e){case ni:t(di()&&(null==navigator?void 0:navigator.onLine));break;case ii:t(async function(){if(li()&&typeof s<"u"&&null!=s&&s.NetInfo){const e=await(null==s?void 0:s.NetInfo.fetch());return null==e?void 0:e.isConnected}return!0}());break;default:t(!0)}})}function gc(e){switch(hi()){case ni:!function(e){!li()&&di()&&(window.addEventListener("online",()=>e(!0)),window.addEventListener("offline",()=>e(!1)))}(e);break;case ii:!function(e){var t;li()&&typeof s<"u"&&null!=s&&s.NetInfo&&(null==(t=s)||t.NetInfo.addEventListener(t=>e(null==t?void 0:t.isConnected)))}(e)}}const mc={};class fc{static get(e){return mc[e]}static set(e,t){mc[e]=t}static delete(e){delete mc[e]}}var wc={};const vc="core",yc=`wc@2:${vc}:`,bc="error",Ec={database:":memory:"},Cc="client_ed25519_seed",Ic=u.ONE_DAY,Nc=u.SIX_HOURS,Ac="wss://relay.walletconnect.org",Sc="relayer_message",Pc="relayer_message_ack",kc="relayer_connect",_c="relayer_disconnect",Oc="relayer_error",Tc="relayer_connection_stalled",xc="relayer_publish",Rc="payload",Uc="connect",Dc="disconnect",$c="error",Mc="2.21.0",Lc={link_mode:"link_mode",relay:"relay"},jc="inbound",qc="outbound",Bc="WALLETCONNECT_LINK_MODE_APPS",Fc="subscription_created",Wc="subscription_deleted",zc="subscription_sync",Hc="subscription_resubscribed",Vc={wc_pairingDelete:{req:{ttl:u.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:u.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:u.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:u.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:u.ONE_DAY,prompt:!1,tag:0},res:{ttl:u.ONE_DAY,prompt:!1,tag:0}}},Kc="pairing_create",Gc="pairing_expire",Jc="pairing_delete",Yc="pairing_ping",Zc="history_created",Qc="history_updated",Xc="history_deleted",el="history_sync",tl="expirer_created",sl="expirer_deleted",il="expirer_expired",rl="expirer_sync",nl="https://verify.walletconnect.org",ol=nl,al=`${ol}/v3`,cl=["https://verify.walletconnect.com",nl],ll="pairing_started",dl="pairing_uri_validation_success",hl="pairing_uri_not_expired",ul="store_new_pairing",pl="subscribing_pairing_topic",gl="subscribe_pairing_topic_success",ml="existing_pairing",fl="pairing_not_expired",wl="emit_inactive_pairing",vl="emit_session_proposal",yl="no_internet_connection",bl="malformed_pairing_uri",El="active_pairing_already_exists",Cl="subscribe_pairing_topic_failure",Il="pairing_expired",Nl="proposal_listener_not_found",Al="session_approve_started",Sl="session_namespaces_validation_success",Pl="subscribing_session_topic",kl="subscribe_session_topic_success",_l="publishing_session_approve",Ol="session_approve_publish_success",Tl="store_session",xl="publishing_session_settle",Rl="session_settle_publish_success",Ul="no_internet_connection",Dl="proposal_expired",$l="subscribe_session_topic_failure",Ml="session_approve_publish_failure",Ll="session_settle_publish_failure",jl="session_approve_namespace_validation_failure",ql="proposal_not_found",Bl="authenticated_session_approve_started",Fl="create_authenticated_session_topic",Wl="cacaos_verified",zl="store_authenticated_session",Hl="subscribing_authenticated_session_topic",Vl="subscribe_authenticated_session_topic_success",Kl="publishing_authenticated_session_approve",Gl="no_internet_connection",Jl="invalid_cacao",Yl="subscribe_authenticated_session_topic_failure",Zl="authenticated_session_approve_publish_failure",Ql="authenticated_session_pending_request_not_found";var Xl=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 h(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 h=0,u=n-1;(0!==d||h<r)&&-1!==u;u--,h++)d+=a*o[u]>>>0,o[u]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");r=h,t++}if(" "!==e[t]){for(var p=n-r;p!==n&&0===o[p];)p++;for(var g=new Uint8Array(i+(n-p)),m=i;p!==n;)g[m++]=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 h=t[r],u=0,p=o-1;(0!==h||u<i)&&-1!==p;p--,u++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");i=u,r++}for(var g=o-i;g!==o&&0===l[g];)g++;for(var m=c.repeat(s);g<o;++g)m+=e.charAt(l[g]);return m},decodeUnsafe:h,decode:function(e){var s=h(e);if(s)return s;throw new Error(`Non-${t} character`)}}},ed=Xl;const td=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 sd{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")}}
3class id{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} 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 nd(this,e)}}class rd{constructor(e){this.decoders=e}or(e){return nd(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 nd=(e,t)=>new rd({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class od{constructor(e,t,s,i){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=i,this.encoder=new sd(e,t,s),this.decoder=new id(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ad=({name:e,prefix:t,encode:s,decode:i})=>new od(e,t,s,i),cd=({prefix:e,name:t,alphabet:s})=>{const{encode:i,decode:r}=ed(s,t);return ad({prefix:e,name:t,encode:i,decode:e=>td(r(e))})},ld=({name:e,prefix:t,bitsPerChar:s,alphabet:i})=>ad({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)}),dd=ad({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var hd=Object.freeze({__proto__:null,identity:dd});const ud=ld({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var pd=Object.freeze({__proto__:null,base2:ud});const gd=ld({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var md=Object.freeze({__proto__:null,base8:gd});const fd=cd({prefix:"9",name:"base10",alphabet:"0123456789"});var wd=Object.freeze({__proto__:null,base10:fd});const vd=ld({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),yd=ld({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var bd=Object.freeze({__proto__:null,base16:vd,base16upper:yd});const Ed=ld({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cd=ld({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Id=ld({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Nd=ld({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ad=ld({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Sd=ld({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Pd=ld({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kd=ld({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_d=ld({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Od=Object.freeze({__proto__:null,base32:Ed,base32upper:Cd,base32pad:Id,base32padupper:Nd,base32hex:Ad,base32hexupper:Sd,base32hexpad:Pd,base32hexpadupper:kd,base32z:_d});const Td=cd({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xd=cd({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Rd=Object.freeze({__proto__:null,base36:Td,base36upper:xd});const Ud=cd({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Dd=cd({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var $d=Object.freeze({__proto__:null,base58btc:Ud,base58flickr:Dd});const Md=ld({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
3+/",bitsPerChar:6}),Ld=ld({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),jd=ld({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qd=ld({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Bd=Object.freeze({__proto__:null,base64:Md,base64pad:Ld,base64url:jd,base64urlpad:qd});const Fd=Array.from("ððªâð°ðððððððððððððâð»ð¥ð¾ð¿ðâ¤ðð¤£ððððððð
ððð¥ð¥°ðððð¢ð¤ðððªðâºðð¤ððððð¹ð¤¦ððââ¨ð¤·ð±ðð¸ððððððððð¤©ððð¤ðð¯ððð¶ðð¤â£ððððªðð¥ððð©ð¡ð¤ªðð¥³ð¥ð¤¤ððð³âððð´ðð¬ððð·ð»ðââ
ð¥ºððð¤ð¦âð£ððâ¹ððð âððºðð»ððððð¹ð£ð«ðððµð¤ðð´ð¤ð¼ð«â½ð¤âðð¤«ðð®ðð»ðð¶ðð²ð¿ð§¡ðâ¡ððââðð°ð¤¨ð¶ð¤ð¶ð°ðð¢ð¤ðð¨ð¨ð¤¬âððºð¤ððð±ðð¶ð¥´â¶â¡âðð¸â¬ð¨ðð¦ð·ðºâ ð
ððµðð¤²ð¤ ð¤§ððµð
ð§ð¾ððð¤ðð¤¯ð·âð§ð¯ððð¤ððâð´ð£ð¸ððð¥ð¤¢ð
ð¡ð©ðð¸ð»ð¤ð¤®ð¼ð¥µð©ððð¼ðð£ð¥"),Wd=Fd.reduce((e,t,s)=>(e[s]=t,e),[]),zd=Fd.reduce((e,t,s)=>(e[t.codePointAt(0)]=s,e),[]);const Hd=ad({prefix:"ð",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+=Wd[t],"")},decode:function(e){const t=[];for(const s of e){const e=zd[s.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${s}`);t.push(e)}return new Uint8Array(t)}});var Vd=Object.freeze({__proto__:null,base256emoji:Hd}),Kd=function e(t,s,i){s=s||[];for(var r=i=i||0;t>=Yd;)s[i++]=255&t|Gd,t/=128;for(;t&Jd;)s[i++]=255&t|Gd,t>>>=7;return s[i]=0|t,e.bytes=i-r+1,s},Gd=128,Jd=-128,Yd=Math.pow(2,31);var Zd=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&Xd)<<n:(i&Xd)*Math.pow(2,n),n+=7}while(i>=Qd);return e.bytes=o-s,r},Qd=128,Xd=127;var eh=Math.pow(2,7),th=Math.pow(2,14),sh=Math.pow(2,21),ih=Math.pow(2,28),rh=Math.pow(2,35),nh=Math.pow(2,42),oh=Math.pow(2,49),ah=Math.pow(2,56),ch=Math.pow(2,63),lh={encode:Kd,decode:Zd,encodingLength:function(e){return e<eh?1:e<th?2:e<sh?3:e<ih?4:e<rh?5:e<nh?6:e<oh?7:e<ah?8:e<ch?9:10}};const dh=(e,t,s=0)=>(lh.encode(e,t,s),t),hh=e=>lh.encodingLength(e),uh=(e,t)=>{const s=t.byteLength,i=hh(e),r=i+hh(s),n=new Uint8Array(r+s);return dh(e,n,0),dh(s,n,i),n.set(t,r),new ph(e,s,t,n)};class ph{constructor(e,t,s,i){this.code=e,this.size=t,this.digest=s,this.bytes=i}}const gh=({name:e,code:t,encode:s})=>new mh(e,t,s);class mh{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?uh(this.code,t):t.then(e=>uh(this.code,e))}throw Error("Unknown type, must be binary type")}}const fh=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),wh=gh({name:"sha2-256",code:18,encode:fh("SHA-256")}),vh=gh({name:"sha2-512",code:19,encode:fh("SHA-512")});Object.freeze({__proto__:null,sha256:wh,sha512:vh});const yh=td,bh={code:0,name:"identity",encode:yh,digest:e=>uh(0,yh(e))};Object.freeze({__proto__:null,identity:bh});new TextEncoder,new TextDecoder;const Eh={...hd,...pd,...md,...wd,...bd,...Od,...Rd,...$d,...Bd,...Vd};function Ch(e,t,s,i){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:s},decoder:{decode:i}}}const Ih=Ch("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),Nh=Ch("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}),Ah={utf8:Ih,"utf-8":Ih,hex:Eh.base16,latin1:Nh,ascii:Nh,binary:Nh,...Eh};var Sh=Object.defineProperty,Ph=(e,t,s)=>((e,t,s)=>t in e?Sh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class kh{constructor(e,t){this.core=e,this.logger=t,Ph(this,"keychain",new Map),Ph(this,"name","keychain"),Ph(this,"version","0.3"),Ph(this,"initialized",!1),Ph(this,"storagePrefix",yc),Ph(this,"init",async()=>
3{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}}),Ph(this,"has",e=>(this.isInitialized(),this.keychain.has(e))),Ph(this,"set",async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()}),Ph(this,"get",e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=Ka("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}),Ph(this,"del",async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()}),this.core=e,this.logger=E(t,this.name)}get context(){return N(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,vi(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?yi(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Ka("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _h=Object.defineProperty,Oh=(e,t,s)=>((e,t,s)=>t in e?_h(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Th{constructor(e,t,s){this.core=e,this.logger=t,Oh(this,"name","crypto"),Oh(this,"keychain"),Oh(this,"randomSessionIdentifier",ha()),Oh(this,"initialized",!1),Oh(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Oh(this,"hasKeys",e=>(this.isInitialized(),this.keychain.has(e))),Oh(this,"getClientId",async()=>{this.isInitialized();const e=await this.getClientSeed(),t=R(e);return U(t.publicKey)}),Oh(this,"generateKeyPair",()=>{this.isInitialized();const e=function(){const e=Vo.utils.randomPrivateKey(),t=Vo.getPublicKey(e);return{privateKey:h(e,aa),publicKey:h(t,aa)}}();return this.setPrivateKey(e.publicKey,e.privateKey)}),Oh(this,"signJWT",async e=>{this.isInitialized();const t=await this.getClientSeed(),s=R(t),i=this.randomSessionIdentifier,r=Ic;return await D(i,e,r,s)}),Oh(this,"generateSharedKey",(e,t,s)=>{this.isInitialized();const i=function(e,t){const s=Vo.getSharedSecret(d(e,aa),d(t,aa)),i=bn(kn,s,void 0,void 0,32);return h(i,aa)}(this.getPrivateKey(e),t);return this.setSymKey(i,s)}),Oh(this,"setSymKey",async(e,t)=>{this.isInitialized();const s=t||ua(e);return await this.keychain.set(s,e),s}),Oh(this,"deleteKeyPair",async e=>{this.isInitialized(),await this.keychain.del(e)}),Oh(this,"deleteSymKey",async e=>{this.isInitialized(),await this.keychain.del(e)}),Oh(this,"encode",async(e,t,s)=>{this.isInitialized();const i=ba(s),r=$(t);if(Ca(i))return function(e,t){const s=ga(2),i=Yi(12),r=va({type:s,sealed:d(e,da),iv:i});return t===la?fa(r):r}(r,null==s?void 0:s.encoding);if(Ea(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=ga(typeof e.type<"u"?e.type:0);if(1===ma(t)&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof e.senderPublicKey<"u"?d(e.senderPublicKey,aa):void 0,i=typeof e.iv<"u"?d(e.iv,aa):Yi(12),r=d(e.symKey,aa),n=va({type:t,sealed:mn(r,i).encrypt(d(e.message,da)),iv:i,senderPublicKey:s});return e.encoding===la?fa(n):n}({type:o,symKey:n,message:r,senderPublicKey:a,encoding:null==s?void 0:s.encoding})}),Oh(this,"decode",async(e,t,s)=>{this.isInitialized();const i=function(e,t){const s=ya({encoded:e,encoding:null==t?void 0:t.encoding});return ba({type:ma(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?h(s.senderPublicKey,aa):void 0,receiverPublicKey:null==t?void 0:t.receiverPublicKey})}(t,s);if(Ca(i)){const e=function(e,t){const{sealed:s}=ya({encoded:e,encoding:t});return h(s,da)}(t,null==s?void 0:s.encoding);return M(e)}if(Ea(i)){const t=i.receiverPublicKey,s=i.senderPublicKey;e=await this.generateSharedKey(t,s)}try{const i=function(e){const t=d(e.symKey,aa),{sealed:s,iv:i}=ya({encoded:e.encoded,encoding:e.encoding}),r=mn(t,i).decrypt(s);if(null===r)throw new Error("Failed to decrypt");return h(r,da)}({symKey:this.getSymKey(e),encoded:t,encoding:null==s?void 0:s.encoding});return M(i)}catch(r){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(r)}}),Oh(this,"getPayloadType",(e,t=ca)=>ma(ya({encoded:e,encoding:t}).type)),Oh(this,"getPayloadSenderPublicKey",(e,t=ca)=>{const s=ya({encoded:e,encoding:t});return s.senderPublicKey?h(s.senderPublicKey,aa):void 0}),this.core=e,this.logger=E(t,this.name),this.keychain=s||new kh(this.core,this.logger)}get context(){return N(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(Cc)}catch{e=ha(),await this.keychain.set(Cc,e)}return function(e,t="utf8"){const s=Ah[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}=Ka("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xh=Object.defineProperty,Rh=Object.defineProperties,Uh=Object.getOwnPropertyDescriptors,Dh=Object.getOwnPropertySymbols,$h=Object.prototype.hasOwnProperty,Mh=Object.prototype.propertyIsEnumerable,Lh=(e,t,s)=>t in e?xh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,jh=(e,t,s)=>Lh(e,"symbol"!=typeof t?t+"":t,s);class qh extends Rs{constructor(e,t){super(e,t),this.logger=e,this.core=t,jh(this,"messages",new Map),jh(this,"messagesWithoutClientAck",new Map),jh(this,"name","messages"),jh(this,"version","0.3"),jh(this,"initialized",!1),jh(this,"storagePrefix",yc),jh(this,"init",async()=>
3{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}}}),jh(this,"set",async(e,t,s)=>{this.isInitialized();const i=pa(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===jc){const s=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,((e,t)=>Rh(e,Uh(t)))(((e,t)=>{for(var s in t||(t={}))$h.call(t,s)&&Lh(e,s,t[s]);if(Dh)for(var s of Dh(t))Mh.call(t,s)&&Lh(e,s,t[s]);return e})({},s),{[i]:t}))}return await this.persist(),i}),jh(this,"get",e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t}),jh(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}),jh(this,"has",(e,t)=>{this.isInitialized();return typeof this.get(e)[pa(t)]<"u"}),jh(this,"ack",async(e,t)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(e);if(typeof s>"u")return;delete s[pa(t)],0===Object.keys(s).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,s),await this.persist()}),jh(this,"del",async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()}),this.logger=E(e,this.name),this.core=t}get context(){return N(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,vi(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,vi(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?yi(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?yi(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=Ka("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Bh=Object.defineProperty,Fh=Object.defineProperties,Wh=Object.getOwnPropertyDescriptors,zh=Object.getOwnPropertySymbols,Hh=Object.prototype.hasOwnProperty,Vh=Object.prototype.propertyIsEnumerable,Kh=(e,t,s)=>t in e?Bh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Gh=(e,t)=>{for(var s in t||(t={}))Hh.call(t,s)&&Kh(e,s,t[s]);if(zh)for(var s of zh(t))Vh.call(t,s)&&Kh(e,s,t[s]);return e},Jh=(e,t)=>Fh(e,Wh(t)),Yh=(e,t,s)=>Kh(e,"symbol"!=typeof t?t+"":t,s);class Zh extends Us{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Yh(this,"events",new n.EventEmitter),Yh(this,"name","publisher"),Yh(this,"queue",new Map),Yh(this,"publishTimeout",u.toMiliseconds(u.ONE_MINUTE)),Yh(this,"initialPublishTimeout",u.toMiliseconds(15*u.ONE_SECOND)),Yh(this,"needsTransportRestart",!1),Yh(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)||Nc,n=Na(s),o=(null==s?void 0:s.prompt)||!1,a=(null==s?void 0:s.tag)||0,c=(null==s?void 0:s.id)||L().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(xc,n),i(l))};this.relayer.events.on(xc,n);const d=Ei(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(xc,n)}catch(h){this.queue.set(c,Jh(Gh({},l),{attempt:1})),this.logger.warn(h,null==h?void 0:h.message)}});this.logger.trace({type:"method",method:"publish",params:{id:c,topic:e,message:t,opts:s}}),await Ei(i,this.publishTimeout,d)}catch(h){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(h),null!=(i=null==s?void 0:s.internal)&&i.throwOnFailedPublish)throw h}finally{this.queue.delete(c)}}),Yh(this,"on",(e,t)=>{this.events.on(e,t)}),Yh(this,"once",(e,t)=>{this.events.once(e,t)}),Yh(this,"off",(e,t)=>{this.events.off(e,t)}),Yh(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.relayer=e,this.logger=E(t,this.name),this.registerEventListeners()}get context(){return N(this.logger)}async rpcPublish(e){var t,s,i,r;const{topic:n,message:o,ttl:a=Nc,prompt:c,tag:l,id:d,attestation:h,tvf:u}=e,p={method:Aa(Na().protocol).publish,params:Gh({topic:n,message:o,ttl:a,prompt:c,tag:l,attestation:h},u),id:d};Za(null==(t=p.params)?void 0:t.prompt)&&(null==(s=p.params)||delete s.prompt),Za(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(xc,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,Jh(Gh({},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(Jh(Gh({},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(S.pulse,()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(Tc);this.checkQueue()}),this.relayer.on(Pc,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Qh=Object.defineProperty,Xh=(e,t,s)=>((e,t,s)=>t in e?Qh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class eu{constructor(){Xh(this,"map",new Map),Xh(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),Xh(this,"get",e=>this.map.get(e)||[]),Xh(this,"exists",(e,t)=>this.get(e).includes(t)),Xh(this,"delete",(e,t)=>{if(typeof t>"u")return void this.map.delete(e);
3if(!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)}),Xh(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var tu=Object.defineProperty,su=Object.defineProperties,iu=Object.getOwnPropertyDescriptors,ru=Object.getOwnPropertySymbols,nu=Object.prototype.hasOwnProperty,ou=Object.prototype.propertyIsEnumerable,au=(e,t,s)=>t in e?tu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,cu=(e,t)=>{for(var s in t||(t={}))nu.call(t,s)&&au(e,s,t[s]);if(ru)for(var s of ru(t))ou.call(t,s)&&au(e,s,t[s]);return e},lu=(e,t)=>su(e,iu(t)),du=(e,t,s)=>au(e,"symbol"!=typeof t?t+"":t,s);class hu extends Ms{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,du(this,"subscriptions",new Map),du(this,"topicMap",new eu),du(this,"events",new n.EventEmitter),du(this,"name","subscription"),du(this,"version","0.3"),du(this,"pending",new Map),du(this,"cached",[]),du(this,"initialized",!1),du(this,"storagePrefix",yc),du(this,"subscribeTimeout",u.toMiliseconds(u.ONE_MINUTE)),du(this,"initialSubscribeTimeout",u.toMiliseconds(15*u.ONE_SECOND)),du(this,"clientId"),du(this,"batchSubscribeTopicsLimit",500),du(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),du(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=Na(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(mr){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(mr),mr}}),du(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)}),du(this,"isSubscribed",e=>new Promise(t=>{t(this.topicMap.topics.includes(e))})),du(this,"isKnownTopic",e=>new Promise(t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some(t=>t.topic===e))})),du(this,"on",(e,t)=>{this.events.on(e,t)}),du(this,"once",(e,t)=>{this.events.once(e,t)}),du(this,"off",(e,t)=>{this.events.off(e,t)}),du(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),du(this,"start",async()=>{await this.onConnect()}),du(this,"stop",async()=>{await this.onDisconnect()}),du(this,"restart",async()=>{await this.restore(),await this.onRestart()}),du(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)}),du(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(S.pulse,async()=>{await this.checkPending()}),this.events.on(Fc,async e=>{const t=Fc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}),this.events.on(Wc,async e=>{const t=Wc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})}),this.relayer=e,this.logger=E(t,this.name),this.clientId=""}get context(){return N(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=Na(s);await this.restartToComplete({topic:e,id:t,relay:i}),await this.rpcUnsubscribe(e,t,i);const r=Ga("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}}
3async rpcSubscribe(e,t,s){var i;(!s||(null==s?void 0:s.transportType)===Lc.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const r={method:Aa(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});const n=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)===Lc.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch(e=>this.logger.warn(e))},u.toMiliseconds(u.ONE_SECOND)),t;const i=new Promise(async t=>{const s=i=>{i.topic===e&&(this.events.removeListener(Fc,s),t(i.id))};this.events.on(Fc,s);try{const i=await Ei(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(Fc,s),t(i)}catch{}}),o=await Ei(i,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!o&&n)throw new Error(`Subscribing to ${e} failed, please try again`);return o?t:null}catch(o){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Tc),n)throw o}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t={method:Aa(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 Ei(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(Tc)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t={method:Aa(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 Ei(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(Tc)}return s}rpcUnsubscribe(e,t,s){const i={method:Aa(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,lu(cu({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(e=>{this.setSubscription(e.id,cu({},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,cu({},t)),this.topicMap.set(t.topic,e),this.events.emit(Fc,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}=Ka("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(Wc,lu(cu({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(zc)}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(Hc)}
3async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:e}=Ka("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(gr){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(gr)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async e=>lu(cu({},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))}(u.toMiliseconds(u.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}=Ka("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 pa(e+await this.getClientId())}}var uu=Object.defineProperty,pu=Object.getOwnPropertySymbols,gu=Object.prototype.hasOwnProperty,mu=Object.prototype.propertyIsEnumerable,fu=(e,t,s)=>t in e?uu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,wu=(e,t)=>{for(var s in t||(t={}))gu.call(t,s)&&fu(e,s,t[s]);if(pu)for(var s of pu(t))mu.call(t,s)&&fu(e,s,t[s]);return e},vu=(e,t,s)=>fu(e,"symbol"!=typeof t?t+"":t,s);class yu extends Ds{constructor(e){super(e),vu(this,"protocol","wc"),vu(this,"version",2),vu(this,"core"),vu(this,"logger"),vu(this,"events",new n.EventEmitter),vu(this,"provider"),vu(this,"messages"),vu(this,"subscriber"),vu(this,"publisher"),vu(this,"name","relayer"),vu(this,"transportExplicitlyClosed",!1),vu(this,"initialized",!1),vu(this,"connectionAttemptInProgress",!1),vu(this,"relayUrl"),vu(this,"projectId"),vu(this,"packageName"),vu(this,"bundleId"),vu(this,"hasExperiencedNetworkDisruption",!1),vu(this,"pingTimeout"),vu(this,"heartBeatTimeout",u.toMiliseconds(u.THIRTY_SECONDS+u.FIVE_SECONDS)),vu(this,"reconnectTimeout"),vu(this,"connectPromise"),vu(this,"reconnectInProgress",!1),vu(this,"requestsInFlight",[]),vu(this,"connectTimeout",u.toMiliseconds(15*u.ONE_SECOND)),vu(this,"request",async e=>{var t,s;this.logger.debug("Publishing Request Payload");const i=e.id||L().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}}),vu(this,"resetPingTimeout",()=>{ci()&&(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))}),vu(this,"onPayloadHandler",e=>{this.onProviderPayload(e),this.resetPingTimeout()}),vu(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected ð"),this.startPingTimeout(),this.events.emit(kc)}),vu(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected ð"),this.requestsInFlight=[],this.onProviderDisconnect()}),vu(this,"onProviderErrorHandler",e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(Oc,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),vu(this,"registerProviderListeners",()=>{this.provider.on(Rc,this.onPayloadHandler),this.provider.on(Uc,this.onConnectHandler),this.provider.on(Dc,this.onDisconnectHandler),this.provider.on($c,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&"string"!=typeof e.logger?E(e.logger,this.name):P(y({level:e.logger||"error"})),this.messages=new qh(this.logger,e.core),this.subscriber=new hu(this,this.logger),this.publisher=new Zh(this,this.logger),this.relayUrl=(null==e?void 0:e.relayUrl)||Ac,this.projectId=e.projectId,li()&&typeof s<"u"&&typeof(null==s?void 0:s.Platform)<"u"&&"android"===(null==s?void 0:s.Platform.OS)?this.packageName=ui():li()&&typeof s<"u"&&typeof(null==s?void 0:s.Platform)<"u"&&"ios"===(null==s?void 0:s.Platform.OS)&&(this.bundleId=ui()),this.provider={}}
3async 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(gr){this.logger.warn(gr,null==gr?void 0:gr.message)}}get context(){return N(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:Lc.relay},qc)}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(Fc,c),o())};return await Promise.all([new Promise(e=>{o=e,this.subscriber.on(Fc,c)}),new Promise(async(s,i)=>{a=await this.subscriber.subscribe(e,wu({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 Ei(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 pc()))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:Ni(u.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,e)}this.events.emit(Sc,e),await this.recordMessageEvent(e,jc)}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=()=>
3{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Dc,s),await Ei(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(Dc,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(e,t)=>{const s=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Dc,s),await this.subscriber.start().then(e).catch(t).finally(()=>{this.provider.off(Dc,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,u.toMiliseconds(1*t))),t++}}startPingTimeout(){var e,t,s,i,r;if(ci())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 k(new _(fi({sdkVersion:Mc,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}),O(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:Lc.relay,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(wu({type:"event",event:t.id},o)),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else T(e)&&this.events.emit(Pc,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,jc),this.events.emit(Sc,e))}async acknowledgePayload(e){const t=x(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Rc,this.onPayloadHandler),this.provider.off(Uc,this.onConnectHandler),this.provider.off(Dc,this.onDisconnectHandler),this.provider.off($c,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await pc();gc(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(S.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&function(){var e;return!di()||!p.getDocument()||"visible"===(null==(e=p.getDocument())?void 0:e.visibilityState)}())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(pr){this.logger.warn(pr,null==pr?void 0:pr.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(_c),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},u.toMiliseconds(.1)))))}isInitialized(){if(!this.initialized){const{message:e}=Ka("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 bu(){}function Eu(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 Cu(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}
3function Iu(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Nu="[object Arguments]",Au="[object Object]";function Su(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 Pu(e,t,n,o)}return Pu(e,t,n,o)}function Pu(e,t,s,i){if(Object.is(e,t))return!0;let n=Iu(e),o=Iu(t);if(n===Nu&&(n=Au),o===Nu&&(o=Au),n!==o)return!1;switch(n){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 a=(s=s??new Map).get(e),c=s.get(t);if(null!=a&&null!=c)return a===t;s.set(e,t),s.set(t,e);try{switch(n){case"[object Map]":if(e.size!==t.size)return!1;for(const[r,n]of e.entries())if(!t.has(r)||!Su(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=>Su(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 r<"u"&&r.isBuffer(e)!==r.isBuffer(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Su(e[r],t[r],r,e,t,s,i))return!1;return!0;case"[object ArrayBuffer]":return e.byteLength===t.byteLength&&Pu(new Uint8Array(e),new Uint8Array(t),s,i);case"[object DataView]":return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&Pu(new Uint8Array(e),new Uint8Array(t),s,i);case"[object Error]":return e.name===t.name&&e.message===t.message;case Au:{if(!(Pu(e.constructor,t.constructor,s,i)||Eu(e)&&Eu(t)))return!1;const r=[...Object.keys(e),...Cu(e)],n=[...Object.keys(t),...Cu(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(!Su(a,t[n],n,e,t,s,i))return!1}return!0}default:return!1}}finally{s.delete(e),s.delete(t)}}function ku(e,t){return function(e,t,s){return Su(e,t,void 0,void 0,void 0,void 0,s)}(e,t,bu)}var _u=Object.defineProperty,Ou=Object.getOwnPropertySymbols,Tu=Object.prototype.hasOwnProperty,xu=Object.prototype.propertyIsEnumerable,Ru=(e,t,s)=>t in e?_u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Uu=(e,t)=>{for(var s in t||(t={}))Tu.call(t,s)&&Ru(e,s,t[s]);if(Ou)for(var s of Ou(t))xu.call(t,s)&&Ru(e,s,t[s]);return e},Du=(e,t,s)=>Ru(e,"symbol"!=typeof t?t+"":t,s);class $u extends $s{constructor(e,t,s,i=yc,r=void 0){super(e,t,s,i),this.core=e,this.logger=t,this.name=s,Du(this,"map",new Map),Du(this,"version","0.3"),Du(this,"cached",[]),Du(this,"initialized",!1),Du(this,"getKey"),Du(this,"storagePrefix",yc),Du(this,"recentlyDeleted",[]),Du(this,"recentlyDeletedLimit",200),Du(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(e=>{this.getKey&&null!==e&&!Za(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)}),Du(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())}),Du(this,"get",e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e))),Du(this,"getAll",e=>(this.isInitialized(),e?this.values.filter(t=>Object.keys(e).every(s=>ku(t[s],e[s]))):this.values)),Du(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=Uu(Uu({},this.getData(e)),t);this.map.set(e,s),await this.persist()}),Du(this,"delete",async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",ke
3y:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())}),this.logger=E(t,this.name),this.storagePrefix=i,this.getKey=r}get context(){return N(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}=Ka("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=Ka("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}=Ka("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(gr){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(gr)}}isInitialized(){if(!this.initialized){const{message:e}=Ka("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Mu=Object.defineProperty,Lu=(e,t,s)=>((e,t,s)=>t in e?Mu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class ju{constructor(e,t){this.core=e,this.logger=t,Lu(this,"name","pairing"),Lu(this,"version","0.3"),Lu(this,"events",new o),Lu(this,"pairings"),Lu(this,"initialized",!1),Lu(this,"storagePrefix",yc),Lu(this,"ignoredPayloadTypes",[1]),Lu(this,"registeredMethods",[]),Lu(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Lu(this,"register",({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]}),Lu(this,"create",async e=>{this.isInitialized();const t=ha(),s=await this.core.crypto.setSymKey(t),i=Ni(u.FIVE_MINUTES),r={protocol:"irn"},n={topic:s,expiry:i,relay:r,active:!1,methods:null==e?void 0:e.methods},o=_a({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(Kc,n),this.core.expirer.set(s,i),await this.pairings.set(s,n),await this.core.relayer.subscribe(s,{transportType:null==e?void 0:e.transportType}),{topic:s,uri:o}}),Lu(this,"pair",async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:null==e?void 0:e.uri,trace:[ll]}});this.isValidPair(e,t);const{topic:s,symKey:i,relay:r,expiryTimestamp:n,methods:o}=Pa(e.uri);let a;if(t.props.properties.topic=s,t.addTrace(dl),t.addTrace(hl),this.pairings.keys.includes(s)){if(a=this.pairings.get(s),t.addTrace(ml),a.active)throw t.setError(El),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);t.addTrace(fl)}const c=n||Ni(u.FIVE_MINUTES),l={topic:s,relay:r,expiry:c,active:!1,methods:o};this.core.expirer.set(s,c),await this.pairings.set(s,l),t.addTrace(ul),e.activatePairing&&await this.activate({topic:s}),this.events.emit(Kc,l),t.addTrace(wl),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(i,s),t.addTrace(pl);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(yl)}try{await this.core.relayer.subscribe(s,{relay:r})}catch(d){throw t.setError(Cl),d}return t.addTrace(gl),l}),Lu(this,"activate",async({topic:e})=>{this.isInitialized();const t=Ni(u.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})}),Lu(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}=bi();this.events.once(Si("pairing_ping",e),({error:e})=>{e?r(e):i()}),await s()}}),Lu(this,"updateExpiry",async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})}),Lu(this,"updateMetadata",async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})}),Lu(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Lu(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",Ga("USER_DISCONNECTED")),await this.deletePairing(t))}),Lu(this,"formatUriFromPairing",e=>{this.isInitialized();const{topic:t,relay:s,expiry:i,methods:r}=e,n=this.core.crypto.keychain.get(t);return _a({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:n,relay:s,expiryTimestamp:i,methods:r})}),Lu(this,"sendRequest",async(e,t,s)=>{const i=A(t,s),r=await this.core.crypto.encode(e,i),n=Vc[t].req;return this.core.history.set(e,i),this.core.relayer.publish(e,r,n),i.id}),Lu(this,"sendResult",async(e,t,s)=>{const i=x(e,s),r=await this.core.crypto.encode(t,i),n=(await this.core.history.get(t,e)).request.method,o=Vc[n].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(i)}),Lu(this,"sendError",async(e,t,s)=>{const i=j(e,s),r=await this.core.crypto.encode(t,i),n=(await this.core.history.get(t,e)).request.method,o=Vc[n]?Vc[n].res:Vc.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(i)}),Lu(this,"deletePairing",async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Ga("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])}),Lu(this,"cleanup",async()=>{const e=this.pairings.getAll().filter(e=>Ai(e.expiry));await Promise.all(e.map(e=>this.deletePairing(e.topic)))}),Lu(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)}}),Lu(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)}),Lu(this,"onPairingPingRequest",async(e,t)=>{const{id:s}=t;try{this.isValidPing({topic:e}),await this.sendResult(s,e,!0),this.events.emit(Yc,{id:s,topic:e})}catch(i){await this.sendError(s,e,i),this.logger.error(i)}}),Lu(this,"onPairingPingResponse",(e,t)=>{const{id:s}=t;setTimeout(()=>{q(t)?this.events.emit(Si("pairing_ping",s),{}):B(t)&&this.events.emit(Si("pairing_ping",s),{error:t.error})},500)}),Lu(this,"onPairingDeleteRequest",async(e,t)=>{const{id:s}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(Jc,{id:s,topic:e})}catch(i){await this.sendError(s,e,i),this.logger.error(i)}}),Lu(this,"onUnknownRpcMethodRequest",async(e,t)=>{const{id:s,method:i}=t;try{if(this.registeredMethods.includes(i))return;const t=Ga("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)}}),Lu(this,"onUnknownRpcMethodResponse",e=>{this.registeredMethods.includes(e)||this.logger.error(Ga("WC_METHOD_UNSUPPORTED",e))}),Lu(this,"isValidPair",(e,t)=>{var s;if(!ac(e)){const{message:s}=Ka("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(bl),new Error(s)}if(!function(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if(Qa(e,!1))return!!t(e)||t(xi(e))}catch{}return!1}(e.uri)){const{message:s}=Ka("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(bl),new Error(s)}const i=Pa(null==e?void 0:e.uri);if(null==(s=null==i?void 0:i.relay)||!s.protocol){const{message:e}=Ka("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(bl),new Error(e)}if(null==i||!i.symKey){const{message:e}=Ka("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(bl),new Error(e)}if(null!=i&&i.expiryTimestamp&&u.toMiliseconds(null==i?void 0:i.expiryTimestamp)<Date.now()){t.setError(Il);const{message:e}=Ka("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}}),Lu(this,"isValidPing",async e=>{if(!ac(e)){const{message:t}=Ka("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)}),Lu(this,"isValidDisconnect",async e=>{if(!ac(e)){const{message:t}=Ka("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)}),Lu(this,"isValidPairingTopic",async e=>{if(!Qa(e,!1)){const{message:t}=Ka("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=Ka("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Ai(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=Ka("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}),this.core=e,this.logger=E(t,this.name),this.pairings=new $u(this.core,this.logger,this.name,this.storagePrefix)}get context(){return N(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Ka("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Sc,async e=>{const{topic:t,message:s,transportType:i}=e;if(this.pairings.keys.includes(t)&&i!==Lc.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const e=await this.core.crypto.decode(t,s);O(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):T(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(mr){this.logger.error(mr)}})}registerExpirerEvents(){this.core.expirer.on(il,async e=>{const{topic:t}=Ii(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Gc,{topic:t}))})}}var qu=Object.defineProperty,Bu=(e,t,s)=>((e,t,s)=>t in e?qu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Fu extends xs{constructor(e,t){super(e,t),this.core=e,this.logger=t,Bu(this,"records",new Map),Bu(this,"events",new n.EventEmitter),Bu(this,"name","history"),Bu(this,"version","0.3"),Bu(this,"cac
3hed",[]),Bu(this,"initialized",!1),Bu(this,"storagePrefix",yc),Bu(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)}),Bu(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:Ni(u.THIRTY_DAYS)};this.records.set(i.id,i),this.persist(),this.events.emit(Zc,i)}),Bu(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=B(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(Qc,t))}),Bu(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))),Bu(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(Xc,s)}}),this.persist()}),Bu(this,"exists",async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e)),Bu(this,"on",(e,t)=>{this.events.on(e,t)}),Bu(this,"once",(e,t)=>{this.events.once(e,t)}),Bu(this,"off",(e,t)=>{this.events.off(e,t)}),Bu(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=E(t,this.name)}get context(){return N(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:A(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}=Ka("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(el)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=Ka("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(gr){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(gr)}}registerEventListeners(){this.events.on(Zc,e=>{const t=Zc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Qc,e=>{const t=Qc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Xc,e=>{const t=Xc;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(S.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{u.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Xc,t,!1),e=!0)}),e&&this.persist()}catch(gr){this.logger.warn(gr)}}isInitialized(){if(!this.initialized){const{message:e}=Ka("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Wu=Object.defineProperty,zu=(e,t,s)=>((e,t,s)=>t in e?Wu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Hu extends Ls{constructor(e,t){super(e,t),this.core=e,this.logger=t,zu(this,"expirations",new Map),zu(this,"events",new n.EventEmitter),zu(this,"name","expirer"),zu(this,"version","0.3"),zu(this,"cac
3hed",[]),zu(this,"initialized",!1),zu(this,"storagePrefix",yc),zu(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)}),zu(this,"has",e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}}),zu(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(tl,{target:s,expiration:i})}),zu(this,"get",e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)}),zu(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(sl,{target:t,expiration:s})}}),zu(this,"on",(e,t)=>{this.events.on(e,t)}),zu(this,"once",(e,t)=>{this.events.once(e,t)}),zu(this,"off",(e,t)=>{this.events.off(e,t)}),zu(this,"removeListener",(e,t)=>{this.events.removeListener(e,t)}),this.logger=E(t,this.name)}get context(){return N(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 Ci("topic",e)}(e);if("number"==typeof e)return function(e){return Ci("id",e)}(e);const{message:t}=Ka("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(rl)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=Ka("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(gr){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(gr)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:t}=Ka("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:s}=t;u.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(il,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(S.pulse,()=>this.checkExpirations()),this.events.on(tl,e=>{const t=tl;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(il,e=>{const t=il;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(sl,e=>{const t=sl;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Ka("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Vu=Object.defineProperty,Ku=(e,t,s)=>((e,t,s)=>t in e?Vu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Gu extends js{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,Ku(this,"name","verify-api"),Ku(this,"abortController"),Ku(this,"isDevEnv"),Ku(this,"verifyUrlV3",al),Ku(this,"storagePrefix",yc),Ku(this,"version",2),Ku(this,"publicKey"),Ku(this,"fetchPromise"),Ku(this,"init",async()=>{var e;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&u.toMiliseconds(null==(e=this.publicKey)?void 0:e.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ku(this,"register",async e=>{if(!di()||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=p.getDocument(),t=this.startAbortTimer(5*u.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=>
3{if(r.data&&"string"==typeof r.data)try{const n=JSON.parse(r.data);if("verify_attestation"===n.type){if(f(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(n){this.logger.warn(n)}return""}),Ku(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(f(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)}),Ku(this,"fetchAttestation",async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const s=this.startAbortTimer(5*u.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}),Ku(this,"getVerifyUrl",e=>{let t=e||ol;return cl.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${ol}`),t=ol),t}),Ku(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(u.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)}}),Ku(this,"persistPublicKey",async e=>{this.logger.debug("persisting public key to local storage",e),await this.store.setItem(this.storeKey,e),this.publicKey=e}),Ku(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ku(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")}}),Ku(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ku(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}),Ku(this,"validateAttestation",(e,t)=>{const s=Ia(e,t.publicKey),i={hasExpired:u.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=E(t,this.name),this.abortController=new AbortController,this.isDevEnv=Ti(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return N(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),u.toMiliseconds(e))}}var Ju=Object.defineProperty,Yu=(e,t,s)=>((e,t,s)=>t in e?Ju(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Zu extends qs{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Yu(this,"context","echo"),Yu(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=E(t,this.context)}}var Qu=Object.defineProperty,Xu=Object.getOwnPropertySymbols,ep=Object.prototype.hasOwnProperty,tp=Object.prototype.propertyIsEnumerable,sp=(e,t,s)=>t in e?Qu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,ip=(e,t)=>{for(var s in t||(t={}))ep.call(t,s)&&sp(e,s,t[s]);if(Xu)for(var s of Xu(t))tp.call(t,s)&&sp(e,s,t[s]);return e},rp=(e,t,s)=>sp(e,"symbol"!=typeof t?t+"":t,s);
3class np extends Bs{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,rp(this,"context","event-client"),rp(this,"storagePrefix",yc),rp(this,"storageVersion",.1),rp(this,"events",new Map),rp(this,"shouldPersist",!1),rp(this,"init",async()=>{if(!Ti())try{const e={eventId:Oi(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:mi(this.core.relayer.protocol,this.core.relayer.version,Mc)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}}),rp(this,"createEvent",e=>{const{event:t="ERROR",type:s="",properties:{topic:i,trace:r}}=e,n=Oi(),o=this.core.projectId||"",a=Date.now(),c=ip({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}),rp(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?ip(ip({},i),this.setMethods(i.eventId)):void 0}),rp(this,"deleteEvent",e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0}),rp(this,"setEventListeners",()=>{this.core.heartbeat.on(S.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(e=>{u.fromMiliseconds(Date.now())-u.fromMiliseconds(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)})})}),rp(this,"setMethods",e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)})),rp(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)}),rp(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)}),rp(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),rp(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,ip(ip({},e),this.setMethods(e.eventId)))})}catch(e){this.logger.warn(e)}}),rp(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(mr){this.logger.warn(mr)}}),rp(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-${Mc}${t}`,{method:"POST",body:JSON.stringify(e)})}),rp(this,"getAppDomain",()=>gi().url),this.logger=E(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 op=Object.defineProperty,ap=Object.getOwnPropertySymbols,cp=Object.prototype.hasOwnProperty,lp=Object.prototype.propertyIsEnumerable,dp=(e,t,s)=>t in e?op(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,hp=(e,t)=>{for(var s in t||(t={}))cp.call(t,s)&&dp(e,s,t[s]);if(ap)for(var s of ap(t))lp.call(t,s)&&dp(e,s,t[s]);return e},up=(e,t,s)=>dp(e,"symbol"!=typeof t?t+"":t,s);const pp=class e extends _s{constructor(e){var t;super(e),up(this,"protocol","wc"),up(this,"version",2),up(this,"name",vc),up(this,"relayUrl"),up(this,"projectId"),up(this,"customStoragePrefix"),up(this,"events",new n.EventEmitter),up(this,"logger"),up(this,"heartbeat"),up(this,"relayer"),up(this,"crypto"),up(this,"storage"),up(this,"history"),up(this,"expirer"),up(this,"pairing"),up(this,"verify"),up(this,"echoClient"),up(this,"linkModeSupportedApps"),up(this,"eventClient"),up(this,"initialized",!1),up(this,"logChunkController"),up(this,"on",(e,t)=>this.events.on(e,t)),up(this,"once",(e,t)=>this.events.once(e,t)),up(this,"off",(e,t)=>this.events.off(e,t)),up(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),up(this,"dispatchEnvelope",({topic:e,message:t,sessionExists:s})=>{if(!e||!t)return;const i={topic:e,message:t,publishedAt:Date.now(),transportType:Lc.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(a){}this.projectId=null==e?void 0:e.projectId,this.relayUrl=(null==e?void 0:e.relayUrl)||Ac,this.customStoragePrefix=null!=e&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=y({level:"string"==typeof(null==e?void 0:e.logger)&&e.logger?e.logger:bc,name:vc}),{logger:r,chunkLoggerController:o}=b({opts:i,maxSizeInBytes:null==e?void 0:e.maxLogBlobSizeInBytes,loggerOverride:null==e?void 0:e.logger});this.logChunkController=o,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=E(r,this.name),this.heartbeat=new C,this.crypto=new Th(this,this.logger,null==e?void 0:e.keychain),this.history=new Fu(this,this.logger),this.expirer=new Hu(this,this.logger),this.storage=null!=e&&e.storage?e.storage:new I(hp(hp({},Ec),null==e?void 0:e.storageOptions)),this.relayer=new yu({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new ju(this,this.logger),this.verify=new Gu(this,this.logger,this.storage),this.echoClient=new Zu(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new np(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 N(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(Bc,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(
3),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(Bc)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(gr){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,gr),this.logger.error(gr.message),gr}}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(pr){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 t<"u"&&"true"===wc.DISABLE_GLOBAL_CORE}catch{return!0}}},gp="client",mp=`wc@2:${gp}:`,fp=gp,wp="error",vp="WALLETCONNECT_DEEPLINK_CHOICE",yp="Proposal expired",bp=u.SEVEN_DAYS,Ep={wc_sessionPropose:{req:{ttl:u.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:u.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:u.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:u.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:u.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:u.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:u.ONE_DAY,prompt:!1,tag:1104},res:{ttl:u.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:u.ONE_DAY,prompt:!1,tag:1106},res:{ttl:u.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:u.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:u.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:u.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:u.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:u.ONE_DAY,prompt:!1,tag:1112},res:{ttl:u.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:u.ONE_DAY,prompt:!1,tag:1114},res:{ttl:u.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:u.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:u.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:u.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:u.FIVE_MINUTES,prompt:!1,tag:1119}}},Cp={min:u.FIVE_MINUTES,max:u.SEVEN_DAYS},Ip="IDLE",Np="ACTIVE",Ap={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Sp=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Pp="[email protected]:auth:",kp=`${Pp}:PUB_KEY`;var _p=Object.defineProperty,Op=Object.defineProperties,Tp=Object.getOwnPropertyDescriptors,xp=Object.getOwnPropertySymbols,Rp=Object.prototype.hasOwnProperty,Up=Object.prototype.propertyIsEnumerable,Dp=(e,t,s)=>t in e?_p(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,$p=(e,t)=>{for(var s in t||(t={}))Rp.call(t,s)&&Dp(e,s,t[s]);if(xp)for(var s of xp(t))Up.call(t,s)&&Dp(e,s,t[s]);return e},Mp=(e,t)=>Op(e,Tp(t)),Lp=(e,t,s)=>Dp(e,"symbol"!=typeof t?t+"":t,s);class jp extends Hs{constructor(e){super(e),Lp(this,"name","engine"),Lp(this,"events",new o),Lp(this,"initialized",!1),Lp(this,"requestQueue",{state:Ip,queue:[]}),Lp(this,"sessionRequestQueue",{state:Ip,queue:[]}),Lp(this,"requestQueueDelay",u.ONE_SECOND),Lp(this,"expectedPairingMethodMap",new Map),Lp(this,"recentlyDeletedMap",new Map),Lp(this,"recentlyDeletedLimit",200),Lp(this,"relayMessageCache",[]),Lp(this,"pendingSessions",new Map),Lp(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(Ep)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},u.toMiliseconds(this.requestQueueDelay)))}),Lp(this,"connect",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t=Mp($p({},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=Wa(e),l=Wa(t),d={},h=Object.keys(c).concat(Object.keys(l));for(const u of h)d[u]={chains:Pi(null==(s=c[u])?void 0:s.chains,null==(i=l[u])?void 0:i.chains),methods:Pi(null==(r=c[u])?void 0:r.methods,null==(n=l[u])?void 0:n.methods),events:Pi(null==(o=c[u])?void 0:o.events,null==(a=l[u])?void 0:a.events)};return d}(t.requiredNamespaces,t.optionalNamespaces),t.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:r,sessionProperties:n,scopedProperties:o,relays:a}=t;let c,l=s,d=!1;try{if(l){const e=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=e.active}}catch(E){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),E}if(!l||!d){const{topic:e,uri:t}=await this.client.core.pairing.create();l=e,c=t}if(!l){const{message:e}=Ka("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(e)}const h=await this.client.core.crypto.generateKeyPair(),p=Ep.wc_sessionPropose.req.ttl||u.FIVE_MINUTES,g=Ni(p),m=Mp($p($p({requiredNamespaces:i,optionalNamespaces:r,relays:a??[{protocol:"irn"}],proposer:{publicKey:h,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},n&&{sessionProperties:n}),o&&{scopedProperties:o}),{id:F()}),f=Si("session_connect",m.id),{reject:w,resolve:v,done:y}=bi(p,yp),b=({id:e})=>
3{e===m.id&&(this.client.events.off("proposal_expire",b),this.pendingSessions.delete(m.id),this.events.emit(f,{error:{message:yp,code:0}}))};return this.client.events.on("proposal_expire",b),this.events.once(f,({error:e,session:t})=>{this.client.events.off("proposal_expire",b),e?w(e):t&&v(t)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:m,throwOnFailedPublish:!0,clientRpcId:m.id}),await this.setProposal(m.id,m),{uri:c,approval:y}}),Lp(this,"pair",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(pr){throw this.client.logger.error("pair() failed"),pr}}),Lp(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:[Al]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(I){throw r.setError(Ul),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(ql),I}try{await this.isValidApprove(e)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(jl),I}const{id:n,relayProtocol:o,namespaces:a,sessionProperties:c,scopedProperties:l,sessionConfig:d}=e,h=this.client.proposal.get(n);this.client.core.eventClient.deleteEvent({eventId:r.eventId});const{pairingTopic:u,proposer:p,requiredNamespaces:g,optionalNamespaces:m}=h;let f=null==(s=this.client.core.eventClient)?void 0:s.getEvent({topic:u});f||(f=null==(i=this.client.core.eventClient)?void 0:i.createEvent({type:Al,properties:{topic:u,trace:[Al,Sl]}}));const w=await this.client.core.crypto.generateKeyPair(),v=p.publicKey,y=await this.client.core.crypto.generateSharedKey(w,v),b=$p($p($p({relay:{protocol:o??"irn"},namespaces:a,controller:{publicKey:w,metadata:this.client.metadata},expiry:Ni(bp)},c&&{sessionProperties:c}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),E=Lc.relay;f.addTrace(Pl);try{await this.client.core.relayer.subscribe(y,{transportType:E})}catch(I){throw f.setError($l),I}f.addTrace(kl);const C=Mp($p({},b),{topic:y,requiredNamespaces:g,optionalNamespaces:m,pairingTopic:u,acknowledged:!1,self:b.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:w,transportType:Lc.relay});await this.client.session.set(y,C),f.addTrace(Tl);try{f.addTrace(xl),await this.sendRequest({topic:y,method:"wc_sessionSettle",params:b,throwOnFailedPublish:!0}).catch(e=>{throw null==f||f.setError(Ll),e}),f.addTrace(Rl),f.addTrace(_l),await this.sendResult({id:n,topic:u,result:{relay:{protocol:o??"irn"},responderPublicKey:w},throwOnFailedPublish:!0}).catch(e=>{throw null==f||f.setError(Ml),e}),f.addTrace(Ol)}catch(I){throw this.client.logger.error(I),this.client.session.delete(y,Ga("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(y),I}return this.client.core.eventClient.deleteEvent({eventId:f.eventId}),await this.client.core.pairing.updateMetadata({topic:u,metadata:p.metadata}),await this.client.proposal.delete(n,Ga("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:u}),await this.setExpiry(y,Ni(bp)),{topic:y,acknowledged:()=>Promise.resolve(this.client.session.get(y))}}),Lp(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:Ep.wc_sessionPropose.reject}),await this.client.proposal.delete(t,Ga("USER_DISCONNECTED")))}),Lp(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}=bi(),o=F(),a=L().toString(),c=this.client.session.get(t).namespaces;return this.events.once(Si("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}}),Lp(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=F(),{done:i,resolve:r,reject:n}=bi();return this.events.once(Si("session_extend",s),({error:e})=>{e?n(e):r()}),await this.setExpiry(t,Ni(bp)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(e=>{n(e)}),{acknowledged:i}}),Lp(this,"request",async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:t,request:s,topic:i,expiry:r=Ep.wc_sessionRequest.req.ttl}=e,n=this.client.session.get(i);(null==n?void 0:n.transportType)===Lc.relay&&await this.confirmOnlineStateOrThrow();const o=F(),a=L().toString(),{done:c,resolve:l,reject:d}=bi(r,"Request expired. Please try again.");this.events.once(Si("session_request",o),({error:e,result:t})=>{e?d(e):l(t)});const h="wc_sessionRequest",u=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);if(u)return await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:i,method:h,params:{request:Mp($p({},s),{expiryTimestamp:Ni(r)}),chainId:t},expiry:r,throwOnFailedPublish:!0,appLink:u}).catch(e=>d(e)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:t,id:o}),await c();const p={request:Mp($p({},s),{expiryTimestamp:Ni(r)}),chainId:t},g=this.shouldSetTVF(h,p);return await Promise.all([new Promise(async e=>{await this.sendRequest($p({clientRpcId:o,relayRpcId:a,topic:i,method:h,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(di()&&(s=localStorage.getItem(t),s))return s;s=await e.getItem(t)}catch(r){}return s}(this.client.core.storage,vp);await ki({id:o,topic:i,wcDeepLink:e})}e()}),c()]).then(e=>e[2])}),Lp(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===Lc.relay&&await this.confirmOnlineStateOrThrow();const n=this.getAppLinkIfEnabled(r.peer.metadata,r.transportType);q(s)?await this.sendResult({id:i,topic:t,result:s.result,throwOnFailedPublish:!0,appLink:n}
3):B(s)&&await this.sendError({id:i,topic:t,error:s.error,appLink:n}),this.cleanupAfterResponse(e)}),Lp(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=F(),s=L().toString(),{done:i,resolve:r,reject:n}=bi();this.events.once(Si("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}))}),Lp(this,"emit",async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:s,chainId:i}=e,r=L().toString(),n=F();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:r,clientRpcId:n})}),Lp(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:Ga("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=Ka("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}await this.client.core.pairing.disconnect({topic:t})}}),Lp(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!!wi(r,i)&&(i.forEach(t=>{const{accounts:i,methods:r,events:o}=e.namespaces[t],a=qa(i),c=s[t];wi(Gs(t,c),a)&&wi(c.methods,r)&&wi(c.events,o)||(n=!1)}),n)}(t,e)))),Lp(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),Lp(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?Lc.link_mode:Lc.relay;r===Lc.relay&&await this.confirmOnlineStateOrThrow();const{chains:n,statement:o="",uri:a,domain:c,nonce:l,type:d,exp:h,nbf:u,methods:p=[],expiry:g}=e,m=[...e.resources||[]],{topic:f,uri:w}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:r});this.client.logger.info({message:"Generated new pairing",pairing:{topic:f,uri:w}});const v=await this.client.core.crypto.generateKeyPair(),y=ua(v);if(await Promise.all([this.client.auth.authKeys.set(kp,{responseTopic:y,publicKey:v}),this.client.auth.pairingTopics.set(y,{topic:y,pairingTopic:f})]),await this.client.core.relayer.subscribe(y,{transportType:r}),this.client.logger.info(`sending request to new pairing topic: ${f}`),p.length>0){const{namespace:e}=Ks(n[0]);let t=Dr(e,"request",p);jr(m)&&(t=$r(t,m.pop())),m.push(t)}const b=g&&g>Ep.wc_sessionAuthenticate.req.ttl?g:Ep.wc_sessionAuthenticate.req.ttl,E={authPayload:{type:d??"caip122",chains:n,statement:o,aud:a,domain:c,version:"1",nonce:l,iat:(new Date).toISOString(),exp:h,nbf:u,resources:m},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:Ni(b)},C={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:n,methods:[...new Set(["personal_sign",...p])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:f,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:Ni(Ep.wc_sessionPropose.req.ttl),id:F()},{done:I,resolve:N,reject:S}=bi(b,"Request expired"),P=F(),k=Si("session_connect",C.id),_=Si("session_request",P),O=async({error:e,session:t})=>{this.events.off(_,T),e?S(e):t&&N({session:t})},T=async e=>{var s,i,n;if(await this.deletePendingAuthRequest(P,{message:"fulfilled",code:0}),e.error){const t=Ga("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(k,O),S(e.error.message))}
3await this.deleteProposal(C.id),this.events.off(k,O);const{cacaos:o,responder:a}=e.result,c=[],l=[];for(const t of o){await _r({cacao:t,projectId:this.client.core.projectId})||(this.client.logger.error(t,"Signature verification failed"),S(Ga("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:e}=t,s=jr(e.resources),i=[Pr(e.iss)],r=kr(e.iss);if(s){const e=Mr(s),t=Lr(s);c.push(...e),i.push(...t)}for(const t of i)l.push(`${t}:${r}`)}const d=await this.client.core.crypto.generateSharedKey(v,a.publicKey);let h;c.length>0&&(h={topic:d,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:a,controller:a.publicKey,expiry:Ni(bp),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:f,namespaces:za([...new Set(c)],[...new Set(l)]),transportType:r},await this.client.core.relayer.subscribe(d,{transportType:r}),await this.client.session.set(d,h),f&&await this.client.core.pairing.updateMetadata({topic:f,metadata:a.metadata}),h=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:Lc.link_mode})),N({auths:o,session:h})};let x;this.events.once(k,O),this.events.once(_,T);try{if(i){const e=A("wc_sessionAuthenticate",E,P);this.client.core.history.set(f,e);const s=await this.client.core.crypto.encode("",e,{type:2,encoding:la});x=Oa(t,f,s)}else await Promise.all([this.sendRequest({topic:f,method:"wc_sessionAuthenticate",params:E,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:P}),this.sendRequest({topic:f,method:"wc_sessionPropose",params:C,expiry:Ep.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:C.id})])}catch(R){throw this.events.off(k,O),this.events.off(_,T),R}return await this.setProposal(C.id,C),await this.setAuthRequest(P,{request:Mp($p({},E),{verifyContext:{}}),pairingTopic:f,transportType:r}),{uri:x??w,response:I}}),Lp(this,"approveSessionAuthenticate",async e=>{const{id:t,auths:s}=e,i=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[Bl]}});try{this.isInitialized()}catch(g){throw i.setError(Gl),g}const r=this.getPendingAuthRequest(t);if(!r)throw i.setError(Ql),new Error(`Could not find pending auth request with id ${t}`);const n=r.transportType||Lc.relay;n===Lc.relay&&await this.confirmOnlineStateOrThrow();const o=r.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ua(o),l={type:1,receiverPublicKey:o,senderPublicKey:a},d=[],h=[];for(const m of s){if(!(await _r({cacao:m,projectId:this.client.core.projectId}))){i.setError(Jl);const e=Ga("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:c,error:e,encodeOpts:l}),new Error(e.message)}i.addTrace(Wl);const{p:e}=m,s=jr(e.resources),r=[Pr(e.iss)],n=kr(e.iss);if(s){const e=Mr(s),t=Lr(s);d.push(...e),r.push(...t)}for(const t of r)h.push(`${t}:${n}`)}const u=await this.client.core.crypto.generateSharedKey(a,o);let p;if(i.addTrace(Fl),(null==d?void 0:d.length)>0){p={topic:u,acknowledged:!0,self:{publicKey:a,metadata:this.client.metadata},peer:{publicKey:o,metadata:r.requester.metadata},controller:o,expiry:Ni(bp),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:za([...new Set(d)],[...new Set(h)]),transportType:n},i.addTrace(Hl);try{await this.client.core.relayer.subscribe(u,{transportType:n})}catch(g){throw i.setError(Yl),g}i.addTrace(Vl),await this.client.session.set(u,p),i.addTrace(zl),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}i.addTrace(Kl);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(Zl),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}}),Lp(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===Lc.relay&&await this.confirmOnlineStateOrThrow();const r=i.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),o=ua(r),a={type:1,receiverPublicKey:r,senderPublicKey:n};
3await this.sendError({id:t,topic:o,error:s,encodeOpts:a,rpcOpts:Ep.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,Ga("USER_DISCONNECTED"))}),Lp(this,"formatAuthMessage",e=>{this.isInitialized();const{request:t,iss:s}=e;return Or(t,s)}),Lp(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(gr){this.client.logger.error(gr)}},50)}),Lp(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(pr){this.client.logger.error(pr)}}),Lp(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,Ga("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(vp).catch(e=>this.client.logger.warn(e)),this.getPendingSessionRequests().forEach(e=>{e.topic===s&&this.deletePendingSessionRequest(e.id,Ga("USER_DISCONNECTED"))}),s===(null==(t=this.sessionRequestQueue.queue[0])?void 0:t.topic)&&(this.sessionRequestQueue.state=Ip),r&&this.client.events.emit("session_delete",{id:n,topic:s})}),Lp(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(Dl)}catch{}await Promise.all([this.client.proposal.delete(e,Ga("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")}),Lp(this,"deletePendingSessionRequest",async(e,t,s=!1)=>{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=Ip,this.client.events.emit("session_request_expire",{id:e}))}),Lp(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)])}),Lp(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}))}),Lp(this,"setProposal",async(e,t)=>{this.client.core.expirer.set(e,Ni(Ep.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)}),Lp(this,"setAuthRequest",async(e,t)=>{const{request:s,pairingTopic:i,transportType:r=Lc.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})}),Lp(this,"setPendingSessionRequest",async e=>{const{id:t,topic:s,params:i,verifyContext:r}=e,n=i.request.expiryTimestamp||Ni(Ep.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})}),Lp(this,"sendRequest",async e=>{const{topic:t,method:i,params:r,expiry:n,relayRpcId:o,clientRpcId:a,throwOnFailedPublish:c,appLink:l,tvf:d}=e,h=A(i,r,a);let u;const p=!!l;try{const e=p?la:ca;u=await this.client.core.crypto.encode(t,h,{encoding:e})}catch(f){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),f}let g;if(Sp.includes(i)){const e=pa(JSON.stringify(h)),t=pa(u);g=await this.client.core.verify.register({id:t,decryptedId:e})}const m=Ep[i].req;if(m.attestation=g,n&&(m.ttl=n),o&&(m.id=o),this.client.core.history.set(t,h),p){const e=Oa(l,t,u);await s.Linking.openURL(e,this.client.name)}else{const e=Ep[i].req;n&&(e.ttl=n),o&&(e.id=o),e.tvf=Mp($p({},d),{correlationId:h.id}),c?(e.internal=Mp($p({},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 h.id}),Lp(this,"sendResult",async e=>{const{id:t,topic:i,result:r,throwOnFailedPublish:n,encodeOpts:o,appLink:a}=e,c=x(t,r);let l;const d=a&&typeof(null==s?void 0:s.Linking)<"u";try{const e=d?la:ca;l=await this.client.core.crypto.encode(i,c,Mp($p({},o||{}),{encoding:e}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,u;try{h=await this.client.core.history.get(i,t);const e=h.request;try{this.shouldSetTVF(e.method,e.params)&&(u=this.getTVFParams(t,e.params,r))}catch(g){this.client.logger.warn("sendResult() -> getTVFParams() failed",g)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${t}) failed`),p}if(d){const e=Oa(a,i,l);await s.Linking.openURL(e,this.client.name)}else{const e=h.request.method,s=Ep[e].res;s.tvf=Mp($p({},u),{correlationId:t}),n?(s.internal=Mp($p({},s.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,s)):this.client.core.relayer.publish(i,l,s).catch(e=>this.client.logger.error(e))}await this.client.core.history.resolve(c)}),Lp(this,"sendError",async e=>{const{id:t,topic:i,error:r,encodeOpts:n,rpcOpts:o,appLink:a}=e,c=j(t,r);let l;const d=a&&typeof(null==s?void 0:s.Linking)<"u";try{const e=d?la:ca;l=await this.client.core.crypto.encode(i,c,Mp($p({},n||{}),{encoding:e}))}catch(u){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),u}let h;try{h=await this.client.core.history.get(i,t)}catch(u){throw this.client.logger.error(`sendError() -> history.get(${i}, ${t}) failed`),u}if(d){const e=Oa(a,i,l);await s.Linking.openURL(e,this.client.name)}else{const e=h.request.method,t=o||Ep[e].res;this.client.core.relayer.publish(i,l,t)}await this.client.core.history.resolve(c)}),Lp(this,"cleanup",async()=>{const e=[],t=[];
3this.client.session.getAll().forEach(t=>{let s=!1;Ai(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=>{Ai(e.expiryTimestamp)&&t.push(e.id)}),await Promise.all([...e.map(e=>this.deleteSession({topic:e})),...t.map(e=>this.deleteProposal(e))])}),Lp(this,"onProviderMessageEvent",async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)}),Lp(this,"onRelayEventRequest",async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()}),Lp(this,"processRequestsQueue",async()=>{if(this.requestQueue.state!==Np){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Np;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(pr){this.client.logger.warn(pr)}}this.requestQueue.state=Ip}else this.client.logger.info("Request queue already active, skipping...")}),Lp(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
3({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}`)}}),Lp(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}`)}}),Lp(this,"onRelayEventUnknownPayload",e=>{const{topic:t}=e,{message:s}=Ka("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),Lp(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)}),Lp(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(Nl)),this.isValidConnect($p({},s.params));const a=n.expiryTimestamp||Ni(Ep.wc_sessionPropose.req.ttl),c=$p({id:o,pairingTopic:t,expiryTimestamp:a},n);await this.setProposal(o,c);const l=await this.getVerifyContext({attestationId:i,hash:pa(JSON.stringify(s)),encryptedId:r,metadata:c.proposer.metadata});null==e||e.addTrace(vl),this.client.events.emit("session_proposal",{id:o,params:c,verifyContext:l})}catch(a){await this.sendError({id:o,topic:t,error:a,rpcOpts:Ep.wc_sessionPropose.autoReject}),this.client.logger.error(a)}}),Lp(this,"onSessionProposeResponse",async(e,t,s)=>{const{id:i}=t;if(q(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(B(t)){await this.client.proposal.delete(i,Ga("USER_DISCONNECTED"));const e=Si("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})}}),Lp(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 h=this.client.proposal.get(d.proposalId),u=Mp($p($p($p({topic:e,relay:s,expiry:n,namespaces:o,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:h.requiredNamespaces,optionalNamespaces:h.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:Lc.relay});await this.client.session.set(u.topic,u),await this.setExpiry(u.topic,u.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:u.peer.metadata}),this.client.events.emit("session_connect",{session:u}),this.events.emit(Si("session_connect",d.proposalId),{session:u}
3),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(u),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)}}),Lp(this,"onSessionSettleResponse",async(e,t)=>{const{id:s}=t;q(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(Si("session_approve",s),{})):B(t)&&(await this.client.session.delete(e,Ga("USER_DISCONNECTED")),this.events.emit(Si("session_approve",s),{error:t.error}))}),Lp(this,"onSessionUpdateRequest",async(e,t)=>{const{params:s,id:i}=t;try{const t=`${e}_session_update`,n=fc.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:Ga("INVALID_UPDATE_REQUEST")});this.isValidUpdate($p({topic:e},s));try{fc.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 fc.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)}}),Lp(this,"isRequestOutOfSync",(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3)),Lp(this,"onSessionUpdateResponse",(e,t)=>{const{id:s}=t,i=Si("session_update",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);q(t)?this.events.emit(Si("session_update",s),{}):B(t)&&this.events.emit(Si("session_update",s),{error:t.error})}),Lp(this,"onSessionExtendRequest",async(e,t)=>{const{id:s}=t;try{this.isValidExtend({topic:e}),await this.setExpiry(e,Ni(bp)),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)}}),Lp(this,"onSessionExtendResponse",(e,t)=>{const{id:s}=t,i=Si("session_extend",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);q(t)?this.events.emit(Si("session_extend",s),{}):B(t)&&this.events.emit(Si("session_extend",s),{error:t.error})}),Lp(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)}}),Lp(this,"onSessionPingResponse",(e,t)=>{const{id:s}=t,i=Si("session_ping",s);setTimeout(()=>{if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners 2176`);q(t)?this.events.emit(Si("session_ping",s),{}):B(t)&&this.events.emit(Si("session_ping",s),{error:t.error})},500)}),Lp(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(xc,async()=>{t(await this.deleteSession({topic:e,id:s}))})}),this.sendResult({id:s,topic:e,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:e,error:Ga("USER_DISCONNECTED")})]).catch(e=>this.client.logger.error(e))}catch(i){this.client.logger.error(i)}}),Lp(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($p({topic:r},d));const e=this.client.session.get(r),n={id:l,topic:r,params:d,verifyContext:await this.getVerifyContext({attestationId:o,hash:pa(JSON.stringify(A("wc_sessionRequest",d,l))),encryptedId:a,metadata:e.peer.metadata,transportType:c})};await this.setPendingSessionRequest(n),c===Lc.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())}
3catch(h){await this.sendError({id:l,topic:r,error:h}),this.client.logger.error(h)}}),Lp(this,"onSessionRequestResponse",(e,t)=>{const{id:s}=t,i=Si("session_request",s);if(0===this.events.listenerCount(i))throw new Error(`emitting ${i} without any listeners`);q(t)?this.events.emit(Si("session_request",s),{result:t.result}):B(t)&&this.events.emit(Si("session_request",s),{error:t.error})}),Lp(this,"onSessionEventRequest",async(e,t)=>{const{id:s,params:i}=t;try{const t=`${e}_session_event_${i.event.name}`,r=fc.get(t);if(r&&this.isRequestOutOfSync(r,s))return void this.client.logger.info(`Discarding out of sync request - ${s}`);this.isValidEmit($p({topic:e},i)),this.client.events.emit("session_event",{id:s,topic:e,params:i}),fc.set(t,s)}catch(r){await this.sendError({id:s,topic:e,error:r}),this.client.logger.error(r)}}),Lp(this,"onSessionAuthenticateResponse",(e,t)=>{const{id:s}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),q(t)?this.events.emit(Si("session_request",s),{result:t.result}):B(t)&&this.events.emit(Si("session_request",s),{error:t.error})}),Lp(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:pa(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===Lc.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:Ep.wc_sessionAuthenticate.autoReject,appLink:r})}}),Lp(this,"addSessionRequestToSessionRequestQueue",e=>{this.sessionRequestQueue.queue.push(e)}),Lp(this,"cleanupAfterResponse",e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ip,this.processSessionRequestQueue()},u.toMiliseconds(this.requestQueueDelay))}),Lp(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=Si("session_request",e.request.id);if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners`);this.events.emit(Si("session_request",e.request.id),{error:t})})}),Lp(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Np)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.sessionRequestQueue.state=Np,this.emitSessionRequest(e)}catch(pr){this.client.logger.error(pr)}else this.client.logger.info("session request queue is empty.")}),Lp(this,"emitSessionRequest",e=>{this.client.events.emit("session_request",e)}),Lp(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);
3t&&this.onSessionProposeRequest({topic:e.topic,payload:A("wc_sessionPropose",Mp($p({},t),{requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties}),t.id)})}),Lp(this,"isValidConnect",async e=>{if(!ac(e)){const{message:t}=Ka("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(Za(t)||await this.isValidPairingTopic(t),!function(e){let t=!1;return e?e&&Ja(e)&&e.length&&e.forEach(e=>{t=oc(e)}):t=!0,t}(o)){const{message:e}=Ka("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(!Za(s)&&0!==Ya(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(!Za(i)&&0!==Ya(i)&&this.validateNamespaces(i,"optionalNamespaces"),Za(r)||this.validateSessionProps(r,"sessionProperties"),!Za(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)}`)}}),Lp(this,"validateNamespaces",(e,t)=>{const s=function(e,t,s){let i=null;if(e&&Ya(e)){const r=rc(e,t);r&&(i=r);const n=sc(e,t,s);n&&(i=n)}else i=Ka("MISSING_OR_INVALID",`${t}, ${s} should be an object with data`);return i}(e,"connect()",t);if(s)throw new Error(s.message)}),Lp(this,"isValidApprove",async e=>{if(!ac(e))throw new Error(Ka("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=nc(s,"approve()");if(a)throw new Error(a.message);const c=hc(o.requiredNamespaces,s,"approve()");if(c)throw new Error(c.message);if(!Qa(i,!0)){const{message:e}=Ka("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(e)}if(Za(r)||this.validateSessionProps(r,"sessionProperties"),!Za(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(", ")}`)}}),Lp(this,"isValidReject",async e=>{if(!ac(e)){const{message:t}=Ka("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&&Xa(e.code,!1)&&e.message&&Qa(e.message,!1))}(s)){const{message:e}=Ka("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(e)}}),Lp(this,"isValidSessionSettleRequest",e=>{if(!ac(e)){const{message:t}=Ka("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:s,namespaces:i,expiry:r}=e;if(!oc(t)){const{message:e}=Ka("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const n=function(e,t){let s=null;return Qa(null==e?void 0:e.publicKey,!1)||(s=Ka("MISSING_OR_INVALID",`${t} controller public key should be a string`)),s}(s,"onSessionSettleRequest()");if(n)throw new Error(n.message);const o=nc(i,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(Ai(r)){const{message:e}=Ka("EXPIRED","onSessionSettleRequest()");throw new Error(e)}}),Lp(this,"isValidUpdate",async e=>{if(!ac(e)){const{message:t}=Ka("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=nc(s,"update()");if(r)throw new Error(r.message);
3const n=hc(i.requiredNamespaces,s,"update()");if(n)throw new Error(n.message)}),Lp(this,"isValidExtend",async e=>{if(!ac(e)){const{message:t}=Ka("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)}),Lp(this,"isValidRequest",async e=>{if(!ac(e)){const{message:t}=Ka("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(!cc(n,i)){const{message:e}=Ka("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(e)}if(!function(e){return!(Za(e)||!Qa(e.method,!1))}(s)){const{message:e}=Ka("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(e)}if(!lc(n,i,s.method)){const{message:e}=Ka("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(e)}if(r&&!function(e,t){return Xa(e,!1)&&e<=t.max&&e>=t.min}(r,Cp)){const{message:e}=Ka("MISSING_OR_INVALID",`request() expiry: ${r}. Expiry must be a number (in seconds) between ${Cp.min} and ${Cp.max}`);throw new Error(e)}}),Lp(this,"isValidRespond",async e=>{var t;if(!ac(e)){const{message:t}=Ka("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!(Za(e)||Za(e.result)&&Za(e.error)||!Xa(e.id,!1)||!Qa(e.jsonrpc,!1))}(i)){const{message:e}=Ka("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(e)}}),Lp(this,"isValidPing",async e=>{if(!ac(e)){const{message:t}=Ka("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),Lp(this,"isValidEmit",async e=>{if(!ac(e)){const{message:t}=Ka("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(!cc(r,i)){const{message:e}=Ka("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(e)}if(!function(e){return!(Za(e)||!Qa(e.name,!1))}(s)){const{message:e}=Ka("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}if(!dc(r,i,s.name)){const{message:e}=Ka("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(e)}}),Lp(this,"isValidDisconnect",async e=>{if(!ac(e)){const{message:t}=Ka("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)}),Lp(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(!Qa(s,!1))throw new Error("uri is required parameter");if(!Qa(i,!1))throw new Error("domain is required parameter");if(!Qa(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map(e=>Ks(e).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:n}=Ks(t[0]);if("eip155"!==n)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),Lp(this,"getVerifyContext",async e=>{const{attestationId:t,hash:s,encryptedId:i,metadata:r,transportType:n}=e,o={verified:{verifyUrl:r.verifyUrl||ol,validation:"UNKNOWN",origin:r.url||""}};try{if(n===Lc.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}),Lp(this,"validateSessionProps",(e,t)=>{Object.values(e).forEach((s,i)=>{if(null==s){const{message:r}=Ka("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${s} for key ${Object.keys(e)[i]}`);throw new Error(r)}})}),Lp(this,"getPendingAuthRequest",e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0}),Lp(this,"addToRecentlyDeleted",(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0;const t=this.recentlyDeletedLimit/2;
3for(const s of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(s)}}}),Lp(this,"checkRecentlyDeleted",e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:s}=Ka("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(s)}}),Lp(this,"isLinkModeEnabled",(e,t)=>{var i,r,n,o,a,c,l,d,h;return!(!e||t!==Lc.link_mode)&&(!0===(null==(r=null==(i=this.client.metadata)?void 0:i.redirect)?void 0:r.linkMode)&&void 0!==(null==(o=null==(n=this.client.metadata)?void 0:n.redirect)?void 0:o.universal)&&""!==(null==(c=null==(a=this.client.metadata)?void 0:a.redirect)?void 0:c.universal)&&void 0!==(null==(l=null==e?void 0:e.redirect)?void 0:l.universal)&&""!==(null==(d=null==e?void 0:e.redirect)?void 0:d.universal)&&!0===(null==(h=null==e?void 0:e.redirect)?void 0:h.linkMode)&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof(null==s?void 0:s.Linking)<"u")}),Lp(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}),Lp(this,"handleLinkModeMessage",({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=_i(e,"topic")||"",s=decodeURIComponent(_i(e,"wc_ev")||""),i=this.client.session.keys.includes(t);i&&this.client.session.update(t,{transportType:Lc.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:s,sessionExists:i})}),Lp(this,"registerLinkModeListeners",async()=>{var e;if(Ti()||li()&&null!=(e=this.client.metadata.redirect)&&e.linkMode){const e=null==s?void 0:s.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)}}}),Lp(this,"shouldSetTVF",(e,t)=>{if(!t||"wc_sessionRequest"!==e)return!1;const{request:s}=t;return Object.keys(Ap).includes(s.method)}),Lp(this,"getTVFParams",(e,t,s)=>{var i,r;try{const n=t.request.method,o=this.extractTxHashesFromResult(n,s);return Mp($p({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{}}),Lp(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}),Lp(this,"extractTxHashesFromResult",(e,t)=>{try{if("string"==typeof t)return[t];const s=t[Ap[e].key];if(Ja(s))return"solana_signAllTransactions"===e?s.map(e=>function(e){const t=atob(e),s=new Uint8Array(t.length);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);const i=s[0];if(0===i)throw new Error("No signatures found");const n=1+64*i;if(s.length<n)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const o=r.from(e,"base64").slice(1,65);return w.encode(o)}(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(mr){this.client.logger.warn("processPendingMessageEvents failed",mr)}}isInitialized(){if(!this.initialized){const{message:e}=Ka("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Sc,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(kp)?this.client.auth.authKeys.get(kp):{publicKey:void 0};try{const e=await this.client.core.crypto.decode(t,s,{receiverPublicKey:n,encoding:r===Lc.link_mode?la:ca});O(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:i,transportType:r,encryptedId:pa(s)})):T(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(il,async e=>
3{const{topic:t,id:s}=Ii(e.target);return s&&this.client.pendingRequest.keys.includes(s)?await this.deletePendingSessionRequest(s,Ka("EXPIRED"),!0):s&&this.client.auth.requests.keys.includes(s)?await this.deletePendingAuthRequest(s,Ka("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(Kc,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Jc,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Qa(e,!1)){const{message:t}=Ka("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}=Ka("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Ai(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=Ka("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!Qa(e,!1)){const{message:t}=Ka("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}=Ka("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Ai(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=Ka("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=Ka("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(Qa(e,!1)){const{message:t}=Ka("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=Ka("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}=Ka("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=Ka("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Ai(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=Ka("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class qp extends $u{constructor(e,t){super(e,t,"proposal",mp),this.core=e,this.logger=t}}let Bp=class extends $u{constructor(e,t){super(e,t,"session",mp),this.core=e,this.logger=t}};class Fp extends $u{constructor(e,t){super(e,t,"request",mp,e=>e.id),this.core=e,this.logger=t}}class Wp extends $u{constructor(e,t){super(e,t,"authKeys",Pp,()=>kp),this.core=e,this.logger=t}}class zp extends $u{constructor(e,t){super(e,t,"pairingTopics",Pp),this.core=e,this.logger=t}}class Hp extends $u{constructor(e,t){super(e,t,"requests",Pp,e=>e.id),this.core=e,this.logger=t}}var Vp=Object.defineProperty,Kp=(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 Gp{constructor(e,t){this.core=e,this.logger=t,Kp(this,"authKeys"),Kp(this,"pairingTopics"),Kp(this,"requests"),this.authKeys=new Wp(this.core,this.logger),this.pairingTopics=new zp(this.core,this.logger),this.requests=new Hp(this.core,this.logger)}
3async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Jp=Object.defineProperty,Yp=(e,t,s)=>((e,t,s)=>t in e?Jp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let Zp=class e extends zs{constructor(e){super(e),Yp(this,"protocol","wc"),Yp(this,"version",2),Yp(this,"name",fp),Yp(this,"metadata"),Yp(this,"core"),Yp(this,"logger"),Yp(this,"events",new n.EventEmitter),Yp(this,"engine"),Yp(this,"session"),Yp(this,"proposal"),Yp(this,"pendingRequest"),Yp(this,"auth"),Yp(this,"signConfig"),Yp(this,"on",(e,t)=>this.events.on(e,t)),Yp(this,"once",(e,t)=>this.events.once(e,t)),Yp(this,"off",(e,t)=>this.events.off(e,t)),Yp(this,"removeListener",(e,t)=>this.events.removeListener(e,t)),Yp(this,"removeAllListeners",e=>this.events.removeAllListeners(e)),Yp(this,"connect",async e=>{try{return await this.engine.connect(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"pair",async e=>{try{return await this.engine.pair(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"approve",async e=>{try{return await this.engine.approve(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"reject",async e=>{try{return await this.engine.reject(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"update",async e=>{try{return await this.engine.update(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"extend",async e=>{try{return await this.engine.extend(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"request",async e=>{try{return await this.engine.request(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"respond",async e=>{try{return await this.engine.respond(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"ping",async e=>{try{return await this.engine.ping(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"emit",async e=>{try{return await this.engine.emit(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"disconnect",async e=>{try{return await this.engine.disconnect(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"find",e=>{try{return this.engine.find(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(pr){throw this.logger.error(pr.message),pr}}),Yp(this,"authenticate",async(e,t)=>{try{return await this.engine.authenticate(e,t)}catch(s){throw this.logger.error(s.message),s}}),Yp(this,"formatAuthMessage",e=>{try{return this.engine.formatAuthMessage(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(this,"approveSessionAuthenticate",async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(t){throw this.logger.error(t.message),t}}),Yp(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)||fp,this.metadata=pi(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:P(y({level:(null==e?void 0:e.logger)||wp}));this.core=(null==e?void 0:e.core)||new pp(e),this.logger=E(t,this.name),this.session=new Bp(this.core,this.logger),this.proposal=new qp(this.core,this.logger),this.pendingRequest=new Fp(this.core,this.logger),this.engine=new jp(this),this.auth=new Gp(this.core,this.logger)}static async init(t){const s=new e(t);return await s.initialize(),s}get context(){return N(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()},u.toMiliseconds(u.ONE_SECOND))}catch(mr){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(mr.message),mr}}};const Qp="error",Xp="wc@2:universal_provider:",eg="https://rpc.walletconnect.org/v1/",tg="generic",sg=`${eg}bundler`,ig="default_chain_changed";function rg(){}function ng(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function og(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function ag(e){return"object"==typeof e&&null!==e}function cg(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}
3function lg(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const dg="[object RegExp]",hg="[object String]",ug="[object Number]",pg="[object Boolean]",gg="[object Arguments]",mg="[object Symbol]",fg="[object Date]",wg="[object Map]",vg="[object Set]",yg="[object Array]",bg="[object ArrayBuffer]",Eg="[object Object]",Cg="[object DataView]",Ig="[object Uint8Array]",Ng="[object Uint8ClampedArray]",Ag="[object Uint16Array]",Sg="[object Uint32Array]",Pg="[object Int8Array]",kg="[object Int16Array]",_g="[object Int32Array]",Og="[object Float32Array]",Tg="[object Float64Array]";function xg(e,t,s,i=new Map,n=void 0){const o=null==n?void 0:n(e,t,s,i);if(null!=o)return o;if(ng(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 r=0;r<e.length;r++)t[r]=xg(e[r],r,s,i,n);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[r,o]of e)t.set(r,xg(o,r,s,i,n));return t}if(e instanceof Set){const t=new Set;i.set(e,t);for(const r of e)t.add(xg(r,void 0,s,i,n));return t}if(typeof r<"u"&&r.isBuffer(e))return e.subarray();if(og(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);i.set(e,t);for(let r=0;r<e.length;r++)t[r]=xg(e[r],r,s,i,n);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),Rg(t,e,s,i,n),t}if(typeof File<"u"&&e instanceof File){const t=new File([e],e.name,{type:e.type});return i.set(e,t),Rg(t,e,s,i,n),t}if(e instanceof Blob){const t=new Blob([e],{type:e.type});return i.set(e,t),Rg(t,e,s,i,n),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,Rg(t,e,s,i,n),t}if("object"==typeof e&&function(e){switch(lg(e)){case gg:case yg:case bg:case Cg:case pg:case fg:case Og:case Tg:case Pg:case kg:case _g:case wg:case ug:case Eg:case dg:case vg:case hg:case mg:case Ig:case Ng:case Ag:case Sg:return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return i.set(e,t),Rg(t,e,s,i,n),t}return e}function Rg(e,t,s=e,i,r){const n=[...Object.keys(t),...cg(t)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=xg(t[a],a,s,i,r))}}function Ug(e,t){return function(e,t){return xg(e,void 0,e,new Map,t)}(e,(t,s,i,r)=>{if("object"==typeof e)switch(Object.prototype.toString.call(e)){case ug:case hg:case pg:{const t=new e.constructor(null==e?void 0:e.valueOf());return Rg(t,e),t}case gg:{const t={};return Rg(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}})}function Dg(e){return Ug(e)}function $g(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===lg(e)}function Mg(e){return og(e)}function Lg(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 jg(e,t,s,i){if(ng(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(i.has(t))return function(e){if(ng(e))return e;if(Array.isArray(e)||og(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 n=[...Object.keys(t),...cg(t)];for(let o=0;o<n.length;o++){const a=n[o];let c=t[a],l=e[a];if($g(c)&&(c={...c}),$g(l)&&(l={...l}),typeof r<"u"&&r.isBuffer(c)&&(c=Dg(c)),Array.isArray(c))if("object"==typeof l&&null!=l){const e=[],t=Reflect.ownKeys(l);for(let s=0;s<t.length;s++){const i=t[s];e[i]=l[i]}l=e}else l=[];const d=s(l,c,a,e,t,i);null!=d?e[a]=d:Array.isArray(c)||ag(l)&&ag(c)?e[a]=jg(l,c,s,i):null==l&&Lg(c)?e[a]=jg({},c,s,i):null==l&&Mg(c)?e[a]=Dg(c):(void 0===l||void 0!==c)&&(e[a]=c)}return e}function qg(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=jg(r,s[n],i,new Map);return r}(e,...t,rg)}var Bg=Object.defineProperty,Fg=Object.defineProperties,Wg=Object.getOwnPropertyDescriptors,zg=Object.getOwnPropertySymbols,Hg=Object.prototype.hasOwnProperty,Vg=Object.prototype.propertyIsEnumerable,Kg=(e,t,s)=>t in e?Bg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Gg=(e,t)=>{for(var s in t||(t={}))Hg.call(t,s)&&Kg(e,s,t[s]);if(zg)for(var s of zg(t))Vg.call(t,s)&&Kg(e,s,t[s]);return e},Jg=(e,t)=>Fg(e,Wg(t));function Yg(e,t,s){var i;const r=Ks(e);return(null==(i=t.rpcMap)?void 0:i[r.reference])||`${eg}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function Zg(e){return e.includes(":")?e.split(":")[1]:e}function Qg(e){return e.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function Xg(e={},t={}){return qg(em(e),em(t))}function em(e){var t,s,i,r,n;const o={};if(!Ya(e))return o;for(const[a,c]of Object.entries(e)){const e=Ba(a)?[a]:c.chains,l=c.methods||[],d=c.events||[],h=c.rpcMap||{},u=Fa(a);o[u]=Jg(Gg(Gg({},o[u]),c),{chains:Pi(e,null==(t=o[u])?void 0:t.chains),methods:Pi(l,null==(s=o[u])?void 0:s.methods),events:Pi(d,null==(i=o[u])?void 0:i.events)}),(Ya(h)||Ya((null==(r=o[u])?void 0:r.rpcMap)||{}))&&(o[u].rpcMap=Gg(Gg({},h),null==(n=o[u])?void 0:n.rpcMap))}return o}function tm(e){return e.includes(":")?e.split(":")[2]:e}function sm(e){const t={};for(const[s,i]of Object.entries(e)){const e=i.methods||[],r=i.events||[],n=i.accounts||[],o=Ba(s)?[s]:i.chains?i.chains:Qg(i.accounts);t[s]={chains:o,methods:e,events:r,accounts:n}}return t}function im(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 rm={},nm=e=>rm[e],om=(e,t)=>{rm[e]=t};var am=Object.defineProperty,cm=(e,t,s)=>((e,t,s)=>t in e?am(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class lm{constructor(e){cm(this,"name","polkadot"),cm(this,"client"),cm(this,"httpProviders"),cm(this,"events"),cm(this,"namespace"),cm(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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(ig,`${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=Zg(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||Yg(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new k(new W(s,nm("disableProviderPing")))}}var dm=Object.defineProperty,hm=Object.defineProperties,um=Object.getOwnPropertyDescriptors,pm=Object.getOwnPropertySymbols,gm=Object.prototype.hasOwnProperty,mm=Object.prototype.propertyIsEnumerable,fm=(e,t,s)=>t in e?dm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,wm=(e,t)=>{for(var s in t||(t={}))gm.call(t,s)&&fm(e,s,t[s]);if(pm)for(var s of pm(t))mm.call(t,s)&&fm(e,s,t[s]);return e},vm=(e,t)=>
3hm(e,um(t)),ym=(e,t,s)=>fm(e,"symbol"!=typeof t?t+"":t,s);class bm{constructor(e){ym(this,"name","eip155"),ym(this,"client"),ym(this,"chainId"),ym(this,"namespace"),ym(this,"httpProviders"),ym(this,"events"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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(ig,`${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||Yg(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new k(new W(s,nm("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(Zg(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:vm(wm({},c.sessionProperties||{}),{capabilities:vm(wm({},l||{}),{[a]:d})})})}catch(h){}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(A("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()}
3getBundlerUrl(e,t){return`${sg}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var Em=Object.defineProperty,Cm=(e,t,s)=>((e,t,s)=>t in e?Em(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Im{constructor(e){Cm(this,"name","solana"),Cm(this,"client"),Cm(this,"httpProviders"),Cm(this,"events"),Cm(this,"namespace"),Cm(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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(ig,`${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=Zg(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||Yg(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new k(new W(s,nm("disableProviderPing")))}}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","cosmos"),Am(this,"client"),Am(this,"httpProviders"),Am(this,"events"),Am(this,"namespace"),Am(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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(ig,`${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=Zg(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||Yg(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new k(new W(s,nm("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","algorand"),km(this,"client"),km(this,"httpProviders"),km(this,"events"),km(this,"namespace"),km(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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||Yg(`${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(ig,`${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||Yg(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new k(new W(s,nm("disableProviderPing")))}}var Om=Object.defineProperty,Tm=(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 xm{constructor(e){Tm(this,"name","cip34"),Tm(this,"client"),Tm(this,"httpProviders"),Tm(this,"events"),Tm(this,"namespace"),Tm(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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(ig,`${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=Zg(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 k(new W(s,nm("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 Dm{constructor(e){Um(this,"name","elrond"),Um(this,"client"),Um(this,"httpProviders"),Um(this,"events"),Um(this,"namespace"),Um(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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(ig,`${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=Zg(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||Yg(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new k(new W(s,nm("disableProviderPing")))}}var $m=Object.defineProperty,Mm=(e,t,s)=>((e,t,s)=>t in e?$m(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Lm{constructor(e){Mm(this,"name","multiversx"),Mm(this,"client"),Mm(this,"httpProviders"),Mm(this,"events"),Mm(this,"namespace"),Mm(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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(ig,`${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=Zg(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||Yg(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new k(new W(s,nm("disableProviderPing")))}}var jm=Object.defineProperty,qm=(e,t,s)=>((e,t,s)=>t in e?jm(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","near"),qm(this,"client"),qm(this,"httpProviders"),qm(this,"events"),qm(this,"namespace"),qm(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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||Yg(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(ig,`${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||Yg(e,this.namespace);return typeof s>"u"?void 0:new k(new W(s,nm("disableProviderPing")))}}var Fm=Object.defineProperty,Wm=(e,t,s)=>((e,t,s)=>t in e?Fm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class zm{constructor(e){Wm(this,"name","tezos"),Wm(this,"client"),Wm(this,"httpProviders"),Wm(this,"events"),Wm(this,"namespace"),Wm(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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||Yg(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(ig,`${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||Yg(e,this.namespace);return typeof s>"u"?void 0:new k(new W(s))}}var Hm=Object.defineProperty,Vm=(e,t,s)=>((e,t,s)=>t in e?Hm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);
3class Km{constructor(e){Vm(this,"name",tg),Vm(this,"client"),Vm(this,"httpProviders"),Vm(this,"events"),Vm(this,"namespace"),Vm(this,"chainId"),this.namespace=e.namespace,this.events=nm("events"),this.client=nm("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(ig,`${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=>{const t=Ks(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||Yg(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new k(new W(s,nm("disableProviderPing")))}}var Gm=Object.defineProperty,Jm=Object.defineProperties,Ym=Object.getOwnPropertyDescriptors,Zm=Object.getOwnPropertySymbols,Qm=Object.prototype.hasOwnProperty,Xm=Object.prototype.propertyIsEnumerable,ef=(e,t,s)=>t in e?Gm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,tf=(e,t)=>{for(var s in t||(t={}))Qm.call(t,s)&&ef(e,s,t[s]);if(Zm)for(var s of Zm(t))Xm.call(t,s)&&ef(e,s,t[s]);return e},sf=(e,t)=>Jm(e,Ym(t)),rf=(e,t,s)=>ef(e,"symbol"!=typeof t?t+"":t,s);let nf=class e{constructor(e){rf(this,"client"),rf(this,"namespaces"),rf(this,"optionalNamespaces"),rf(this,"sessionProperties"),rf(this,"scopedProperties"),rf(this,"events",new o),rf(this,"rpcProviders",{}),rf(this,"session"),rf(this,"providerOpts"),rf(this,"logger"),rf(this,"uri"),rf(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:P(y({level:(null==e?void 0:e.logger)||Qp})),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:tf({},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,x(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:Ga("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=sm(this.session.namespaces);this.namespaces=Xg(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=sm(i.namespaces);return this.namespaces=Xg(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===tg?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(Ja(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 Zp.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Qp,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=>Fa(e)))];om("client",this.client),om("events",this.events),om("disableProviderPing",this.disableProviderPing),e.forEach(e
3=>{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=Qg(t),i=Xg(this.namespaces,this.optionalNamespaces),r=sf(tf({},i[e]),{accounts:t,chains:s});switch(e){case"eip155":this.rpcProviders[e]=new bm({namespace:r});break;case"algorand":this.rpcProviders[e]=new _m({namespace:r});break;case"solana":this.rpcProviders[e]=new Im({namespace:r});break;case"cosmos":this.rpcProviders[e]=new Sm({namespace:r});break;case"polkadot":this.rpcProviders[e]=new lm({namespace:r});break;case"cip34":this.rpcProviders[e]=new xm({namespace:r});break;case"elrond":this.rpcProviders[e]=new Dm({namespace:r});break;case"multiversx":this.rpcProviders[e]=new Lm({namespace:r});break;case"near":this.rpcProviders[e]=new Bm({namespace:r});break;case"tezos":this.rpcProviders[e]=new zm({namespace:r});break;default:this.rpcProviders[tg]?this.rpcProviders[tg].updateNamespace(r):this.rpcProviders[tg]=new Km({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&&Ja(e)&&this.events.emit("accountsChanged",e.map(tm))}else if("chainChanged"===r.name){const e=s.chainId,t=s.event.data,i=Fa(e),r=im(e)!==im(t)?`${i}:${im(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=sf(tf({},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",sf(tf({},Ga("USER_DISCONNECTED")),{data:e.topic})))}),this.on(ig,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[tg]}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=Xg(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=>Fa(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=Fa(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(tm);if(!Ja(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(`${Xp}/${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(`${Xp}/${e}${s}`)}async deleteFromStore(e){var t;const s=(null==(t=this.session)?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Xp}/${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(Xp)&&await this.client.core.storage.removeItem(e)}catch(gr){this.logger.warn("Failed to cleanup storage",gr)}}};const of={getSIWX:()=>lt.state.siwx,async initializeIfEnabled(){var e;const t=lt.state.siwx,s=cs.getActiveCaipAddress();if(!t||!s)return;const[i,r,n]=s.split(":");
3if(cs.checkIfSupportedNetwork(i))try{if((await t.getSessions(`${i}:${r}`,n)).length)return;await ws.open({view:"SIWXSignMessage"})}catch(o){Ot.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await(null==(e=Zt._getClient())?void 0:e.disconnect().catch(console.error)),$t.reset("Connect"),Vt.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const e=lt.state.siwx,t=rt.getPlainAddress(cs.getActiveCaipAddress()),s=cs.getActiveCaipNetwork(),i=Zt._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();Ft.getConnectorId(s.chainNamespace)===se.CONNECTOR_ID.AUTH&&$t.pushTransactionStack({});const o=await i.signMessage(n);await e.addSession({data:r,message:n,signature:o}),ws.close(),Ot.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){const e=this.getSIWXEventProperties();ws.state.open&&"ApproveTransaction"!==$t.state.view||await ws.open({view:"SIWXSignMessage"}),e.isSmartAccount?Vt.showError("This application might not support Smart Accounts"):Vt.showError("Signature declined"),Ot.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 Zt.disconnect():ws.close(),$t.reset("Connect"),Ot.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){}},async getSessions(){const e=lt.state.siwx,t=rt.getPlainAddress(cs.getActiveCaipAddress()),s=cs.getActiveCaipNetwork();return e&&t&&s?e.getSessions(s.caipNetworkId,t):[]},async isSIWXCloseDisabled(){var e;const t=this.getSIWX();if(t){const s="ApproveTransaction"===$t.state.view,i="SIWXSignMessage"===$t.state.view;if(s||i)return(null==(e=t.getRequired)?void 0:e.call(t))&&0===(await this.get
3Sessions()).length}return!1},async universalProviderAuthenticate({universalProvider:e,chains:t,methods:s}){var i,r,n;const o=of.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=cs.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(Vt.showLoading("Authenticating...",{autoClose:!1}),gs.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),Ot.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:of.getSIWXEventProperties()})}catch(d){throw Ot.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:of.getSIWXEventProperties()}),await e.disconnect().catch(console.error),d}finally{Vt.hide()}}return!0},getSIWXEventProperties(){var e,t;const s=cs.state.activeChain;return{network:(null==(e=cs.state.activeCaipNetwork)?void 0:e.caipNetworkId)||"",isSmartAccount:(null==(t=gs.state.preferredAccountTypes)?void 0:t[s])===Wt.SMART_ACCOUNT}},async clearSessions(){const e=this.getSIWX();e&&await e.setSessions([])}};function af(e,t){return Ft.getConnectorId(e)===t}const cf="eip155",lf="WALLET_CONNECT",df="INJECTED",hf="ANNOUNCED",uf={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:{[se.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[se.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[se.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[se.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[se.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[se.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-454
30-9e6a2b9cae00"},ConnectorNamesMap:{[se.CONNECTOR_ID.INJECTED]:"Browser Wallet",[se.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[se.CONNECTOR_ID.COINBASE]:"Coinbase",[se.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[se.CONNECTOR_ID.LEDGER]:"Ledger",[se.CONNECTOR_ID.SAFE]:"Safe"}},pf={getCaipTokens(e){if(!e)return;const t={};return Object.entries(e).forEach(([e,s])=>{t[`${cf}:${e}`]=s}),t},isLowerCaseMatch:(e,t)=>(null==e?void 0:e.toLowerCase())===(null==t?void 0:t.toLowerCase())};new AbortController;const gf={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 mf={createLogger(e,t="error"){const s=y({level:t}),{logger:i}=b({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 ff(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 wf=["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"],vf={extendRpcUrlWithProjectId(e,t){let s=!1;try{s="rpc.walletconnect.org"===new URL(e).host}catch(gr){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:se.CHAIN.EVM},getCaipNetworkId(e){return this.isCaipNetwork(e)?e.caipNetworkId:`${se.CHAIN.EVM}:${e.id}`},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 wf.includes(t)?ff(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),h=null==(r=e.rpcUrls.default.http)?void 0:r[0],u=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])||h,g=(null==(c=null==i?void 0:i[d])?void 0:c.map(e=>e.url))||[],m=[...g,u],f=[...g];return p&&!f.includes(p)&&f.push(p),{...e,chainNamespace:l,caipNetworkId:d,assets:{imageId:uf.NetworkImageIds[e.id],imageUrl:null==t?void 0:t[e.id]},rpcUrls:{...e.rpcUrls,default:{http:m},chainDefault:{http:f}}}},extendCaipNetworks:(e,{customNetworkImageUrls:t,projectId:s,customRpcUrls:i})=>e.map(e=>vf.extendCaipNetwork(e,{customNetworkImageUrls:t,customRpcUrls:i,projectId:s}
3)),getViemTransport(e,t,s){var i,r,n;const o=[];return null==s||s.forEach(e=>{o.push(Z(e.url,e.config))}),wf.includes(e.caipNetworkId)&&o.push(Z(ff(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(Z(e))}),X(o)},extendWagmiTransports(e,t,s){if(wf.includes(e.caipNetworkId)){const i=this.getDefaultRpcUrl(e,e.caipNetworkId,t);return X([s,Z(i)])}return s},getUnsupportedNetwork:e=>({id:e.split(":")[1],caipNetworkId:e,name:se.UNSUPPORTED_NETWORK_NAME,chainNamespace:e.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}),getCaipNetworkFromStorage(e){var t;const s=it.getActiveCaipNetworkId(),i=cs.getAllRequestedCaipNetworks(),r=Array.from((null==(t=cs.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]))}},yf={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},bf=Ye({providers:{...yf},providerIds:{...yf}}),Ef={state:bf,subscribeKey:(e,t)=>et(bf,e,t),subscribe:e=>Ze(bf,()=>{e(bf)}),subscribeProviders:e=>Ze(bf.providers,()=>e(bf.providers)),setProvider(e,t){t&&(bf.providers[e]=Xe(t))},getProvider:e=>bf.providers[e],setProviderId(e,t){t&&(bf.providerIds[e]=t)},getProviderId(e){if(e)return bf.providerIds[e]},reset(){bf.providers={...yf},bf.providerIds={...yf}},resetChain(e){bf.providers[e]=void 0,bf.providerIds[e]=void 0}},Cf={VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},If={filterOutDuplicatesByRDNS(e){const t=lt.state.enableEIP6963?Ft.state.connectors:[],s=it.getRecentWallets(),i=t.map(e=>{var t;return null==(t=e.info)?void 0:t.rdns}).filter(Boolean),r=s.map(e=>
3e.rdns).filter(Boolean),n=i.concat(r);if(n.includes("io.metamask.mobile")&&rt.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=Ft.state.connectors.filter(e=>"ANNOUNCED"===e.type||"INJECTED"===e.type),s=it.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}=Ft.state,{featuredWalletIds:s}=lt.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=lt.state.features)?void 0:s.connectMethodsOrder),r=t||Ft.state.connectors;if(i)return i;const{injected:n,announced:o}=Nf.getConnectorsByType(r,Ut.state.recommended,Ut.state.featured),a=n.filter(Nf.showConnector),c=o.filter(Nf.showConnector);return a.length||c.length?["wallet","email","social"]:Cf.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(e){const t=Boolean(e.rdns)&&Ut.state.excludedWallets.some(t=>t.rdns===e.rdns),s=Boolean(e.name)&&Ut.state.excludedWallets.some(t=>pf.isLowerCaseMatch(t.name,e.name));return t||s}},Nf={getConnectorsByType(e,t,s){const{customWallets:i}=lt.state,r=it.getRecentWallets(),n=If.filterOutDuplicateWallets(t),o=If.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)&&Ut.state.excludedWallets.some(e=>Boolean(e.rdns)&&e.rdns===s),r=Boolean(e.name)&&Ut.state.excludedWallets.some(t=>pf.isLowerCaseMatch(t.name,e.name));if("INJECTED"===e.type){if("Browser Wallet"===e.name){if(!rt.isMobile())return!1;if(rt.isMobile()&&!s&&!Zt.checkInstalled())return!1}if(i||r)return!1}return"ANNOUNCED"!==e.type&&"EXTERNAL"!==e.type||!i&&!r},getIsConnectedWithWC:()=>Array.from(cs.state.chains.values()).some(e=>Ft.getConnectorId(e.namespace)===se.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=lt.state.features)?void 0:e.connectorTypeOrder)()??[]}){const l=Nf.getIsConnectedWithWC(),d=[{type:"walletConnect",isEnabled:lt.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),h=new Set(d.map(e=>e.type)),u=c.filter(e=>h.has(e)).map(e=>({type:e,isEnabled:!0})),p=d.filter(({type:e})=>!u.some(({type:t})=>t===e));return Array.from(new Set([...u,...p].map(({type:e})=>e)))}},Af=globalThis,Sf=Af.ShadowRoot&&(void 0===Af.ShadyCSS||Af.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Pf=Symbol(),kf=new WeakMap;let _f=class{constructor(e,t,s){if(this._$cssResult$=!0,s!==Pf)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(Sf&&void 0===e){const s=void 0!==t&&1===t.length;s&&(e=kf.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),s&&kf.set(t,e))}return e}toString(){return this.cssText}};const Of=e=>new _f("string"==typeof e?e:e+"",void 0,Pf),Tf=(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 _f(s,e,Pf)},xf=Sf?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const s of e.cssRules)t+=s.cssText;return Of(t)})(e):e,{is:Rf,defineProperty:Uf,getOwnPropertyDescriptor:Df,getOwnPropertyNames:$f,getOwnPropertySymbols:Mf,getPrototypeOf:Lf}=Object,jf=globalThis,qf=jf.trustedTypes,Bf=qf?qf.emptyScript:"",Ff=jf.reactiveElementPolyfillSupport,Wf=(e,t)=>e,zf={toAttribute(e,t){switch(t){case Boolean:e=e?Bf: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}},Hf=(e,t)=>
3!Rf(e,t),Vf={attribute:!0,type:String,converter:zf,reflect:!1,useDefault:!1,hasChanged:Hf}; 4/** 5 * @license 6 * Copyright 2017 Google LLC 7 * SPDX-License-Identifier: BSD-3-Clause 8 */Symbol.metadata??(Symbol.metadata=Symbol("metadata")),jf.litPropertyMetadata??(jf.litPropertyMetadata=new WeakMap);let Kf=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=Vf){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&&Uf(this.prototype,e,i)}}static getPropertyDescriptor(e,t,s){const{get:i,set:r}=Df(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)??Vf}static _$Ei(){if(this.hasOwnProperty(Wf("elementProperties")))return;const e=Lf(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Wf("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Wf("properties"))){const e=this.properties,t=[...$f(e),...Mf(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(xf(e))}else void 0!==e&&t.push(xf(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=>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))}
8removeController(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(Sf)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const s of t){const t=document.createElement("style"),i=Af.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:zf).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:zf;this._$Em=n,this[n]=o.fromAttribute(t,e.type)??(null==(i=this._$Ej)?void 0:i.get(n))??null,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??Hf)(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){}};Kf.elementStyles=[],Kf.shadowRootOptions={mode:"open"},Kf[Wf("elementProperties")]=new Map,Kf[Wf("finalized")]=new Map,null==Ff||Ff({ReactiveElement:Kf}),(jf.reactiveElementVersions??(jf.reactiveElementVersions=[])).push("2.1.0"); 9/** 10 * @license 11 * Copyright 2017 Google LLC 12 * SPDX-License-Identifier: BSD-3-Clause 13 */ 14const Gf=globalThis,Jf=Gf.trustedTypes,Yf=Jf?Jf.createPolicy("lit-html",{createHTML:e=>e}):void 0,Zf="$lit$",Qf=`lit$${Math.random().toFixed(9).slice(2)}$`,Xf="?"+Qf,ew=`<${Xf}>`,tw=document,sw=()=>tw.createComment(""),iw=e=>null===e||"object"!=typeof e&&"function"!=typeof e,rw=Array.isArray,nw="[ \t\n\f\r]",ow=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,aw=/-->
14/g,cw=/>/g,lw=RegExp(`>|${nw}(?:([^\\s"'>=/]+)(${nw}*=${nw}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),dw=/'/g,hw=/"/g,uw=/^(?:script|style|textarea|title)$/i,pw=e=>(t,...s)=>({_$litType$:e,strings:t,values:s}),gw=pw(1),mw=pw(2),fw=Symbol.for("lit-noChange"),ww=Symbol.for("lit-nothing"),vw=new WeakMap,yw=tw.createTreeWalker(tw,129);function bw(e,t){if(!rw(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==Yf?Yf.createHTML(t):t}class Ew{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=ow;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===ow?"!--"===c[1]?o=aw:void 0!==c[1]?o=cw:void 0!==c[2]?(uw.test(c[2])&&(r=RegExp("</"+c[2],"g")),o=lw):void 0!==c[3]&&(o=lw):o===lw?">"===c[0]?(o=r??ow,l=-1):void 0===c[1]?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=void 0===c[3]?lw:'"'===c[3]?hw:dw):o===hw||o===dw?o=lw:o===aw||o===cw?o=ow:(o=lw,r=void 0);const h=o===lw&&e[a+1].startsWith("/>")?" ":"";n+=o===ow?t+ew:l>=0?(i.push(s),t.slice(0,l)+Zf+t.slice(l)+Qf+h):t+Qf+(-2===l?a:h)}return[bw(e,n+(e[s]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),i]})(e,t);if(this.el=Ew.createElement(c,s),yw.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(i=yw.nextNode())&&a.length<o;){if(1===i.nodeType){if(i.hasAttributes())for(const e of i.getAttributeNames())if(e.endsWith(Zf)){const t=l[n++],s=i.getAttribute(e).split(Qf),o=/([.?@])?(.*)/.exec(t);a.push({type:1,index:r,name:o[2],strings:s,ctor:"."===o[1]?Sw:"?"===o[1]?Pw:"@"===o[1]?kw:Aw}),i.removeAttribute(e)}else e.startsWith(Qf)&&(a.push({type:6,index:r}),i.removeAttribute(e));if(uw.test(i.tagName)){const e=i.textContent.split(Qf),t=e.length-1;if(t>0){i.textContent=Jf?Jf.emptyScript:"";for(let s=0;s<t;s++)i.append(e[s],sw()),yw.nextNode(),a.push({type:2,index:++r});i.append(e[t],sw())}}}else if(8===i.nodeType)if(i.data===Xf)a.push({type:2,index:r});else{let e=-1;for(;-1!==(e=i.data.indexOf(Qf,e+1));)a.push({type:7,index:r}),e+=Qf.length-1}r++}}static createElement(e,t){const s=tw.createElement("template");return s.innerHTML=e,s}}function Cw(e,t,s=e,i){var r,n;if(t===fw)return t;let o=void 0!==i?null==(r=s._$Co)?void 0:r[i]:s._$Cl;const a=iw(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=Cw(e,o._$AS(e,t.values),o,i)),t}class Iw{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)??tw).importNode(t,!0);yw.currentNode=i;let r=yw.nextNode(),n=0,o=0,a=s[0];for(;void 0!==a;){if(n===a.index){let t;2===a.type?t=new Nw(r,r.nextSibling,this,e):1===a.type?t=new a.ctor(r,a.name,a.strings,this,e):6===a.type&&(t=new _w(r,this,e)),this._$AV.push(t),a=s[++o]}n!==(null==a?void 0:a.index)&&(r=yw.nextNode(),n++)}return yw.currentNode=tw,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 Nw{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=ww,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=Cw(this,e,t),iw(e)?e===ww||null==e||""===e?(this._$AH!==ww&&this._$AR(),this._$AH=ww):e!==this._$AH&&e!==fw&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>rw(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!==ww&&iw(this._$AH)?this._$AA.nextSibling.data=e:this.T(tw.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=Ew.createElement(bw(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 Iw(r,this),t=e.u(this.options);e.p(s),this.T(t),this._$AH=e}}_$AC(e){let t=vw.get(e.strings);return void 0===t&&vw.set(e.strings,t=new Ew(e)),t}k(e){rw(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 Nw(this.O(sw()),this.O(sw()),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;
14for(null==(s=this._$AP)||s.call(this,!1,!0,t);e&&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 Aw{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,s,i,r){this.type=1,this._$AH=ww,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=ww}_$AI(e,t=this,s,i){const r=this.strings;let n=!1;if(void 0===r)e=Cw(this,e,t,0),n=!iw(e)||e!==this._$AH&&e!==fw,n&&(this._$AH=e);else{const i=e;let o,a;for(e=r[0],o=0;o<r.length-1;o++)a=Cw(this,i[s+o],t,o),a===fw&&(a=this._$AH[o]),n||(n=!iw(a)||a!==this._$AH[o]),a===ww?e=ww:e!==ww&&(e+=(a??"")+r[o+1]),this._$AH[o]=a}n&&!i&&this.j(e)}j(e){e===ww?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Sw extends Aw{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===ww?void 0:e}}class Pw extends Aw{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==ww)}}class kw extends Aw{constructor(e,t,s,i,r){super(e,t,s,i,r),this.type=5}
14_$AI(e,t=this){if((e=Cw(this,e,t,0)??ww)===fw)return;const s=this._$AH,i=e===ww&&s!==ww||e.capture!==s.capture||e.once!==s.once||e.passive!==s.passive,r=e!==ww&&(s===ww||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 _w{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){Cw(this,e)}}const Ow=Gf.litHtmlPolyfillSupport;null==Ow||Ow(Ew,Nw),(Gf.litHtmlVersions??(Gf.litHtmlVersions=[])).push("3.3.0");const Tw=globalThis; 15/** 16 * @license 17 * Copyright 2017 Google LLC 18 * SPDX-License-Identifier: BSD-3-Clause 19 */class xw extends Kf{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 Nw(t.insertBefore(sw(),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 fw}}xw._$litElement$=!0,xw.finalized=!0,null==(e=Tw.litElementHydrateSupport)||e.call(Tw,{LitElement:xw});const Rw=Tw.litElementPolyfillSupport;let Uw,Dw,$w;function Mw(e,t){Uw=document.createElement("style"),Dw=document.createElement("style"),$w=document.createElement("style"),Uw.textContent=jw(e).core.cssText,Dw.textContent=jw(e).dark.cssText,$w.textContent=jw(e).light.cssText,document.head.appendChild(Uw),document.head.appendChild(Dw),document.head.appendChild($w),Lw(t)}function Lw(e){Dw&&$w&&("light"===e?(Dw.removeAttribute("media"),$w.media="enabled"):($w.removeAttribute("media"),Dw.media="enabled"))}function jw(e){return{core:Tf` 20 @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap'); 21 @keyframes w3m-shake { 22 0% { 23 transform: scale(1) rotate(0deg); 24 } 25 20% { 26 transform: scale(1) rotate(-1deg); 27 } 28 40% { 29 transform: scale(1) rotate(1.5deg); 30 } 31 60% { 32 transform: scale(1) rotate(-1.5deg); 33 } 34 80% { 35 transform: scale(1) rotate(1deg); 36 } 37 100% { 38 transform: scale(1) rotate(0deg); 39 } 40 } 41 @keyframes w3m-iframe-fade-out { 42 0% { 43 opacity: 1; 44 } 45 100% { 46 opacity: 0; 47 } 48 } 49 @keyframes w3m-iframe-zoom-in { 50 0% { 51 transform: translateY(50px); 52 opacity: 0; 53 } 54 100% { 55 transform: translateY(0px); 56 opacity: 1; 57 } 58 } 59 @keyframes w3m-iframe-zoom-in-mobile { 60 0% { 61 transform: scale(0.95); 62 opacity: 0; 63 } 64 100% { 65 transform: scale(1); 66 opacity: 1; 67 } 68 } 69 :root { 70 --w3m-modal-width: 360px; 71 --w3m-color-mix-strength: ${Of((null==e?void 0:e["--w3m-color-mix-strength"])?`${e["--w3m-color-mix-strength"]}%`:"0%")}; 72 --w3m-font-family: ${Of((null==e?void 0:e["--w3m-font-family"])||"Inter, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;")}; 73 --w3m-font-size-master: ${Of((null==e?void 0:e["--w3m-font-size-master"])||"10px")}; 74 --w3m-border-radius-master: ${Of((null==e?void 0:e["--w3m-border-radius-master"])||"4px")}; 75 --w3m-z-index: ${Of((null==e?void 0:e["--w3m-z-index"])||
vendor: 15,824 bytes, lines 75-501
75999)}; 76 77 --wui-font-family: var(--w3m-font-family); 78 79 --wui-font-size-mini: calc(var(--w3m-font-size-master) * 0.8); 80 --wui-font-size-micro: var(--w3m-font-size-master); 81 --wui-font-size-tiny: calc(var(--w3m-font-size-master) * 1.2); 82 --wui-font-size-small: calc(var(--w3m-font-size-master) * 1.4); 83 --wui-font-size-paragraph: calc(var(--w3m-font-size-master) * 1.6); 84 --wui-font-size-medium: calc(var(--w3m-font-size-master) * 1.8); 85 --wui-font-size-large: calc(var(--w3m-font-size-master) * 2); 86 --wui-font-size-title-6: calc(var(--w3m-font-size-master) * 2.2); 87 --wui-font-size-medium-title: calc(var(--w3m-font-size-master) * 2.4); 88 --wui-font-size-2xl: calc(var(--w3m-font-size-master) * 4); 89 90 --wui-border-radius-5xs: var(--w3m-border-radius-master); 91 --wui-border-radius-4xs: calc(var(--w3m-border-radius-master) * 1.5); 92 --wui-border-radius-3xs: calc(var(--w3m-border-radius-master) * 2); 93 --wui-border-radius-xxs: calc(var(--w3m-border-radius-master) * 3); 94 --wui-border-radius-xs: calc(var(--w3m-border-radius-master) * 4); 95 --wui-border-radius-s: calc(var(--w3m-border-radius-master) * 5); 96 --wui-border-radius-m: calc(var(--w3m-border-radius-master) * 7); 97 --wui-border-radius-l: calc(var(--w3m-border-radius-master) * 9); 98 --wui-border-radius-3xl: calc(var(--w3m-border-radius-master) * 20); 99 100 --wui-font-weight-light: 400; 101 --wui-font-weight-regular: 500; 102 --wui-font-weight-medium: 600; 103 --wui-font-weight-bold: 700; 104 105 --wui-letter-spacing-2xl: -1.6px; 106 --wui-letter-spacing-medium-title: -0.96px; 107 --wui-letter-spacing-title-6: -0.88px; 108 --wui-letter-spacing-large: -0.8px; 109 --wui-letter-spacing-medium: -0.72px; 110 --wui-letter-spacing-paragraph: -0.64px; 111 --wui-letter-spacing-small: -0.56px; 112 --wui-letter-spacing-tiny: -0.48px; 113 --wui-letter-spacing-micro: -0.2px; 114 --wui-letter-spacing-mini: -0.16px; 115 116 --wui-spacing-0: 0px; 117 --wui-spacing-4xs: 2px; 118 --wui-spacing-3xs: 4px; 119 --wui-spacing-xxs: 6px; 120 --wui-spacing-2xs: 7px; 121 --wui-spacing-xs: 8px; 122 --wui-spacing-1xs: 10px; 123 --wui-spacing-s: 12px; 124 --wui-spacing-m: 14px; 125 --wui-spacing-l: 16px; 126 --wui-spacing-2l: 18px; 127 --wui-spacing-xl: 20px; 128 --wui-spacing-xxl: 24px; 129 --wui-spacing-2xl: 32px; 130 --wui-spacing-3xl: 40px; 131 --wui-spacing-4xl: 90px; 132 --wui-spacing-5xl: 95px; 133 134 --wui-icon-box-size-xxs: 14px; 135 --wui-icon-box-size-xs: 20px; 136 --wui-icon-box-size-sm: 24px; 137 --wui-icon-box-size-md: 32px; 138 --wui-icon-box-size-mdl: 36px; 139 --wui-icon-box-size-lg: 40px; 140 --wui-icon-box-size-2lg: 48px; 141 --wui-icon-box-size-xl: 64px; 142 143 --wui-icon-size-inherit: inherit; 144 --wui-icon-size-xxs: 10px; 145 --wui-icon-size-xs: 12px; 146 --wui-icon-size-sm: 14px; 147 --wui-icon-size-md: 16px; 148 --wui-icon-size-mdl: 18px; 149 --wui-icon-size-lg: 20px; 150 --wui-icon-size-xl: 24px; 151 --wui-icon-size-xxl: 28px; 152 153 --wui-wallet-image-size-inherit: inherit; 154 --wui-wallet-image-size-sm: 40px; 155 --wui-wallet-image-size-md: 56px; 156 --wui-wallet-image-size-lg: 80px; 157 158 --wui-visual-size-size-inherit: inherit; 159 --wui-visual-size-sm: 40px; 160 --wui-visual-size-md: 55px; 161 --wui-visual-size-lg: 80px; 162 163 --wui-box-size-md: 100px; 164 --wui-box-size-lg: 120px; 165 166 --wui-ease-out-power-2: cubic-bezier(0, 0, 0.22, 1); 167 --wui-ease-out-power-1: cubic-bezier(0, 0, 0.55, 1); 168 169 --wui-ease-in-power-3: cubic-bezier(0.66, 0, 1, 1); 170 --wui-ease-in-power-2: cubic-bezier(0.45, 0, 1, 1); 171 --wui-ease-in-power-1: cubic-bezier(0.3, 0, 1, 1); 172 173 --wui-ease-inout-power-1: cubic-bezier(0.45, 0, 0.55, 1); 174 175 --wui-duration-lg: 200ms; 176 --wui-duration-md: 125ms; 177 --wui-duration-sm: 75ms; 178 179 --wui-path-network-sm: path( 180 'M15.4 2.1a5.21 5.21 0 0 1 5.2 0l11.61 6.7a5.21 5.21 0 0 1 2.61 4.52v13.4c0 1.87-1 3.59-2.6 4.52l-11.61 6.7c-1.62.93-3.6.93-5.22 0l-11.6-6.7a5.21 5.21 0 0 1-2.61-4.51v-13.4c0-1.87 1-3.6 2.6-4.52L15.4 2.1Z' 181 ); 182 183 --wui-path-network-md: path( 184 'M43.4605 10.7248L28.0485 1.61089C25.5438 0.129705 22.4562 0.129705 19.9515 1.61088L4.53951 10.7248C2.03626 12.2051 0.5 14.9365 0.5 17.886V36.1139C0.5 39.0635 2.03626 41.7949 4.53951 43.2752L19.9515 52.3891C22.4562 53.8703 25.5438 53.8703 28.0485 52.3891L43.4605 43.2752C45.9637 41.7949 47.5 39.0635 47.5 36.114V17.8861C47.5 14.9365 45.9637 12.2051 43.4605 10.7248Z' 185 ); 186 187 --wui-path-network-lg: path( 188 'M78.3244 18.926L50.1808 2.45078C45.7376 -0.150261 40.2624 -0.150262 35.8192 2.45078L7.6756 18.926C3.23322 21.5266 0.5 26.3301 0.5 31.5248V64.4752C0.5 69.6699 3.23322 74.4734 7.6756 77.074L35.8192 93.5492C40.2624 96.1503 45.7376 96.1503 50.1808 93.5492L78.3244 77.074C82.7668 74.4734 85.5 69.6699 85.5 64.4752V31.5248C85.5 26.3301 82.7668 21.5266 78.3244 18.926Z' 189 ); 190 191 --wui-width-network-sm: 36px; 192 --wui-width-network-md: 48px; 193 --wui-width-network-lg: 86px; 194 195 --wui-height-network-sm: 40px; 196 --wui-height-network-md: 54px; 197 --wui-height-network-lg: 96px; 198 199 --wui-icon-size-network-xs: 12px; 200 --wui-icon-size-network-sm: 16px; 201 --wui-icon-size-network-md: 24px; 202 --wui-icon-size-network-lg: 42px; 203 204 --wui-color-inherit: inherit; 205 206 --wui-color-inverse-100: #fff; 207 --wui-color-inverse-000: #000; 208 209 --wui-cover: rgba(20, 20, 20, 0.8); 210 211 --wui-color-modal-bg: var(--wui-color-modal-bg-base); 212 213 --wui-color-accent-100: var(--wui-color-accent-base-100); 214 --wui-color-accent-090: var(--wui-color-accent-base-090); 215 --wui-color-accent-080: var(--wui-color-accent-base-080); 216 217 --wui-color-success-100: var(--wui-color-success-base-100); 218 --wui-color-success-125: var(--wui-color-success-base-125); 219 220 --wui-color-warning-100: var(--wui-color-warning-base-100); 221 222 --wui-color-error-100: var(--wui-color-error-base-100); 223 --wui-color-error-125: var(--wui-color-error-base-125); 224 225 --wui-color-blue-100: var(--wui-color-blue-base-100); 226 --wui-color-blue-90: var(--wui-color-blue-base-90); 227 228 --wui-icon-box-bg-error-100: var(--wui-icon-box-bg-error-base-100); 229 --wui-icon-box-bg-blue-100: var(--wui-icon-box-bg-blue-base-100); 230 --wui-icon-box-bg-success-100: var(--wui-icon-box-bg-success-base-100); 231 --wui-icon-box-bg-inverse-100: var(--wui-icon-box-bg-inverse-base-100); 232 233 --wui-all-wallets-bg-100: var(--wui-all-wallets-bg-100); 234 235 --wui-avatar-border: var(--wui-avatar-border-base); 236 237 --wui-thumbnail-border: var(--wui-thumbnail-border-base); 238 239 --wui-wallet-button-bg: var(--wui-wallet-button-bg-base); 240 241 --wui-box-shadow-blue: var(--wui-color-accent-glass-020); 242 } 243 244 @supports (background: color-mix(in srgb, white 50%, black)) { 245 :root { 246 --wui-color-modal-bg: color-mix( 247 in srgb, 248 var(--w3m-color-mix) var(--w3m-color-mix-strength), 249 var(--wui-color-modal-bg-base) 250 ); 251 252 --wui-box-shadow-blue: color-mix(in srgb, var(--wui-color-accent-100) 20%, transparent); 253 254 --wui-color-accent-100: color-mix( 255 in srgb, 256 var(--wui-color-accent-base-100) 100%, 257 transparent 258 ); 259 --wui-color-accent-090: color-mix( 260 in srgb, 261 var(--wui-color-accent-base-100) 90%, 262 transparent 263 ); 264 --wui-color-accent-080: color-mix( 265 in srgb, 266 var(--wui-color-accent-base-100) 80%, 267 transparent 268 ); 269 --wui-color-accent-glass-090: color-mix( 270 in srgb, 271 var(--wui-color-accent-base-100) 90%, 272 transparent 273 ); 274 --wui-color-accent-glass-080: color-mix( 275 in srgb, 276 var(--wui-color-accent-base-100) 80%, 277 transparent 278 ); 279 --wui-color-accent-glass-020: color-mix( 280 in srgb, 281 var(--wui-color-accent-base-100) 20%, 282 transparent 283 ); 284 --wui-color-accent-glass-015: color-mix( 285 in srgb, 286 var(--wui-color-accent-base-100) 15%, 287 transparent 288 ); 289 --wui-color-accent-glass-010: color-mix( 290 in srgb, 291 var(--wui-color-accent-base-100) 10%, 292 transparent 293 ); 294 --wui-color-accent-glass-005: color-mix( 295 in srgb, 296 var(--wui-color-accent-base-100) 5%, 297 transparent 298 ); 299 --wui-color-accent-002: color-mix( 300 in srgb, 301 var(--wui-color-accent-base-100) 2%, 302 transparent 303 ); 304 305 --wui-color-fg-100: color-mix( 306 in srgb, 307 var(--w3m-color-mix) var(--w3m-color-mix-strength), 308 var(--wui-color-fg-100) 309 ); 310 --wui-color-fg-125: color-mix( 311 in srgb, 312 var(--w3m-color-mix) var(--w3m-color-mix-strength), 313 var(--wui-color-fg-125) 314 ); 315 --wui-color-fg-150: color-mix( 316 in srgb, 317 var(--w3m-color-mix) var(--w3m-color-mix-strength), 318 var(--wui-color-fg-150) 319 ); 320 --wui-color-fg-175: color-mix( 321 in srgb, 322 var(--w3m-color-mix) var(--w3m-color-mix-strength), 323 var(--wui-color-fg-175) 324 ); 325 --wui-color-fg-200: color-mix( 326 in srgb, 327 var(--w3m-color-mix) var(--w3m-color-mix-strength), 328 var(--wui-color-fg-200) 329 ); 330 --wui-color-fg-225: color-mix( 331 in srgb, 332 var(--w3m-color-mix) var(--w3m-color-mix-strength), 333 var(--wui-color-fg-225) 334 ); 335 --wui-color-fg-250: color-mix( 336 in srgb, 337 var(--w3m-color-mix) var(--w3m-color-mix-strength), 338 var(--wui-color-fg-250) 339 ); 340 --wui-color-fg-275: color-mix( 341 in srgb, 342 var(--w3m-color-mix) var(--w3m-color-mix-strength), 343 var(--wui-color-fg-275) 344 ); 345 --wui-color-fg-300: color-mix( 346 in srgb, 347 var(--w3m-color-mix) var(--w3m-color-mix-strength), 348 var(--wui-color-fg-300) 349 ); 350 --wui-color-fg-325: color-mix( 351 in srgb, 352 var(--w3m-color-mix) var(--w3m-color-mix-strength), 353 var(--wui-color-fg-325) 354 ); 355 --wui-color-fg-350: color-mix( 356 in srgb, 357 var(--w3m-color-mix) var(--w3m-color-mix-strength), 358 var(--wui-color-fg-350) 359 ); 360 361 --wui-color-bg-100: color-mix( 362 in srgb, 363 var(--w3m-color-mix) var(--w3m-color-mix-strength), 364 var(--wui-color-bg-100) 365 ); 366 --wui-color-bg-125: color-mix( 367 in srgb, 368 var(--w3m-color-mix) var(--w3m-color-mix-strength), 369 var(--wui-color-bg-125) 370 ); 371 --wui-color-bg-150: color-mix( 372 in srgb, 373 var(--w3m-color-mix) var(--w3m-color-mix-strength), 374 var(--wui-color-bg-150) 375 ); 376 --wui-color-bg-175: color-mix( 377 in srgb, 378 var(--w3m-color-mix) var(--w3m-color-mix-strength), 379 var(--wui-color-bg-175) 380 ); 381 --wui-color-bg-200: color-mix( 382 in srgb, 383 var(--w3m-color-mix) var(--w3m-color-mix-strength), 384 var(--wui-color-bg-200) 385 ); 386 --wui-color-bg-225: color-mix( 387 in srgb, 388 var(--w3m-color-mix) var(--w3m-color-mix-strength), 389 var(--wui-color-bg-225) 390 ); 391 --wui-color-bg-250: color-mix( 392 in srgb, 393 var(--w3m-color-mix) var(--w3m-color-mix-strength), 394 var(--wui-color-bg-250) 395 ); 396 --wui-color-bg-275: color-mix( 397 in srgb, 398 var(--w3m-color-mix) var(--w3m-color-mix-strength), 399 var(--wui-color-bg-275) 400 ); 401 --wui-color-bg-300: color-mix( 402 in srgb, 403 var(--w3m-color-mix) var(--w3m-color-mix-strength), 404 var(--wui-color-bg-300) 405 ); 406 --wui-color-bg-325: color-mix( 407 in srgb, 408 var(--w3m-color-mix) var(--w3m-color-mix-strength), 409 var(--wui-color-bg-325) 410 ); 411 --wui-color-bg-350: color-mix( 412 in srgb, 413 var(--w3m-color-mix) var(--w3m-color-mix-strength), 414 var(--wui-color-bg-350) 415 ); 416 417 --wui-color-success-100: color-mix( 418 in srgb, 419 var(--w3m-color-mix) var(--w3m-color-mix-strength), 420 var(--wui-color-success-base-100) 421 ); 422 --wui-color-success-125: color-mix( 423 in srgb, 424 var(--w3m-color-mix) var(--w3m-color-mix-strength), 425 var(--wui-color-success-base-125) 426 ); 427 428 --wui-color-warning-100: color-mix( 429 in srgb, 430 var(--w3m-color-mix) var(--w3m-color-mix-strength), 431 var(--wui-color-warning-base-100) 432 ); 433 434 --wui-color-error-100: color-mix( 435 in srgb, 436 var(--w3m-color-mix) var(--w3m-color-mix-strength), 437 var(--wui-color-error-base-100) 438 ); 439 --wui-color-blue-100: color-mix( 440 in srgb, 441 var(--w3m-color-mix) var(--w3m-color-mix-strength), 442 var(--wui-color-blue-base-100) 443 ); 444 --wui-color-blue-90: color-mix( 445 in srgb, 446 var(--w3m-color-mix) var(--w3m-color-mix-strength), 447 var(--wui-color-blue-base-90) 448 ); 449 --wui-color-error-125: color-mix( 450 in srgb, 451 var(--w3m-color-mix) var(--w3m-color-mix-strength), 452 var(--wui-color-error-base-125) 453 ); 454 455 --wui-icon-box-bg-error-100: color-mix( 456 in srgb, 457 var(--w3m-color-mix) var(--w3m-color-mix-strength), 458 var(--wui-icon-box-bg-error-base-100) 459 ); 460 --wui-icon-box-bg-accent-100: color-mix( 461 in srgb, 462 var(--w3m-color-mix) var(--w3m-color-mix-strength), 463 var(--wui-icon-box-bg-blue-base-100) 464 ); 465 --wui-icon-box-bg-success-100: color-mix( 466 in srgb, 467 var(--w3m-color-mix) var(--w3m-color-mix-strength), 468 var(--wui-icon-box-bg-success-base-100) 469 ); 470 --wui-icon-box-bg-inverse-100: color-mix( 471 in srgb, 472 var(--w3m-color-mix) var(--w3m-color-mix-strength), 473 var(--wui-icon-box-bg-inverse-base-100) 474 ); 475 476 --wui-all-wallets-bg-100: color-mix( 477 in srgb, 478 var(--w3m-color-mix) var(--w3m-color-mix-strength), 479 var(--wui-all-wallets-bg-100) 480 ); 481 482 --wui-avatar-border: color-mix( 483 in srgb, 484 var(--w3m-color-mix) var(--w3m-color-mix-strength), 485 var(--wui-avatar-border-base) 486 ); 487 488 --wui-thumbnail-border: color-mix( 489 in srgb, 490 var(--w3m-color-mix) var(--w3m-color-mix-strength), 491 var(--wui-thumbnail-border-base) 492 ); 493 494 --wui-wallet-button-bg: color-mix( 495 in srgb, 496 var(--w3m-color-mix) var(--w3m-color-mix-strength), 497 var(--wui-wallet-button-bg-base) 498 ); 499 } 500 } 501 `,
501light:Tf` 502 :root { 503 --w3m-color-mix: ${Of((null==e?void 0:e["--w3m-color-mix"])||"#fff")}; 504 --w3m-accent: ${Of(je(e,"dark")["--w3m-accent"])}; 505 --w3m-default: #fff; 506 507 --wui-color-modal-bg-base: ${Of(je(e,"dark")["--w3m-background"])}; 508 --wui-color-accent-base-100: var(--w3m-accent); 509 510 --wui-color-blueberry-100: hsla(230, 100%, 67%, 1); 511 --wui-color-blueberry-090: hsla(231, 76%, 61%, 1); 512 --wui-color-blueberry-080: hsla(230, 59%, 55%, 1); 513 --wui-color-blueberry-050: hsla(231, 100%, 70%, 0.1); 514 515 --wui-color-fg-100: #e4e7e7; 516 --wui-color-fg-125: #d0d5d5; 517 --wui-color-fg-150: #a8b1b1; 518 --wui-color-fg-175: #a8b0b0; 519 --wui-color-fg-200: #949e9e; 520 --wui-color-fg-225: #868f8f; 521 --wui-color-fg-250: #788080; 522 --wui-color-fg-275: #788181; 523 --wui-color-fg-300: #6e7777; 524 --wui-color-fg-325: #9a9a9a; 525 --wui-color-fg-350: #363636; 526 527 --wui-color-bg-100: #141414; 528 --wui-color-bg-125: #191a1a; 529 --wui-color-bg-150: #1e1f1f; 530 --wui-color-bg-175: #222525; 531 --wui-color-bg-200: #272a2a; 532 --wui-color-bg-225: #2c3030; 533 --wui-color-bg-250: #313535; 534 --wui-color-bg-275: #363b3b; 535 --wui-color-bg-300: #3b4040; 536 --wui-color-bg-325: #252525; 537 --wui-color-bg-350: #ffffff; 538 539 --wui-color-success-base-100: #26d962; 540 --wui-color-success-base-125: #30a46b; 541 542 --wui-color-warning-base-100: #f3a13f; 543 544 --wui-color-error-base-100: #f25a67; 545 --wui-color-error-base-125: #df4a34; 546 547 --wui-color-blue-base-100: rgba(102, 125, 255, 1); 548 --wui-color-blue-base-90: rgba(102, 125, 255, 0.9); 549 550 --wui-color-success-glass-001: rgba(38, 217, 98, 0.01); 551 --wui-color-success-glass-002: rgba(38, 217, 98, 0.02); 552 --wui-color-success-glass-005: rgba(38, 217, 98, 0.05); 553 --wui-color-success-glass-010: rgba(38, 217, 98, 0.1); 554 --wui-color-success-glass-015: rgba(38, 217, 98, 0.15); 555 --wui-color-success-glass-020: rgba(38, 217, 98, 0.2); 556 --wui-color-success-glass-025: rgba(38, 217, 98, 0.25); 557 --wui-color-success-glass-030: rgba(38, 217, 98, 0.3); 558 --wui-color-success-glass-060: rgba(38, 217, 98, 0.6); 559 --wui-color-success-glass-080: rgba(38, 217, 98, 0.8); 560 561 --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2); 562 563 --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2); 564 565 --wui-color-error-glass-001: rgba(242, 90, 103, 0.01); 566 --wui-color-error-glass-002: rgba(242, 90, 103, 0.02); 567 --wui-color-error-glass-005: rgba(242, 90, 103, 0.05); 568 --wui-color-error-glass-010: rgba(242, 90, 103, 0.1); 569 --wui-color-error-glass-015: rgba(242, 90, 103, 0.15); 570 --wui-color-error-glass-020: rgba(242, 90, 103, 0.2); 571 --wui-color-error-glass-025: rgba(242, 90, 103, 0.25); 572 --wui-color-error-glass-030: rgba(242, 90, 103, 0.3); 573 --wui-color-error-glass-060: rgba(242, 90, 103, 0.6); 574 --wui-color-error-glass-080: rgba(242, 90, 103, 0.8); 575 576 --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2); 577 578 --wui-color-gray-glass-001: rgba(255, 255, 255, 0.01); 579 --wui-color-gray-glass-002: rgba(255, 255, 255, 0.02); 580 --wui-color-gray-glass-005: rgba(255, 255, 255, 0.05); 581 --wui-color-gray-glass-010: rgba(255, 255, 255, 0.1); 582 --wui-color-gray-glass-015: rgba(255, 255, 255, 0.15); 583 --wui-color-gray-glass-020: rgba(255, 255, 255, 0.2); 584 --wui-color-gray-glass-025: rgba(255, 255, 255, 0.25); 585 --wui-color-gray-glass-030: rgba(255, 255, 255, 0.3); 586 --wui-color-gray-glass-060: rgba(255, 255, 255, 0.6); 587 --wui-color-gray-glass-080: rgba(255, 255, 255, 0.8); 588 --wui-color-gray-glass-090: rgba(255, 255, 255, 0.9); 589 590 --wui-color-dark-glass-100: rgba(42, 42, 42, 1); 591 592 --wui-icon-box-bg-error-base-100: #3c2426; 593 --wui-icon-box-bg-blue-base-100: #20303f; 594 --wui-icon-box-bg-success-base-100: #1f3a28; 595 --wui-icon-box-bg-inverse-base-100: #243240; 596 597 --wui-all-wallets-bg-100: #222b35; 598 599 --wui-avatar-border-base: #252525; 600
601 --wui-thumbnail-border-base: #252525; 602 603 --wui-wallet-button-bg-base: var(--wui-color-bg-125); 604 605 --w3m-card-embedded-shadow-color: rgb(17 17 18 / 25%); 606 } 607 `,dark:Tf` 608 :root { 609 --w3m-color-mix: ${Of((null==e?void 0:e["--w3m-color-mix"])||"#000")}; 610 --w3m-accent: ${Of(je(e,"light")["--w3m-accent"])}; 611 --w3m-default: #000; 612 613 --wui-color-modal-bg-base: ${Of(je(e,"light")["--w3m-background"])}; 614 --wui-color-accent-base-100: var(--w3m-accent); 615 616 --wui-color-blueberry-100: hsla(231, 100%, 70%, 1); 617 --wui-color-blueberry-090: hsla(231, 97%, 72%, 1); 618 --wui-color-blueberry-080: hsla(231, 92%, 74%, 1); 619 620 --wui-color-fg-100: #141414; 621 --wui-color-fg-125: #2d3131; 622 --wui-color-fg-150: #474d4d; 623 --wui-color-fg-175: #636d6d; 624 --wui-color-fg-200: #798686; 625 --wui-color-fg-225: #828f8f; 626 --wui-color-fg-250: #8b9797; 627 --wui-color-fg-275: #95a0a0; 628 --wui-color-fg-300: #9ea9a9; 629 --wui-color-fg-325: #9a9a9a; 630 --wui-color-fg-350: #d0d0d0; 631 632 --wui-color-bg-100: #ffffff; 633 --wui-color-bg-125: #f5fafa; 634 --wui-color-bg-150: #f3f8f8; 635 --wui-color-bg-175: #eef4f4; 636 --wui-color-bg-200: #eaf1f1; 637 --wui-color-bg-225: #e5eded; 638 --wui-color-bg-250: #e1e9e9; 639 --wui-color-bg-275: #dce7e7; 640 --wui-color-bg-300: #d8e3e3; 641 --wui-color-bg-325: #f3f3f3; 642 --wui-color-bg-350: #202020; 643 644 --wui-color-success-base-100: #26b562; 645 --wui-color-success-base-125: #30a46b; 646 647 --wui-color-warning-base-100: #f3a13f; 648 649 --wui-color-error-base-100: #f05142; 650 --wui-color-error-base-125: #df4a34; 651 652 --wui-color-blue-base-100: rgba(102, 125, 255, 1); 653 --wui-color-blue-base-90: rgba(102, 125, 255, 0.9); 654 655 --wui-color-success-glass-001: rgba(38, 181, 98, 0.01); 656 --wui-color-success-glass-002: rgba(38, 181, 98, 0.02); 657 --wui-color-success-glass-005: rgba(38, 181, 98, 0.05); 658 --wui-color-success-glass-010: rgba(38, 181, 98, 0.1); 659 --wui-color-success-glass-015: rgba(38, 181, 98, 0.15); 660 --wui-color-success-glass-020: rgba(38, 181, 98, 0.2); 661 --wui-color-success-glass-025: rgba(38, 181, 98, 0.25); 662 --wui-color-success-glass-030: rgba(38, 181, 98, 0.3); 663 --wui-color-success-glass-060: rgba(38, 181, 98, 0.6); 664 --wui-color-success-glass-080: rgba(38, 181, 98, 0.8); 665 666 --wui-color-success-glass-reown-020: rgba(48, 164, 107, 0.2); 667 668 --wui-color-warning-glass-reown-020: rgba(243, 161, 63, 0.2); 669 670 --wui-color-error-glass-001: rgba(240, 81, 66, 0.01); 671 --wui-color-error-glass-002: rgba(240, 81, 66, 0.02); 672 --wui-color-error-glass-005: rgba(240, 81, 66, 0.05); 673 --wui-color-error-glass-010: rgba(240, 81, 66, 0.1); 674 --wui-color-error-glass-015: rgba(240, 81, 66, 0.15); 675 --wui-color-error-glass-020: rgba(240, 81, 66, 0.2); 676 --wui-color-error-glass-025: rgba(240, 81, 66, 0.25); 677 --wui-color-error-glass-030: rgba(240, 81, 66, 0.3); 678 --wui-color-error-glass-060: rgba(240, 81, 66, 0.6); 679 --wui-color-error-glass-080: rgba(240, 81, 66, 0.8); 680 681 --wui-color-error-glass-reown-020: rgba(223, 74, 52, 0.2); 682 683 --wui-icon-box-bg-error-base-100: #f4dfdd; 684 --wui-icon-box-bg-blue-base-100: #d9ecfb; 685 --wui-icon-box-bg-success-base-100: #daf0e4; 686 --wui-icon-box-bg-inverse-base-100: #dcecfc; 687 688 --wui-all-wallets-bg-100: #e8f1fa; 689 690 --wui-avatar-border-base: #f3f4f4; 691 692 --wui-thumbnail-border-base: #eaefef; 693 694 --wui-wallet-button-bg-base: var(--wui-color-bg-125); 695 696 --wui-color-gray-glass-001: rgba(0, 0, 0, 0.01); 697 --wui-color-gray-glass-002: rgba(0, 0, 0, 0.02); 698 --wui-color-gray-glass-005: rgba(0, 0, 0, 0.05); 699 --wui-color-gray-glass-010: rgba(0, 0, 0, 0.1); 700 --wui-color-gray-glass-015: rgba(0, 0, 0, 0.15); 701 --wui-color-gray-glass-020: rgba(0, 0, 0, 0.2); 702 --wui-color-gray-glass-025: rgba(0, 0, 0, 0.25); 703 --wui-color-gray-glass-030: rgba(0, 0, 0, 0.3); 704 --wui-color-gray-glass-060: rgba(0, 0, 0, 0.6); 705 --wui-color-gray-glass-080: rgba(0, 0, 0, 0.8); 706 --wui-color-gray-glass-090: rgba(0, 0, 0, 0.9); 707 708 --wui-color-dark-glass-100: rgba(233, 233, 233, 1); 709 710 --w3m-card-embedded-shadow-color: rgb(224 225 233 / 25%); 711 } 712 `}}null==Rw||Rw({LitElement:xw}),(Tw.litElementVersions??(Tw.litElementVersions=[])).push("4.2.0");const qw=Tf` 713 *, 714 *::after, 715 *::before, 716 :host { 717 margin: 0; 718 padding: 0; 719 box-sizing: border-box; 720 font-style: normal; 721 text-rendering: optimizeSpeed; 722 -webkit-font-smoothing: antialiased; 723 -moz-osx-font-smoothing: grayscale; 724 -webkit-tap-highlight-color: transparent; 725 font-family: var(--wui-font-family); 726 backface-visibility: hidden; 727 } 728`,Bw=Tf` 729 button, 730 a { 731 cursor: pointer; 732 display: flex; 733 justify-content: center;
734 align-items: center; 735 position: relative; 736 transition: 737 color var(--wui-duration-lg) var(--wui-ease-out-power-1), 738 background-color var(--wui-duration-lg) var(--wui-ease-out-power-1), 739 border var(--wui-duration-lg) var(--wui-ease-out-power-1), 740 border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1), 741 box-shadow var(--wui-duration-lg) var(--wui-ease-out-power-1); 742 will-change: background-color, color, border, box-shadow, border-radius; 743 outline: none; 744 border: none; 745 column-gap: var(--wui-spacing-3xs); 746 background-color: transparent; 747 text-decoration: none; 748 } 749 750 wui-flex { 751 transition: border-radius var(--wui-duration-lg) var(--wui-ease-out-power-1); 752 will-change: border-radius; 753 } 754 755 button:disabled > wui-wallet-image, 756 button:disabled > wui-all-wallets-image, 757 button:disabled > wui-network-image, 758 button:disabled > wui-image, 759 button:disabled > wui-transaction-visual, 760 button:disabled > wui-logo { 761 filter: grayscale(1); 762 } 763 764 @media (hover: hover) and (pointer: fine) { 765 button:hover:enabled { 766 background-color: var(--wui-color-gray-glass-005); 767 } 768 769 button:active:enabled { 770 background-color: var(--wui-color-gray-glass-010); 771 } 772 } 773 774 button:disabled > wui-icon-box { 775 opacity: 0.5; 776 } 777 778 input { 779 border: none; 780 outline: none; 781 appearance: none; 782 } 783`,Fw=Tf` 784 .wui-color-inherit { 785 color: var(--wui-color-inherit); 786 } 787 788 .wui-color-accent-100 { 789 color: var(--wui-color-accent-100); 790 } 791 792 .wui-color-error-100 { 793 color: var(--wui-color-error-100); 794 } 795 796 .wui-color-blue-100 { 797 color: var(--wui-color-blue-100); 798 } 799 800 .wui-color-blue-90 { 801 color: var(--wui-color-blue-90); 802 } 803 804 .wui-color-error-125 { 805 color: var(--wui-color-error-125); 806 } 807 808 .wui-color-success-100 { 809 color: var(--wui-color-success-100); 810 } 811 812 .wui-color-success-125 { 813 color: var(--wui-color-success-125); 814 } 815 816 .wui-color-inverse-100 { 817 color: var(--wui-color-inverse-100); 818 } 819 820 .wui-color-inverse-000 { 821 color: var(--wui-color-inverse-000); 822 } 823 824 .wui-color-fg-100 { 825 color: var(--wui-color-fg-100); 826 } 827 828 .wui-color-fg-200 { 829 color: var(--wui-color-fg-200); 830 } 831 832 .wui-color-fg-300 { 833 color: var(--wui-color-fg-300); 834 } 835 836 .wui-color-fg-325 { 837 color: var(--wui-color-fg-325); 838 } 839 840 .wui-color-fg-350 { 841 color: var(--wui-color-fg-350); 842 } 843 844 .wui-bg-color-inherit { 845 background-color: var(--wui-color-inherit); 846 } 847 848 .wui-bg-color-blue-100 { 849 background-color: var(--wui-color-accent-100); 850 } 851 852 .wui-bg-color-error-100 { 853 background-color: var(--wui-color-error-100); 854 } 855 856 .wui-bg-color-error-125 { 857 background-color: var(--wui-color-error-125); 858 } 859 860 .wui-bg-color-success-100 { 861 background-color: var(--wui-color-success-100); 862 } 863 864 .wui-bg-color-success-125 { 865 background-color: var(--wui-color-success-100); 866 } 867 868 .wui-bg-color-inverse-100 { 869 background-color: var(--wui-color-inverse-100); 870 } 871 872 .wui-bg-color-inverse-000 { 873 background-color: var(--wui-color-inverse-000); 874 } 875 876 .wui-bg-color-fg-100 { 877 background-color: var(--wui-color-fg-100); 878 } 879 880 .wui-bg-color-fg-200 { 881 background-color: var(--wui-color-fg-200); 882 } 883 884 .wui-bg-color-fg-300 { 885 background-color: var(--wui-color-fg-300); 886 } 887 888 .wui-color-fg-325 { 889 background-color: var(--wui-color-fg-325); 890 } 891 892 .wui-color-fg-350 { 893 background-color: var(--wui-color-fg-350); 894 } 895`,Ww=4902,zw=5e3,Hw=32603,Vw=["http://localhost:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"];function Kw(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const Gw=Kw({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"}
895),Jw=Kw({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"});Kw({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"}),Kw({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}}),Kw({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 Yw={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"]},Zw={getMethodsByChainNamespace:e=>Yw[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;if(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 Gw.caipNetworkId:a.chains.push(Gw.deprecatedCaipNetworkId);break;case Jw.caipNetworkId:a.chains.push(Jw.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 Ss.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}
895else try{if(new URL(i).origin===e)return!0}catch(gr){if(i===e)return!0}return!1}};class Qw{constructor({provider:e,namespace:t}){this.id=se.CONNECTOR_ID.WALLET_CONNECT,this.name=uf.ConnectorNamesMap[se.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=uf.ConnectorImageIds[se.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=cs.getCaipNetworks.bind(cs),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=lt.state.universalProviderConfigOverride,s=Zw.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 of.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:Xw})}}const Xw=["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 ev{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=e=>cs.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:se.CONNECTOR_ID.AUTH,type:"AUTH",name:se.CONNECTOR_NAMES.AUTH,provider:e,imageId:uf.ConnectorImageIds[se.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(e=>!t.has(e.id)&&(t.add(e.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){gs.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=gs.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 Qw);if(!e)throw new Error("WalletConnectConnector not found");return e}}class tv extends ev{setUniversalProvider(e){this.addConnector(new Qw({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=>rt.createAccount(e,t,"bip122"===e?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var t,s,i,r,n;if(!(e.caipNetwork&&st.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(gs.state.balanceLoading&&e.chainId===(null==(r=cs.state.activeCaipNetwork)?void 0:r.id))return{balance:gs.state.balance||"0.00",symbol:gs.state.balanceSymbol||""};const o=(await gs.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;
895if(!r)throw new Error("UniversalAdapter:signMessage - provider is undefined");let a="";if((null==(t=cs.state.activeCaipNetwork)?void 0:t.chainNamespace)===se.CHAIN.SOLANA){a=(await r.request({method:"solana_signMessage",params:{message:w.encode((new TextEncoder).encode(n)),pubkey:o}},null==(s=cs.state.activeCaipNetwork)?void 0:s.caipNetworkId)).signature}else a=await r.request({method:"personal_sign",params:[n,o]},null==(i=cs.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===se.CHAIN.EVM)try{await(null==(t=c.provider)?void 0:t.request({method:"wallet_switchEthereumChain",params:[{chainId:Q(a.id)}]}))}catch(l){if(l.code===Ww||l.code===Hw||l.code===zw||(null==(i=null==(s=null==l?void 0:l.data)?void 0:s.originalError)?void 0:i.code)===Ww)try{await(null==(o=c.provider)?void 0:o.request({method:"wallet_addEthereumChain",params:[{chainId:Q(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 sv=["email","socials","swaps","onramp","activity","reownBranding"],iv={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?st.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?st.DEFAULT_REMOTE_FEATURES.socials:"boolean"==typeof e?!!e&&st.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?st.DEFAULT_REMOTE_FEATURES.swaps:"boolean"==typeof e?!!e&&st.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?st.DEFAULT_REMOTE_FEATURES.onramp:"boolean"==typeof e?!!e&&st.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?st.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?st.DEFAULT_REMOTE_FEATURES.reownBranding:Boolean(e)}},rv={localSettingsOverridden:new Set,getApiConfig:(e,t)=>null==t?void 0:t.find(t=>t.id===e),addWarning(e,t){if(void 0!==e){const e=iv[t],s=e.isLegacy?`"features.${e.localFeatureName}" (now "${t}")`:`"features.${t}"`;this.localSettingsOverridden.add(s)}},processFeature(e,t,s,i,r){const n=iv[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)=>
895iv[e].processApi(t),processFallbackFeature:(e,t)=>iv[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 Ut.fetchProjectConfig(),r=null!=i}catch(gr){}const n=r&&!t?st.DEFAULT_REMOTE_FEATURES:st.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const e of sv){const o=this.processFeature(e,s,i,r,t);Object.assign(n,{[e]:o})}}catch(gr){return st.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.`;At.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${e}`},"warning")}return n}};class nv{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=cs.getNetworkData(e))?void 0:s.requestedCaipNetworks)?void 0:i.find(e=>e.id===t);if(o)return o;const a=null==(r=cs.getNetworkData(e))?void 0:r.caipNetwork;if(a)return a;return null==(n=cs.getRequestedCaipNetworks(e).filter(t=>t.chainNamespace===e))?void 0:n[0]}return cs.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const e=this.getCaipNetwork();if(e)return e.id},this.getCaipNetworks=e=>cs.getCaipNetworks(e),this.getActiveChainNamespace=()=>cs.state.activeChain,this.setRequestedCaipNetworks=(e,t)=>{cs.setRequestedCaipNetworks(e,t)},this.getApprovedCaipNetworkIds=()=>cs.getAllApprovedCaipNetworkIds(),this.getCaipAddress=e=>cs.state.activeChain!==e&&e?cs.getAccountProp("caipAddress",e):cs.state.activeCaipAddress,this.setClientId=e=>{us.setClientId(e)},this.getProvider=e=>Ef.getProvider(e),this.getProviderType=e=>Ef.getProviderId(e),this.getPreferredAccountType=e=>{var t;return null==(t=gs.state.preferredAccountTypes)?void 0:t[e]},this.setCaipAddress=(e,t)=>{gs.setCaipAddress(e,t),e&<.state.enableEmbedded&&this.close()},this.setBalance=(e,t,s)=>{gs.setBalance(e,t,s)},this.setProfileName=(e,t)=>{gs.setProfileName(e,t)},this.setProfileImage=(e,t)=>{gs.setProfileImage(e,t)},this.setUser=(e,t)=>{gs.setUser(e,t)},this.resetAccount=e=>{gs.resetAccount(e)},this.setCaipNetwork=e=>{cs.setActiveCaipNetwork(e)},this.setCaipNetworkOfNamespace=(e,t)=>{cs.setChainNetworkData(t,{caipNetwork:e})},this.setAllAccounts=(e,t)=>{gs.setAllAccounts(e,t),lt.setHasMultipleAddresses((null==e?void 0:e.length)>1)},this.setStatus=(e,t)=>{gs.setStatus(e,t),Ft.isConnected()?it.setConnectionStatus("connected"):it.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=e=>cs.getAccountProp("address",e),this.setConnectors=e=>{const t=[...Ft.state.allConnectors,...e];Ft.setConnectors(t)},this.setConnections=(e,t)=>{Zt.setConnections(e,t)},this.fetchIdentity=e=>us.fetchIdentity(e),this.getReownName=e=>Ss.getNamesForAddress(e),this.getConnectors=()=>Ft.getConnectors(),this.getConnectorImage=e=>It.getConnectorImage(e),this.setConnectedWalletInfo=(e,t)=>{const s=Ef.getProviderId(t),i=e?{...e,type:s}:void 0;gs.setConnectedWalletInfo(i,t)},this.getIsConnectedState=()=>Boolean(cs.state.activeCaipAddress),this.addAddressLabel=(e,t,s)=>{gs.addAddressLabel(e,t,s)},this.removeAddressLabel=(e,t)=>
895{gs.removeAddressLabel(e,t)},this.getAddress=e=>cs.state.activeChain!==e&&e?cs.getAccountProp("address",e):gs.state.address,this.setApprovedCaipNetworksData=e=>cs.setApprovedCaipNetworksData(e),this.resetNetwork=e=>{cs.resetNetwork(e)},this.addConnector=e=>{Ft.addConnector(e)},this.resetWcConnection=()=>{Zt.resetWcConnection()},this.setAddressExplorerUrl=(e,t)=>{gs.setAddressExplorerUrl(e,t)},this.setSmartAccountDeployed=(e,t)=>{gs.setSmartAccountDeployed(e,t)},this.setSmartAccountEnabledNetworks=(e,t)=>{cs.setSmartAccountEnabledNetworks(e,t)},this.setPreferredAccountType=(e,t)=>{gs.setPreferredAccountType(e,t)},this.setEIP6963Enabled=e=>{lt.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 rv.fetchRemoteFeatures(e),lt.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&Es.setOnrampProviders(this.remoteFeatures.onramp),((null==(t=lt.state.remoteFeatures)?void 0:t.email)||Array.isArray(null==(s=lt.state.remoteFeatures)?void 0:s.socials)&&(null==(i=lt.state.remoteFeatures)?void 0:i.socials.length)>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await Ut.fetchAllowedOrigins();if(e&&rt.isClient()){const t=window.location.origin;Zw.isOriginAllowed(t,e,Vw)||At.open(gf.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else At.open(gf.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){var t;const{...s}=e;delete s.adapters,delete s.universalProvider,Ot.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&&jt.setThemeMode(e.themeMode),e.themeVariables&&jt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");cs.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&cs.setActiveCaipNetwork(t)}initializeConnectionController(e){Zt.setWcBasic(e.basic??!1)}initializeConnectorController(){Ft.initialize(this.chainNamespaces)}initializeProjectSettings(e){lt.setProjectId(e.projectId),lt.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var t;lt.setDebug(!1!==e.debug),lt.setEnableWalletConnect(!1!==e.enableWalletConnect),lt.setEnableWalletGuide(!1!==e.enableWalletGuide),lt.setEnableWallets(!1!==e.enableWallets),lt.setEIP6963Enabled(!1!==e.enableEIP6963),lt.setEnableNetworkSwitch(!1!==e.enableNetworkSwitch),lt.setEnableAuthLogger(!1!==e.enableAuthLogger),lt.setCustomRpcUrls(e.customRpcUrls),lt.setEnableEmbedded(e.enableEmbedded),lt.setAllWallets(e.allWallets),lt.setIncludeWalletIds(e.includeWalletIds),lt.setExcludeWalletIds(e.excludeWalletIds),lt.setFeaturedWalletIds(e.featuredWalletIds),lt.setTokens(e.tokens),lt.setTermsConditionsUrl(e.termsConditionsUrl),lt.setPrivacyPolicyUrl(e.privacyPolicyUrl),lt.setCustomWallets(e.customWallets),lt.setFeatures(e.features),lt.setAllowUnsupportedChain(e.allowUnsupportedChain),lt.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),lt.setPreferUniversalLinks(e.experimental_preferUniversalLinks),lt.setDefaultAccountTypes(e.defaultAccountTypes);const s=it.getPreferredAccountTypes()||{},i={...lt.state.defaultAccountTypes,...s};gs.setPreferredAccountTypes(i);const r=this.getDefaultMetaData();if(!e.metadata&&r&&(e.metadata=r),lt.setMetadata(e.metadata),lt.setDisableAppend(e.disableAppend),lt.setEnableEmbedded(e.enableEmbedded),lt.setSIWX(e.siwx),!e.projectId)return void At.open(gf.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");
895if((null==(t=e.adapters)?void 0:t.find(e=>e.namespace===se.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");lt.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,t,s,i;return rt.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=vf.getUnsupportedNetwork(`${t}:${e}`);cs.setActiveCaipNetwork(s)}}getDefaultNetwork(){return vf.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return vf.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return vf.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?vf.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e){try{const t=this.getAdapter(e),s=Ef.getProvider(e),i=Ef.getProviderId(e),{caipAddress:r}=cs.getAccountData(e)||{};this.setLoading(!0,e),r&&(null==t?void 0:t.disconnect)&&await t.disconnect({provider:s,providerType:i}),it.removeConnectedNamespace(e),Ef.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),Ft.removeConnectorId(e),cs.resetAccount(e),cs.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=cs.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),it.setConnectedNamespaces([...cs.state.chains.keys()]),this.chainNamespaces.forEach(e=>{Ft.setConnectorId(lf,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,h,u;const p=cs.state.activeChain,g=r||p,m=this.getAdapter(g);if(r&&r!==p&&!n){const e=this.getCaipNetworks().find(e=>e.chainNamespace===r);e&&this.setCaipNetwork(e)}if(!m)throw new Error("Adapter not found");const f=this.getCaipNetwork(g),w=await m.connect({id:e,info:t,type:s,provider:i,socialUri:o,chainId:(null==n?void 0:n.id)||(null==f?void 0:f.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==(u=null==(h=null==(d=null==f?void 0:f.rpcUrls)?void 0:d.default)?void 0:h.http)?void 0:u[0])});if(!w)return;it.addConnectedNamespace(g),this.syncProvider({...w,chainNamespace:g});const v=gs.state.allAccounts,{accounts:y}=(null==v?void 0:v.length)>0?{accounts:[...v]}:await m.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=cs.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})),it.addConnectedNamespace(n),this.syncConnectedWalletInfo(n))},disconnect:async e=>{const t=function(e){const t=Array.from(cs.state.chains.keys());let s=[];return e?(s.push([e,cs.state.chains.get(e)]),af(e,se.CONNECTOR_ID.WALLET_CONNECT)?t.forEach(t=>{t!==e&&af(t,se.CONNECTOR_ID.WALLET_CONNECT)&&s.push([t,cs.state.chains.get(t)])}):af(e,se.CONNECTOR_ID.AUTH)&&t.forEach(t=>{t!==e&&af(t,se.CONNECTOR_ID.AUTH)&&s.push([t,cs.state.chains.get(t)])})):s=Array.from(cs.state.chains.entries()),s}(e);try{const s=await Promise.allSettled(t.map(async([e])=>this.disconnectNamespace(e)));is.resetSend(),Zt.resetWcConnection(),await of.clearSessions(),Ft.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(", "));it.deleteConnectedSocialProvider(),Ot.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(cs.state.activeChain),s=await(null==t?void 0:t.signMessage({message:e,address:gs.state.address,provider:Ef.getProvider(cs.state.activeChain)}));return(null==s?void 0:s.signature)||""},sendTransaction:async e=>{const t=e.chainNamespace;if(st.SEND_SUPPORTED_NAMESPACES.includes(t)){const s=this.getAdapter(cs.state.activeChain),i=Ef.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===se.CHAIN.EVM){const t=this.getAdapter(cs.state.activeChain),s=Ef.getProvider(cs.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:gs.state.address,chainId:Number(null==(e=this.getCaipNetwork())?void 0:e.id),chainNamespace:cs.state.activeChain}),gs.state.profileImage||!1},getEnsAddress:async e=>await Zw.resolveReownName(e),writeContract:async e=>{const t=this.getAdapter(cs.state.activeChain),s=this.getCaipNetwork(),i=this.getCaipAddress(),r=Ef.getProvider(cs.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(cs.state.activeChain);return(null==s?void 0:s.parseUnits({value:e,decimals:t}))??0n},formatUnits:(e,t)=>{const s=this.getAdapter(cs.state.activeChain);return(null==s?void 0:s.formatUnits({value:e,decimals:t}))??"0"},getCapabilities:async e=>{const t=this.getAdapter(cs.state.activeChain);return await(null==t?void 0:t.getCapabilities(e))},grantPermissions:async e=>{const t=this.getAdapter(cs.state.activeChain);return await(null==t?void 0:t.grantPermissions(e))},revokePermissions:async e=>{const t=this.getAdapter(cs.state.activeChain);return(null==t?void 0:t.revokePermissions)?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>{const t=this.getAdapter(cs.state.activeChain);return await(null==t?void 0:t.walletGetAssets(e))??{}},updateBalance:e=>{const t=this.getCaipNetwork(e);t&&gs.state.address&&this.updateNativeBalance(gs.state.address,null==t?void 0:t.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Zt.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){var e,t,s,i,r;if(Ef.getProviderId(cs.state.activeChain)===lf){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=Ef.getProvider(t),i=Ef.getProviderId(t);if(e.chainNamespace===cs.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===lf)this.syncWalletConnectAccount();else{const s=this.getAddressByChainNamespace(t);s&&this.syncAccount({address:s,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}
895getChainsFromNamespaces(e={}){return Object.values(e).flatMap(e=>{const t=e.chains||[],s=e.accounts.map(e=>{const{chainId:t,chainNamespace:s}=be.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 tv({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=it.getConnectionStatus();"connected"===s?this.setStatus("connecting",e):"disconnected"===s?(it.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=cs.state.activeChain===e,n=cs.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=gs.state.address,t=cs.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=cs.state.activeChain===e;n&&s?this.syncAccount({address:t,chainId:s,chainNamespace:e}):n&&(null==(i=cs.state.activeCaipNetwork)?void 0:i.id)?this.syncAccount({address:t,chainId:null==(r=cs.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===se.CHAIN.EVM&&rt.isSafeApp()&&Ft.setConnectorId(se.CONNECTOR_ID.SAFE,e);const t=Ft.getConnectorId(e);switch(this.setStatus("connecting",e),t){case se.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case se.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=Ft.getConnectorId(e),o=this.getCaipNetwork(e),a=Ft.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([rt.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(gr){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=cs.state.activeCaipNetwork)?void 0:n.id,l=a.find(e=>{const{chainId:t}=be.parseCaipAddress(e);return t===(null==c?void 0:c.toString())})||a[0];if(l){const t=be.validateCaipAddress(l),{chainId:s,address:i}=be.parseCaipAddress(t);if(Ef.setProviderId(e,lf),this.caipNetworks&&cs.state.activeCaipNetwork&&(null==o?void 0:o.namespace)!==se.CHAIN.EVM){const t=null==o?void 0:o.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:cs.state.activeCaipNetwork});Ef.setProvider(e,t)}else Ef.setProvider(e,this.universalProvider);Ft.setConnectorId(se.CONNECTOR_ID.WALLET_CONNECT,e),it.addConnectedNamespace(e),this.syncWalletConnectAccounts(e),await this.syncAccount({address:i,chainId:s,chainNamespace:e})}else this.setStatus("disconnected",e);this.syncConnectedWalletInfo(e),await cs.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}=be.parseCaipAddress(e);return t}).filter((e,t,s)=>s.indexOf(e)===t);o&&this.setAllAccounts(o.map(t=>rt.createAccount(e,t,"bip122"===e?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:s,chainNamespace:i}){Ef.setProviderId(i,e),Ef.setProvider(i,t),Ft.setConnectorId(s,i)}async syncAllAccounts(e){const t=Ft.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===cs.state.activeChain,r=cs.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:n,chainId:o,chainNamespace:a}=e,{chainId:c}=it.getActiveNetworkProps(),l=o||c,d=(null==(t=cs.state.activeCaipNetwork)?void 0:t.name)===se.UNSUPPORTED_NETWORK_NAME,h=cs.getNetworkProp("supportsAllNetworks",a);if(this.setStatus("connected",a),(!d||h)&&l){let e=this.getCaipNetworks().find(e=>e.id.toString()===l.toString()),t=this.getCaipNetworks().find(e=>e.chainNamespace===a);if(!h&&!e&&!t){const s=this.getApprovedCaipNetworkIds()||[],i=s.find(e=>{var t;return(null==(t=be.parseCaipNetworkId(e))?void 0:t.chainId)===l.toString()}),r=s.find(e=>{var t;return(null==(t=be.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)===cs.state.activeChain?lt.state.enableNetworkSwitch&&!lt.state.allowUnsupportedChain&&(null==(s=cs.state.activeCaipNetwork)?void 0:s.name)===se.UNSUPPORTED_NETWORK_NAME?cs.showUnsupportedChainUI():this.setCaipNetwork(o):i||r&&this.setCaipNetworkOfNamespace(r,a),this.syncConnectedWalletInfo(a),pf.isLowerCaseMatch(n,gs.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);
895if(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=Ft.getConnectorId(e),i=Ef.getProviderId(e);if(i===hf||i===df){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===lf){const s=Ef.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===se.CONNECTOR_ID.COINBASE){const t=this.getConnectors().find(e=>e.id===se.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(t)},e)}}async syncBalance(e){const t=ie.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=cs.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=mf.createLogger((e,...t)=>{e&&this.handleAlertError(e)}),h={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};lt.setManualWCControl(Boolean(null==(l=this.options)?void 0:l.manualWCControl)),this.universalProvider=this.options.universalProvider??await nf.init(h),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Zt.setUri(e)}),this.universalProvider.on("connect",Zt.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Zt.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(Zw.isSessionEventData(e)){const{name:t,data:s}=e.params.event;"accountsChanged"===t&&Array.isArray(s)&&rt.isCaipAddress(s[0])&&this.syncAccount(be.parseCaipAddress(s[0]))}}))}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&rt.isClient()&&(null==(e=this.options)?void 0:e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}
895async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Ot.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(gf.UniversalProviderErrors).find(([,{message:t}])=>e.message.includes(t)),[s,i]=t??[],{message:r,alertErrorKey:n}=i??{};if(s&&r&&!this.reportedAlertErrors[s]){const e=gf.ALERT_ERRORS[n];e&&(At.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)&&Zt.setUri(e.uri),(null==e?void 0:e.arguments)&&"Swap"===(null==e?void 0:e.view)?ws.open({...e,data:{swap:e.arguments}}):ws.open(e)}async close(){await this.injectModalUi(),ws.close()}setLoading(e,t){ws.setLoading(e,t)}async disconnect(e){await Zt.disconnect(e)}getSIWX(){return lt.state.siwx}getError(){return""}getChainId(){var e;return null==(e=cs.state.activeCaipNetwork)?void 0:e.id}async switchNetwork(e){const t=this.getCaipNetworks().find(t=>t.id===e.id);t?await cs.switchActiveNetwork(t):At.open(gf.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error")}getWalletProvider(){return cs.state.activeChain?Ef.state.providers[cs.state.activeChain]:null}getWalletProviderType(){return Ef.getProviderId(cs.state.activeChain)}subscribeProviders(e){return Ef.subscribeProviders(e)}getThemeMode(){return jt.state.themeMode}getThemeVariables(){return jt.state.themeVariables}setThemeMode(e){jt.setThemeMode(e),Lw(jt.state.themeMode)}setTermsConditionsUrl(e){lt.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){lt.setPrivacyPolicyUrl(e)}setThemeVariables(e){jt.setThemeVariables(e),function(e){Uw&&Dw&&$w&&(Uw.textContent=jw(e).core.cssText,Dw.textContent=jw(e).dark.cssText,$w.textContent=jw(e).light.cssText)}(jt.state.themeVariables)}subscribeTheme(e){return jt.subscribe(e)}getWalletInfo(){return gs.state.connectedWalletInfo}getAccount(e){var t;const s=Ft.getAuthConnector(e),i=cs.getAccountData(e),r=cs.state.activeChain,n=it.getConnectedConnectorId(e||r);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:rt.getPlainAddress(i.caipAddress),isConnected:Boolean(i.caipAddress),status:i.status,embeddedWalletInfo:s&&n===se.CONNECTOR_ID.AUTH?{user:i.user?{...i.user,username:it.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?cs.subscribeChainProp("accountState",s,t):cs.subscribe(s),Ft.subscribe(s)}subscribeNetwork(e){return cs.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:null==t?void 0:t.id,caipNetworkId:null==t?void 0:t.caipNetworkId})})}subscribeWalletInfo(e){return gs.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){gs.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){cs.subscribeKey("activeCaipNetwork",e)}getState(){return Xt.state}subscribeState(e){return Xt.subscribe(e)}showErrorMessage(e){Vt.showError(e)}showSuccessMessage(e){Vt.showSuccess(e)}getEvent(){return{...Ot.state}}subscribeEvents(e){return Ot.subscribe(e)}replace(e){$t.replace(e)}redirect(e){$t.push(e)}popTransactionStack(e){$t.popTransactionStack(e)}isOpen(){return ws.state.open}isTransactionStackEmpty(){return 0===$t.state.transactionStack.length}static getInstance(){return this.instance}updateFeatures(e){lt.setFeatures(e)}updateRemoteFeatures(e){lt.setRemoteFeatures(e)}updateOptions(e){const t={...lt.state||{},...e};lt.setOptions(t)}setConnectMethodsOrder(e){lt.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){lt.setWalletFeaturesOrder(e)}setCollapseWallets(e){lt.setCollapseWallets(e)}setSocialsOrder(e){lt.setSocialsOrder(e)}getConnectMethodsOrder(){return If.getConnectOrderMethod(lt.state.features,Ft.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)||cs.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&&cs.removeNetwork(e,t)}}let ov=!1;class av extends nv{async open(e){Ft.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Zt.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}
895async injectModalUi(){if(!ov&&rt.isClient()){await a(()=>import("./basic-BP359C7t.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])),await a(()=>import("./w3m-modal-DbvUgcN5.js"),__vite__mapDeps([8,1,2,3,4,5,6,7]));if(!document.querySelector("w3m-modal")){const e=document.createElement("w3m-modal");lt.state.disableAppend||lt.state.enableEmbedded||document.body.insertAdjacentElement("beforeend",e)}ov=!0}}}const cv=Object.freeze(Object.defineProperty({__proto__:null,AppKit:av,createAppKit:function(e){return new av({...e,basic:!0,sdkVersion:"html-core-1.7.8"})}},Symbol.toStringTag,{value:"Module"}));export{At as A,Zt as B,cs as C,it as D,Ot as E,st as F,cv as G,ws as M,lt as O,$t as R,of as S,jt as T,If as W,Ze as a,mw as b,xw as c,Fw as d,Bw as e,It as f,bt as g,Cf as h,Tf as i,Ft as j,gs as k,Vt as l,Ut as m,Mw as n,rt as o,Ye as p,se as q,qw as r,et as s,Hf as t,zf as u,ww as v,ft as w,gw as x,fw as y,Nf 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.