@dcl/governance-site 1.15.1-20473093943.commit-ad8dc42 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/{UserAvatar-41371133.js → UserAvatar-78751cb5.js} +1 -1
- package/assets/{basic-de12c849.js → basic-ca749c4c.js} +1 -1
- package/assets/{core-0c13d1dd.js → core-806d78ea.js} +7 -7
- package/assets/{features-e842dc9f.js → features-b72c9430.js} +1 -1
- package/assets/{fortmatic-dbae6d9f.js → fortmatic-12e0f2e5.js} +1 -1
- package/assets/{index-2a49049d.js → index-073512a1.js} +1 -1
- package/assets/{index-726bc846.js → index-2ef9f1d1.js} +14 -14
- package/assets/{index-bc60e460.js → index-372705ba.js} +1 -1
- package/assets/{index-6dad6f13.js → index-4be588a0.js} +1 -1
- package/assets/{index-37d53923.js → index-74e34dfb.js} +2 -2
- package/assets/{index-a5cbd387.css → index-a8255d1c.css} +4 -4
- package/assets/{index-16e232ba.js → index-bbb36593.js} +1 -1
- package/assets/{index-c2e969f4.js → index-c1c8440f.js} +1 -1
- package/assets/{tslib.es6-1071ccd0.js → tslib.es6-82b9ba96.js} +1 -1
- package/assets/{w3m-modal-d813356f.js → w3m-modal-26eff9d9.js} +1 -1
- package/index.html +4 -4
- package/package.json +2 -2
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{e as Ks,bD as Bh,_ as Ao,h as de,B as Ee,i as rr,x as ol}from"./index-726bc846.js";import{d as qi,s as Xn,c as $g,g as Kl,a as Ug,b as Dg,k as Lg,e as Bg,f as _o,I as Mr,h as Mg,i as V,j as es,t as Rt,l as xr,m as Mh,n as Fr,o as Fg,p as jg,q as qg,r as Wg,u as Hg,v as Kg,w as ai,x as uc,C as zg,y as Vg,z as al,A as Gg,B as cl,D as ll,E as gi,F as jr,G as Es,P as zl,Q as Yg,H as Jg,J as jn,K as Fh,L as ks,M as bs,N as Xs,O as jh}from"./index-37d53923.js";import{_ as Xg}from"./index-c2e969f4.js";function Zg(t,e){for(var s=0;s<e.length;s++){const n=e[s];if(typeof n!="string"&&!Array.isArray(n)){for(const r in n)if(r!=="default"&&!(r in t)){const i=Object.getOwnPropertyDescriptor(n,r);i&&Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>n[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}const U={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:"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",sui:"Sui",stacks:"Stacks"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof Ks<"u"&&typeof{}<"u"?{}.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}}},IS_DEVELOPMENT:typeof Ks<"u"&&{}.NODE_ENV==="development",DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]},qh={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return(t==null?void 0:t.filter(s=>s.chainNamespace===e))||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){var r;if(!e)return;const s=t.find(i=>i.caipNetworkId===e);if(s)return s.name;const[n]=e.split(":");return((r=U.CHAIN_NAME_MAP)==null?void 0:r[n])||void 0}},Wh=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var Qg=20,em=1,Zn=1e6,Vl=1e6,tm=-7,sm=21,nm=!1,Ri="[big.js] ",ir=Ri+"Invalid ",Go=ir+"decimal places",rm=ir+"rounding mode",Hh=Ri+"Division by zero",Te={},Is=void 0,im=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Kh(){function t(e){var s=this;if(!(s instanceof t))return e===Is?Kh():new t(e);if(e instanceof t)s.s=e.s,s.e=e.e,s.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(ir+"value");e=e===0&&1/e<0?"-0":String(e)}om(s,e)}s.constructor=t}return t.prototype=Te,t.DP=Qg,t.RM=em,t.NE=tm,t.PE=sm,t.strict=nm,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function om(t,e){var s,n,r;if(!im.test(e))throw Error(ir+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(s=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(s<0&&(s=n),s+=+e.slice(n+1),e=e.substring(0,n)):s<0&&(s=e.length),r=e.length,n=0;n<r&&e.charAt(n)=="0";)++n;if(n==r)t.c=[t.e=0];else{for(;r>0&&e.charAt(--r)=="0";);for(t.e=s-n-1,t.c=[],s=0;n<=r;)t.c[s++]=+e.charAt(n++)}return t}function or(t,e,s,n){var r=t.c;if(s===Is&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(rm);if(e<1)n=s===3&&(n||!!r[0])||e===0&&(s===1&&r[0]>=5||s===2&&(r[0]>5||r[0]===5&&(n||r[1]!==Is))),r.length=1,n?(t.e=t.e-e+1,r[0]=1):r[0]=t.e=0;else if(e<r.length){if(n=s===1&&r[e]>=5||s===2&&(r[e]>5||r[e]===5&&(n||r[e+1]!==Is||r[e-1]&1))||s===3&&(n||!!r[0]),r.length=e,n){for(;++r[--e]>9;)if(r[e]=0,e===0){++t.e,r.unshift(1);break}}for(e=r.length;!r[--e];)r.pop()}return t}function ar(t,e,s){var n=t.e,r=t.c.join(""),i=r.length;if(e)r=r.charAt(0)+(i>1?"."+r.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)r="0"+r;r="0."+r}else if(n>0)if(++n>i)for(n-=i;n--;)r+="0";else n<i&&(r=r.slice(0,n)+"."+r.slice(n));else i>1&&(r=r.charAt(0)+"."+r.slice(1));return t.s<0&&s?"-"+r:r}Te.abs=function(){var t=new this.constructor(this);return t.s=1,t};Te.cmp=function(t){var e,s=this,n=s.c,r=(t=new s.constructor(t)).c,i=s.s,o=t.s,a=s.e,c=t.e;if(!n[0]||!r[0])return n[0]?i:r[0]?-o:0;if(i!=o)return i;if(e=i<0,a!=c)return a>c^e?1:-1;for(o=(a=n.length)<(c=r.length)?a:c,i=-1;++i<o;)if(n[i]!=r[i])return n[i]>r[i]^e?1:-1;return a==c?0:a>c^e?1:-1};Te.div=function(t){var e=this,s=e.constructor,n=e.c,r=(t=new s(t)).c,i=e.s==t.s?1:-1,o=s.DP;if(o!==~~o||o<0||o>Zn)throw Error(Go);if(!r[0])throw Error(Hh);if(!n[0])return t.s=i,t.c=[t.e=0],t;var a,c,l,d,u,h=r.slice(),p=a=r.length,g=n.length,f=n.slice(0,a),w=f.length,E=t,I=E.c=[],_=0,v=o+(E.e=e.e-t.e)+1;for(E.s=i,i=v<0?0:v,h.unshift(0);w++<a;)f.push(0);do{for(l=0;l<10;l++){if(a!=(w=f.length))d=a>w?1:-1;else for(u=-1,d=0;++u<a;)if(r[u]!=f[u]){d=r[u]>f[u]?1:-1;break}if(d<0){for(c=w==a?r:h;w;){if(f[--w]<c[w]){for(u=w;u&&!f[--u];)f[u]=9;--f[u],f[w]+=10}f[w]-=c[w]}for(;!f[0];)f.shift()}else break}I[_++]=d?l:++l,f[0]&&d?f[w]=n[p]||0:f=[n[p]]}while((p++<g||f[0]!==Is)&&i--);return!I[0]&&_!=1&&(I.shift(),E.e--,v--),_>v&&or(E,v,s.RM,f[0]!==Is),E};Te.eq=function(t){return this.cmp(t)===0};Te.gt=function(t){return this.cmp(t)>0};Te.gte=function(t){return this.cmp(t)>-1};Te.lt=function(t){return this.cmp(t)<0};Te.lte=function(t){return this.cmp(t)<1};Te.minus=Te.sub=function(t){var e,s,n,r,i=this,o=i.constructor,a=i.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,i.plus(t);var l=i.c.slice(),d=i.e,u=t.c,h=t.e;if(!l[0]||!u[0])return u[0]?t.s=-c:l[0]?t=new o(i):t.s=1,t;if(a=d-h){for((r=a<0)?(a=-a,n=l):(h=d,n=u),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(s=((r=l.length<u.length)?l:u).length,a=c=0;c<s;c++)if(l[c]!=u[c]){r=l[c]<u[c];break}if(r&&(n=l,l=u,u=n,t.s=-t.s),(c=(s=u.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;s>a;){if(l[--s]<u[s]){for(e=s;e&&!l[--e];)l[e]=9;--l[e],l[s]+=10}l[s]-=u[s]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(t.s=1,l=[h=0]),t.c=l,t.e=h,t};Te.mod=function(t){var e,s=this,n=s.constructor,r=s.s,i=(t=new n(t)).s;if(!t.c[0])throw Error(Hh);return s.s=t.s=1,e=t.cmp(s)==1,s.s=r,t.s=i,e?new n(s):(r=n.DP,i=n.RM,n.DP=n.RM=0,s=s.div(t),n.DP=r,n.RM=i,this.minus(s.times(t)))};Te.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};Te.plus=Te.add=function(t){var e,s,n,r=this,i=r.constructor;if(t=new i(t),r.s!=t.s)return t.s=-t.s,r.minus(t);var o=r.e,a=r.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new i(r):t.s=r.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,n=l):(e=-e,n=a),n.reverse();e--;)n.push(0);n.reverse()}for(a.length-l.length<0&&(n=l,l=a,a=n),e=l.length,s=0;e;a[e]%=10)s=(a[--e]=a[e]+l[e]+s)/10|0;for(s&&(a.unshift(s),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t};Te.pow=function(t){var e=this,s=new e.constructor("1"),n=s,r=t<0;if(t!==~~t||t<-Vl||t>Vl)throw Error(ir+"exponent");for(r&&(t=-t);t&1&&(n=n.times(e)),t>>=1,!!t;)e=e.times(e);return r?s.div(n):n};Te.prec=function(t,e){if(t!==~~t||t<1||t>Zn)throw Error(ir+"precision");return or(new this.constructor(this),t,e)};Te.round=function(t,e){if(t===Is)t=0;else if(t!==~~t||t<-Zn||t>Zn)throw Error(Go);return or(new this.constructor(this),t+this.e+1,e)};Te.sqrt=function(){var t,e,s,n=this,r=n.constructor,i=n.s,o=n.e,a=new r("0.5");if(!n.c[0])return new r(n);if(i<0)throw Error(Ri+"No square root");i=Math.sqrt(+ar(n,!0,!0)),i===0||i===1/0?(e=n.c.join(""),e.length+o&1||(e+="0"),i=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new r((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+o)):t=new r(i+""),o=t.e+(r.DP+=4);do s=t,t=a.times(s.plus(n.div(s)));while(s.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return or(t,(r.DP-=4)+t.e+1,r.RM)};Te.times=Te.mul=function(t){var e,s=this,n=s.constructor,r=s.c,i=(t=new n(t)).c,o=r.length,a=i.length,c=s.e,l=t.e;if(t.s=s.s==t.s?1:-1,!r[0]||!i[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=r,r=i,i=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+i[c]*r[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t};Te.toExponential=function(t,e){var s=this,n=s.c[0];if(t!==Is){if(t!==~~t||t<0||t>Zn)throw Error(Go);for(s=or(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return ar(s,!0,!!n)};Te.toFixed=function(t,e){var s=this,n=s.c[0];if(t!==Is){if(t!==~~t||t<0||t>Zn)throw Error(Go);for(s=or(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return ar(s,!1,!!n)};Te[Symbol.for("nodejs.util.inspect.custom")]=Te.toJSON=Te.toString=function(){var t=this,e=t.constructor;return ar(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};Te.toNumber=function(){var t=+ar(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(Ri+"Imprecise conversion");return t};Te.toPrecision=function(t,e){var s=this,n=s.constructor,r=s.c[0];if(t!==Is){if(t!==~~t||t<1||t>Zn)throw Error(ir+"precision");for(s=or(new n(s),t,e);s.c.length<t;)s.c.push(0)}return ar(s,t<=s.e||s.e<=n.NE||s.e>=n.PE,!!r)};Te.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(Ri+"valueOf disallowed");return ar(t,t.e<=e.NE||t.e>=e.PE,!0)};var am=Kh();const Zs=am,cm={bigNumber(t){return t?new Zs(t):new Zs(0)},multiply(t,e){if(t===void 0||e===void 0)return new Zs(0);const s=new Zs(t),n=new Zs(e);return s.times(n)},toFixed(t,e=2){return t===void 0||t===""?new Zs(0).toFixed(e):new Zs(t).toFixed(e)},formatNumberToLocalString(t,e=2){return t===void 0||t===""?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"})},parseLocalStringToNumber(t){if(t===void 0||t==="")return 0;const e=t.replace(/,/gu,"");return new Zs(e).toNumber()}},lm=[{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"}]}],dm=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],um=[{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"}]}],hm={getERC20Abi:t=>U.USDT_CONTRACT_ADDRESSES.includes(t)?um:lm,getSwapAbi:()=>dm},tt={validateCaipAddress(t){var e;if(((e=t.split(":"))==null?void 0:e.length)!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,n,r]=e;if(!s||!n||!r)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:n,address:r}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,n]=e;if(!s||!n)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:n}}},js={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError"},isRpcProviderError(t){try{if(typeof t=="object"&&t!==null){const e=t,s=typeof e.message=="string",n=typeof e.code=="number";return s&&n}return!1}catch{return!1}},isUserRejectedMessage(t){return t.toLowerCase().includes("user rejected")||t.toLowerCase().includes("user cancelled")||t.toLowerCase().includes("user canceled")},isUserRejectedRequestError(t){if(js.isRpcProviderError(t)){const e=t.code===js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,s=t.code===js.RPC_ERROR_CODE.USER_REJECTED_METHODS;return e||s||js.isUserRejectedMessage(t.message)}return t instanceof Error?js.isUserRejectedMessage(t.message):!1}};class pm extends Error{constructor(e,s){super(s.message,{cause:e}),this.name=js.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=s.code}}class zh extends pm{constructor(e){super(e,{code:js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=js.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const te={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version"};function pa(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Z={setItem(t,e){si()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(si())return localStorage.getItem(t)||void 0},removeItem(t){si()&&localStorage.removeItem(t)},clear(){si()&&localStorage.clear()}};function si(){return typeof window<"u"&&typeof localStorage<"u"}function Io(t,e){return e==="light"?{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const fm=Symbol(),Gl=Object.getPrototypeOf,hc=new WeakMap,gm=t=>t&&(hc.has(t)?hc.get(t):Gl(t)===Object.prototype||Gl(t)===Array.prototype),mm=t=>gm(t)&&t[fm]||null,Yl=(t,e=!0)=>{hc.set(t,e)},dl=t=>typeof t=="object"&&t!==null,wm=t=>dl(t)&&!Pi.has(t)&&(Array.isArray(t)||!(Symbol.iterator in t))&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!(t instanceof Error)&&!(t instanceof Number)&&!(t instanceof Date)&&!(t instanceof String)&&!(t instanceof RegExp)&&!(t instanceof ArrayBuffer)&&!(t instanceof Promise),Vh=(t,e)=>{const s=pc.get(t);if((s==null?void 0:s[0])===e)return s[1];const n=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return Yl(n,!0),pc.set(t,[e,n]),Reflect.ownKeys(t).forEach(r=>{if(Object.getOwnPropertyDescriptor(n,r))return;const i=Reflect.get(t,r),{enumerable:o}=Reflect.getOwnPropertyDescriptor(t,r),a={value:i,enumerable:o,configurable:!0};if(Pi.has(i))Yl(i,!1);else if(An.has(i)){const[c,l]=An.get(i);a.value=Vh(c,l())}Object.defineProperty(n,r,a)}),Object.preventExtensions(n)},ym=(t,e,s,n)=>({deleteProperty(r,i){const o=Reflect.get(r,i);s(i);const a=Reflect.deleteProperty(r,i);return a&&n(["delete",[i],o]),a},set(r,i,o,a){const c=!t()&&Reflect.has(r,i),l=Reflect.get(r,i,a);if(c&&(Jl(l,o)||mi.has(o)&&Jl(l,mi.get(o))))return!0;s(i),dl(o)&&(o=mm(o)||o);const d=!An.has(o)&&Em(o)?ke(o):o;return e(i,d),Reflect.set(r,i,d,a),n(["set",[i],o,l]),!0}}),An=new WeakMap,Pi=new WeakSet,pc=new WeakMap,po=[1],mi=new WeakMap;let Jl=Object.is,bm=(t,e)=>new Proxy(t,e),Em=wm,Cm=Vh,vm=ym;function ke(t={}){if(!dl(t))throw new Error("object required");const e=mi.get(t);if(e)return e;let s=po[0];const n=new Set,r=(w,E=++po[0])=>{s!==E&&(i=s=E,n.forEach(I=>I(w,E)))};let i=s;const o=(w=po[0])=>(i!==w&&(i=w,c.forEach(([E])=>{const I=E[1](w);I>s&&(s=I)})),s),a=w=>(E,I)=>{const _=[...E];_[1]=[w,..._[1]],r(_,I)},c=new Map,l=(w,E)=>{const I=!Pi.has(E)&&An.get(E);if(I)if(n.size){const _=I[2](a(w));c.set(w,[I,_])}else c.set(w,[I])},d=w=>{var E;const I=c.get(w);I&&(c.delete(w),(E=I[1])==null||E.call(I))},u=w=>(n.add(w),n.size===1&&c.forEach(([I,_],v)=>{const T=I[2](a(v));c.set(v,[I,T])}),()=>{n.delete(w),n.size===0&&c.forEach(([I,_],v)=>{_&&(_(),c.set(v,[I]))})});let h=!0;const p=vm(()=>h,l,d,r),g=bm(t,p);mi.set(t,g);const f=[t,o,u];return An.set(g,f),Reflect.ownKeys(t).forEach(w=>{const E=Object.getOwnPropertyDescriptor(t,w);"value"in E&&E.writable&&(g[w]=t[w])}),h=!1,g}function st(t,e,s){const n=An.get(t);let r;const i=[],o=n[2];let a=!1;const l=o(d=>{if(i.push(d),s){e(i.splice(0));return}r||(r=Promise.resolve().then(()=>{r=void 0,a&&e(i.splice(0))}))});return a=!0,()=>{a=!1,l()}}function wi(t){const e=An.get(t),[s,n]=e;return Cm(s,n())}function yi(t){return Pi.add(t),t}function Am(){return{proxyStateMap:An,refSet:Pi,snapCache:pc,versionHolder:po,proxyCache:mi}}function nt(t,e,s,n){let r=t[e];return st(t,()=>{const i=t[e];Object.is(r,i)||s(r=i)},n)}const{proxyStateMap:_m,snapCache:Im}=Am(),Wi=t=>_m.has(t);function Sm(t){const e=[];let s=0;const n=new Map,r=new WeakMap,i=()=>{const l=Im.get(a),d=l==null?void 0:l[1];if(d&&!r.has(d)){const u=new Map(n);r.set(d,u)}},o=l=>r.get(l)||n;if(t){if(typeof t[Symbol.iterator]!="function")throw new TypeError(`proxyMap:
|
|
1
|
+
import{e as Ks,bD as Bh,_ as Ao,h as de,B as Ee,i as rr,x as ol}from"./index-2ef9f1d1.js";import{d as qi,s as Xn,c as $g,g as Kl,a as Ug,b as Dg,k as Lg,e as Bg,f as _o,I as Mr,h as Mg,i as V,j as es,t as Rt,l as xr,m as Mh,n as Fr,o as Fg,p as jg,q as qg,r as Wg,u as Hg,v as Kg,w as ai,x as uc,C as zg,y as Vg,z as al,A as Gg,B as cl,D as ll,E as gi,F as jr,G as Es,P as zl,Q as Yg,H as Jg,J as jn,K as Fh,L as ks,M as bs,N as Xs,O as jh}from"./index-74e34dfb.js";import{_ as Xg}from"./index-c1c8440f.js";function Zg(t,e){for(var s=0;s<e.length;s++){const n=e[s];if(typeof n!="string"&&!Array.isArray(n)){for(const r in n)if(r!=="default"&&!(r in t)){const i=Object.getOwnPropertyDescriptor(n,r);i&&Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>n[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}const U={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:"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",sui:"Sui",stacks:"Stacks"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof Ks<"u"&&typeof{}<"u"?{}.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}}},IS_DEVELOPMENT:typeof Ks<"u"&&{}.NODE_ENV==="development",DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]},qh={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return(t==null?void 0:t.filter(s=>s.chainNamespace===e))||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){var r;if(!e)return;const s=t.find(i=>i.caipNetworkId===e);if(s)return s.name;const[n]=e.split(":");return((r=U.CHAIN_NAME_MAP)==null?void 0:r[n])||void 0}},Wh=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var Qg=20,em=1,Zn=1e6,Vl=1e6,tm=-7,sm=21,nm=!1,Ri="[big.js] ",ir=Ri+"Invalid ",Go=ir+"decimal places",rm=ir+"rounding mode",Hh=Ri+"Division by zero",Te={},Is=void 0,im=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Kh(){function t(e){var s=this;if(!(s instanceof t))return e===Is?Kh():new t(e);if(e instanceof t)s.s=e.s,s.e=e.e,s.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(ir+"value");e=e===0&&1/e<0?"-0":String(e)}om(s,e)}s.constructor=t}return t.prototype=Te,t.DP=Qg,t.RM=em,t.NE=tm,t.PE=sm,t.strict=nm,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function om(t,e){var s,n,r;if(!im.test(e))throw Error(ir+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(s=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(s<0&&(s=n),s+=+e.slice(n+1),e=e.substring(0,n)):s<0&&(s=e.length),r=e.length,n=0;n<r&&e.charAt(n)=="0";)++n;if(n==r)t.c=[t.e=0];else{for(;r>0&&e.charAt(--r)=="0";);for(t.e=s-n-1,t.c=[],s=0;n<=r;)t.c[s++]=+e.charAt(n++)}return t}function or(t,e,s,n){var r=t.c;if(s===Is&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(rm);if(e<1)n=s===3&&(n||!!r[0])||e===0&&(s===1&&r[0]>=5||s===2&&(r[0]>5||r[0]===5&&(n||r[1]!==Is))),r.length=1,n?(t.e=t.e-e+1,r[0]=1):r[0]=t.e=0;else if(e<r.length){if(n=s===1&&r[e]>=5||s===2&&(r[e]>5||r[e]===5&&(n||r[e+1]!==Is||r[e-1]&1))||s===3&&(n||!!r[0]),r.length=e,n){for(;++r[--e]>9;)if(r[e]=0,e===0){++t.e,r.unshift(1);break}}for(e=r.length;!r[--e];)r.pop()}return t}function ar(t,e,s){var n=t.e,r=t.c.join(""),i=r.length;if(e)r=r.charAt(0)+(i>1?"."+r.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)r="0"+r;r="0."+r}else if(n>0)if(++n>i)for(n-=i;n--;)r+="0";else n<i&&(r=r.slice(0,n)+"."+r.slice(n));else i>1&&(r=r.charAt(0)+"."+r.slice(1));return t.s<0&&s?"-"+r:r}Te.abs=function(){var t=new this.constructor(this);return t.s=1,t};Te.cmp=function(t){var e,s=this,n=s.c,r=(t=new s.constructor(t)).c,i=s.s,o=t.s,a=s.e,c=t.e;if(!n[0]||!r[0])return n[0]?i:r[0]?-o:0;if(i!=o)return i;if(e=i<0,a!=c)return a>c^e?1:-1;for(o=(a=n.length)<(c=r.length)?a:c,i=-1;++i<o;)if(n[i]!=r[i])return n[i]>r[i]^e?1:-1;return a==c?0:a>c^e?1:-1};Te.div=function(t){var e=this,s=e.constructor,n=e.c,r=(t=new s(t)).c,i=e.s==t.s?1:-1,o=s.DP;if(o!==~~o||o<0||o>Zn)throw Error(Go);if(!r[0])throw Error(Hh);if(!n[0])return t.s=i,t.c=[t.e=0],t;var a,c,l,d,u,h=r.slice(),p=a=r.length,g=n.length,f=n.slice(0,a),w=f.length,E=t,I=E.c=[],_=0,v=o+(E.e=e.e-t.e)+1;for(E.s=i,i=v<0?0:v,h.unshift(0);w++<a;)f.push(0);do{for(l=0;l<10;l++){if(a!=(w=f.length))d=a>w?1:-1;else for(u=-1,d=0;++u<a;)if(r[u]!=f[u]){d=r[u]>f[u]?1:-1;break}if(d<0){for(c=w==a?r:h;w;){if(f[--w]<c[w]){for(u=w;u&&!f[--u];)f[u]=9;--f[u],f[w]+=10}f[w]-=c[w]}for(;!f[0];)f.shift()}else break}I[_++]=d?l:++l,f[0]&&d?f[w]=n[p]||0:f=[n[p]]}while((p++<g||f[0]!==Is)&&i--);return!I[0]&&_!=1&&(I.shift(),E.e--,v--),_>v&&or(E,v,s.RM,f[0]!==Is),E};Te.eq=function(t){return this.cmp(t)===0};Te.gt=function(t){return this.cmp(t)>0};Te.gte=function(t){return this.cmp(t)>-1};Te.lt=function(t){return this.cmp(t)<0};Te.lte=function(t){return this.cmp(t)<1};Te.minus=Te.sub=function(t){var e,s,n,r,i=this,o=i.constructor,a=i.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,i.plus(t);var l=i.c.slice(),d=i.e,u=t.c,h=t.e;if(!l[0]||!u[0])return u[0]?t.s=-c:l[0]?t=new o(i):t.s=1,t;if(a=d-h){for((r=a<0)?(a=-a,n=l):(h=d,n=u),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(s=((r=l.length<u.length)?l:u).length,a=c=0;c<s;c++)if(l[c]!=u[c]){r=l[c]<u[c];break}if(r&&(n=l,l=u,u=n,t.s=-t.s),(c=(s=u.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;s>a;){if(l[--s]<u[s]){for(e=s;e&&!l[--e];)l[e]=9;--l[e],l[s]+=10}l[s]-=u[s]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(t.s=1,l=[h=0]),t.c=l,t.e=h,t};Te.mod=function(t){var e,s=this,n=s.constructor,r=s.s,i=(t=new n(t)).s;if(!t.c[0])throw Error(Hh);return s.s=t.s=1,e=t.cmp(s)==1,s.s=r,t.s=i,e?new n(s):(r=n.DP,i=n.RM,n.DP=n.RM=0,s=s.div(t),n.DP=r,n.RM=i,this.minus(s.times(t)))};Te.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};Te.plus=Te.add=function(t){var e,s,n,r=this,i=r.constructor;if(t=new i(t),r.s!=t.s)return t.s=-t.s,r.minus(t);var o=r.e,a=r.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new i(r):t.s=r.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,n=l):(e=-e,n=a),n.reverse();e--;)n.push(0);n.reverse()}for(a.length-l.length<0&&(n=l,l=a,a=n),e=l.length,s=0;e;a[e]%=10)s=(a[--e]=a[e]+l[e]+s)/10|0;for(s&&(a.unshift(s),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t};Te.pow=function(t){var e=this,s=new e.constructor("1"),n=s,r=t<0;if(t!==~~t||t<-Vl||t>Vl)throw Error(ir+"exponent");for(r&&(t=-t);t&1&&(n=n.times(e)),t>>=1,!!t;)e=e.times(e);return r?s.div(n):n};Te.prec=function(t,e){if(t!==~~t||t<1||t>Zn)throw Error(ir+"precision");return or(new this.constructor(this),t,e)};Te.round=function(t,e){if(t===Is)t=0;else if(t!==~~t||t<-Zn||t>Zn)throw Error(Go);return or(new this.constructor(this),t+this.e+1,e)};Te.sqrt=function(){var t,e,s,n=this,r=n.constructor,i=n.s,o=n.e,a=new r("0.5");if(!n.c[0])return new r(n);if(i<0)throw Error(Ri+"No square root");i=Math.sqrt(+ar(n,!0,!0)),i===0||i===1/0?(e=n.c.join(""),e.length+o&1||(e+="0"),i=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new r((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+o)):t=new r(i+""),o=t.e+(r.DP+=4);do s=t,t=a.times(s.plus(n.div(s)));while(s.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return or(t,(r.DP-=4)+t.e+1,r.RM)};Te.times=Te.mul=function(t){var e,s=this,n=s.constructor,r=s.c,i=(t=new n(t)).c,o=r.length,a=i.length,c=s.e,l=t.e;if(t.s=s.s==t.s?1:-1,!r[0]||!i[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=r,r=i,i=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+i[c]*r[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t};Te.toExponential=function(t,e){var s=this,n=s.c[0];if(t!==Is){if(t!==~~t||t<0||t>Zn)throw Error(Go);for(s=or(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return ar(s,!0,!!n)};Te.toFixed=function(t,e){var s=this,n=s.c[0];if(t!==Is){if(t!==~~t||t<0||t>Zn)throw Error(Go);for(s=or(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return ar(s,!1,!!n)};Te[Symbol.for("nodejs.util.inspect.custom")]=Te.toJSON=Te.toString=function(){var t=this,e=t.constructor;return ar(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};Te.toNumber=function(){var t=+ar(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(Ri+"Imprecise conversion");return t};Te.toPrecision=function(t,e){var s=this,n=s.constructor,r=s.c[0];if(t!==Is){if(t!==~~t||t<1||t>Zn)throw Error(ir+"precision");for(s=or(new n(s),t,e);s.c.length<t;)s.c.push(0)}return ar(s,t<=s.e||s.e<=n.NE||s.e>=n.PE,!!r)};Te.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(Ri+"valueOf disallowed");return ar(t,t.e<=e.NE||t.e>=e.PE,!0)};var am=Kh();const Zs=am,cm={bigNumber(t){return t?new Zs(t):new Zs(0)},multiply(t,e){if(t===void 0||e===void 0)return new Zs(0);const s=new Zs(t),n=new Zs(e);return s.times(n)},toFixed(t,e=2){return t===void 0||t===""?new Zs(0).toFixed(e):new Zs(t).toFixed(e)},formatNumberToLocalString(t,e=2){return t===void 0||t===""?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"})},parseLocalStringToNumber(t){if(t===void 0||t==="")return 0;const e=t.replace(/,/gu,"");return new Zs(e).toNumber()}},lm=[{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"}]}],dm=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],um=[{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"}]}],hm={getERC20Abi:t=>U.USDT_CONTRACT_ADDRESSES.includes(t)?um:lm,getSwapAbi:()=>dm},tt={validateCaipAddress(t){var e;if(((e=t.split(":"))==null?void 0:e.length)!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,n,r]=e;if(!s||!n||!r)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:n,address:r}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,n]=e;if(!s||!n)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:n}}},js={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError"},isRpcProviderError(t){try{if(typeof t=="object"&&t!==null){const e=t,s=typeof e.message=="string",n=typeof e.code=="number";return s&&n}return!1}catch{return!1}},isUserRejectedMessage(t){return t.toLowerCase().includes("user rejected")||t.toLowerCase().includes("user cancelled")||t.toLowerCase().includes("user canceled")},isUserRejectedRequestError(t){if(js.isRpcProviderError(t)){const e=t.code===js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,s=t.code===js.RPC_ERROR_CODE.USER_REJECTED_METHODS;return e||s||js.isUserRejectedMessage(t.message)}return t instanceof Error?js.isUserRejectedMessage(t.message):!1}};class pm extends Error{constructor(e,s){super(s.message,{cause:e}),this.name=js.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=s.code}}class zh extends pm{constructor(e){super(e,{code:js.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=js.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}}const te={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version"};function pa(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Z={setItem(t,e){si()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(si())return localStorage.getItem(t)||void 0},removeItem(t){si()&&localStorage.removeItem(t)},clear(){si()&&localStorage.clear()}};function si(){return typeof window<"u"&&typeof localStorage<"u"}function Io(t,e){return e==="light"?{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":(t==null?void 0:t["--w3m-accent"])||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const fm=Symbol(),Gl=Object.getPrototypeOf,hc=new WeakMap,gm=t=>t&&(hc.has(t)?hc.get(t):Gl(t)===Object.prototype||Gl(t)===Array.prototype),mm=t=>gm(t)&&t[fm]||null,Yl=(t,e=!0)=>{hc.set(t,e)},dl=t=>typeof t=="object"&&t!==null,wm=t=>dl(t)&&!Pi.has(t)&&(Array.isArray(t)||!(Symbol.iterator in t))&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!(t instanceof Error)&&!(t instanceof Number)&&!(t instanceof Date)&&!(t instanceof String)&&!(t instanceof RegExp)&&!(t instanceof ArrayBuffer)&&!(t instanceof Promise),Vh=(t,e)=>{const s=pc.get(t);if((s==null?void 0:s[0])===e)return s[1];const n=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return Yl(n,!0),pc.set(t,[e,n]),Reflect.ownKeys(t).forEach(r=>{if(Object.getOwnPropertyDescriptor(n,r))return;const i=Reflect.get(t,r),{enumerable:o}=Reflect.getOwnPropertyDescriptor(t,r),a={value:i,enumerable:o,configurable:!0};if(Pi.has(i))Yl(i,!1);else if(An.has(i)){const[c,l]=An.get(i);a.value=Vh(c,l())}Object.defineProperty(n,r,a)}),Object.preventExtensions(n)},ym=(t,e,s,n)=>({deleteProperty(r,i){const o=Reflect.get(r,i);s(i);const a=Reflect.deleteProperty(r,i);return a&&n(["delete",[i],o]),a},set(r,i,o,a){const c=!t()&&Reflect.has(r,i),l=Reflect.get(r,i,a);if(c&&(Jl(l,o)||mi.has(o)&&Jl(l,mi.get(o))))return!0;s(i),dl(o)&&(o=mm(o)||o);const d=!An.has(o)&&Em(o)?ke(o):o;return e(i,d),Reflect.set(r,i,d,a),n(["set",[i],o,l]),!0}}),An=new WeakMap,Pi=new WeakSet,pc=new WeakMap,po=[1],mi=new WeakMap;let Jl=Object.is,bm=(t,e)=>new Proxy(t,e),Em=wm,Cm=Vh,vm=ym;function ke(t={}){if(!dl(t))throw new Error("object required");const e=mi.get(t);if(e)return e;let s=po[0];const n=new Set,r=(w,E=++po[0])=>{s!==E&&(i=s=E,n.forEach(I=>I(w,E)))};let i=s;const o=(w=po[0])=>(i!==w&&(i=w,c.forEach(([E])=>{const I=E[1](w);I>s&&(s=I)})),s),a=w=>(E,I)=>{const _=[...E];_[1]=[w,..._[1]],r(_,I)},c=new Map,l=(w,E)=>{const I=!Pi.has(E)&&An.get(E);if(I)if(n.size){const _=I[2](a(w));c.set(w,[I,_])}else c.set(w,[I])},d=w=>{var E;const I=c.get(w);I&&(c.delete(w),(E=I[1])==null||E.call(I))},u=w=>(n.add(w),n.size===1&&c.forEach(([I,_],v)=>{const T=I[2](a(v));c.set(v,[I,T])}),()=>{n.delete(w),n.size===0&&c.forEach(([I,_],v)=>{_&&(_(),c.set(v,[I]))})});let h=!0;const p=vm(()=>h,l,d,r),g=bm(t,p);mi.set(t,g);const f=[t,o,u];return An.set(g,f),Reflect.ownKeys(t).forEach(w=>{const E=Object.getOwnPropertyDescriptor(t,w);"value"in E&&E.writable&&(g[w]=t[w])}),h=!1,g}function st(t,e,s){const n=An.get(t);let r;const i=[],o=n[2];let a=!1;const l=o(d=>{if(i.push(d),s){e(i.splice(0));return}r||(r=Promise.resolve().then(()=>{r=void 0,a&&e(i.splice(0))}))});return a=!0,()=>{a=!1,l()}}function wi(t){const e=An.get(t),[s,n]=e;return Cm(s,n())}function yi(t){return Pi.add(t),t}function Am(){return{proxyStateMap:An,refSet:Pi,snapCache:pc,versionHolder:po,proxyCache:mi}}function nt(t,e,s,n){let r=t[e];return st(t,()=>{const i=t[e];Object.is(r,i)||s(r=i)},n)}const{proxyStateMap:_m,snapCache:Im}=Am(),Wi=t=>_m.has(t);function Sm(t){const e=[];let s=0;const n=new Map,r=new WeakMap,i=()=>{const l=Im.get(a),d=l==null?void 0:l[1];if(d&&!r.has(d)){const u=new Map(n);r.set(d,u)}},o=l=>r.get(l)||n;if(t){if(typeof t[Symbol.iterator]!="function")throw new TypeError(`proxyMap:
|
|
2
2
|
initial state must be iterable
|
|
3
3
|
tip: structure should be [[key, value]]`);for(const[l,d]of t)n.set(l,s),e[s++]=d}const a={data:e,index:s,epoch:0,get size(){return Wi(this)||i(),o(this).size},get(l){const u=o(this).get(l);if(u===void 0){this.epoch;return}return this.data[u]},has(l){const d=o(this);return this.epoch,d.has(l)},set(l,d){if(!Wi(this))throw new Error("Cannot perform mutations on a snapshot");const u=n.get(l);return u===void 0?(n.set(l,this.index),this.data[this.index++]=d):this.data[u]=d,this.epoch++,this},delete(l){if(!Wi(this))throw new Error("Cannot perform mutations on a snapshot");const d=n.get(l);return d===void 0?!1:(delete this.data[d],n.delete(l),this.epoch++,!0)},clear(){if(!Wi(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,n.clear()},forEach(l){this.epoch,o(this).forEach((u,h)=>{l(this.data[u],h,this)})},*entries(){this.epoch;const l=o(this);for(const[d,u]of l)yield[d,this.data[u]]},*keys(){this.epoch;const l=o(this);for(const d of l.keys())yield d},*values(){this.epoch;const l=o(this);for(const d of l.values())yield this.data[d]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=ke(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}const fa=(typeof Ks<"u"&&typeof{}<"u"?{}.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Gh=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Nm="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",ye={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:fa,SECURE_SITE_DASHBOARD:`${fa}/dashboard`,SECURE_SITE_FAVICON:`${fa}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],SUGGESTED_TOKENS_BY_CHAIN:{"eip155:42161":["USD₮0"]},BALANCE_SUPPORTED_CHAINS:[U.CHAIN.EVM,U.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[U.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[U.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[U.CHAIN.EVM,U.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[U.CHAIN.EVM,U.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[U.CHAIN.EVM],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[U.CHAIN.EVM,U.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0}},B={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=B.getActiveNamespace(),e=B.getActiveCaipNetworkId(),s=e?e.split(":")[1]:void 0,n=s?isNaN(Number(s))?s:Number(s):void 0;return{namespace:t,caipNetworkId:e,chainId:n}},setWalletConnectDeepLink({name:t,href:e}){try{Z.setItem(te.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Z.getItem(te.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Z.removeItem(te.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Z.setItem(te.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Z.setItem(te.ACTIVE_CAIP_NETWORK_ID,t),B.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Z.getItem(te.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Z.removeItem(te.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=pa(t);Z.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=B.getRecentWallets();e.find(n=>n.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Z.setItem(te.RECENT_WALLETS,JSON.stringify(e)),Z.setItem(te.RECENT_WALLET,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Z.getItem(te.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const t=Z.getItem(te.RECENT_WALLET);return t?JSON.parse(t):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{Z.removeItem(te.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(t,e){try{const s=pa(t);Z.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Z.getItem(te.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=pa(t);return Z.getItem(e)}catch{console.info("Unable to get connected connector id in namespace",t)}},setConnectedSocialProvider(t){try{Z.setItem(te.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Z.getItem(te.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Z.removeItem(te.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Z.getItem(te.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var s;const t=Z.getItem(te.ACTIVE_CAIP_NETWORK_ID);return(s=t==null?void 0:t.split(":"))==null?void 0:s[1]},setConnectionStatus(t){try{Z.setItem(te.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Z.getItem(te.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Z.getItem(te.CONNECTED_NAMESPACES);return t!=null&&t.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Z.setItem(te.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=B.getConnectedNamespaces();e.includes(t)||(e.push(t),B.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=B.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),B.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Z.getItem(te.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Z.setItem(te.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Z.removeItem(te.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Z.getItem(te.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=B.getBalanceCache();Z.setItem(te.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=B.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;B.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=B.getBalanceCache();e[t.caipAddress]=t,Z.setItem(te.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Z.getItem(te.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=B.getBalanceCache();Z.setItem(te.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const s=B.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),B.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=B.getNativeBalanceCache();e[t.caipAddress]=t,Z.setItem(te.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Z.getItem(te.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const s=B.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;B.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=B.getEnsCache();e[t.address]=t,Z.setItem(te.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=B.getEnsCache();Z.setItem(te.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Z.getItem(te.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=B.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;B.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=B.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Z.setItem(te.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=B.getIdentityCache();Z.setItem(te.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Z.removeItem(te.PORTFOLIO_CACHE),Z.removeItem(te.NATIVE_BALANCE_CACHE),Z.removeItem(te.ENS_CACHE),Z.removeItem(te.IDENTITY_CACHE),Z.removeItem(te.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Z.setItem(te.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Z.getItem(te.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s=B.getConnections(),n=s[e]??[],r=new Map;for(const o of n)r.set(o.connectorId,{...o});for(const o of t){const a=r.get(o.connectorId),c=o.connectorId===U.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(u=>u.address.toLowerCase())),d=o.accounts.filter(u=>!l.has(u.address.toLowerCase()));a.accounts.push(...d)}else r.set(o.connectorId,{...o})}const i={...s,[e]:Array.from(r.values())};Z.setItem(te.CONNECTIONS,JSON.stringify(i))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=Z.getItem(te.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}},deleteAddressFromConnection({connectorId:t,address:e,namespace:s}){try{const n=B.getConnections(),r=n[s]??[],i=new Map(r.map(a=>[a.connectorId,a])),o=i.get(t);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase()).length===0?i.delete(t):i.set(t,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase())})),Z.setItem(te.CONNECTIONS,JSON.stringify({...n,[s]:Array.from(i.values())}))}catch{console.error(`Unable to remove address "${e}" from connector "${t}" in namespace "${s}"`)}},getDisconnectedConnectorIds(){try{const t=Z.getItem(te.DISCONNECTED_CONNECTOR_IDS);return t?JSON.parse(t):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(t,e){try{const s=B.getDisconnectedConnectorIds(),n=s[e]??[];n.push(t),Z.setItem(te.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[e]:Array.from(new Set(n))}))}catch{console.error(`Unable to set disconnected connector id "${t}" for namespace "${e}"`)}},removeDisconnectedConnectorId(t,e){try{const s=B.getDisconnectedConnectorIds();let n=s[e]??[];n=n.filter(r=>r.toLowerCase()!==t.toLowerCase()),Z.setItem(te.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[e]:Array.from(new Set(n))}))}catch{console.error(`Unable to remove disconnected connector id "${t}" for namespace "${e}"`)}},isConnectorDisconnected(t,e){try{return(B.getDisconnectedConnectorIds()[e]??[]).some(r=>r.toLowerCase()===t.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${t}" for namespace "${e}"`)}return!1},getTransactionsCache(){try{const t=Z.getItem(te.HISTORY_TRANSACTIONS_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:t,chainId:e=""}){var s;try{const r=(s=B.getTransactionsCache()[t])==null?void 0:s[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;B.removeTransactionsCache({address:t,chainId:e})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:t,chainId:e="",timestamp:s,transactions:n}){try{const r=B.getTransactionsCache();r[t]={...r[t],[e]:{timestamp:s,transactions:n}},Z.setItem(te.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(r))}catch{console.info("Unable to update transactions cache",{address:t,chainId:e,timestamp:s,transactions:n})}},removeTransactionsCache({address:t,chainId:e}){try{const s=B.getTransactionsCache(),n=(s==null?void 0:s[t])||{},{[e]:r,...i}=n;Z.setItem(te.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...s,[t]:i}))}catch{console.info("Unable to remove transactions cache",{address:t,chainId:e})}},getTokenPriceCache(){try{const t=Z.getItem(te.TOKEN_PRICE_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(t){try{const s=B.getTokenPriceCache()[t.join(",")];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.tokenPrice))return s.tokenPrice;B.removeTokenPriceCache(t)}catch{console.info("Unable to get token price cache for addresses",t)}},updateTokenPriceCache(t){try{const e=B.getTokenPriceCache();e[t.addresses.join(",")]={timestamp:t.timestamp,tokenPrice:t.tokenPrice},Z.setItem(te.TOKEN_PRICE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update token price cache",t)}},removeTokenPriceCache(t){try{const e=B.getTokenPriceCache();Z.setItem(te.TOKEN_PRICE_CACHE,JSON.stringify({...e,[t.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",t)}},getLatestAppKitVersion(){try{const t=this.getLatestAppKitVersionCache(),e=t==null?void 0:t.version;return e&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.latestAppKitVersion)?e:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const t=Z.getItem(te.LATEST_APPKIT_VERSION);return t?JSON.parse(t):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(t){try{const e=B.getLatestAppKitVersionCache();e.timestamp=t.timestamp,e.version=t.version,Z.setItem(te.LATEST_APPKIT_VERSION,JSON.stringify(e))}catch{console.info("Unable to update latest AppKit version on local storage",t)}}},J={isMobile(){var t;return this.isClient()?!!(window!=null&&window.matchMedia&&typeof window.matchMedia=="function"&&((t=window.matchMedia("(pointer:coarse)"))!=null&&t.matches)||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t==null?void 0:t.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return J.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window==null?void 0:window.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=ye.TEN_SEC_MS:!0},isAllowedRetry(t,e=ye.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return(window==null?void 0:window.self)!==(window==null?void 0:window.top)}catch{return!1}},isSafeApp(){var t,e;if(J.isClient()&&window.self!==window.top)try{const s=(e=(t=window==null?void 0:window.location)==null?void 0:t.ancestorOrigins)==null?void 0:e[0],n="https://app.safe.global";if(s){const r=new URL(s),i=new URL(n);return r.hostname===i.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+ye.FOUR_MINUTES_MS},getNetworkId(t){return t==null?void 0:t.split(":")[1]},getPlainAddress(t){return t==null?void 0:t.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let s;return(...n)=>{function r(){t(...n)}s&&clearTimeout(s),s=setTimeout(r,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(J.isHttpUrl(t))return this.formatUniversalUrl(t,e);let n=t,r=s;n.includes("://")||(n=t.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),r&&!(r!=null&&r.endsWith("/"))&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${n}wc?uri=${i}`,redirectUniversalLink:r?`${r}wc?uri=${i}`:void 0,href:n}},formatUniversalUrl(t,e){if(!J.isHttpUrl(t))return this.formatNativeUrl(t,e);let s=t;s.endsWith("/")||(s=`${s}/`);const n=encodeURIComponent(e);return{redirect:`${s}wc?uri=${n}`,href:s}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?B.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window==null||window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window==null?void 0:window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){var s,n;if(typeof window>"u")return!1;const t=window!=null&&window.matchMedia&&typeof window.matchMedia=="function"?(s=window.matchMedia("(display-mode: standalone)"))==null?void 0:s.matches:!1,e=(n=window==null?void 0:window.navigator)==null?void 0:n.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,n)=>{const r=new Image;r.onload=s,r.onerror=n,r.crossOrigin="anonymous",r.src=t});return Promise.race([e,J.wait(2e3)])},parseBalance(t,e){let s="0.000";if(typeof t=="string"){const c=Number(t);if(!isNaN(c)){const l=(Math.floor(c*1e3)/1e3).toFixed(3);l&&(s=l)}}const[n,r]=s.split("."),i=n||"0",o=r||"000";return{formattedText:`${i}.${o}${e?` ${e}`:""}`,value:i,decimals:o,symbol:e}},getApiUrl(){return U.W3M_API_URL},getBlockchainApiUrl(){return U.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return U.PULSE_API_URL},getUUID(){return crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){var e,s;return typeof t=="string"?t:typeof((s=(e=t==null?void 0:t.issues)==null?void 0:e[0])==null?void 0:s.message)=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const s={};return e&&t&&(t.forEach((n,r)=>{s[n]=r}),e.sort((n,r)=>{const i=s[n.id],o=s[r.id];return i!==void 0&&o!==void 0?i-o:i!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const s of t)e+=s.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[s,n]=e.split(".");return{dollars:s,pennies:n}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const s=new Set;return t.filter(n=>{const r=n[e];return s.has(r)?!1:(s.add(r),!0)})},generateSdkVersion(t,e,s){const r=t.length===0?ye.ADAPTER_TYPES.UNIVERSAL:t.map(i=>i.adapterType).join(",");return`${e}-${r}-${s}`},createAccount(t,e,s,n,r){return{namespace:t,address:e,type:s,publicKey:n,path:r}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),s=e[0];return e.filter(Boolean).length===3&&s in U.CHAIN_NAME_MAP},getAccount(t){return t?typeof t=="string"?{address:t,chainId:void 0}:{address:t.address,chainId:t.chainId}:{address:void 0,chainId:void 0}},isMac(){const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window==null?void 0:window.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const r="provider_authorization_url=",i=t.substring(t.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(i),s,e);return t.replace(i,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const n=t.indexOf(e);if(n===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const r=t.indexOf("&",n),i=e.length,o=r!==-1?r:t.length,a=t.substring(0,n+i),c=t.substring(n+i,o),l=t.substring(r),d=c+s;return a+d+l}},yn={APP_EVENT_KEY:"@w3m-app/",FRAME_EVENT_KEY:"@w3m-frame/",RPC_METHOD_KEY:"RPC_",STORAGE_KEY:"@appkit-wallet/",SESSION_TOKEN_KEY:"SESSION_TOKEN_KEY",EMAIL_LOGIN_USED_KEY:"EMAIL_LOGIN_USED_KEY",LAST_USED_CHAIN_KEY:"LAST_USED_CHAIN_KEY",LAST_EMAIL_LOGIN_TIME:"LAST_EMAIL_LOGIN_TIME",EMAIL:"EMAIL",PREFERRED_ACCOUNT_TYPE:"PREFERRED_ACCOUNT_TYPE",SMART_ACCOUNT_ENABLED:"SMART_ACCOUNT_ENABLED",SMART_ACCOUNT_ENABLED_NETWORKS:"SMART_ACCOUNT_ENABLED_NETWORKS",SOCIAL_USERNAME:"SOCIAL_USERNAME",APP_SWITCH_NETWORK:"@w3m-app/SWITCH_NETWORK",APP_CONNECT_EMAIL:"@w3m-app/CONNECT_EMAIL",APP_CONNECT_DEVICE:"@w3m-app/CONNECT_DEVICE",APP_CONNECT_OTP:"@w3m-app/CONNECT_OTP",APP_CONNECT_SOCIAL:"@w3m-app/CONNECT_SOCIAL",APP_GET_SOCIAL_REDIRECT_URI:"@w3m-app/GET_SOCIAL_REDIRECT_URI",APP_GET_USER:"@w3m-app/GET_USER",APP_SIGN_OUT:"@w3m-app/SIGN_OUT",APP_IS_CONNECTED:"@w3m-app/IS_CONNECTED",APP_GET_CHAIN_ID:"@w3m-app/GET_CHAIN_ID",APP_RPC_REQUEST:"@w3m-app/RPC_REQUEST",APP_UPDATE_EMAIL:"@w3m-app/UPDATE_EMAIL",APP_UPDATE_EMAIL_PRIMARY_OTP:"@w3m-app/UPDATE_EMAIL_PRIMARY_OTP",APP_UPDATE_EMAIL_SECONDARY_OTP:"@w3m-app/UPDATE_EMAIL_SECONDARY_OTP",APP_AWAIT_UPDATE_EMAIL:"@w3m-app/AWAIT_UPDATE_EMAIL",APP_SYNC_THEME:"@w3m-app/SYNC_THEME",APP_SYNC_DAPP_DATA:"@w3m-app/SYNC_DAPP_DATA",APP_GET_SMART_ACCOUNT_ENABLED_NETWORKS:"@w3m-app/GET_SMART_ACCOUNT_ENABLED_NETWORKS",APP_INIT_SMART_ACCOUNT:"@w3m-app/INIT_SMART_ACCOUNT",APP_SET_PREFERRED_ACCOUNT:"@w3m-app/SET_PREFERRED_ACCOUNT",APP_CONNECT_FARCASTER:"@w3m-app/CONNECT_FARCASTER",APP_GET_FARCASTER_URI:"@w3m-app/GET_FARCASTER_URI",APP_RELOAD:"@w3m-app/RELOAD",APP_RPC_ABORT:"@w3m-app/RPC_ABORT",FRAME_SWITCH_NETWORK_ERROR:"@w3m-frame/SWITCH_NETWORK_ERROR",FRAME_SWITCH_NETWORK_SUCCESS:"@w3m-frame/SWITCH_NETWORK_SUCCESS",FRAME_CONNECT_EMAIL_ERROR:"@w3m-frame/CONNECT_EMAIL_ERROR",FRAME_CONNECT_EMAIL_SUCCESS:"@w3m-frame/CONNECT_EMAIL_SUCCESS",FRAME_CONNECT_DEVICE_ERROR:"@w3m-frame/CONNECT_DEVICE_ERROR",FRAME_CONNECT_DEVICE_SUCCESS:"@w3m-frame/CONNECT_DEVICE_SUCCESS",FRAME_CONNECT_OTP_SUCCESS:"@w3m-frame/CONNECT_OTP_SUCCESS",FRAME_CONNECT_OTP_ERROR:"@w3m-frame/CONNECT_OTP_ERROR",FRAME_CONNECT_SOCIAL_SUCCESS:"@w3m-frame/CONNECT_SOCIAL_SUCCESS",FRAME_CONNECT_SOCIAL_ERROR:"@w3m-frame/CONNECT_SOCIAL_ERROR",FRAME_CONNECT_FARCASTER_SUCCESS:"@w3m-frame/CONNECT_FARCASTER_SUCCESS",FRAME_CONNECT_FARCASTER_ERROR:"@w3m-frame/CONNECT_FARCASTER_ERROR",FRAME_GET_FARCASTER_URI_SUCCESS:"@w3m-frame/GET_FARCASTER_URI_SUCCESS",FRAME_GET_FARCASTER_URI_ERROR:"@w3m-frame/GET_FARCASTER_URI_ERROR",FRAME_GET_SOCIAL_REDIRECT_URI_SUCCESS:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_SUCCESS",FRAME_GET_SOCIAL_REDIRECT_URI_ERROR:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_ERROR",FRAME_GET_USER_SUCCESS:"@w3m-frame/GET_USER_SUCCESS",FRAME_GET_USER_ERROR:"@w3m-frame/GET_USER_ERROR",FRAME_SIGN_OUT_SUCCESS:"@w3m-frame/SIGN_OUT_SUCCESS",FRAME_SIGN_OUT_ERROR:"@w3m-frame/SIGN_OUT_ERROR",FRAME_IS_CONNECTED_SUCCESS:"@w3m-frame/IS_CONNECTED_SUCCESS",FRAME_IS_CONNECTED_ERROR:"@w3m-frame/IS_CONNECTED_ERROR",FRAME_GET_CHAIN_ID_SUCCESS:"@w3m-frame/GET_CHAIN_ID_SUCCESS",FRAME_GET_CHAIN_ID_ERROR:"@w3m-frame/GET_CHAIN_ID_ERROR",FRAME_RPC_REQUEST_SUCCESS:"@w3m-frame/RPC_REQUEST_SUCCESS",FRAME_RPC_REQUEST_ERROR:"@w3m-frame/RPC_REQUEST_ERROR",FRAME_SESSION_UPDATE:"@w3m-frame/SESSION_UPDATE",FRAME_UPDATE_EMAIL_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SUCCESS",FRAME_UPDATE_EMAIL_ERROR:"@w3m-frame/UPDATE_EMAIL_ERROR",FRAME_UPDATE_EMAIL_PRIMARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_PRIMARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_ERROR",FRAME_UPDATE_EMAIL_SECONDARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_SECONDARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_ERROR",FRAME_SYNC_THEME_SUCCESS:"@w3m-frame/SYNC_THEME_SUCCESS",FRAME_SYNC_THEME_ERROR:"@w3m-frame/SYNC_THEME_ERROR",FRAME_SYNC_DAPP_DATA_SUCCESS:"@w3m-frame/SYNC_DAPP_DATA_SUCCESS",FRAME_SYNC_DAPP_DATA_ERROR:"@w3m-frame/SYNC_DAPP_DATA_ERROR",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR",FRAME_INIT_SMART_ACCOUNT_SUCCESS:"@w3m-frame/INIT_SMART_ACCOUNT_SUCCESS",FRAME_INIT_SMART_ACCOUNT_ERROR:"@w3m-frame/INIT_SMART_ACCOUNT_ERROR",FRAME_SET_PREFERRED_ACCOUNT_SUCCESS:"@w3m-frame/SET_PREFERRED_ACCOUNT_SUCCESS",FRAME_SET_PREFERRED_ACCOUNT_ERROR:"@w3m-frame/SET_PREFERRED_ACCOUNT_ERROR",FRAME_READY:"@w3m-frame/READY",FRAME_RELOAD_SUCCESS:"@w3m-frame/RELOAD_SUCCESS",FRAME_RELOAD_ERROR:"@w3m-frame/RELOAD_ERROR",FRAME_RPC_ABORT_SUCCESS:"@w3m-frame/RPC_ABORT_SUCCESS",FRAME_RPC_ABORT_ERROR:"@w3m-frame/RPC_ABORT_ERROR",RPC_RESPONSE_TYPE_ERROR:"RPC_RESPONSE_ERROR",RPC_RESPONSE_TYPE_TX:"RPC_RESPONSE_TRANSACTION_HASH",RPC_RESPONSE_TYPE_OBJECT:"RPC_RESPONSE_OBJECT"},Qt={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},Xl={address:/^0x(?:[A-Fa-f0-9]{40})$/u,transactionHash:/^0x(?:[A-Fa-f0-9]{64})$/u,signedMessage:/^0x(?:[a-fA-F0-9]{62,})$/u},fc={set(t,e){ga.isClient&&localStorage.setItem(`${yn.STORAGE_KEY}${t}`,e)},get(t){return ga.isClient?localStorage.getItem(`${yn.STORAGE_KEY}${t}`):null},delete(t,e){ga.isClient&&(e?localStorage.removeItem(t):localStorage.removeItem(`${yn.STORAGE_KEY}${t}`))}},Hi=30*1e3,ga={checkIfAllowedToTriggerEmail(){const t=fc.get(yn.LAST_EMAIL_LOGIN_TIME);if(t){const e=Date.now()-Number(t);if(e<Hi){const s=Math.ceil((Hi-e)/1e3);throw new Error(`Please try again after ${s} seconds`)}}},getTimeToNextEmailLogin(){const t=fc.get(yn.LAST_EMAIL_LOGIN_TIME);if(t){const e=Date.now()-Number(t);if(e<Hi)return Math.ceil((Hi-e)/1e3)}return 0},checkIfRequestExists(t){return Qt.NOT_SAFE_RPC_METHODS.includes(t.method)||Qt.SAFE_RPC_METHODS.includes(t.method)},getResponseType(t){return typeof t=="string"&&((t==null?void 0:t.match(Xl.transactionHash))||(t==null?void 0:t.match(Xl.signedMessage)))?yn.RPC_RESPONSE_TYPE_TX:yn.RPC_RESPONSE_TYPE_OBJECT},checkIfRequestIsSafe(t){return Qt.SAFE_RPC_METHODS.includes(t.method)},isClient:typeof window<"u"};var ut=Xg();const Tm=Bh(ut),Om=Zg({__proto__:null,default:Tm},[ut]);async function Hr(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class xi{constructor({baseUrl:e,clientId:s}){this.baseUrl=e,this.clientId=s}async get({headers:e,signal:s,cache:n,...r}){const i=this.createUrl(r);return(await Hr(i,{method:"GET",headers:e,signal:s,cache:n})).json()}async getBlob({headers:e,signal:s,...n}){const r=this.createUrl(n);return(await Hr(r,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await Hr(i,{method:"POST",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}async put({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await Hr(i,{method:"PUT",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}async delete({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await Hr(i,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}createUrl({path:e,params:s}){const n=new URL(e,this.baseUrl);return s&&Object.entries(s).forEach(([r,i])=>{i&&n.searchParams.append(r,i)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}sendBeacon({body:e,...s}){const n=this.createUrl(s);return navigator.sendBeacon(n.toString(),e?JSON.stringify(e):void 0)}}const gc={getFeatureValue(t,e){const s=e==null?void 0:e[t];return s===void 0?ye.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;let e=t;return J.isTelegram()&&(J.isIos()&&(e=e.filter(s=>s!=="google")),J.isMac()&&(e=e.filter(s=>s!=="x")),J.isAndroid()&&(e=e.filter(s=>!["facebook","x"].includes(s)))),J.isMobile()&&(e=e.filter(s=>s!=="facebook")),e},isSocialsEnabled(){var t,e,s,n;return Array.isArray((t=k.state.features)==null?void 0:t.socials)&&((e=k.state.features)==null?void 0:e.socials.length)>0||Array.isArray((s=k.state.remoteFeatures)==null?void 0:s.socials)&&((n=k.state.remoteFeatures)==null?void 0:n.socials.length)>0},isEmailEnabled(){var t,e;return!!((t=k.state.features)!=null&&t.email||(e=k.state.remoteFeatures)!=null&&e.email)}},ee=ke({features:ye.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:ye.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1,coinbasePreference:"all"}),k={state:ee,subscribeKey(t,e){return nt(ee,t,e)},setOptions(t){Object.assign(ee,t)},setRemoteFeatures(t){var s,n;if(!t)return;const e={...ee.remoteFeatures,...t};ee.remoteFeatures=e,(s=ee.remoteFeatures)!=null&&s.socials&&(ee.remoteFeatures.socials=gc.filterSocialsByPlatform(ee.remoteFeatures.socials)),(n=ee.features)!=null&&n.pay&&(ee.remoteFeatures.email=!1,ee.remoteFeatures.socials=!1)},setFeatures(t){var s;if(!t)return;ee.features||(ee.features=ye.DEFAULT_FEATURES);const e={...ee.features,...t};ee.features=e,(s=ee.features)!=null&&s.pay&&ee.remoteFeatures&&(ee.remoteFeatures.email=!1,ee.remoteFeatures.socials=!1)},setProjectId(t){ee.projectId=t},setCustomRpcUrls(t){ee.customRpcUrls=t},setAllWallets(t){ee.allWallets=t},setIncludeWalletIds(t){ee.includeWalletIds=t},setExcludeWalletIds(t){ee.excludeWalletIds=t},setFeaturedWalletIds(t){ee.featuredWalletIds=t},setTokens(t){ee.tokens=t},setTermsConditionsUrl(t){ee.termsConditionsUrl=t},setPrivacyPolicyUrl(t){ee.privacyPolicyUrl=t},setCustomWallets(t){ee.customWallets=t},setIsSiweEnabled(t){ee.isSiweEnabled=t},setIsUniversalProvider(t){ee.isUniversalProvider=t},setSdkVersion(t){ee.sdkVersion=t},setMetadata(t){ee.metadata=t},setDisableAppend(t){ee.disableAppend=t},setEIP6963Enabled(t){ee.enableEIP6963=t},setDebug(t){ee.debug=t},setEnableWalletGuide(t){ee.enableWalletGuide=t},setEnableAuthLogger(t){ee.enableAuthLogger=t},setEnableWallets(t){ee.enableWallets=t},setPreferUniversalLinks(t){ee.experimental_preferUniversalLinks=t},setSIWX(t){if(t)for(const[e,s]of Object.entries(ye.SIWX_DEFAULTS))t[e]??(t[e]=s);ee.siwx=t},setConnectMethodsOrder(t){ee.features={...ee.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){ee.features={...ee.features,walletFeaturesOrder:t}},setSocialsOrder(t){ee.remoteFeatures={...ee.remoteFeatures,socials:t}},setCollapseWallets(t){ee.features={...ee.features,collapseWallets:t}},setEnableEmbedded(t){ee.enableEmbedded=t},setAllowUnsupportedChain(t){ee.allowUnsupportedChain=t},setManualWCControl(t){ee.manualWCControl=t},setEnableNetworkSwitch(t){ee.enableNetworkSwitch=t},setEnableMobileFullScreen(t){ee.enableMobileFullScreen=J.isMobile()&&t},setEnableReconnect(t){ee.enableReconnect=t},setCoinbasePreference(t){ee.coinbasePreference=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(ee.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){ee.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return ee.universalProviderConfigOverride},getSnapshot(){return wi(ee)}},Dn=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),He=ke({...Dn}),Rm={state:He,subscribeKey(t,e){return nt(He,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=J.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){He.message=Dn.message,He.variant=Dn.variant,He.svg=Dn.svg,He.open=Dn.open,He.autoClose=Dn.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:n=Dn.autoClose}){He.open?(He.open=!1,setTimeout(()=>{He.message=t,He.variant=s,He.svg=e,He.open=!0,He.autoClose=n},150)):(He.message=t,He.variant=s,He.svg=e,He.open=!0,He.autoClose=n)}},vs=Rm,Pm={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},Yh=J.getBlockchainApiUrl(),bt=ke({clientId:null,api:new xi({baseUrl:Yh,clientId:null}),supportedChains:{http:[],ws:[]}}),re={state:bt,async get(t){const{st:e,sv:s}=re.getSdkProperties(),n=k.state.projectId,r={...t.params||{},st:e,sv:s,projectId:n};return bt.api.get({...t,params:r})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=k.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{bt.supportedChains.http.length||await re.getSupportedNetworks()}catch{return!1}return bt.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await re.get({path:"v1/supported-chains"});return bt.supportedChains=t,t}catch{return bt.supportedChains}},async fetchIdentity({address:t}){const e=B.getIdentityFromCacheForAddress(t);if(e)return e;const s=await re.get({path:`/v1/identity/${t}`,params:{sender:m.state.activeCaipAddress?J.getPlainAddress(m.state.activeCaipAddress):void 0}});return B.updateIdentityCache({address:t,identity:s,timestamp:Date.now()}),s},async fetchTransactions({account:t,cursor:e,signal:s,cache:n,chainId:r}){var c;if(!await re.isNetworkSupported((c=m.state.activeCaipNetwork)==null?void 0:c.caipNetworkId))return{data:[],next:void 0};const o=B.getTransactionsCacheForAddress({address:t,chainId:r});if(o)return o;const a=await re.get({path:`/v1/account/${t}/history`,params:{cursor:e,chainId:r},signal:s,cache:n});return B.updateTransactionsCache({address:t,chainId:r,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:n,gasPrice:r}){var o;return await re.isNetworkSupported((o=m.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?re.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:s,to:n,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){var s;return await re.isNetworkSupported((s=m.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?re.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){var r;if(!await re.isNetworkSupported((r=m.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))return{fungibles:[]};const s=B.getTokenPriceCacheForAddresses(t);if(s)return s;const n=await bt.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:k.state.projectId},headers:{"Content-Type":"application/json"}});return B.updateTokenPriceCache({addresses:t,timestamp:Date.now(),tokenPrice:n}),n},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){var n;return await re.isNetworkSupported((n=m.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?re.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){var r;const{st:e,sv:s}=re.getSdkProperties();if(!await re.isNetworkSupported((r=m.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))throw new Error("Network not supported for Gas Price");return re.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:s}})},async generateSwapCalldata({amount:t,from:e,to:s,userAddress:n,disableEstimate:r}){var o;if(!await re.isNetworkSupported((o=m.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return bt.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:ye.CONVERT_SLIPPAGE_TOLERANCE},projectId:k.state.projectId,from:e,to:s,userAddress:n,disableEstimate:r}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){var o;const{st:n,sv:r}=re.getSdkProperties();if(!await re.isNetworkSupported((o=m.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return re.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:t,to:e,st:n,sv:r}})},async getBalance(t,e,s){var l;const{st:n,sv:r}=re.getSdkProperties();if(!await re.isNetworkSupported((l=m.state.activeCaipNetwork)==null?void 0:l.caipNetworkId))return vs.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=B.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await re.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:n,sv:r}});return B.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){var s;return await re.isNetworkSupported((s=m.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?re.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){var n,r;if(!await re.isNetworkSupported((n=m.state.activeCaipNetwork)==null?void 0:n.caipNetworkId))return[];const s=(r=m.getAccountData())==null?void 0:r.address;return re.get({path:`/v1/profile/reverse/${t}`,params:{sender:s,apiVersion:"2"}})},async getEnsNameSuggestions(t){var s;return await re.isNetworkSupported((s=m.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?re.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:n}){var i;return await re.isNetworkSupported((i=m.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?bt.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:s,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:s,purchaseAmount:n,paymentAmount:r}){var a;return await re.isNetworkSupported((a=m.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await bt.api.post({path:"/v1/generators/onrampurl",params:{projectId:k.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:r}})).url:""},async getOnrampOptions(){var e;if(!await re.isNetworkSupported((e=m.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await re.get({path:"/v1/onramp/options"})}catch{return Pm}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}){var r;try{return await re.isNetworkSupported((r=m.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?await bt.api.post({path:"/v1/onramp/quote",params:{projectId:k.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}}):null}catch{return{networkFee:{amount:s,currency:e.id},paymentSubtotal:{amount:s,currency:e.id},paymentTotal:{amount:s,currency:e.id},purchaseAmount:{amount:s,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){var s;return await re.isNetworkSupported((s=m.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?re.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){var r;return await re.isNetworkSupported((r=m.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?bt.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:k.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){bt.clientId=t,bt.api=new xi({baseUrl:Yh,clientId:t})}},Gt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"},BINANCE:{id:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25",appId:"yFK5FCqYprrXDiVFbhyRx7",deeplink:"bnc://app.binance.com/mp/app",url:"https://app.binance.com/en/download"}},xm={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,n=encodeURIComponent(s);if(t===Gt.PHANTOM.id&&!("phantom"in window)){const r=s.startsWith("https")?"https":"http",i=s.split("/")[2],o=encodeURIComponent(`${r}://${i}`);window.location.href=`${Gt.PHANTOM.url}/ul/browse/${n}?ref=${o}`}if(t===Gt.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Gt.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),e===U.CHAIN.SOLANA&&t===Gt.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Gt.COINBASE.url}/dapp?cb_url=${n}`),e===U.CHAIN.BITCOIN&&t===Gt.BINANCE.id&&!("binancew3w"in window)){const r=m.state.activeCaipNetwork,i=window.btoa("/pages/browser/index"),o=window.btoa(`url=${n}&defaultChainId=${(r==null?void 0:r.id)??1}`),a=new URL(Gt.BINANCE.deeplink);a.searchParams.set("appId",Gt.BINANCE.appId),a.searchParams.set("startPagePath",i),a.searchParams.set("startPageQuery",o);const c=new URL(Gt.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}},km=Object.freeze({enabled:!0,events:[]}),$m=new xi({baseUrl:J.getAnalyticsUrl(),clientId:null}),Um=5,Dm=60*1e3,Qs=ke({...km}),Lm={state:Qs,subscribeKey(t,e){return nt(Qs,t,e)},async sendError(t,e){if(!Qs.enabled)return;const s=Date.now();if(Qs.events.filter(i=>{const o=new Date(i.properties.timestamp||"").getTime();return s-o<Dm}).length>=Um)return;const r={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Qs.events.push(r);try{if(typeof window>"u")return;const{projectId:i,sdkType:o,sdkVersion:a}=k.state;await $m.post({path:"/e",params:{projectId:i,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:J.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){Qs.enabled=!0},disable(){Qs.enabled=!1},clearEvents(){Qs.events=[]}};class Qn extends Error{constructor(e,s,n){super(e),this.originalName="AppKitError",this.name="AppKitError",this.category=s,this.originalError=n,n&&n instanceof Error&&(this.originalName=n.name),Object.setPrototypeOf(this,Qn.prototype);let r=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){const i=n.stack,o=i.indexOf(`
|
|
4
4
|
`);if(o>-1){const a=i.substring(o+1);this.stack=`${this.name}: ${this.message}
|
|
5
5
|
${a}`,r=!0}}r||(Error.captureStackTrace?Error.captureStackTrace(this,Qn):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Zl(t,e){let s="";try{t instanceof Error?s=t.message:typeof t=="string"?s=t:typeof t=="object"&&t!==null?Object.keys(t).length===0?s="Unknown error":s=(t==null?void 0:t.message)||JSON.stringify(t):s=String(t)}catch(r){s="Unknown error",console.error("Error parsing error message",r)}const n=t instanceof Qn?t:new Qn(s,e,t);throw Lm.sendError(n,n.category),n}function ns(t,e="INTERNAL_SDK_ERROR"){const s={};return Object.keys(t).forEach(n=>{const r=t[n];if(typeof r=="function"){let i=r;r.constructor.name==="AsyncFunction"?i=async(...o)=>{try{return await r(...o)}catch(a){return Zl(a,e)}}:i=(...o)=>{try{return r(...o)}catch(a){return Zl(a,e)}},s[n]=i}else s[n]=r}),s}const xt=ke({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Bm={state:xt,subscribeNetworkImages(t){return st(xt.networkImages,()=>t(xt.networkImages))},subscribeKey(t,e){return nt(xt,t,e)},subscribe(t){return st(xt,()=>t(xt))},setWalletImage(t,e){xt.walletImages[t]=e},setNetworkImage(t,e){xt.networkImages[t]=e},setChainImage(t,e){xt.chainImages[t]=e},setConnectorImage(t,e){xt.connectorImages={...xt.connectorImages,[t]:e}},setTokenImage(t,e){xt.tokenImages[t]=e},setCurrencyImage(t,e){xt.currencyImages[t]=e}},Zt=ns(Bm),Mm={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:""},ma=ke({networkImagePromises:{}}),Jh={async fetchWalletImage(t){if(t)return await Q._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(ma.networkImagePromises[t]||(ma.networkImagePromises[t]=Q._fetchNetworkImage(t)),await ma.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return Zt.state.walletImages[t]},getWalletImage(t){if(t!=null&&t.image_url)return t==null?void 0:t.image_url;if(t!=null&&t.image_id)return Zt.state.walletImages[t.image_id]},getNetworkImage(t){var e,s,n;if((e=t==null?void 0:t.assets)!=null&&e.imageUrl)return(s=t==null?void 0:t.assets)==null?void 0:s.imageUrl;if((n=t==null?void 0:t.assets)!=null&&n.imageId)return Zt.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return Zt.state.networkImages[t]},getConnectorImage(t){var e;if(t!=null&&t.imageUrl)return t.imageUrl;if((e=t==null?void 0:t.info)!=null&&e.icon)return t.info.icon;if(t!=null&&t.imageId)return Zt.state.connectorImages[t.imageId]},getChainImage(t){return Zt.state.networkImages[Mm[t]]},getTokenImage(t){if(t)return Zt.state.tokenImages[t]}},Fm=J.getAnalyticsUrl(),jm=new xi({baseUrl:Fm,clientId:null}),qm=["MODAL_CREATED"],Wm=45,Ql=1e3*10,Be=ke({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),he={state:Be,subscribe(t){return st(Be,()=>t(Be))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=k.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},shouldFlushEvents(){const t=JSON.stringify(Be.pendingEvents).length/1024>Wm,e=Be.lastFlush+Ql<Date.now();return t||e},_setPendingEvent(t){var e,s;try{let n=(e=m.getAccountData())==null?void 0:e.address;if("address"in t.data&&t.data.address&&(n=t.data.address),qm.includes(t.data.event)||typeof window>"u")return;const r=(s=m.getActiveCaipNetwork())==null?void 0:s.caipNetworkId;this.state.pendingEvents.push({eventId:J.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:n,properties:{..."properties"in t.data?t.data.properties:{},caipNetworkId:r}}}),Be.reportedErrors.FORBIDDEN=!1,he.shouldFlushEvents()&&he._submitPendingEvents()}catch(n){console.warn("_setPendingEvent",n)}},sendEvent(t){var s;Be.timestamp=Date.now(),Be.data=t;const e=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];((s=k.state.features)!=null&&s.analytics||e.includes(t.event))&&he._setPendingEvent(Be),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(t){Be.walletImpressions.push(t)},_transformPendingEventsForBatch(t){try{return t.filter(e=>e.props.event!=="WALLET_IMPRESSION_V2")}catch{return t}},_submitPendingEvents(){if(Be.lastFlush=Date.now(),!(Be.pendingEvents.length===0&&Be.walletImpressions.length===0))try{const t=he._transformPendingEventsForBatch(Be.pendingEvents);Be.walletImpressions.length&&t.push({eventId:J.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION_V2",items:[...Be.walletImpressions]}}),jm.sendBeacon({path:"/batch",params:he.getSdkProperties(),body:t}),Be.reportedErrors.FORBIDDEN=!1,Be.pendingEvents=[],Be.walletImpressions=[]}catch{Be.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){var t,e,s;Be.subscribedToVisibilityChange||typeof document>"u"||(Be.subscribedToVisibilityChange=!0,(t=document==null?void 0:document.addEventListener)==null||t.call(document,"visibilitychange",()=>{document.visibilityState==="hidden"&&he._submitPendingEvents()}),(e=document==null?void 0:document.addEventListener)==null||e.call(document,"freeze",()=>{he._submitPendingEvents()}),(s=window==null?void 0:window.addEventListener)==null||s.call(window,"pagehide",()=>{he._submitPendingEvents()}),setInterval(()=>{he._submitPendingEvents()},Ql))}},Hm=J.getApiUrl(),ft=new xi({baseUrl:Hm,clientId:null}),Km=40,ed=4,zm=20,oe=ke({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1,explorerWallets:[],explorerFilteredWallets:[],plan:{tier:"none",hasExceededUsageLimit:!1,limits:{isAboveRpcLimit:!1,isAboveMauLimit:!1}}}),Q={state:oe,subscribeKey(t,e){return nt(oe,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=k.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return k.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${ft.baseUrl}/getWalletImage/${t}`,s=await ft.getBlob({path:e,params:Q._getSdkProperties()});Zt.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${ft.baseUrl}/public/getAssetImage/${t}`,s=await ft.getBlob({path:e,params:Q._getSdkProperties()});Zt.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${ft.baseUrl}/public/getAssetImage/${t}`,s=await ft.getBlob({path:e,params:Q._getSdkProperties()});Zt.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${ft.baseUrl}/public/getCurrencyImage/${t}`,s=await ft.getBlob({path:e,params:Q._getSdkProperties()});Zt.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${ft.baseUrl}/public/getTokenImage/${t}`,s=await ft.getBlob({path:e,params:Q._getSdkProperties()});Zt.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){const e=t.length,s=J.isMobile()?t==null?void 0:t.filter(r=>r.mobile_link||r.webapp_link?!0:Object.values(Gt).map(o=>o.id).includes(r.id)):t,n=e-s.length;return{filteredWallets:s,mobileFilteredOutWalletsLength:n}},async fetchProjectConfig(){return(await ft.get({path:"/appkit/v1/config",params:Q._getSdkProperties()})).features},async fetchUsage(){try{const t=await ft.get({path:"/appkit/v1/project-limits",params:Q._getSdkProperties()}),{tier:e,isAboveMauLimit:s,isAboveRpcLimit:n}=t.planLimits,r=e==="starter",i=s||n;Q.state.plan={tier:e,hasExceededUsageLimit:r&&i,limits:{isAboveRpcLimit:n,isAboveMauLimit:s}}}catch(t){console.warn("Failed to fetch usage",t)}},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await ft.get({path:"/projects/v1/origins",params:Q._getSdkProperties()});return t}catch(t){if(t instanceof Error&&t.cause instanceof Response){const e=t.cause.status;if(e===U.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:t});if(e>=U.HTTP_STATUS_CODES.SERVER_ERROR&&e<600)throw new Error("SERVER_ERROR",{cause:t});return[]}return[]}},async fetchNetworkImages(){const t=m.getAllRequestedCaipNetworks(),e=t==null?void 0:t.map(({assets:s})=>s==null?void 0:s.imageId).filter(Boolean).filter(s=>!Jh.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>Q._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=q.state,e=t.map(({imageId:s})=>s).filter(Boolean);await Promise.allSettled(e.map(s=>Q._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>Q._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>Q._fetchTokenImage(e)))},async fetchWallets(t){var o;const e=t.exclude??[];Q._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Gt).map(a=>a.id));const n=await ft.get({path:"/getWallets",params:{...Q._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:(o=t.include)==null?void 0:o.join(","),exclude:e.join(",")}}),{filteredWallets:r,mobileFilteredOutWalletsLength:i}=Q._filterWalletsByPlatform(n==null?void 0:n.data);return{data:r||[],count:n==null?void 0:n.count,mobileFilteredOutWalletsLength:i}},async prefetchWalletRanks(){const t=q.state.connectors;if(!(t!=null&&t.length))return;const e={page:1,entries:20,badge:"certified"};if(e.names=t.map(r=>r.name).join(","),m.state.activeChain===U.CHAIN.EVM){const r=[...t.flatMap(i=>{var o;return((o=i.connectors)==null?void 0:o.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}))||[]}),...t.map(i=>{var o;return(o=i.info)==null?void 0:o.rdns})].filter(i=>typeof i=="string"&&i.length>0);r.length&&(e.rdns=r.join(","))}const{data:s}=await Q.fetchWallets(e);oe.explorerWallets=s;const n=m.getRequestedCaipNetworkIds().join(",");oe.explorerFilteredWallets=s.filter(r=>{var i;return(i=r.chains)==null?void 0:i.some(o=>n.includes(o))})},async fetchFeaturedWallets(){const{featuredWalletIds:t}=k.state;if(t!=null&&t.length){const e={...Q._getSdkProperties(),page:1,entries:(t==null?void 0:t.length)??ed,include:t},{data:s}=await Q.fetchWallets(e),n=[...s].sort((i,o)=>t.indexOf(i.id)-t.indexOf(o.id)),r=n.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(r.map(i=>Q._fetchWalletImage(i))),oe.featured=n,oe.allFeatured=n}},async fetchRecommendedWallets(){try{oe.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=k.state,n=[...e??[],...s??[]].filter(Boolean),r=m.getRequestedCaipNetworkIds().join(","),i={page:1,entries:ed,include:t,exclude:n,chains:r},{data:o,count:a}=await Q.fetchWallets(i),c=B.getRecentWallets(),l=o.map(u=>u.image_id).filter(Boolean),d=c.map(u=>u.image_id).filter(Boolean);await Promise.allSettled([...l,...d].map(u=>Q._fetchWalletImage(u))),oe.recommended=o,oe.allRecommended=o,oe.count=a??0}catch{}finally{oe.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:n}=k.state,r=m.getRequestedCaipNetworkIds().join(","),i=[...oe.recommended.map(({id:u})=>u),...s??[],...n??[]].filter(Boolean),o={page:t,entries:Km,include:e,exclude:i,chains:r},{data:a,count:c,mobileFilteredOutWalletsLength:l}=await Q.fetchWallets(o);oe.mobileFilteredOutWalletsLength=l+(oe.mobileFilteredOutWalletsLength??0);const d=a.slice(0,zm).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(d.map(u=>Q._fetchWalletImage(u))),oe.wallets=J.uniqueBy([...oe.wallets,...Q._filterOutExtensions(a)],"id").filter(u=>{var h;return(h=u.chains)==null?void 0:h.some(p=>r.includes(p))}),oe.count=c>oe.count?c:oe.count,oe.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await Q.fetchWallets(e);s&&s.forEach(n=>{oe.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:n}=k.state,r=m.getRequestedCaipNetworkIds().join(",");oe.search=[];const i={page:1,entries:100,search:t==null?void 0:t.trim(),badge_type:e,include:s,exclude:n,chains:r},{data:o}=await Q.fetchWallets(i);he.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:t??""}});const a=o.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>Q._fetchWalletImage(c)),J.wait(300)]),oe.search=Q._filterOutExtensions(o)},initPromise(t,e){const s=oe.promises[t];return s||(oe.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:n=!0,fetchWalletRanks:r=!0}={}){const i=[t&&Q.initPromise("connectorImages",Q.fetchConnectorImages),e&&Q.initPromise("featuredWallets",Q.fetchFeaturedWallets),s&&Q.initPromise("recommendedWallets",Q.fetchRecommendedWallets),n&&Q.initPromise("networkImages",Q.fetchNetworkImages),r&&Q.initPromise("walletRanks",Q.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){var t;(t=k.state.features)!=null&&t.analytics&&Q.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await ft.get({path:"/getAnalyticsConfig",params:Q._getSdkProperties()});k.setFeatures({analytics:t})}catch{k.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!(t!=null&&t.length)){oe.featured=oe.allFeatured,oe.recommended=oe.allRecommended;return}const e=m.getRequestedCaipNetworkIds().join(",");oe.featured=oe.allFeatured.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),oe.recommended=oe.allRecommended.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),oe.filteredWallets=oe.wallets.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))})},clearFilterByNamespaces(){oe.filteredWallets=[]},setFilterByNamespace(t){if(!t){oe.featured=oe.allFeatured,oe.recommended=oe.allRecommended;return}const e=m.getRequestedCaipNetworkIds().join(",");oe.featured=oe.allFeatured.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),oe.recommended=oe.allRecommended.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),oe.filteredWallets=oe.wallets.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))})}},Vm=["ConnectingExternal","ConnectingMultiChain","ConnectingSocial","ConnectingFarcaster"],_e=ke({view:"Connect",history:["Connect"],transactionStack:[]}),Gm={state:_e,subscribeKey(t,e){return nt(_e,t,e)},pushTransactionStack(t){_e.transactionStack.push(t)},popTransactionStack(t){const e=_e.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:n,onCancel:r}=e;switch(t){case"success":s==null||s();break;case"error":n==null||n(),ne.goBack();break;case"cancel":r==null||r(),ne.goBack();break}},push(t,e){let s=t,n=e;Q.state.plan.hasExceededUsageLimit&&Vm.includes(t)&&(s="UsageExceeded",n=void 0),s!==_e.view&&(_e.view=s,_e.history.push(s),_e.data=n)},reset(t,e){_e.view=t,_e.history=[t],_e.data=e},replace(t,e){_e.history.at(-1)===t||(_e.view=t,_e.history[_e.history.length-1]=t,_e.data=e)},goBack(){var n,r;const t=m.state.activeCaipAddress,e=ne.state.view==="ConnectingFarcaster",s=!t&&e;if(_e.history.length>1){_e.history.pop();const[i]=_e.history.slice(-1);i&&(t&&i==="Connect"?_e.view="Account":_e.view=i)}else pe.close();(n=_e.data)!=null&&n.wallet&&(_e.data.wallet=void 0),(r=_e.data)!=null&&r.redirectView&&(_e.data.redirectView=void 0),setTimeout(()=>{var i,o,a;if(s){m.setAccountProp("farcasterUrl",void 0,m.state.activeChain);const c=q.getAuthConnector();(i=c==null?void 0:c.provider)==null||i.reload();const l=wi(k.state);(a=(o=c==null?void 0:c.provider)==null?void 0:o.syncDappData)==null||a.call(o,{metadata:l.metadata,sdkVersion:l.sdkVersion,projectId:l.projectId,sdkType:l.sdkType})}},100)},goBackToIndex(t){if(_e.history.length>1){_e.history=_e.history.slice(0,t+1);const[e]=_e.history.slice(-1);e&&(_e.view=e)}},goBackOrCloseModal(){ne.state.history.length>1?ne.goBack():pe.close()}},ne=ns(Gm),Os=ke({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),mc={state:Os,subscribe(t){return st(Os,()=>t(Os))},setThemeMode(t){Os.themeMode=t;try{const e=q.getAuthConnector();if(e){const s=mc.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:Io(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){Os.themeVariables={...Os.themeVariables,...t};try{const e=q.getAuthConnector();if(e){const s=mc.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:Io(Os.themeVariables,Os.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return wi(Os)}},Dt=ns(mc),Xh=Object.fromEntries(Wh.map(t=>[t,void 0])),Ym=Object.fromEntries(Wh.map(t=>[t,!0])),Ce=ke({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:Xh,filterByNamespaceMap:Ym}),Jm={state:Ce,subscribe(t){return st(Ce,()=>{t(Ce)})},subscribeKey(t,e){return nt(Ce,t,e)},initialize(t){t.forEach(e=>{const s=B.getConnectedConnectorId(e);s&&q.setConnectorId(s,e)})},setActiveConnector(t){t&&(Ce.activeConnector=yi(t))},setConnectors(t){t.filter(r=>!Ce.allConnectors.some(i=>i.id===r.id&&q.getConnectorName(i.name)===q.getConnectorName(r.name)&&i.chain===r.chain)).forEach(r=>{r.type!=="MULTI_CHAIN"&&Ce.allConnectors.push(yi(r))});const s=q.getEnabledNamespaces(),n=q.getEnabledConnectors(s);Ce.connectors=q.mergeMultiChainConnectors(n)},filterByNamespaces(t){Object.keys(Ce.filterByNamespaceMap).forEach(e=>{Ce.filterByNamespaceMap[e]=!1}),t.forEach(e=>{Ce.filterByNamespaceMap[e]=!0}),q.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){Ce.filterByNamespaceMap[t]=e,q.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=q.getEnabledNamespaces(),e=q.getEnabledConnectors(t),s=q.areAllNamespacesEnabled();Ce.connectors=q.mergeMultiChainConnectors(e),s?Q.clearFilterByNamespaces():Q.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(Ce.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return Ce.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(Ce.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=q.generateConnectorMapByName(t),s=[];return e.forEach(n=>{const r=n[0],i=(r==null?void 0:r.id)===U.CONNECTOR_ID.AUTH;n.length>1&&r?s.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...n],type:i?"AUTH":"MULTI_CHAIN",chain:"eip155",id:(r==null?void 0:r.id)||""}):r&&s.push(r)}),s},generateConnectorMapByName(t){const e=new Map;return t.forEach(s=>{const{name:n}=s,r=q.getConnectorName(n);if(!r)return;const i=e.get(r)||[];i.find(a=>a.chain===s.chain)||i.push(s),e.set(r,i)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(s=>{e.find(n=>n.chain===s.chain)||e.push(s)}),e},addConnector(t){var e,s,n;if(t.id===U.CONNECTOR_ID.AUTH){const r=t,i=wi(k.state),o=Dt.getSnapshot().themeMode,a=Dt.getSnapshot().themeVariables;(s=(e=r==null?void 0:r.provider)==null?void 0:e.syncDappData)==null||s.call(e,{metadata:i.metadata,sdkVersion:i.sdkVersion,projectId:i.projectId,sdkType:i.sdkType}),(n=r==null?void 0:r.provider)==null||n.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:Io(a,o)}),q.setConnectors([t])}else q.setConnectors([t])},getAuthConnector(t){var n;const e=t||m.state.activeChain,s=Ce.connectors.find(r=>r.id===U.CONNECTOR_ID.AUTH);if(s)return(n=s==null?void 0:s.connectors)!=null&&n.length?s.connectors.find(i=>i.chain===e):s},getAnnouncedConnectorRdns(){return Ce.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>{var e;return(e=t.info)==null?void 0:e.rdns})},getConnectorById(t){return Ce.allConnectors.find(e=>e.id===t)},getConnector({id:t,rdns:e,namespace:s}){const n=s||m.state.activeChain;return Ce.allConnectors.filter(i=>i.chain===n).find(i=>{var o;return i.explorerId===t||((o=i.info)==null?void 0:o.rdns)===e})},syncIfAuthConnector(t){var i,o;if(t.id!=="AUTH")return;const e=t,s=wi(k.state),n=Dt.getSnapshot().themeMode,r=Dt.getSnapshot().themeVariables;(o=(i=e==null?void 0:e.provider)==null?void 0:i.syncDappData)==null||o.call(i,{metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:Io(r,n)})},getConnectorsByNamespace(t){const e=Ce.allConnectors.filter(s=>s.chain===t);return q.mergeMultiChainConnectors(e)},canSwitchToSmartAccount(t){return m.checkIfSmartAccountEnabled()&&ts(t)===Qt.ACCOUNT_TYPES.EOA},selectWalletConnector(t){var n;const e=(n=ne.state.data)==null?void 0:n.redirectView,s=q.getConnector({id:t.id,rdns:t.rdns});xm.handleMobileDeeplinkRedirect((s==null?void 0:s.explorerId)||t.id,m.state.activeChain),s?ne.push("ConnectingExternal",{connector:s,wallet:t,redirectView:e}):ne.push("ConnectingWalletConnect",{wallet:t,redirectView:e})},getConnectors(t){return t?q.getConnectorsByNamespace(t):q.mergeMultiChainConnectors(Ce.allConnectors)},setFilterByNamespace(t){Ce.filterByNamespace=t,Ce.connectors=q.getConnectors(t),Q.setFilterByNamespace(t)},setConnectorId(t,e){t&&(Ce.activeConnectorIds={...Ce.activeConnectorIds,[e]:t},B.setConnectedConnectorId(e,t))},removeConnectorId(t){Ce.activeConnectorIds={...Ce.activeConnectorIds,[t]:void 0},B.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return Ce.activeConnectorIds[t]},isConnected(t){return t?!!Ce.activeConnectorIds[t]:Object.values(Ce.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){Ce.activeConnectorIds={...Xh}}},q=ns(Jm),Xm=1e3,Kr={checkNamespaceConnectorId(t,e){return q.getConnectorId(t)===e},isSocialProvider(t){return ye.DEFAULT_REMOTE_FEATURES.socials.includes(t)},connectWalletConnect({walletConnect:t,connector:e,closeModalOnConnect:s=!0,redirectViewOnModalClose:n="Connect",onOpen:r,onConnect:i}){return new Promise((o,a)=>{if(t&&q.setActiveConnector(e),r==null||r(J.isMobile()&&t),n){const l=pe.subscribeKey("open",d=>{d||(ne.state.view!==n&&ne.replace(n),l(),a(new Error("Modal closed")))})}const c=m.subscribeKey("activeCaipAddress",l=>{l&&(i==null||i(),s&&pe.close(),c(),o(tt.parseCaipAddress(l)))})})},connectExternal(t){return new Promise((e,s)=>{const n=m.subscribeKey("activeCaipAddress",r=>{r&&(pe.close(),n(),e(tt.parseCaipAddress(r)))});z.connectExternal(t,t.chain).catch(()=>{n(),s(new Error("Connection rejected"))})})},connectSocial({social:t,namespace:e,closeModalOnConnect:s=!0,onOpenFarcaster:n,onConnect:r}){let i,o=!1,a=null;const c=e||m.state.activeChain,l=m.subscribeKey("activeCaipAddress",d=>{d&&(s&&pe.close(),l())});return new Promise((d,u)=>{async function h(g){var f;if((f=g.data)!=null&&f.resultUri)if(g.origin===U.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",h,!1);try{const w=q.getAuthConnector(c);if(w&&!o){i&&i.close(),o=!0;const E=g.data.resultUri;he.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:t}}),B.setConnectedSocialProvider(t),await z.connectExternal({id:w.id,type:w.type,socialUri:E},w.chain);const I=m.state.activeCaipAddress;if(!I){u(new Error("Failed to connect"));return}d(tt.parseCaipAddress(I)),he.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:t}})}}catch(w){he.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:t,message:J.parseError(w)}}),u(new Error("Failed to connect"))}}else he.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:t,message:"Untrusted Origin"}})}async function p(){if(he.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:t}}),t==="farcaster"){n==null||n();const g=pe.subscribeKey("open",w=>{!w&&t==="farcaster"&&(u(new Error("Popup closed")),r==null||r(),g())}),f=q.getAuthConnector();if(f){const w=m.getAccountData(c);if(!(w!=null&&w.farcasterUrl))try{const{url:E}=await f.provider.getFarcasterUri();m.setAccountProp("farcasterUrl",E,c)}catch{u(new Error("Failed to connect to farcaster"))}}}else{const g=q.getAuthConnector();a=J.returnOpenHref(`${U.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(g){const{uri:f}=await g.provider.getSocialRedirectUri({provider:t});if(a&&f){a.location.href=f,i=a;const w=setInterval(()=>{i!=null&&i.closed&&!o&&(u(new Error("Popup closed")),clearInterval(w))},1e3);window.addEventListener("message",h,!1)}else a==null||a.close(),u(new Error("Failed to initiate social connection"))}}catch{u(new Error("Failed to initiate social connection")),a==null||a.close()}}}p()})},connectEmail({closeModalOnConnect:t=!0,redirectViewOnModalClose:e="Connect",onOpen:s,onConnect:n}){return new Promise((r,i)=>{if(s==null||s(),e){const a=pe.subscribeKey("open",c=>{c||(ne.state.view!==e&&ne.replace(e),a(),i(new Error("Modal closed")))})}const o=m.subscribeKey("activeCaipAddress",a=>{a&&(n==null||n(),t&&pe.close(),o(),r(tt.parseCaipAddress(a)))})})},async updateEmail(){const t=B.getConnectedConnectorId(m.state.activeChain),e=q.getAuthConnector();if(!e)throw new Error("No auth connector found");if(t!==U.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");const s=e.provider.getEmail()??"";return await pe.open({view:"UpdateEmailWallet",data:{email:s,redirectView:void 0}}),new Promise((n,r)=>{const i=setInterval(()=>{const a=e.provider.getEmail()??"";a!==s&&(pe.close(),clearInterval(i),o(),n({email:a}))},Xm),o=pe.subscribeKey("open",a=>{a||(ne.state.view!=="Connect"&&ne.push("Connect"),clearInterval(i),o(),r(new Error("Modal closed")))})})},canSwitchToSmartAccount(t){return m.checkIfSmartAccountEnabled()&&ts(t)===Qt.ACCOUNT_TYPES.EOA}};function Zh(){var n,r;const t=((n=m.state.activeCaipNetwork)==null?void 0:n.chainNamespace)||"eip155",e=((r=m.state.activeCaipNetwork)==null?void 0:r.id)||1,s=ye.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`}function ts(t){var s;return(s=m.getAccountData(t))==null?void 0:s.preferredAccountType}function Ki(t){var e,s;return t?(s=(e=m.state.chains.get(t))==null?void 0:e.networkState)==null?void 0:s.caipNetwork:m.state.activeCaipNetwork}const So={getConnectionStatus(t,e){const s=q.state.activeConnectorIds[e],n=z.getConnections(e);return!!s&&t.connectorId===s?"connected":n.some(o=>o.connectorId.toLowerCase()===t.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:t,connectorId:e,addresses:s}){return t.map(n=>{if((e?n.connectorId.toLowerCase()===e.toLowerCase():!1)&&s){const i=n.accounts.filter(o=>!s.some(c=>c.toLowerCase()===o.address.toLowerCase()));return{...n,accounts:i}}return n})},excludeExistingConnections(t,e){const s=new Set(t);return e.filter(n=>!s.has(n.connectorId))},getConnectionsByConnectorId(t,e){return t.filter(s=>s.connectorId.toLowerCase()===e.toLowerCase())},getConnectionsData(t){var a;const e=!!((a=k.state.remoteFeatures)!=null&&a.multiWallet),s=q.state.activeConnectorIds[t],n=z.getConnections(t),i=(z.state.recentConnections.get(t)??[]).filter(c=>q.getConnectorById(c.connectorId)),o=So.excludeExistingConnections([...n.map(c=>c.connectorId),...s?[s]:[]],i);return e?{connections:n,recentConnections:o}:{connections:n.filter(c=>c.connectorId.toLowerCase()===(s==null?void 0:s.toLowerCase())),recentConnections:[]}}},$e=ke({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Zm={state:$e,subscribe(t){return st($e,()=>t($e))},setLastNetworkInView(t){$e.lastNetworkInView=t},async fetchTransactions(t){var e;if(!t)throw new Error("Transactions can't be fetched without an accountAddress");$e.loading=!0;try{const s=await re.fetchTransactions({account:t,cursor:$e.next,chainId:(e=m.state.activeCaipNetwork)==null?void 0:e.caipNetworkId}),n=fo.filterSpamTransactions(s.data),r=fo.filterByConnectedChain(n),i=[...$e.transactions,...r];$e.loading=!1,$e.transactions=i,$e.transactionsByYear=fo.groupTransactionsByYearAndMonth($e.transactionsByYear,r),$e.empty=i.length===0,$e.next=s.next?s.next:void 0}catch{const n=m.state.activeChain;he.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:k.state.projectId,cursor:$e.next,isSmartAccount:ts(n)===Qt.ACCOUNT_TYPES.SMART_ACCOUNT}}),vs.showError("Failed to fetch transactions"),$e.loading=!1,$e.empty=!0,$e.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const s=t;return e.forEach(n=>{const r=new Date(n.metadata.minedAt).getFullYear(),i=new Date(n.metadata.minedAt).getMonth(),o=s[r]??{},c=(o[i]??[]).filter(l=>l.id!==n.id);s[r]={...o,[i]:[...c,n].sort((l,d)=>new Date(d.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),s},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(n=>{var r;return((r=n.nft_info)==null?void 0:r.flags.is_spam)===!0}))},filterByConnectedChain(t){var n;const e=(n=m.state.activeCaipNetwork)==null?void 0:n.caipNetworkId;return t.filter(r=>r.metadata.chain===e)},clearCursor(){$e.next=void 0},resetTransactions(){$e.transactions=[],$e.transactionsByYear={},$e.lastNetworkInView=void 0,$e.loading=!1,$e.empty=!1,$e.next=void 0}},fo=ns(Zm,"API_ERROR"),me=ke({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,buffering:!1,status:"disconnected"});let On;const Qm={state:me,subscribe(t){return st(me,()=>t(me))},subscribeKey(t,e){return nt(me,t,e)},_getClient(){return me._client},setClient(t){me._client=yi(t)},initialize(t){const e=t.filter(s=>!!s.namespace).map(s=>s.namespace);z.syncStorageConnections(e)},syncStorageConnections(t){const e=B.getConnections(),s=t??Array.from(m.state.chains.keys());for(const n of s){const r=e[n]??[],i=new Map(me.recentConnections);i.set(n,r),me.recentConnections=i}},getConnections(t){return t?me.connections.get(t)??[]:[]},hasAnyConnection(t){const e=z.state.connections;return Array.from(e.values()).flatMap(s=>s).some(({connectorId:s})=>s===t)},async connectWalletConnect({cache:t="auto"}={}){var s,n,r,i;const e=J.isTelegram()||J.isSafari()&&J.isIos();if(t==="always"||t==="auto"&&e){if(On){await On,On=void 0;return}if(!J.isPairingExpired(me==null?void 0:me.wcPairingExpiry)){const o=me.wcUri;me.wcUri=o;return}On=(n=(s=z._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:n.call(s).catch(()=>{}),z.state.status="connecting",await On,On=void 0,me.wcPairingExpiry=void 0,z.state.status="connected"}else await((i=(r=z._getClient())==null?void 0:r.connectWalletConnect)==null?void 0:i.call(r))},async connectExternal(t,e,s=!0){var r,i;const n=await((i=(r=z._getClient())==null?void 0:r.connectExternal)==null?void 0:i.call(r,t));return s&&m.setActiveNamespace(e),n},async reconnectExternal(t){var s,n;await((n=(s=z._getClient())==null?void 0:s.reconnectExternal)==null?void 0:n.call(s,t));const e=t.chain||m.state.activeChain;e&&q.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){var n;if(!e)return;pe.setLoading(!0,m.state.activeChain);const s=q.getAuthConnector();s&&(m.setAccountProp("preferredAccountType",t,e),await s.provider.setPreferredAccount(t),B.setPreferredAccountTypes(Object.entries(m.state.chains).reduce((r,[i,o])=>{const a=i,c=ts(a);return c!==void 0&&(r[a]=c),r},{})),await z.reconnectExternal(s),pe.setLoading(!1,m.state.activeChain),he.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:((n=m.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}}))},async signMessage(t){var e;return(e=z._getClient())==null?void 0:e.signMessage(t)},parseUnits(t,e){var s;return(s=z._getClient())==null?void 0:s.parseUnits(t,e)},formatUnits(t,e){var s;return(s=z._getClient())==null?void 0:s.formatUnits(t,e)},updateBalance(t){var e;return(e=z._getClient())==null?void 0:e.updateBalance(t)},async sendTransaction(t){var e;return(e=z._getClient())==null?void 0:e.sendTransaction(t)},async getCapabilities(t){var e;return(e=z._getClient())==null?void 0:e.getCapabilities(t)},async grantPermissions(t){var e;return(e=z._getClient())==null?void 0:e.grantPermissions(t)},async walletGetAssets(t){var e;return((e=z._getClient())==null?void 0:e.walletGetAssets(t))??{}},async estimateGas(t){var e;return(e=z._getClient())==null?void 0:e.estimateGas(t)},async writeContract(t){var e;return(e=z._getClient())==null?void 0:e.writeContract(t)},async getEnsAddress(t){var e;return(e=z._getClient())==null?void 0:e.getEnsAddress(t)},async getEnsAvatar(t){var e;return(e=z._getClient())==null?void 0:e.getEnsAvatar(t)},checkInstalled(t){var e,s;return((s=(e=z._getClient())==null?void 0:e.checkInstalled)==null?void 0:s.call(e,t))||!1},resetWcConnection(){me.wcUri=void 0,me.wcPairingExpiry=void 0,me.wcLinking=void 0,me.recentWallet=void 0,me.status="disconnected",fo.resetTransactions(),B.deleteWalletConnectDeepLink(),B.deleteRecentWallet()},resetUri(){me.wcUri=void 0,me.wcPairingExpiry=void 0,On=void 0},finalizeWcConnection(t){var n,r;const{wcLinking:e,recentWallet:s}=z.state;e&&B.setWalletConnectDeepLink(e),s&&B.setAppKitRecent(s),t&&he.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:t,properties:{method:e?"mobile":"qrcode",name:((r=(n=ne.state.data)==null?void 0:n.wallet)==null?void 0:r.name)||"Unknown",view:ne.state.view,walletRank:s==null?void 0:s.order}})},setWcBasic(t){me.wcBasic=t},setUri(t){me.wcUri=t,me.wcPairingExpiry=J.getPairingExpiry()},setWcLinking(t){me.wcLinking=t},setWcError(t){me.wcError=t,me.buffering=!1},setRecentWallet(t){me.recentWallet=t},setBuffering(t){me.buffering=t},setStatus(t){me.status=t},setIsSwitchingConnection(t){me.isSwitchingConnection=t},async disconnect({id:t,namespace:e,initialDisconnect:s}={}){var n;try{await((n=z._getClient())==null?void 0:n.disconnect({id:t,chainNamespace:e,initialDisconnect:s}))}catch(r){throw new Qn("Failed to disconnect","INTERNAL_SDK_ERROR",r)}},async disconnectConnector({id:t,namespace:e}){var s;try{await((s=z._getClient())==null?void 0:s.disconnectConnector({id:t,namespace:e}))}catch(n){throw new Qn("Failed to disconnect connector","INTERNAL_SDK_ERROR",n)}},setConnections(t,e){const s=new Map(me.connections);s.set(e,t),me.connections=s},async handleAuthAccountSwitch({address:t,namespace:e}){var i,o;const s=m.getAccountData(e),n=(o=(i=s==null?void 0:s.user)==null?void 0:i.accounts)==null?void 0:o.find(a=>a.type==="smartAccount"),r=n&&n.address.toLowerCase()===t.toLowerCase()&&Kr.canSwitchToSmartAccount(e)?"smartAccount":"eoa";await z.setPreferredAccountType(r,e)},async handleActiveConnection({connection:t,namespace:e,address:s}){const n=q.getConnectorById(t.connectorId),r=t.connectorId===U.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${t.connectorId}`);if(r)s&&await z.handleAuthAccountSwitch({address:s,namespace:e});else{const i=await z.connectExternal({id:n.id,type:n.type,provider:n.provider,address:s,chain:e},e);return i==null?void 0:i.address}return s},async handleDisconnectedConnection({connection:t,namespace:e,address:s,closeModalOnConnect:n}){var l,d;const r=q.getConnectorById(t.connectorId),i=(d=(l=t.auth)==null?void 0:l.name)==null?void 0:d.toLowerCase(),o=t.connectorId===U.CONNECTOR_ID.AUTH,a=t.connectorId===U.CONNECTOR_ID.WALLET_CONNECT;if(!r)throw new Error(`No connector found for connection: ${t.connectorId}`);let c;if(o)if(i&&Kr.isSocialProvider(i)){const{address:u}=await Kr.connectSocial({social:i,closeModalOnConnect:n,onOpenFarcaster(){pe.open({view:"ConnectingFarcaster"})},onConnect(){ne.replace("ProfileWallets")}});c=u}else{const{address:u}=await Kr.connectEmail({closeModalOnConnect:n,onOpen(){pe.open({view:"EmailLogin"})},onConnect(){ne.replace("ProfileWallets")}});c=u}else if(a){const{address:u}=await Kr.connectWalletConnect({walletConnect:!0,connector:r,closeModalOnConnect:n,onOpen(h){const p=h?"AllWallets":"ConnectingWalletConnect";pe.state.open?ne.push(p):pe.open({view:p})},onConnect(){ne.replace("ProfileWallets")}});c=u}else{const u=await z.connectExternal({id:r.id,type:r.type,provider:r.provider,chain:e},e);u&&(c=u.address)}return o&&s&&await z.handleAuthAccountSwitch({address:s,namespace:e}),c},async switchConnection({connection:t,address:e,namespace:s,closeModalOnConnect:n,onChange:r}){var c;let i;const o=(c=m.getAccountData(s))==null?void 0:c.caipAddress;if(o){const{address:l}=tt.parseCaipAddress(o);i=l}const a=So.getConnectionStatus(t,s);switch(a){case"connected":case"active":{const l=await z.handleActiveConnection({connection:t,namespace:s,address:e});if(i&&l){const d=l.toLowerCase()!==i.toLowerCase();r==null||r({address:l,namespace:s,hasSwitchedAccount:d,hasSwitchedWallet:a==="active"})}break}case"disconnected":{const l=await z.handleDisconnectedConnection({connection:t,namespace:s,address:e,closeModalOnConnect:n});l&&(r==null||r({address:l,namespace:s,hasSwitchedAccount:!0,hasSwitchedWallet:!0}));break}default:throw new Error(`Invalid connection status: ${a}`)}}},z=ns(Qm),wa={createBalance(t,e){const s={name:t.metadata.name||"",symbol:t.metadata.symbol||"",decimals:t.metadata.decimals||0,value:t.metadata.value||0,price:t.metadata.price||0,iconUrl:t.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:e,address:t.address==="native"?void 0:this.convertAddressToCAIP10Address(t.address,e),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:t.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance({hex:t,decimals:e}){return ut.formatUnits(BigInt(t),e)},convertAddressToCAIP10Address(t,e){return`${e}:${t}`},createCAIP2ChainId(t,e){return`${e}:${parseInt(t,16)}`},getChainIdHexFromCAIP2ChainId(t){const e=t.split(":");if(e.length<2||!e[1])return"0x0";const s=e[1],n=parseInt(s,10);return isNaN(n)?"0x0":`0x${n.toString(16)}`},isWalletGetAssetsResponse(t){return typeof t!="object"||t===null?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(s=>this.isValidAsset(s)))},isValidAsset(t){return typeof t=="object"&&t!==null&&typeof t.address=="string"&&typeof t.balance=="string"&&(t.type==="ERC20"||t.type==="NATIVE")&&typeof t.metadata=="object"&&t.metadata!==null&&typeof t.metadata.name=="string"&&typeof t.metadata.symbol=="string"&&typeof t.metadata.decimals=="number"&&typeof t.metadata.price=="number"&&typeof t.metadata.iconUrl=="string"}};let ya;async function td(){if(!ya){const{createPublicClient:t,http:e,defineChain:s}=await Ao(()=>Promise.resolve().then(()=>Om),void 0);ya={createPublicClient:t,http:e,defineChain:s}}return ya}const wc={getBlockchainApiRpcUrl(t,e){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",t),s.searchParams.set("projectId",e),s.toString()},async getViemChain(t){const{defineChain:e}=await td(),{chainId:s}=tt.parseCaipNetworkId(t.caipNetworkId);return e({...t,id:Number(s)})},async createViemPublicClient(t){const{createPublicClient:e,http:s}=await td(),n=k.state.projectId,r=await wc.getViemChain(t);if(!r)throw new Error(`Chain ${t.caipNetworkId} not found in viem/chains`);return e({chain:r,transport:s(wc.getBlockchainApiRpcUrl(t.caipNetworkId,n))})}},ul={async getMyTokensWithBalance(t){var a;const e=(a=m.getAccountData())==null?void 0:a.address,s=m.state.activeCaipNetwork,n=q.getConnectorId("eip155")===U.CONNECTOR_ID.AUTH;if(!e||!s)return[];const r=`${s.caipNetworkId}:${e}`,i=B.getBalanceCacheForCaipAddress(r);if(i)return i.balances;if(s.chainNamespace===U.CHAIN.EVM&&n){const c=await this.getEIP155Balances(e,s);if(c)return this.filterLowQualityTokens(c)}const o=await re.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(t,e){var s,n;try{const r=wa.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),i=await z.getCapabilities(t);if(!((n=(s=i==null?void 0:i[r])==null?void 0:s.assetDiscovery)!=null&&n.supported))return null;const o=await z.walletGetAssets({account:t,chainFilter:[r]});if(!wa.isWalletGetAssetsResponse(o))return null;const c=(o[r]||[]).map(l=>wa.createBalance(l,e.caipNetworkId));return B.updateBalanceCache({caipAddress:`${e.caipNetworkId}:${t}`,balance:{balances:c},timestamp:Date.now()}),c}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:t,assetAddress:e,caipNetwork:s}){const n=await wc.createViemPublicClient(s),{address:r}=tt.parseCaipAddress(t),[{result:i},{result:o},{result:a},{result:c}]=await n.multicall({contracts:[{address:e,functionName:"name",args:[],abi:ut.erc20Abi},{address:e,functionName:"symbol",args:[],abi:ut.erc20Abi},{address:e,functionName:"balanceOf",args:[r],abi:ut.erc20Abi},{address:e,functionName:"decimals",args:[],abi:ut.erc20Abi}]});return{name:i,symbol:o,decimals:c,balance:a&&c?ut.formatUnits(a,c):"0"}}},ba={adapters:{}},Qh={state:ba,initialize(t){ba.adapters={...t}},get(t){return ba.adapters[t]}},No={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0},Et=ke({providers:{...No},providerIds:{...No}}),Ue={state:Et,subscribeKey(t,e){return nt(Et,t,e)},subscribe(t){return st(Et,()=>{t(Et)})},subscribeProviders(t){return st(Et.providers,()=>t(Et.providers))},setProvider(t,e){t&&e&&(Et.providers[t]=yi(e))},getProvider(t){if(t)return Et.providers[t]},setProviderId(t,e){e&&(Et.providerIds[t]=e)},getProviderId(t){if(t)return Et.providerIds[t]},reset(){Et.providers={...No},Et.providerIds={...No}},resetChain(t){Et.providers[t]=void 0,Et.providerIds[t]=void 0}},ur=ke({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),Ws={state:ur,subscribe(t){return st(ur,()=>t(ur))},subscribeOpen(t){return nt(ur,"open",t)},set(t){Object.assign(ur,{...ur,...t})}},ew={async getTokenList(t){var n;const e=await re.fetchSwapTokens({chainId:t});return((n=e==null?void 0:e.tokens)==null?void 0:n.map(r=>({...r,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0})))||[]},async fetchGasPrice(){var e;const t=m.state.activeCaipNetwork;if(!t)return null;try{switch(t.chainNamespace){case"solana":const s=(e=await(z==null?void 0:z.estimateGas({chainNamespace:"solana"})))==null?void 0:e.toString();return{standard:s,fast:s,instant:s};case"eip155":default:return await re.fetchGasPrice({chainId:t.caipNetworkId})}}catch{return null}},async fetchSwapAllowance({tokenAddress:t,userAddress:e,sourceTokenAmount:s,sourceTokenDecimals:n}){const r=await re.fetchSwapAllowance({tokenAddress:t,userAddress:e});if(r!=null&&r.allowance&&s&&n){const i=z.parseUnits(s,n)||0;return BigInt(r.allowance)>=i}return!1},async getMyTokensWithBalance(t){const e=await ul.getMyTokensWithBalance(t);return m.setAccountProp("tokenBalance",e,m.state.activeChain),this.mapBalancesToSwapTokens(e)},mapBalancesToSwapTokens(t){return(t==null?void 0:t.map(e=>({...e,address:e!=null&&e.address?e.address:Zh(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]},async handleSwapError(t){var e,s;try{const n=t==null?void 0:t.cause;if(!(n!=null&&n.json))return;const r=await n.json(),i=(s=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:s.description;return i!=null&&i.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}},we=ke({tokenBalances:[],loading:!1}),tw={state:we,subscribe(t){return st(we,()=>t(we))},subscribeKey(t,e){return nt(we,t,e)},setToken(t){t&&(we.token=yi(t))},setTokenAmount(t){we.sendTokenAmount=t},setReceiverAddress(t){we.receiverAddress=t},setReceiverProfileImageUrl(t){we.receiverProfileImageUrl=t},setReceiverProfileName(t){we.receiverProfileName=t},setNetworkBalanceInUsd(t){we.networkBalanceInUSD=t},setLoading(t){we.loading=t},getSdkEventProperties(t){var e,s;return{message:J.parseError(t),isSmartAccount:ts(m.state.activeChain)===Qt.ACCOUNT_TYPES.SMART_ACCOUNT,token:((e=we.token)==null?void 0:e.symbol)||"",amount:we.sendTokenAmount??0,network:((s=m.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||""}},async sendToken(){var t;try{switch(ue.setLoading(!0),(t=m.state.activeCaipNetwork)==null?void 0:t.chainNamespace){case"eip155":await ue.sendEvmToken();return;case"solana":await ue.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(e){throw js.isUserRejectedRequestError(e)?new zh(e):e}finally{ue.setLoading(!1)}},async sendEvmToken(){var s,n,r;const t=m.state.activeChain;if(!t)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const e=ts(t);if(!ue.state.sendTokenAmount||!ue.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!ue.state.token)throw new Error("A token is required");if((s=ue.state.token)!=null&&s.address){he.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Qt.ACCOUNT_TYPES.SMART_ACCOUNT,token:ue.state.token.address,amount:ue.state.sendTokenAmount,network:((n=m.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}});const{hash:i}=await ue.sendERC20Token({receiverAddress:ue.state.receiverAddress,tokenAddress:ue.state.token.address,sendTokenAmount:ue.state.sendTokenAmount,decimals:ue.state.token.quantity.decimals});i&&(we.hash=i)}else{he.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Qt.ACCOUNT_TYPES.SMART_ACCOUNT,token:ue.state.token.symbol||"",amount:ue.state.sendTokenAmount,network:((r=m.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}});const{hash:i}=await ue.sendNativeToken({receiverAddress:ue.state.receiverAddress,sendTokenAmount:ue.state.sendTokenAmount,decimals:ue.state.token.quantity.decimals});i&&(we.hash=i)}},async fetchTokenBalance(t){var o,a,c;we.loading=!0;const e=m.state.activeChain,s=(o=m.state.activeCaipNetwork)==null?void 0:o.caipNetworkId,n=(a=m.state.activeCaipNetwork)==null?void 0:a.chainNamespace,r=((c=m.getAccountData(e))==null?void 0:c.caipAddress)??m.state.activeCaipAddress,i=r?J.getPlainAddress(r):void 0;if(we.lastRetry&&!J.isAllowedRetry(we.lastRetry,30*ye.ONE_SEC_MS))return we.loading=!1,[];try{if(i&&s&&n){const l=await ul.getMyTokensWithBalance();return we.tokenBalances=l,we.lastRetry=void 0,l}}catch(l){we.lastRetry=Date.now(),t==null||t(l),vs.showError("Token Balance Unavailable")}finally{we.loading=!1}return[]},fetchNetworkBalance(){if(we.tokenBalances.length===0)return;const t=ew.mapBalancesToSwapTokens(we.tokenBalances);if(!t)return;const e=t.find(s=>s.address===Zh());e&&(we.networkBalanceInUSD=e?cm.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){var o,a,c,l;ne.pushTransactionStack({});const e=t.receiverAddress,s=(o=m.getAccountData())==null?void 0:o.address,n=z.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),r="0x",i=await z.sendTransaction({chainNamespace:U.CHAIN.EVM,to:e,address:s,data:r,value:n??BigInt(0)});return he.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:ts("eip155")===Qt.ACCOUNT_TYPES.SMART_ACCOUNT,token:((a=ue.state.token)==null?void 0:a.symbol)||"",amount:t.sendTokenAmount,network:((c=m.state.activeCaipNetwork)==null?void 0:c.caipNetworkId)||"",hash:i||""}}),(l=z._getClient())==null||l.updateBalance("eip155"),ue.resetSend(),{hash:i}},async sendERC20Token(t){var n,r,i;ne.pushTransactionStack({onSuccess(){ne.replace("Account")}});const e=z.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),s=(n=m.getAccountData())==null?void 0:n.address;if(s&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const o=J.getPlainAddress(t.tokenAddress);if(!o)throw new Error("SendController:sendERC20Token - tokenAddress is required");const a=await z.writeContract({fromAddress:s,tokenAddress:o,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:hm.getERC20Abi(o),chainNamespace:U.CHAIN.EVM});return he.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:ts("eip155")===Qt.ACCOUNT_TYPES.SMART_ACCOUNT,token:((r=ue.state.token)==null?void 0:r.symbol)||"",amount:t.sendTokenAmount,network:((i=m.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||"",hash:a||""}}),ue.resetSend(),{hash:a}}return{hash:void 0}},async sendSolanaToken(){var s,n,r;if(!ue.state.sendTokenAmount||!ue.state.receiverAddress)throw new Error("An amount and receiver address are required");ne.pushTransactionStack({onSuccess(){ne.replace("Account")}});let t;ue.state.token&&ue.state.token.address!==ye.SOLANA_NATIVE_TOKEN_ADDRESS&&(J.isCaipAddress(ue.state.token.address)?t=J.getPlainAddress(ue.state.token.address):t=ue.state.token.address);const e=await z.sendTransaction({chainNamespace:"solana",tokenMint:t,to:ue.state.receiverAddress,value:ue.state.sendTokenAmount});e&&(we.hash=e),(s=z._getClient())==null||s.updateBalance("solana"),he.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:!1,token:((n=ue.state.token)==null?void 0:n.symbol)||"",amount:ue.state.sendTokenAmount,network:((r=m.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||"",hash:e||""}}),ue.resetSend()},resetSend(){we.token=void 0,we.sendTokenAmount=void 0,we.receiverAddress=void 0,we.receiverProfileImageUrl=void 0,we.receiverProfileName=void 0,we.loading=!1,we.tokenBalances=[]}},ue=ns(tw),Ea={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},zi={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},G=ke({chains:Sm(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{connectionControllerClient:void 0},isSwitchingNamespace:!1}),ep={state:G,subscribe(t){return st(G,()=>{t(G)})},subscribeKey(t,e){return nt(G,t,e)},subscribeAccountStateProp(t,e,s){var r;const n=s||G.activeChain;return n?nt(((r=G.chains.get(n))==null?void 0:r.accountState)||{},t,e):()=>{}},subscribeChainProp(t,e,s){let n;return st(G.chains,()=>{var i;const r=s||G.activeChain;if(r){const o=(i=G.chains.get(r))==null?void 0:i[t];n!==o&&(n=o,e(o))}})},initialize(t,e,s){const{chainId:n,namespace:r}=B.getActiveNetworkProps(),i=e==null?void 0:e.find(d=>d.id.toString()===(n==null?void 0:n.toString())),a=t.find(d=>(d==null?void 0:d.namespace)===r)||(t==null?void 0:t[0]),c=t.map(d=>d.namespace).filter(d=>d!==void 0),l=k.state.enableEmbedded?new Set([...c]):new Set([...(e==null?void 0:e.map(d=>d.chainNamespace))??[]]);((t==null?void 0:t.length)===0||!a)&&(G.noAdapters=!0),G.noAdapters||(G.activeChain=a==null?void 0:a.namespace,G.activeCaipNetwork=i,m.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:i}),G.activeChain&&Ws.set({activeChain:a==null?void 0:a.namespace})),l.forEach(d=>{const u=e==null?void 0:e.filter(g=>g.chainNamespace===d),h=B.getPreferredAccountTypes()||{},p={...k.state.defaultAccountTypes,...h};m.state.chains.set(d,{namespace:d,networkState:ke({...zi,caipNetwork:u==null?void 0:u[0]}),accountState:ke({...Ea,preferredAccountType:p[d]}),caipNetworks:u??[],...s}),m.setRequestedCaipNetworks(u??[],d)})},removeAdapter(t){var e,s;if(G.activeChain===t){const n=Array.from(G.chains.entries()).find(([r])=>r!==t);if(n){const r=(s=(e=n[1])==null?void 0:e.caipNetworks)==null?void 0:s[0];r&&m.setActiveCaipNetwork(r)}}G.chains.delete(t)},addAdapter(t,{connectionControllerClient:e},s){if(!t.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");G.chains.set(t.namespace,{namespace:t.namespace,networkState:{...zi,caipNetwork:s[0]},accountState:{...Ea},caipNetworks:s,connectionControllerClient:e}),m.setRequestedCaipNetworks((s==null?void 0:s.filter(n=>n.chainNamespace===t.namespace))??[],t.namespace)},addNetwork(t){var s;const e=G.chains.get(t.chainNamespace);if(e){const n=[...e.caipNetworks||[]];(s=e.caipNetworks)!=null&&s.find(r=>r.id===t.id)||n.push(t),G.chains.set(t.chainNamespace,{...e,caipNetworks:n}),m.setRequestedCaipNetworks(n,t.chainNamespace),q.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){var n,r,i;const s=G.chains.get(t);if(s){const o=((n=G.activeCaipNetwork)==null?void 0:n.id)===e,a=[...((r=s.caipNetworks)==null?void 0:r.filter(c=>c.id!==e))||[]];o&&((i=s==null?void 0:s.caipNetworks)!=null&&i[0])&&m.setActiveCaipNetwork(s.caipNetworks[0]),G.chains.set(t,{...s,caipNetworks:a}),m.setRequestedCaipNetworks(a||[],t),a.length===0&&q.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=G.chains.get(t);s&&(s.networkState={...s.networkState||zi,...e},G.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const n=G.chains.get(t);if(n){const r={...n.accountState||Ea,...e};G.chains.set(t,{...n,accountState:r}),(G.chains.size===1||G.activeChain===t)&&e.caipAddress&&(G.activeCaipAddress=e.caipAddress)}},setChainNetworkData(t,e){if(!t)return;const s=G.chains.get(t);if(s){const n={...s.networkState||zi,...e};G.chains.set(t,{...s,networkState:n})}},setAccountProp(t,e,s,n=!0){m.setChainAccountData(s,{[t]:e},n)},setActiveNamespace(t){var n,r;G.activeChain=t;const e=t?G.chains.get(t):void 0,s=(n=e==null?void 0:e.networkState)==null?void 0:n.caipNetwork;s!=null&&s.id&&t&&(G.activeCaipAddress=(r=e==null?void 0:e.accountState)==null?void 0:r.caipAddress,G.activeCaipNetwork=s,m.setChainNetworkData(t,{caipNetwork:s}),B.setActiveCaipNetworkId(s==null?void 0:s.caipNetworkId),Ws.set({activeChain:t,selectedNetworkId:s==null?void 0:s.caipNetworkId}))},setActiveCaipNetwork(t){var i,o;if(!t)return;const e=G.activeChain===t.chainNamespace;e||m.setIsSwitchingNamespace(!0);const s=G.chains.get(t.chainNamespace);G.activeChain=t.chainNamespace,G.activeCaipNetwork=t,m.setChainNetworkData(t.chainNamespace,{caipNetwork:t});let n=(i=s==null?void 0:s.accountState)==null?void 0:i.address;if(n)G.activeCaipAddress=`${t.chainNamespace}:${t.id}:${n}`;else if(e&&G.activeCaipAddress){const{address:a}=tt.parseCaipAddress(G.activeCaipAddress);n=a,G.activeCaipAddress=`${t.caipNetworkId}:${n}`}else G.activeCaipAddress=void 0;m.setChainAccountData(t.chainNamespace,{address:n,caipAddress:G.activeCaipAddress}),ue.resetSend(),Ws.set({activeChain:G.activeChain,selectedNetworkId:(o=G.activeCaipNetwork)==null?void 0:o.caipNetworkId}),B.setActiveCaipNetworkId(t.caipNetworkId),!m.checkIfSupportedNetwork(t.chainNamespace)&&k.state.enableNetworkSwitch&&!k.state.allowUnsupportedChain&&!z.state.wcBasic&&m.showUnsupportedChainUI()},addCaipNetwork(t){var s;if(!t)return;const e=G.chains.get(t.chainNamespace);e&&((s=e==null?void 0:e.caipNetworks)==null||s.push(t))},async switchActiveNamespace(t){var r;if(!t)return;const e=t!==m.state.activeChain,s=(r=m.getNetworkData(t))==null?void 0:r.caipNetwork,n=m.getCaipNetworkByNamespace(t,s==null?void 0:s.id);e&&n&&await m.switchActiveNetwork(n)},async switchActiveNetwork(t,{throwOnFailure:e=!1}={}){var o;const s=m.state.activeChain;if(!s)throw new Error("ChainController:switchActiveNetwork - namespace is required");const n=Ue.getProviderId(G.activeChain)==="AUTH",r=(o=m.getAccountData(s))==null?void 0:o.address,i=U.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(t.chainNamespace);try{if(r&&t.chainNamespace===s||n&&i){const a=Qh.get(t.chainNamespace);if(!a)throw new Error("Adapter not found");await a.switchNetwork({caipNetwork:t})}m.setActiveCaipNetwork(t)}catch(a){if(e)throw a}he.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})},getConnectionControllerClient(t){const e=t||G.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=G.chains.get(e);if(!(s!=null&&s.connectionControllerClient))throw new Error("ConnectionController client not set");return s.connectionControllerClient},getNetworkProp(t,e){var n;const s=(n=G.chains.get(e))==null?void 0:n.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=G.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:n=[]}=(e==null?void 0:e.networkState)||{};return J.sortRequestedNetworks(s,n).filter(o=>o==null?void 0:o.id)},getAllRequestedCaipNetworks(){const t=[];return G.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const s=m.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){m.setAdapterNetworkState(e,{requestedCaipNetworks:t});const n=m.getAllRequestedCaipNetworks().map(i=>i.chainNamespace),r=Array.from(new Set(n));q.filterByNamespaces(r)},getAllApprovedCaipNetworkIds(){const t=[];return G.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const s=m.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(t){var e,s;return t?(s=(e=G.chains.get(t))==null?void 0:e.networkState)==null?void 0:s.caipNetwork:G.activeCaipNetwork},getActiveCaipAddress(){return G.activeCaipAddress},getApprovedCaipNetworkIds(t){var n;const e=G.chains.get(t);return((n=e==null?void 0:e.networkState)==null?void 0:n.approvedCaipNetworkIds)||[]},setApprovedCaipNetworksData(t,e){m.setAdapterNetworkState(t,e)},checkIfSupportedNetwork(t,e){var r;const s=e||((r=G.activeCaipNetwork)==null?void 0:r.caipNetworkId),n=m.getRequestedCaipNetworks(t);return n.length?n==null?void 0:n.some(i=>i.caipNetworkId===s):!0},checkIfSupportedChainId(t){if(!G.activeChain)return!0;const e=m.getRequestedCaipNetworks(G.activeChain);return e==null?void 0:e.some(s=>s.id===t)},checkIfSmartAccountEnabled(){var n,r;const t=qh.caipNetworkIdToNumber((n=G.activeCaipNetwork)==null?void 0:n.caipNetworkId);if(!G.activeChain||!t)return!1;const s=((r=fc.get(yn.SMART_ACCOUNT_ENABLED_NETWORKS))==null?void 0:r.split(","))||[];return!!(s!=null&&s.includes(t.toString()))},showUnsupportedChainUI(){pe.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=G.activeCaipNetwork;return!!(t!=null&&t.chainNamespace&&ye.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){m.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(t){var r,i;const e=t;if(!e)throw new Error("Chain is required to set account prop");const s=(i=(r=m.state.chains.get(e))==null?void 0:r.accountState)==null?void 0:i.preferredAccountType,n=k.state.defaultAccountTypes[e];G.activeCaipAddress=void 0,m.setChainAccountData(e,{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,preferredAccountType:n||s,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),q.removeConnectorId(e)},setIsSwitchingNamespace(t){G.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){var s,n;const t=[];let e;if(G.chains.forEach(r=>{U.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(i=>i===r.namespace)&&r.namespace&&t.push(r.namespace)}),t.length>0){const r=t[0];return e=r?(n=(s=G.chains.get(r))==null?void 0:s.caipNetworks)==null?void 0:n[0]:void 0,e}},getAccountData(t){var s;const e=t||G.activeChain;if(e)return(s=m.state.chains.get(e))==null?void 0:s.accountState},getNetworkData(t){var s;const e=t||G.activeChain;if(e)return(s=m.state.chains.get(e))==null?void 0:s.networkState},getCaipNetworkByNamespace(t,e){var r,i,o;if(!t)return;const s=m.state.chains.get(t),n=(r=s==null?void 0:s.caipNetworks)==null?void 0:r.find(a=>a.id.toString()===(e==null?void 0:e.toString()));return n||((i=s==null?void 0:s.networkState)==null?void 0:i.caipNetwork)||((o=s==null?void 0:s.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const t=q.state.filterByNamespace;return(t?[G.chains.get(t)]:Array.from(G.chains.values())).flatMap(s=>(s==null?void 0:s.caipNetworks)||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?m.getRequestedCaipNetworks(t):m.getAllRequestedCaipNetworks()},getCaipNetworkById(t,e){return ep.getCaipNetworks(e).find(s=>s.id.toString()===t.toString()||s.caipNetworkId.toString()===t.toString())},setLastConnectedSIWECaipNetwork(t){G.lastConnectedSIWECaipNetwork=t},getLastConnectedSIWECaipNetwork(){return G.lastConnectedSIWECaipNetwork},async fetchTokenBalance(t){var o,a;const e=m.getAccountData();if(!e)return[];const s=(o=m.state.activeCaipNetwork)==null?void 0:o.caipNetworkId,n=(a=m.state.activeCaipNetwork)==null?void 0:a.chainNamespace,r=m.state.activeCaipAddress,i=r?J.getPlainAddress(r):void 0;if(m.setAccountProp("balanceLoading",!0,n),e.lastRetry&&!J.isAllowedRetry(e.lastRetry,30*ye.ONE_SEC_MS))return m.setAccountProp("balanceLoading",!1,n),[];try{if(i&&s&&n){const c=await ul.getMyTokensWithBalance();return m.setAccountProp("tokenBalance",c,n),m.setAccountProp("lastRetry",void 0,n),m.setAccountProp("balanceLoading",!1,n),c}}catch(c){m.setAccountProp("lastRetry",Date.now(),n),t==null||t(c),vs.showError("Token Balance Unavailable")}finally{m.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(t){var c;const e=t.chainNamespace,s=!!((c=m.getAccountData(e))!=null&&c.caipAddress),n=m.getAllApprovedCaipNetworkIds(),r=m.getNetworkProp("supportsAllNetworks",e)!==!1,i=q.getConnectorId(e),o=q.getAuthConnector(),a=i===U.CONNECTOR_ID.AUTH&&o;return!s||r||a?!1:!(n!=null&&n.includes(t.caipNetworkId))}},m=ns(ep),sw={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){var h,p;const s=m.state.activeCaipNetwork,n=m.state.activeChain,r=ne.state.data;if(t.id===(s==null?void 0:s.id))return;const o=!!((h=m.getAccountData(n))!=null&&h.address),a=!!((p=m.getAccountData(t.chainNamespace))!=null&&p.address),c=t.chainNamespace!==n,d=q.getConnectorId(n)===U.CONNECTOR_ID.AUTH,u=U.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(g=>g===t.chainNamespace);e||d&&u?ne.push("SwitchNetwork",{...r,network:t}):o&&c&&!a?ne.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):ne.push("SwitchNetwork",{...r,network:t})}},Ct=ke({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),nw={state:Ct,subscribe(t){return st(Ct,()=>t(Ct))},subscribeKey(t,e){return nt(Ct,t,e)},async open(t){var o,a;const e=t==null?void 0:t.namespace,s=m.state.activeChain,n=e&&e!==s,r=(o=m.getAccountData(t==null?void 0:t.namespace))==null?void 0:o.caipAddress,i=m.state.noAdapters;if(z.state.wcBasic?Q.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await Q.prefetch(),q.setFilterByNamespace(t==null?void 0:t.namespace),pe.setLoading(!0,e),e&&n){const c=((a=m.getNetworkData(e))==null?void 0:a.caipNetwork)||m.getRequestedCaipNetworks(e)[0];c&&(i?(await m.switchActiveNetwork(c),ne.push("ConnectingWalletConnectBasic")):sw.onSwitchNetwork({network:c,ignoreSwitchConfirmation:!0}))}else k.state.manualWCControl||i&&!r?J.isMobile()?ne.reset("AllWallets"):ne.reset("ConnectingWalletConnectBasic"):t!=null&&t.view?ne.reset(t.view,t.data):r?ne.reset("Account"):ne.reset("Connect");Ct.open=!0,Ws.set({open:!0}),he.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!r}})},close(){const t=k.state.enableEmbedded,e=!!m.state.activeCaipAddress;Ct.open&&he.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),Ct.open=!1,ne.reset("Connect"),pe.clearLoading(),t?e?ne.replace("Account"):ne.push("Connect"):Ws.set({open:!1}),z.resetUri()},setLoading(t,e){e&&Ct.loadingNamespaceMap.set(e,t),Ct.loading=t,Ws.set({loading:t})},clearLoading(){Ct.loadingNamespaceMap.clear(),Ct.loading=!1,Ws.set({loading:!1})},shake(){Ct.shake||(Ct.shake=!0,setTimeout(()=>{Ct.shake=!1},500))}},pe=ns(nw),ci={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"}]},yc={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},rw={providers:Gh,selectedProvider:null,error:null,purchaseCurrency:ci,paymentCurrency:yc,purchaseCurrencies:[ci],paymentCurrencies:[],quotesLoading:!1},be=ke(rw),iw={state:be,subscribe(t){return st(be,()=>t(be))},subscribeKey(t,e){return nt(be,t,e)},setSelectedProvider(t){var e,s;if(t&&t.name==="meld"){const n=m.state.activeChain,r=n===U.CHAIN.SOLANA?"SOL":"USDC",i=n?((s=(e=m.state.chains.get(n))==null?void 0:e.accountState)==null?void 0:s.address)??"":"",o=new URL(t.url);o.searchParams.append("publicKey",Nm),o.searchParams.append("destinationCurrencyCode",r),o.searchParams.append("walletAddress",i),o.searchParams.append("externalCustomerId",k.state.projectId),be.selectedProvider={...t,url:o.toString()}}else be.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=Gh.filter(n=>e.includes(n.name));be.providers=s}else be.providers=[]},setPurchaseCurrency(t){be.purchaseCurrency=t},setPaymentCurrency(t){be.paymentCurrency=t},setPurchaseAmount(t){bc.state.purchaseAmount=t},setPaymentAmount(t){bc.state.paymentAmount=t},async getAvailableCurrencies(){const t=await re.getOnrampOptions();be.purchaseCurrencies=t.purchaseCurrencies,be.paymentCurrencies=t.paymentCurrencies,be.paymentCurrency=t.paymentCurrencies[0]||yc,be.purchaseCurrency=t.purchaseCurrencies[0]||ci,await Q.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await Q.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){var t,e;be.quotesLoading=!0;try{const s=await re.getOnrampQuote({purchaseCurrency:be.purchaseCurrency,paymentCurrency:be.paymentCurrency,amount:((t=be.paymentAmount)==null?void 0:t.toString())||"0",network:(e=be.purchaseCurrency)==null?void 0:e.symbol});return be.quotesLoading=!1,be.purchaseAmount=Number(s==null?void 0:s.purchaseAmount.amount),s}catch(s){return be.error=s.message,be.quotesLoading=!1,null}finally{be.quotesLoading=!1}},resetState(){be.selectedProvider=null,be.error=null,be.purchaseCurrency=ci,be.paymentCurrency=yc,be.purchaseCurrencies=[ci],be.paymentCurrencies=[],be.paymentAmount=void 0,be.purchaseAmount=void 0,be.quotesLoading=!1}},bc=ns(iw);var Yo={exports:{}};function ow(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var aw=cw;function cw(t,e,s){var n=s&&s.stringify||ow,r=1;if(typeof t=="object"&&t!==null){var i=e.length+r;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var l="",d=1-r,u=-1,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(u=u>-1?u:0,t.charCodeAt(p+1)){case 100:case 102:if(d>=c||e[d]==null)break;u<p&&(l+=t.slice(u,p)),l+=Number(e[d]),u=p+2,p++;break;case 105:if(d>=c||e[d]==null)break;u<p&&(l+=t.slice(u,p)),l+=Math.floor(Number(e[d])),u=p+2,p++;break;case 79:case 111:case 106:if(d>=c||e[d]===void 0)break;u<p&&(l+=t.slice(u,p));var g=typeof e[d];if(g==="string"){l+="'"+e[d]+"'",u=p+2,p++;break}if(g==="function"){l+=e[d].name||"<anonymous>",u=p+2,p++;break}l+=n(e[d]),u=p+2,p++;break;case 115:if(d>=c)break;u<p&&(l+=t.slice(u,p)),l+=String(e[d]),u=p+2,p++;break;case 37:u<p&&(l+=t.slice(u,p)),l+="%",u=p+2,p++,d--;break}++d}++p}return u===-1?t:(u<h&&(l+=t.slice(u)),l)}const sd=aw;Yo.exports=Ys;const bi=Aw().console||{},lw={mapHttpRequest:Vi,mapHttpResponse:Vi,wrapRequestSerializer:Ca,wrapResponseSerializer:Ca,wrapErrorSerializer:Ca,req:Vi,res:Vi,err:rd,errWithCause:rd};function bn(t,e){return t==="silent"?1/0:e.levels.values[t]}const hl=Symbol("pino.logFuncs"),Ec=Symbol("pino.hierarchy"),dw={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function nd(t,e){const s={logger:e,parent:t[Ec]};e[Ec]=s}function uw(t,e,s){const n={};e.forEach(r=>{n[r]=s[r]?s[r]:bi[r]||bi[dw[r]||"log"]||Ir}),t[hl]=n}function hw(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Ys(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const s=t.browser.write||bi;t.browser.write&&(t.browser.asObject=!0);const n=t.serializers||{},r=hw(t.browser.serialize,n);let i=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(i=!1);const o=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof s=="function"&&a.forEach(function(f){s[f]=s}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",l=Object.create(s);l.log||(l.log=Ir),uw(l,a,s),nd({},l),Object.defineProperty(l,"levelVal",{get:u}),Object.defineProperty(l,"level",{get:h,set:p});const d={transmit:e,serialize:r,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:Ew(t),messageKey:t.messageKey||"msg",onChild:t.onChild||Ir};l.levels=pw(t),l.level=c,l.isLevelEnabled=function(f){return this.levels.values[f]?this.levels.values[f]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=Ir,l.serializers=n,l._serialize=r,l._stdErrSerialize=i,l.child=function(...f){return g.call(this,d,...f)},e&&(l._logEvent=Cc());function u(){return bn(this.level,this)}function h(){return this._level}function p(f){if(f!=="silent"&&!this.levels.values[f])throw Error("unknown level "+f);this._level=f,Rn(this,d,l,"error"),Rn(this,d,l,"fatal"),Rn(this,d,l,"warn"),Rn(this,d,l,"info"),Rn(this,d,l,"debug"),Rn(this,d,l,"trace"),o.forEach(w=>{Rn(this,d,l,w)})}function g(f,w,E){if(!w)throw new Error("missing bindings for child Pino");E=E||{},r&&w.serializers&&(E.serializers=w.serializers);const I=E.serializers;if(r&&I){var _=Object.assign({},n,I),v=t.browser.serialize===!0?Object.keys(_):r;delete w.serializers,pl([w],v,_,this._stdErrSerialize)}function T(D){this._childLevel=(D._childLevel|0)+1,this.bindings=w,_&&(this.serializers=_,this._serialize=v),e&&(this._logEvent=Cc([].concat(D._logEvent.bindings,w)))}T.prototype=this;const P=new T(this);return nd(this,P),P.child=function(...D){return g.call(this,f,...D)},P.level=E.level||this.level,f.onChild(P),P}return l}function pw(t){const e=t.customLevels||{},s=Object.assign({},Ys.levels.values,e),n=Object.assign({},Ys.levels.labels,fw(e));return{values:s,labels:n}}function fw(t){const e={};return Object.keys(t).forEach(function(s){e[t[s]]=s}),e}Ys.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};Ys.stdSerializers=lw;Ys.stdTimeFunctions=Object.assign({},{nullTime:tp,epochTime:sp,unixTime:Cw,isoTime:vw});function gw(t){const e=[];t.bindings&&e.push(t.bindings);let s=t[Ec];for(;s.parent;)s=s.parent,s.logger.bindings&&e.push(s.logger.bindings);return e.reverse()}function Rn(t,e,s,n){if(Object.defineProperty(t,n,{value:bn(t.level,s)>bn(n,s)?Ir:s[hl][n],writable:!0,enumerable:!0,configurable:!0}),t[n]===Ir){if(!e.transmit)return;const i=e.transmit.level||t.level,o=bn(i,s);if(bn(n,s)<o)return}t[n]=ww(t,e,s,n);const r=gw(t);r.length!==0&&(t[n]=mw(r,t[n]))}function mw(t,e){return function(){return e.apply(this,[...t,...arguments])}}function ww(t,e,s,n){return function(r){return function(){const o=e.timestamp(),a=new Array(arguments.length),c=Object.getPrototypeOf&&Object.getPrototypeOf(this)===bi?bi:this;for(var l=0;l<a.length;l++)a[l]=arguments[l];var d=!1;if(e.serialize&&(pl(a,this._serialize,this.serializers,this._stdErrSerialize),d=!0),e.asObject||e.formatters?r.call(c,...yw(this,n,a,o,e)):r.apply(c,a),e.transmit){const u=e.transmit.level||t._level,h=bn(u,s),p=bn(n,s);if(p<h)return;bw(this,{ts:o,methodLevel:n,methodValue:p,transmitLevel:u,transmitValue:s.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:bn(t._level,s)},a,d)}}}(t[hl][n])}function yw(t,e,s,n,r){const{level:i,log:o=u=>u}=r.formatters||{},a=s.slice();let c=a[0];const l={};let d=(t._childLevel|0)+1;if(d<1&&(d=1),n&&(l.time=n),i){const u=i(e,t.levels.values[e]);Object.assign(l,u)}else l.level=t.levels.values[e];if(r.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;d--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;d--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?sd(a.shift(),a):void 0}else typeof c=="string"&&(c=sd(a.shift(),a));return c!==void 0&&(l[r.messageKey]=c),[o(l)]}}function pl(t,e,s,n){for(const r in t)if(n&&t[r]instanceof Error)t[r]=Ys.stdSerializers.err(t[r]);else if(typeof t[r]=="object"&&!Array.isArray(t[r])&&e)for(const i in t[r])e.indexOf(i)>-1&&i in s&&(t[r][i]=s[i](t[r][i]))}function bw(t,e,s,n=!1){const r=e.send,i=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,l=t._logEvent.bindings;n||pl(s,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=s.filter(function(d){return l.indexOf(d)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,r(o,t._logEvent,c),t._logEvent=Cc(l)}function Cc(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function rd(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const s in t)e[s]===void 0&&(e[s]=t[s]);return e}function Ew(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?tp:sp}function Vi(){return{}}function Ca(t){return t}function Ir(){}function tp(){return!1}function sp(){return Date.now()}function Cw(){return Math.round(Date.now()/1e3)}function vw(){return new Date(Date.now()).toISOString()}function Aw(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}Yo.exports.default=Ys;Yo.exports.pino=Ys;var us=Yo.exports;const Jo=Bh(us),id=2147483648,_w={convertEVMChainIdToCoinType(t){if(t>=id)throw new Error("Invalid chainId");return(id|t)>>>0}},qt=ke({suggestions:[],loading:!1}),Iw={state:qt,subscribe(t){return st(qt,()=>t(qt))},subscribeKey(t,e){return nt(qt,t,e)},async resolveName(t){var e,s;try{return await re.lookupEnsName(t)}catch(n){const r=n;throw new Error(((s=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:s.description)||"Error resolving name")}},async isNameRegistered(t){try{return await re.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{qt.loading=!0,qt.suggestions=[];const e=await re.getEnsNameSuggestions(t);return qt.suggestions=e.suggestions||[],qt.suggestions}catch(e){const s=li.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{qt.loading=!1}},async getNamesForAddress(t){try{if(!m.state.activeCaipNetwork)return[];const s=B.getEnsFromCacheForAddress(t);if(s)return s;const n=await re.reverseLookupEnsName({address:t});return B.updateEnsCache({address:t,ens:n,timestamp:Date.now()}),n}catch(e){const s=li.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){var r;const e=m.state.activeCaipNetwork,s=(r=m.getAccountData(e==null?void 0:e.chainNamespace))==null?void 0:r.address,n=q.getAuthConnector();if(!e)throw new Error("Network not found");if(!s||!n)throw new Error("Address or auth connector not found");qt.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});ne.pushTransactionStack({onCancel(){ne.replace("RegisterAccountName")}});const o=await z.signMessage(i);qt.loading=!1;const a=e.id;if(!a)throw new Error("Network not found");const c=_w.convertEVMChainIdToCoinType(Number(a));await re.registerEnsName({coinType:c,address:s,signature:o,message:i}),m.setAccountProp("profileName",t,e.chainNamespace),B.updateEnsCache({address:s,ens:[{name:t,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),ne.replace("RegisterAccountNameSuccess")}catch(i){const o=li.parseEnsApiError(i,`Error registering name ${t}`);throw ne.replace("RegisterAccountName"),new Error(o)}finally{qt.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){var n,r;const s=t;return((r=(n=s==null?void 0:s.reasons)==null?void 0:n[0])==null?void 0:r.description)||e}},li=ns(Iw),Sw={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"]},En={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace(t){return Sw[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const s={...t},n=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>n.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>n.add(r)),e.events&&Object.keys(e.events).forEach(r=>n.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[i]=r.split(":");i&&n.add(i)}),n.forEach(r=>{s[r]||(s[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,i])=>{s[r]&&(s[r].methods=i)}),e.chains&&Object.entries(e.chains).forEach(([r,i])=>{s[r]&&(s[r].chains=i)}),e.events&&Object.entries(e.events).forEach(([r,i])=>{s[r]&&(s[r].events=i)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([i,o])=>{const[a,c]=i.split(":");!a||!c||!s[a]||(s[a].rpcMap||(s[a].rpcMap={}),r.has(a)||(s[a].rpcMap={},r.add(a)),s[a].rpcMap[c]=o)})}return s},createNamespaces(t,e){const s=t.reduce((n,r)=>{const{id:i,chainNamespace:o,rpcUrls:a}=r,c=a.default.http[0];n[o]||(n[o]=this.createDefaultNamespace(o));const l=`${o}:${i}`,d=n[o];switch(d.chains.push(l),l){case"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":d.chains.push("solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ");break;case"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":d.chains.push("solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K");break}return d!=null&&d.rpcMap&&c&&(d.rpcMap[i]=c),n},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{var n;const e=await li.resolveName(t);return((n=(Object.values(e==null?void 0:e.addresses)||[])[0])==null?void 0:n.address)||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],n=e.accounts.map(r=>{const[i,o]=r.split(":");return`${i}:${o}`});return Array.from(new Set([...s,...n]))})},isSessionEventData(t){return typeof t=="object"&&t!==null&&"id"in t&&"topic"in t&&"params"in t&&typeof t.params=="object"&&t.params!==null&&"chainId"in t.params&&"event"in t.params&&typeof t.params.event=="object"&&t.params.event!==null},isUserRejectedRequestError(t){try{if(typeof t=="object"&&t!==null){const e=t,s=typeof e.code=="number",n=s&&e.code===En.RPC_ERROR_CODE.USER_REJECTED_METHODS,r=s&&e.code===En.RPC_ERROR_CODE.USER_REJECTED;return n||r}return!1}catch{return!1}},isOriginAllowed(t,e,s){for(const n of[...e,...s])if(n.includes("*")){const i=`^${n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(i,"u").test(t))return!0}else try{if(new URL(n).origin===t)return!0}catch{if(n===t)return!0}return!1},listenWcProvider({universalProvider:t,namespace:e,onConnect:s,onDisconnect:n,onAccountsChanged:r,onChainChanged:i,onDisplayUri:o}){s&&t.on("connect",()=>{const a=En.getWalletConnectAccounts(t,e);s(a)}),n&&t.on("disconnect",()=>{n()}),r&&t.on("accountsChanged",a=>{var c,l,d,u,h;try{const p=((d=(l=(c=t.session)==null?void 0:c.namespaces)==null?void 0:l[e])==null?void 0:d.accounts)||[],g=(h=(u=t.rpcProviders)==null?void 0:u[e])==null?void 0:h.getDefaultChain(),f=a.map(w=>{const E=p.find(v=>v.includes(`${e}:${g}:${w}`));if(!E)return;const{chainId:I,chainNamespace:_}=tt.parseCaipAddress(E);return{address:w,chainId:I,chainNamespace:_}}).filter(w=>w!==void 0);f.length>0&&r(f)}catch(p){console.warn("Failed to parse accounts for namespace on accountsChanged event",e,a,p)}}),i&&t.on("chainChanged",a=>{i(a)}),o&&t.on("display_uri",a=>{o(a)})},getWalletConnectAccounts(t,e){var r,i,o,a;const s=new Set,n=(a=(o=(i=(r=t==null?void 0:t.session)==null?void 0:r.namespaces)==null?void 0:i[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>tt.parseCaipAddress(c)).filter(({address:c})=>s.has(c.toLowerCase())?!1:(s.add(c.toLowerCase()),!0));return n&&n.length>0?n:[]}},Nw=[U.CONNECTOR_ID.AUTH,U.CONNECTOR_ID.WALLET_CONNECT];class Tw{constructor(e){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=s=>m.getCaipNetworks(s),this.getConnectorId=s=>q.getConnectorId(s),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get connections(){return this.availableConnections}get networks(){return this.getCaipNetworks(this.namespace)}onAuthConnected({accounts:e,chainId:s}){const n=this.getCaipNetworks().filter(r=>r.chainNamespace===this.namespace).find(r=>r.id.toString()===(s==null?void 0:s.toString()));e&&n&&this.addConnection({connectorId:U.CONNECTOR_ID.AUTH,accounts:e,caipNetwork:n})}setAuthProvider(e){e.onConnect(this.onAuthConnected.bind(this)),e.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:U.CONNECTOR_ID.AUTH,type:"AUTH",name:U.CONNECTOR_NAMES.AUTH,provider:e,imageId:void 0,chain:this.namespace,chains:[]})}addConnector(...e){const s=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(n=>s.has(n.id)?!1:(s.add(n.id),!0)),this.emit("connectors",this.availableConnectors)}addConnection(...e){const s=new Set;this.availableConnections=[...e,...this.availableConnections].filter(n=>s.has(n.connectorId.toLowerCase())?!1:(s.add(n.connectorId.toLowerCase()),!0)),this.emit("connections",this.availableConnections)}deleteConnection(e){this.availableConnections=this.availableConnections.filter(s=>s.connectorId.toLowerCase()!==e.toLowerCase()),this.emit("connections",this.availableConnections)}clearConnections(e=!1){this.availableConnections=[],e&&this.emit("connections",this.availableConnections)}setStatus(e,s){m.setAccountProp("status",e,s)}on(e,s){var n;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(n=this.eventListeners.get(e))==null||n.add(s)}off(e,s){const n=this.eventListeners.get(e);n&&n.delete(s)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const n=this.eventListeners.get(e);n&&n.forEach(r=>r(s))}async connectWalletConnect(e){try{return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}catch(s){throw En.isUserRejectedRequestError(s)?new zh(s):s}}async switchNetwork(e){var i;const{caipNetwork:s}=e,n=Ue.getProviderId(s.chainNamespace),r=Ue.getProvider(s.chainNamespace);if(!r)throw new Error("Provider not found");if(n==="WALLET_CONNECT"){r.setDefaultChain(s.caipNetworkId);return}if(n==="AUTH"){const o=(i=q.getAuthConnector())==null?void 0:i.provider;if(!o)throw new Error("Auth provider not found");const a=ts(s.chainNamespace);await o.switchNetwork({chainId:s.caipNetworkId});const c=await o.getUser({chainId:s.caipNetworkId,preferredAccountType:a});this.emit("switchNetwork",c)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s.id==="walletConnect");if(!e)throw new Error("WalletConnectConnector not found");return e}onConnect(e,s){if(e.length>0){const{address:n,chainId:r}=J.getAccount(e[0]),i=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===(r==null?void 0:r.toString())),o=this.connectors.find(a=>a.id===s);n&&(this.emit("accountChanged",{address:n,chainId:r,connector:o}),this.addConnection({connectorId:s,accounts:e.map(a=>{const{address:c}=J.getAccount(a);return{address:c}}),caipNetwork:i}))}}onAccountsChanged(e,s,n=!0){var r,i;if(e.length>0){const{address:o}=J.getAccount(e[0]),a=this.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors});o&&((r=this.getConnectorId(U.CHAIN.EVM))==null?void 0:r.toLowerCase())===s.toLowerCase()&&this.emit("accountChanged",{address:o,chainId:(i=a==null?void 0:a.caipNetwork)==null?void 0:i.id,connector:a==null?void 0:a.connector}),this.addConnection({connectorId:s,accounts:e.map(c=>{const{address:l}=J.getAccount(c);return{address:l}}),caipNetwork:a==null?void 0:a.caipNetwork})}else n&&this.onDisconnect(s)}onDisconnect(e){var s;this.removeProviderListeners(e),this.deleteConnection(e),((s=this.getConnectorId(U.CHAIN.EVM))==null?void 0:s.toLowerCase())===e.toLowerCase()&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(e,s){var o;const n=typeof e=="string"&&e.startsWith("0x")?parseInt(e,16).toString():e.toString(),r=this.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors}),i=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===n);r&&this.addConnection({connectorId:s,accounts:r.accounts,caipNetwork:i}),((o=this.getConnectorId(U.CHAIN.EVM))==null?void 0:o.toLowerCase())===s.toLowerCase()&&this.emit("switchNetwork",{chainId:n})}listenProviderEvents(e,s){if(Nw.includes(e))return;const n=o=>this.onAccountsChanged(o,e),r=o=>this.onChainChanged(o,e),i=()=>this.onDisconnect(e);this.providerHandlers[e]||(s.on("disconnect",i),s.on("accountsChanged",n),s.on("chainChanged",r),this.providerHandlers[e]={provider:s,disconnect:i,accountsChanged:n,chainChanged:r})}removeProviderListeners(e){if(this.providerHandlers[e]){const{provider:s,disconnect:n,accountsChanged:r,chainChanged:i}=this.providerHandlers[e];s.removeListener("disconnect",n),s.removeListener("accountsChanged",r),s.removeListener("chainChanged",i),this.providerHandlers[e]=null}}emitFirstAvailableConnection(){var s;const e=this.getConnection({connections:this.connections,connectors:this.connectors});if(e){const[n]=e.accounts;this.emit("accountChanged",{address:n==null?void 0:n.address,chainId:(s=e.caipNetwork)==null?void 0:s.id,connector:e.connector})}}getConnection({address:e,connectorId:s,connections:n,connectors:r}){if(s){const o=n.find(l=>l.connectorId.toLowerCase()===s.toLowerCase());if(!o)return null;const a=r.find(l=>l.id.toLowerCase()===o.connectorId.toLowerCase()),c=e?o.accounts.find(l=>l.address.toLowerCase()===e.toLowerCase()):o.accounts[0];return{...o,account:c,connector:a}}const i=n.find(o=>o.accounts.length>0&&r.some(a=>a.id.toLowerCase()===o.connectorId.toLowerCase()));if(i){const[o]=i.accounts,a=r.find(c=>c.id.toLowerCase()===i.connectorId.toLowerCase());return{...i,account:o,connector:a}}return null}}let Pn=null;const ds={getSIWX(){return k.state.siwx},async initializeIfEnabled(t=m.getActiveCaipAddress()){var i,o,a;const e=k.state.siwx;if(!(e&&t))return;const[s,n,r]=t.split(":");if(m.checkIfSupportedNetwork(s,`${s}:${n}`))try{if((i=k.state.remoteFeatures)!=null&&i.emailCapture){const l=(o=m.getAccountData(s))==null?void 0:o.user;await pe.open({view:"DataCapture",data:{email:(l==null?void 0:l.email)??void 0}});return}if(Pn&&await Pn,(await e.getSessions(`${s}:${n}`,r)).length)return;await pe.open({view:"SIWXSignMessage"})}catch(c){console.error("SIWXUtil:initializeIfEnabled",c),he.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(c)}),await((a=z._getClient())==null?void 0:a.disconnect().catch(console.error)),ne.reset("Connect"),vs.showError("A problem occurred while trying initialize authentication")}},async isAuthenticated(t=m.getActiveCaipAddress()){if(!k.state.siwx||!t)return!0;const{chainNamespace:s,chainId:n,address:r}=tt.parseCaipAddress(t),i=`${s}:${n}`;return(await ds.getSessions({address:r,caipNetworkId:i})).length>0},async requestSignMessage(){const t=k.state.siwx,e=J.getPlainAddress(m.getActiveCaipAddress()),s=Ki(),n=z._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!n)throw new Error("No ConnectionController client found");try{const r=await t.createMessage({chainId:s.caipNetworkId,accountAddress:e}),i=r.toString();q.getConnectorId(s.chainNamespace)===U.CONNECTOR_ID.AUTH&&ne.pushTransactionStack({});const a=await n.signMessage(i);await t.addSession({data:r,message:i,signature:a}),m.setLastConnectedSIWECaipNetwork(s),pe.close(),he.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){(!pe.state.open||ne.state.view==="ApproveTransaction")&&await pe.open({view:"SIWXSignMessage"}),vs.showError("Error signing message"),he.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(r)}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){var t;try{const e=this.getSIWX();if((t=e==null?void 0:e.getRequired)==null?void 0:t.call(e)){const n=m.getLastConnectedSIWECaipNetwork();if(n){const r=await(e==null?void 0:e.getSessions(n==null?void 0:n.caipNetworkId,J.getPlainAddress(m.getActiveCaipAddress())||""));r&&r.length>0?await m.switchActiveNetwork(n):await z.disconnect()}else await z.disconnect()}else pe.close();pe.close(),he.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getAllSessions(){const t=this.getSIWX(),e=m.getAllRequestedCaipNetworks(),s=[];return await Promise.all(e.map(async n=>{const r=await(t==null?void 0:t.getSessions(n.caipNetworkId,J.getPlainAddress(m.getActiveCaipAddress())||""));r&&s.push(...r)})),s},async getSessions(t){const e=k.state.siwx;let s=t==null?void 0:t.address;if(!s){const r=m.getActiveCaipAddress();s=J.getPlainAddress(r)}let n=t==null?void 0:t.caipNetworkId;if(!n){const r=m.getActiveCaipNetwork();n=r==null?void 0:r.caipNetworkId}return e&&s&&n?e.getSessions(n,s):[]},async isSIWXCloseDisabled(){var e;const t=this.getSIWX();if(t){const s=ne.state.view==="ApproveTransaction",n=ne.state.view==="SIWXSignMessage";if(s||n)return((e=t.getRequired)==null?void 0:e.call(t))&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:t,chainId:e,socialUri:s,preferredAccountType:n,chainNamespace:r}){var u;const i=ds.getSIWX(),o=Ki();if(!i||!r.includes(U.CHAIN.EVM)||(u=k.state.remoteFeatures)!=null&&u.emailCapture){const h=await t.connect({chainId:e,socialUri:s,preferredAccountType:n});return{address:h.address,chainId:h.chainId,accounts:h.accounts}}const a=`${r}:${e}`,c=await i.createMessage({chainId:a,accountAddress:"<<AccountAddress>>"}),l={accountAddress:c.accountAddress,chainId:c.chainId,domain:c.domain,uri:c.uri,version:c.version,nonce:c.nonce,notBefore:c.notBefore,statement:c.statement,resources:c.resources,requestId:c.requestId,issuedAt:c.issuedAt,expirationTime:c.expirationTime,serializedMessage:c.toString()},d=await t.connect({chainId:e,socialUri:s,siwxMessage:l,preferredAccountType:n});return l.accountAddress=d.address,l.serializedMessage=d.message||"",d.signature&&d.message&&await ds.addEmbeddedWalletSession(l,d.message,d.signature),m.setLastConnectedSIWECaipNetwork(o),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(t,e,s){if(Pn)return Pn;const n=ds.getSIWX();return n?(Pn=n.addSession({data:t,message:e,signature:s}).finally(()=>{Pn=null}),Pn):Promise.resolve()},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){var l,d,u;const n=ds.getSIWX(),r=Ki(),i=new Set(e.map(h=>h.split(":")[0]));if(!n||i.size!==1||!i.has("eip155"))return!1;const o=await n.createMessage({chainId:((l=Ki())==null?void 0:l.caipNetworkId)||"",accountAddress:""}),a=await t.authenticate({nonce:o.nonce,domain:o.domain,uri:o.uri,exp:o.expirationTime,iat:o.issuedAt,nbf:o.notBefore,requestId:o.requestId,version:o.version,resources:o.resources,statement:o.statement,chainId:o.chainId,methods:s,chains:[o.chainId,...e.filter(h=>h!==o.chainId)]});vs.showLoading("Authenticating...",{autoClose:!1});const c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:(d=a.session.peer.metadata.icons)==null?void 0:d[0],type:"WALLET_CONNECT"};if(m.setAccountProp("connectedWalletInfo",c,Array.from(i)[0]),(u=a==null?void 0:a.auths)!=null&&u.length){const h=a.auths.map(p=>{const g=t.client.formatAuthMessage({request:p.p,iss:p.p.iss});return{data:{...p.p,accountAddress:p.p.iss.split(":").slice(-1).join(""),chainId:p.p.iss.split(":").slice(2,4).join(":"),uri:p.p.aud,version:p.p.version||o.version,expirationTime:p.p.exp,issuedAt:p.p.iat,notBefore:p.p.nbf},message:g,signature:p.s.s,cacao:p}});try{await n.setSessions(h),r&&m.setLastConnectedSIWECaipNetwork(r),he.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:ds.getSIWXEventProperties()})}catch(p){throw console.error("SIWX:universalProviderAuth - failed to set sessions",p),he.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:ds.getSIWXEventProperties(p)}),await t.disconnect().catch(console.error),p}finally{vs.hide()}}return!0},getSIWXEventProperties(t){var s;const e=m.state.activeChain;if(!e)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:((s=m.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||"",isSmartAccount:ts(e)===Qt.ACCOUNT_TYPES.SMART_ACCOUNT,message:t?J.parseError(t):void 0}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};class Ow{constructor({provider:e,namespace:s}){this.id=U.CONNECTOR_ID.WALLET_CONNECT,this.name="WalletConnect",this.type="WALLET_CONNECT",this.imageId="ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",this.getCaipNetworks=m.getCaipNetworks.bind(m),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=s}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const s=this.getCaipNetworks(),n=k.state.universalProviderConfigOverride,r=En.createNamespaces(s,n);await this.provider.connect({optionalNamespaces:r})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(s=>s.caipNetworkId);return ds.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:Rw})}}const Rw=["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"],rs=ke({message:"",variant:"info",open:!1}),Pw={state:rs,subscribeKey(t,e){return nt(rs,t,e)},open(t,e){const{debug:s}=k.state,{code:n,displayMessage:r,debugMessage:i}=t;r&&s&&(rs.message=r,rs.variant=e,rs.open=!0),i&&console.error(typeof i=="function"?i():i,n?{code:n}:void 0)},warn(t,e,s){rs.open=!0,rs.message=t,rs.variant="warning",e&&console.warn(e,s)},close(){rs.open=!1,rs.message="",rs.variant="info"}},$t=ns(Pw),xw={network:"eip155:8453",asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},kw={network:"eip155:84532",asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}};function $w(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Ye(t,...e){try{return $w(t(...e))}catch(s){return Promise.reject(s)}}function Uw(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function Dw(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function go(t){if(Uw(t))return String(t);if(Dw(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return go(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const vc="base64:";function Lw(t){return typeof t=="string"?t:vc+Fw(t)}function Bw(t){return typeof t!="string"||!t.startsWith(vc)?t:Mw(t.slice(vc.length))}function Mw(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function Fw(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function At(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function jw(...t){return At(t.join(":"))}function Gi(t){return t=At(t),t?t+":":""}function qw(t,e){if(e===void 0)return!0;let s=0,n=t.indexOf(":");for(;n>-1;)s++,n=t.indexOf(":",n+1);return s<=e}function Ww(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const Hw="memory",Kw=()=>{const t=new Map;return{name:Hw,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,s){t.set(e,s)},setItemRaw(e,s){t.set(e,s)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function zw(t={}){const e={mounts:{"":t.driver||Kw()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},s=l=>{for(const d of e.mountpoints)if(l.startsWith(d))return{base:d,relativeKey:l.slice(d.length),driver:e.mounts[d]};return{base:"",relativeKey:l,driver:e.mounts[""]}},n=(l,d)=>e.mountpoints.filter(u=>u.startsWith(l)||d&&l.startsWith(u)).map(u=>({relativeBase:l.length>u.length?l.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(l,d)=>{if(e.watching){d=At(d);for(const u of e.watchListeners)u(l,d)}},i=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await od(e.mounts[l],r,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,d,u)=>{const h=new Map,p=g=>{let f=h.get(g.base);return f||(f={driver:g.driver,base:g.base,items:[]},h.set(g.base,f)),f};for(const g of l){const f=typeof g=="string",w=At(f?g:g.key),E=f?void 0:g.value,I=f||!g.options?d:{...d,...g.options},_=s(w);p(_).items.push({key:w,value:E,relativeKey:_.relativeKey,options:I})}return Promise.all([...h.values()].map(g=>u(g))).then(g=>g.flat())},c={hasItem(l,d={}){l=At(l);const{relativeKey:u,driver:h}=s(l);return Ye(h.hasItem,u,d)},getItem(l,d={}){l=At(l);const{relativeKey:u,driver:h}=s(l);return Ye(h.getItem,u,d).then(p=>qi(p))},getItems(l,d={}){return a(l,d,u=>u.driver.getItems?Ye(u.driver.getItems,u.items.map(h=>({key:h.relativeKey,options:h.options})),d).then(h=>h.map(p=>({key:jw(u.base,p.key),value:qi(p.value)}))):Promise.all(u.items.map(h=>Ye(u.driver.getItem,h.relativeKey,h.options).then(p=>({key:h.key,value:qi(p)})))))},getItemRaw(l,d={}){l=At(l);const{relativeKey:u,driver:h}=s(l);return h.getItemRaw?Ye(h.getItemRaw,u,d):Ye(h.getItem,u,d).then(p=>Bw(p))},async setItem(l,d,u={}){if(d===void 0)return c.removeItem(l);l=At(l);const{relativeKey:h,driver:p}=s(l);p.setItem&&(await Ye(p.setItem,h,go(d),u),p.watch||r("update",l))},async setItems(l,d){await a(l,d,async u=>{if(u.driver.setItems)return Ye(u.driver.setItems,u.items.map(h=>({key:h.relativeKey,value:go(h.value),options:h.options})),d);u.driver.setItem&&await Promise.all(u.items.map(h=>Ye(u.driver.setItem,h.relativeKey,go(h.value),h.options)))})},async setItemRaw(l,d,u={}){if(d===void 0)return c.removeItem(l,u);l=At(l);const{relativeKey:h,driver:p}=s(l);if(p.setItemRaw)await Ye(p.setItemRaw,h,d,u);else if(p.setItem)await Ye(p.setItem,h,Lw(d),u);else return;p.watch||r("update",l)},async removeItem(l,d={}){typeof d=="boolean"&&(d={removeMeta:d}),l=At(l);const{relativeKey:u,driver:h}=s(l);h.removeItem&&(await Ye(h.removeItem,u,d),(d.removeMeta||d.removeMata)&&await Ye(h.removeItem,u+"$",d),h.watch||r("remove",l))},async getMeta(l,d={}){typeof d=="boolean"&&(d={nativeOnly:d}),l=At(l);const{relativeKey:u,driver:h}=s(l),p=Object.create(null);if(h.getMeta&&Object.assign(p,await Ye(h.getMeta,u,d)),!d.nativeOnly){const g=await Ye(h.getItem,u+"$",d).then(f=>qi(f));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(p,g))}return p},setMeta(l,d,u={}){return this.setItem(l+"$",d,u)},removeMeta(l,d={}){return this.removeItem(l+"$",d)},async getKeys(l,d={}){var w;l=Gi(l);const u=n(l,!0);let h=[];const p=[];let g=!0;for(const E of u){(w=E.driver.flags)!=null&&w.maxDepth||(g=!1);const I=await Ye(E.driver.getKeys,E.relativeBase,d);for(const _ of I){const v=E.mountpoint+At(_);h.some(T=>v.startsWith(T))||p.push(v)}h=[E.mountpoint,...h.filter(_=>!_.startsWith(E.mountpoint))]}const f=d.maxDepth!==void 0&&!g;return p.filter(E=>(!f||qw(E,d.maxDepth))&&Ww(E,l))},async clear(l,d={}){l=Gi(l),await Promise.all(n(l,!1).map(async u=>{if(u.driver.clear)return Ye(u.driver.clear,u.relativeBase,d);if(u.driver.removeItem){const h=await u.driver.getKeys(u.relativeBase||"",d);return Promise.all(h.map(p=>u.driver.removeItem(p,d)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>ad(l)))},async watch(l){return await i(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(d=>d!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,d){if(l=Gi(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((u,h)=>h.length-u.length)),e.mounts[l]=d,e.watching&&Promise.resolve(od(d,r,l)).then(u=>{e.unwatch[l]=u}).catch(console.error),c},async unmount(l,d=!0){var u,h;l=Gi(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&((h=(u=e.unwatch)[l])==null||h.call(u),delete e.unwatch[l]),d&&await ad(e.mounts[l]),e.mountpoints=e.mountpoints.filter(p=>p!==l),delete e.mounts[l])},getMount(l=""){l=At(l)+":";const d=s(l);return{driver:d.driver,base:d.base}},getMounts(l="",d={}){return l=At(l),n(l,d.parents).map(h=>({driver:h.driver,base:h.mountpoint}))},keys:(l,d={})=>c.getKeys(l,d),get:(l,d={})=>c.getItem(l,d),set:(l,d,u={})=>c.setItem(l,d,u),has:(l,d={})=>c.hasItem(l,d),del:(l,d={})=>c.removeItem(l,d),remove:(l,d={})=>c.removeItem(l,d)};return c}function od(t,e,s){return t.watch?t.watch((n,r)=>e(n,s+r)):()=>{}}async function ad(t){typeof t.dispose=="function"&&await Ye(t.dispose)}const Vw="idb-keyval";var Gw=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",s=r=>e+r;let n;return t.dbName&&t.storeName&&(n=$g(t.dbName,t.storeName)),{name:Vw,options:t,async hasItem(r){return!(typeof await Kl(s(r),n)>"u")},async getItem(r){return await Kl(s(r),n)??null},setItem(r,i){return Ug(s(r),i,n)},removeItem(r){return Dg(s(r),n)},getKeys(){return Lg(n)},clear(){return Bg(n)}}};const Yw="WALLET_CONNECT_V2_INDEXED_DB",Jw="keyvaluestorage";let Xw=class{constructor(){this.indexedDb=zw({driver:Gw({dbName:Yw,storeName:Jw})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const s=await this.indexedDb.getItem(e);if(s!==null)return s}async setItem(e,s){await this.indexedDb.setItem(e,Xn(s))}async removeItem(e){await this.indexedDb.removeItem(e)}};var va=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof de<"u"?de:typeof self<"u"?self:{},mo={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(s){return this.hasOwnProperty(s)?String(this[s]):null},t.prototype.setItem=function(s,n){this[s]=String(n)},t.prototype.removeItem=function(s){delete this[s]},t.prototype.clear=function(){const s=this;Object.keys(s).forEach(function(n){s[n]=void 0,delete s[n]})},t.prototype.key=function(s){return s=s||0,Object.keys(this)[s]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof va<"u"&&va.localStorage?mo.exports=va.localStorage:typeof window<"u"&&window.localStorage?mo.exports=window.localStorage:mo.exports=new e})();function Zw(t){var e;return[t[0],_o((e=t[1])!=null?e:"")]}let Qw=class{constructor(){this.localStorage=mo.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Zw)}async getItem(e){const s=this.localStorage.getItem(e);if(s!==null)return _o(s)}async setItem(e,s){this.localStorage.setItem(e,Xn(s))}async removeItem(e){this.localStorage.removeItem(e)}};const ey="wc_storage_version",cd=1,ty=async(t,e,s)=>{const n=ey,r=await e.getItem(n);if(r&&r>=cd){s(e);return}const i=await t.getKeys();if(!i.length){s(e);return}const o=[];for(;i.length;){const a=i.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(n,cd),s(e),sy(t,o)},sy=async(t,e)=>{e.length&&e.forEach(async s=>{await t.removeItem(s)})};let ny=class{constructor(){this.initialized=!1,this.setInitialized=s=>{this.storage=s,this.initialized=!0};const e=new Qw;this.storage=e;try{const s=new Xw;ty(e,s,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,s){return await this.initialize(),this.storage.setItem(e,s)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const s=setInterval(()=>{this.initialized&&(clearInterval(s),e())},20)})}};const ry={level:"info"},Xo="custom_context",fl=1e3*1024;var iy=Object.defineProperty,oy=(t,e,s)=>e in t?iy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,hn=(t,e,s)=>oy(t,typeof e!="symbol"?e+"":e,s);let ay=class{constructor(e){hn(this,"nodeValue"),hn(this,"sizeInBytes"),hn(this,"next"),this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},ld=class{constructor(e){hn(this,"lengthInNodes"),hn(this,"sizeInBytes"),hn(this,"head"),hn(this,"tail"),hn(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const s=new ay(e);if(s.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${s.size}`);for(;this.size+s.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=s),this.tail=s):(this.head=s,this.tail=s),this.lengthInNodes++,this.sizeInBytes+=s.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let s=this.head;for(;s!==null;)e.push(s.value),s=s.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const s=e.value;return e=e.next,{done:!1,value:s}}}}};var cy=Object.defineProperty,ly=(t,e,s)=>e in t?cy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Yi=(t,e,s)=>ly(t,typeof e!="symbol"?e+"":e,s);let np=class{constructor(e,s=fl){Yi(this,"logs"),Yi(this,"level"),Yi(this,"levelValue"),Yi(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=us.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=s,this.logs=new ld(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,s){s===us.levels.values.error?console.error(e):s===us.levels.values.warn?console.warn(e):s===us.levels.values.debug?console.debug(e):s===us.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Xn({timestamp:new Date().toISOString(),log:e}));const s=typeof e=="string"?JSON.parse(e).level:e.level;s>=this.levelValue&&this.forwardToConsole(e,s)}getLogs(){return this.logs}clearLogs(){this.logs=new ld(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const s=this.getLogArray();return s.push(Xn({extraMetadata:e})),new Blob(s,{type:"application/json"})}};var dy=Object.defineProperty,uy=(t,e,s)=>e in t?dy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,hy=(t,e,s)=>uy(t,typeof e!="symbol"?e+"":e,s);let py=class{constructor(e,s=fl){hy(this,"baseChunkLogger"),this.baseChunkLogger=new np(e,s)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const s=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=s,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}};var fy=Object.defineProperty,gy=(t,e,s)=>e in t?fy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,my=(t,e,s)=>gy(t,typeof e!="symbol"?e+"":e,s);let wy=class{constructor(e,s=fl){my(this,"baseChunkLogger"),this.baseChunkLogger=new np(e,s)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var yy=Object.defineProperty,by=Object.defineProperties,Ey=Object.getOwnPropertyDescriptors,dd=Object.getOwnPropertySymbols,Cy=Object.prototype.hasOwnProperty,vy=Object.prototype.propertyIsEnumerable,ud=(t,e,s)=>e in t?yy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,To=(t,e)=>{for(var s in e||(e={}))Cy.call(e,s)&&ud(t,s,e[s]);if(dd)for(var s of dd(e))vy.call(e,s)&&ud(t,s,e[s]);return t},Oo=(t,e)=>by(t,Ey(e));function Ay(t){return Oo(To({},t),{level:(t==null?void 0:t.level)||ry.level})}function _y(t,e,s=Xo){return t[s]=e,t}function Pt(t,e=Xo){return t[e]||""}function Iy(t,e,s=Xo){const n=Pt(t,s);return n.trim()?`${n}/${e}`:e}function Ft(t,e,s=Xo){const n=Iy(t,e,s),r=t.child({context:n});return _y(r,n,s)}function Sy(t){var e,s;const n=new py((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Jo(Oo(To({},t.opts),{level:"trace",browser:Oo(To({},(s=t.opts)==null?void 0:s.browser),{write:r=>n.write(r)})})),chunkLoggerController:n}}function Ny(t){var e;const s=new wy((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Jo(Oo(To({},t.opts),{level:"trace"}),s),chunkLoggerController:s}}function rp(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Sy(t):Ny(t)}var Ty=Object.defineProperty,Oy=(t,e,s)=>e in t?Ty(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,hd=(t,e,s)=>Oy(t,typeof e!="symbol"?e+"":e,s);let Ry=class extends Mr{constructor(e){super(),this.opts=e,hd(this,"protocol","wc"),hd(this,"version",2)}};var Py=Object.defineProperty,xy=(t,e,s)=>e in t?Py(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ky=(t,e,s)=>xy(t,typeof e!="symbol"?e+"":e,s);let $y=class extends Mr{constructor(e,s){super(),this.core=e,this.logger=s,ky(this,"records",new Map)}},Uy=class{constructor(e,s){this.logger=e,this.core=s}},Dy=class extends Mr{constructor(e,s){super(),this.relayer=e,this.logger=s}},Ly=class extends Mr{constructor(e){super()}},By=class{constructor(e,s,n,r){this.core=e,this.logger=s,this.name=n}},My=class extends Mr{constructor(e,s){super(),this.relayer=e,this.logger=s}},Fy=class extends Mr{constructor(e,s){super(),this.core=e,this.logger=s}},jy=class{constructor(e,s,n){this.core=e,this.logger=s,this.store=n}},qy=class{constructor(e,s){this.projectId=e,this.logger=s}},Wy=class{constructor(e,s,n){this.core=e,this.logger=s,this.telemetryEnabled=n}};var Hy=Object.defineProperty,Ky=(t,e,s)=>e in t?Hy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pd=(t,e,s)=>Ky(t,typeof e!="symbol"?e+"":e,s);let zy=class{constructor(e){this.opts=e,pd(this,"protocol","wc"),pd(this,"version",2)}},Vy=class{constructor(e){this.client=e}};const Gy="0.1.1";function Yy(){return Gy}class Le extends Error{constructor(e,s={}){const n=(()=>{var c;if(s.cause instanceof Le){if(s.cause.details)return s.cause.details;if(s.cause.shortMessage)return s.cause.shortMessage}return s.cause&&"details"in s.cause&&typeof s.cause.details=="string"?s.cause.details:(c=s.cause)!=null&&c.message?s.cause.message:s.details})(),r=(()=>s.cause instanceof Le&&s.cause.docsPath||s.docsPath)(),o=`https://oxlib.sh${r??""}`,a=[e||"An error occurred.",...s.metaMessages?["",...s.metaMessages]:[],...n||r?["",n?`Details: ${n}`:void 0,r?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
6
|
-
`);super(a,s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Yy()}`}),this.cause=s.cause,this.details=n,this.docs=o,this.docsPath=r,this.shortMessage=e}walk(e){return ip(this,e)}}function ip(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?ip(t.cause,e):e?null:t}const hr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Jy(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ei(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function er(t,...e){if(!Jy(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Xy(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ei(t.outputLen),Ei(t.blockLen)}function kr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function op(t,e){er(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Zy(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function $r(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Aa(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function fs(t,e){return t<<32-e|t>>>e}const Qy=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function e0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function t0(t){for(let e=0;e<t.length;e++)t[e]=e0(t[e]);return t}const fd=Qy?t=>t:t0;function s0(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Zo(t){return typeof t=="string"&&(t=s0(t)),er(t),t}function n0(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];er(r),e+=r.length}const s=new Uint8Array(e);for(let n=0,r=0;n<t.length;n++){const i=t[n];s.set(i,r),r+=i.length}return s}class gl{}function ap(t){const e=n=>t().update(Zo(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function r0(t=32){if(hr&&typeof hr.getRandomValues=="function")return hr.getRandomValues(new Uint8Array(t));if(hr&&typeof hr.randomBytes=="function")return Uint8Array.from(hr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function i0(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function o0(t,e,s){return t&e^~t&s}function a0(t,e,s){return t&e^t&s^e&s}class c0 extends gl{constructor(e,s,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=s,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Aa(this.buffer)}update(e){kr(this),e=Zo(e),er(e);const{view:s,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(r-this.pos,i-o);if(a===r){const c=Aa(e);for(;r<=i-o;o+=r)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){kr(this),op(e,this),this.finished=!0;const{buffer:s,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,$r(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)s[u]=0;i0(n,r-8,BigInt(this.length*8),i),this.process(n,0);const a=Aa(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=a,r%s&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const en=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ji=BigInt(2**32-1),gd=BigInt(32);function l0(t,e=!1){return e?{h:Number(t&Ji),l:Number(t>>gd&Ji)}:{h:Number(t>>gd&Ji)|0,l:Number(t&Ji)|0}}function d0(t,e=!1){const s=t.length;let n=new Uint32Array(s),r=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=l0(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const u0=(t,e,s)=>t<<s|e>>>32-s,h0=(t,e,s)=>e<<s|t>>>32-s,p0=(t,e,s)=>e<<s-32|t>>>64-s,f0=(t,e,s)=>t<<s-32|e>>>64-s,g0=BigInt(0),zr=BigInt(1),m0=BigInt(2),w0=BigInt(7),y0=BigInt(256),b0=BigInt(113),cp=[],lp=[],dp=[];for(let t=0,e=zr,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],cp.push(2*(5*n+s)),lp.push((t+1)*(t+2)/2%64);let r=g0;for(let i=0;i<7;i++)e=(e<<zr^(e>>w0)*b0)%y0,e&m0&&(r^=zr<<(zr<<BigInt(i))-zr);dp.push(r)}const up=d0(dp,!0),E0=up[0],C0=up[1],md=(t,e,s)=>s>32?p0(t,e,s):u0(t,e,s),wd=(t,e,s)=>s>32?f0(t,e,s):h0(t,e,s);function v0(t,e=24){const s=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],d=s[c+1],u=md(l,d,1)^s[a],h=wd(l,d,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=lp[o],c=md(r,i,a),l=wd(r,i,a),d=cp[o];r=t[d],i=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=E0[n],t[1]^=C0[n]}$r(s)}class ml extends gl{constructor(e,s,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=s,this.outputLen=n,this.enableXOF=r,this.rounds=i,Ei(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Zy(this.state)}clone(){return this._cloneInto()}keccak(){fd(this.state32),v0(this.state32,this.rounds),fd(this.state32),this.posOut=0,this.pos=0}update(e){kr(this),e=Zo(e),er(e);const{blockLen:s,state:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:n,blockLen:r}=this;e[n]^=s,s&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){kr(this,!1),er(e),this.finish();const s=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(s.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ei(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(op(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,$r(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new ml(s,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const A0=(t,e,s)=>ap(()=>new ml(e,t,s)),_0=(()=>A0(1,136,256/8))(),I0=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),tn=new Uint32Array(64);class S0 extends c0{constructor(e=32){super(64,e,8,!1),this.A=en[0]|0,this.B=en[1]|0,this.C=en[2]|0,this.D=en[3]|0,this.E=en[4]|0,this.F=en[5]|0,this.G=en[6]|0,this.H=en[7]|0}get(){const{A:e,B:s,C:n,D:r,E:i,F:o,G:a,H:c}=this;return[e,s,n,r,i,o,a,c]}set(e,s,n,r,i,o,a,c){this.A=e|0,this.B=s|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let u=0;u<16;u++,s+=4)tn[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const h=tn[u-15],p=tn[u-2],g=fs(h,7)^fs(h,18)^h>>>3,f=fs(p,17)^fs(p,19)^p>>>10;tn[u]=f+tn[u-7]+g+tn[u-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=fs(a,6)^fs(a,11)^fs(a,25),p=d+h+o0(a,c,l)+I0[u]+tn[u]|0,f=(fs(n,2)^fs(n,13)^fs(n,22))+a0(n,r,i)|0;d=l,l=c,c=a,a=o+p|0,o=i,i=r,r=n,n=p+f|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,r,i,o,a,c,l,d)}roundClean(){$r(tn)}destroy(){this.set(0,0,0,0,0,0,0,0),$r(this.buffer)}}const N0=ap(()=>new S0);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wl=BigInt(0),Ac=BigInt(1);function ki(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function yl(t){if(!ki(t))throw new Error("Uint8Array expected")}function Ci(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Xi(t){const e=t.toString(16);return e.length&1?"0"+e:e}function hp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?wl:BigInt("0x"+t)}const pp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",T0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function vi(t){if(yl(t),pp)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=T0[t[s]];return e}const Rs={_0:48,_9:57,A:65,F:70,a:97,f:102};function yd(t){if(t>=Rs._0&&t<=Rs._9)return t-Rs._0;if(t>=Rs.A&&t<=Rs.F)return t-(Rs.A-10);if(t>=Rs.a&&t<=Rs.f)return t-(Rs.a-10)}function Ro(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(pp)return Uint8Array.fromHex(t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=yd(t.charCodeAt(i)),a=yd(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[r]=o*16+a}return n}function Yn(t){return hp(vi(t))}function fp(t){return yl(t),hp(vi(Uint8Array.from(t).reverse()))}function $i(t,e){return Ro(t.toString(16).padStart(e*2,"0"))}function gp(t,e){return $i(t,e).reverse()}function Jt(t,e,s){let n;if(typeof e=="string")try{n=Ro(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(ki(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const r=n.length;if(typeof s=="number"&&r!==s)throw new Error(t+" of length "+s+" expected, got "+r);return n}function Po(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];yl(r),e+=r.length}const s=new Uint8Array(e);for(let n=0,r=0;n<t.length;n++){const i=t[n];s.set(i,r),r+=i.length}return s}const _a=t=>typeof t=="bigint"&&wl<=t;function bl(t,e,s){return _a(t)&&_a(e)&&_a(s)&&e<=t&&t<s}function Sr(t,e,s,n){if(!bl(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function O0(t){let e;for(e=0;t>wl;t>>=Ac,e+=1);return e}const Qo=t=>(Ac<<BigInt(t))-Ac,Ia=t=>new Uint8Array(t),bd=t=>Uint8Array.from(t);function R0(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");let n=Ia(t),r=Ia(t),i=0;const o=()=>{n.fill(1),r.fill(0),i=0},a=(...u)=>s(r,n,...u),c=(u=Ia(0))=>{r=a(bd([0]),u),n=a(),u.length!==0&&(r=a(bd([1]),u),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const h=[];for(;u<e;){n=a();const p=n.slice();h.push(p),u+=n.length}return Po(...h)};return(u,h)=>{o(),c(u);let p;for(;!(p=h(l()));)c();return o(),p}}const P0={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||ki(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function ea(t,e,s={}){const n=(r,i,o)=>{const a=P0[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[r];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(r)+" is invalid. Expected "+i+", got "+c)};for(const[r,i]of Object.entries(e))n(r,i,!1);for(const[r,i]of Object.entries(s))n(r,i,!0);return t}function Ed(t){const e=new WeakMap;return(s,...n)=>{const r=e.get(s);if(r!==void 0)return r;const i=t(s,...n);return e.set(s,i),i}}function x0(t,e){if(_d(t)>e)throw new Q0({givenSize:_d(t),maxSize:e})}const Ps={zero:48,nine:57,A:65,F:70,a:97,f:102};function Cd(t){if(t>=Ps.zero&&t<=Ps.nine)return t-Ps.zero;if(t>=Ps.A&&t<=Ps.F)return t-(Ps.A-10);if(t>=Ps.a&&t<=Ps.f)return t-(Ps.a-10)}function k0(t,e={}){const{dir:s,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new eb({size:t.length,targetSize:n,type:"Bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const o=s==="right";r[o?i:n-i-1]=t[o?i:t.length-i-1]}return r}function mp(t,e){if(_n(t)>e)throw new W0({givenSize:_n(t),maxSize:e})}function $0(t,e){if(typeof e=="number"&&e>0&&e>_n(t)-1)throw new bp({offset:e,position:"start",size:_n(t)})}function U0(t,e,s){if(typeof e=="number"&&typeof s=="number"&&_n(t)!==s-e)throw new bp({offset:s,position:"end",size:_n(t)})}function wp(t,e={}){const{dir:s,size:n=32}=e;if(n===0)return t;const r=t.replace("0x","");if(r.length>n*2)throw new H0({size:Math.ceil(r.length/2),targetSize:n,type:"Hex"});return`0x${r[s==="right"?"padEnd":"padStart"](n*2,"0")}`}const D0="#__bigint";function El(t,e,s){return JSON.stringify(t,(n,r)=>typeof e=="function"?e(n,r):typeof r=="bigint"?r.toString()+D0:r,s)}const L0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function B0(t,e={}){const{strict:s=!1}=e;if(!t)throw new vd(t);if(typeof t!="string")throw new vd(t);if(s&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Ad(t);if(!t.startsWith("0x"))throw new Ad(t)}function M0(...t){return`0x${t.reduce((e,s)=>e+s.replace("0x",""),"")}`}function Cl(t){return t instanceof Uint8Array?xo(t):Array.isArray(t)?xo(new Uint8Array(t)):t}function xo(t,e={}){let s="";for(let r=0;r<t.length;r++)s+=L0[t[r]];const n=`0x${s}`;return typeof e.size=="number"?(mp(n,e.size),yp(n,e.size)):n}function Sa(t,e={}){const{signed:s,size:n}=e,r=BigInt(t);let i;n?s?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&s?-i-1n:0;if(i&&r>i||r<o){const l=typeof t=="bigint"?"n":"";throw new q0({max:i?`${i}${l}`:void 0,min:`${o}${l}`,signed:s,size:n,value:`${t}${l}`})}const c=`0x${(s&&r<0?(1n<<BigInt(n*8))+BigInt(r):r).toString(16)}`;return n?F0(c,n):c}function F0(t,e){return wp(t,{dir:"left",size:e})}function yp(t,e){return wp(t,{dir:"right",size:e})}function Ls(t,e,s,n={}){const{strict:r}=n;$0(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(s??t.length)*2)}`;return r&&U0(i,e,s),i}function _n(t){return Math.ceil((t.length-2)/2)}function j0(t,e={}){const{strict:s=!1}=e;try{return B0(t,{strict:s}),!0}catch{return!1}}class q0 extends Le{constructor({max:e,min:s,signed:n,size:r,value:i}){super(`Number \`${i}\` is not in safe${r?` ${r*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${s}\` to \`${e}\`)`:`(above \`${s}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class vd extends Le{constructor(e){super(`Value \`${typeof e=="object"?El(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Ad extends Le{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}let W0=class extends Le{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed \`${s}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class bp extends Le{constructor({offset:e,position:s,size:n}){super(`Slice ${s==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let H0=class extends Le{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${s}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const K0=new TextEncoder;function z0(t){if(!(t instanceof Uint8Array)){if(!t)throw new Zi(t);if(typeof t!="object")throw new Zi(t);if(!("BYTES_PER_ELEMENT"in t))throw new Zi(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new Zi(t)}}function V0(t){return t instanceof Uint8Array?t:typeof t=="string"?Y0(t):G0(t)}function G0(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Y0(t,e={}){const{size:s}=e;let n=t;s&&(mp(t,s),n=yp(t,s));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,o=new Uint8Array(i);for(let a=0,c=0;a<i;a++){const l=Cd(r.charCodeAt(c++)),d=Cd(r.charCodeAt(c++));if(l===void 0||d===void 0)throw new Le(`Invalid byte sequence ("${r[c-2]}${r[c-1]}" in "${r}").`);o[a]=l*16+d}return o}function J0(t,e={}){const{size:s}=e,n=K0.encode(t);return typeof s=="number"?(x0(n,s),X0(n,s)):n}function X0(t,e){return k0(t,{dir:"right",size:e})}function _d(t){return t.length}function Z0(t){try{return z0(t),!0}catch{return!1}}class Zi extends Le{constructor(e){super(`Value \`${typeof e=="object"?El(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class Q0 extends Le{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed \`${s}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class eb extends Le{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${s}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function Ep(t,e={}){const{as:s=typeof t=="string"?"Hex":"Bytes"}=e,n=_0(V0(t));return s==="Bytes"?n:xo(n)}class tb extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const s=super.get(e);return super.has(e)&&s!==void 0&&(this.delete(e),super.set(e,s)),s}set(e,s){if(super.set(e,s),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const sb={checksum:new tb(8192)},Na=sb.checksum;function Cp(t,e={}){const{compressed:s}=e,{prefix:n,x:r,y:i}=t;if(s===!1||typeof r=="bigint"&&typeof i=="bigint"){if(n!==4)throw new Id({prefix:n,cause:new cb});return}if(s===!0||typeof r=="bigint"&&typeof i>"u"){if(n!==3&&n!==2)throw new Id({prefix:n,cause:new ab});return}throw new ob({publicKey:t})}function nb(t){const e=(()=>{if(j0(t))return vp(t);if(Z0(t))return rb(t);const{prefix:s,x:n,y:r}=t;return typeof n=="bigint"&&typeof r=="bigint"?{prefix:s??4,x:n,y:r}:{prefix:s,x:n}})();return Cp(e),e}function rb(t){return vp(xo(t))}function vp(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new lb({publicKey:t});if(t.length===130){const n=BigInt(Ls(t,0,32)),r=BigInt(Ls(t,32,64));return{prefix:4,x:n,y:r}}if(t.length===132){const n=Number(Ls(t,0,1)),r=BigInt(Ls(t,1,33)),i=BigInt(Ls(t,33,65));return{prefix:n,x:r,y:i}}const e=Number(Ls(t,0,1)),s=BigInt(Ls(t,1,33));return{prefix:e,x:s}}function ib(t,e={}){Cp(t);const{prefix:s,x:n,y:r}=t,{includePrefix:i=!0}=e;return M0(i?Sa(s,{size:1}):"0x",Sa(n,{size:32}),typeof r=="bigint"?Sa(r,{size:32}):"0x")}class ob extends Le{constructor({publicKey:e}){super(`Value \`${El(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class Id extends Le{constructor({prefix:e,cause:s}){super(`Prefix "${e}" is invalid.`,{cause:s}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class ab extends Le{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class cb extends Le{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let lb=class extends Le{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${_n(Cl(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const db=/^0x[a-fA-F0-9]{40}$/;function Ap(t,e={}){const{strict:s=!0}=e;if(!db.test(t))throw new Sd({address:t,cause:new pb});if(s){if(t.toLowerCase()===t)return;if(_p(t)!==t)throw new Sd({address:t,cause:new fb})}}function _p(t){if(Na.has(t))return Na.get(t);Ap(t,{strict:!1});const e=t.substring(2).toLowerCase(),s=Ep(J0(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)s[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(s[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const r=`0x${n.join("")}`;return Na.set(t,r),r}function ub(t,e={}){const{checksum:s=!1}=e;return Ap(t),s?_p(t):t}function hb(t,e={}){const s=Ep(`0x${ib(t).slice(4)}`).substring(26);return ub(`0x${s}`,e)}class Sd extends Le{constructor({address:e,cause:s}){super(`Address "${e}" is invalid.`,{cause:s}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class pb extends Le{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class fb extends Le{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class Ip extends gl{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,Xy(e);const n=Zo(s);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),$r(i)}update(e){return kr(this),this.iHash.update(e),this}digestInto(e){kr(this),er(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Sp=(t,e,s)=>new Ip(t,e).update(s).digest();Sp.create=(t,e)=>new Ip(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Tt=BigInt(0),gt=BigInt(1),qn=BigInt(2),gb=BigInt(3),Np=BigInt(4),Tp=BigInt(5),Op=BigInt(8);function It(t,e){const s=t%e;return s>=Tt?s:e+s}function Wt(t,e,s){let n=t;for(;e-- >Tt;)n*=n,n%=s;return n}function _c(t,e){if(t===Tt)throw new Error("invert: expected non-zero number");if(e<=Tt)throw new Error("invert: expected positive modulus, got "+e);let s=It(t,e),n=e,r=Tt,i=gt;for(;s!==Tt;){const a=n/s,c=n%s,l=r-i*a;n=s,s=c,r=i,i=l}if(n!==gt)throw new Error("invert: does not exist");return It(r,e)}function Rp(t,e){const s=(t.ORDER+gt)/Np,n=t.pow(e,s);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function mb(t,e){const s=(t.ORDER-Tp)/Op,n=t.mul(e,qn),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,qn),r),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function wb(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-gt,s=0;for(;e%qn===Tt;)e/=qn,s++;let n=qn;const r=vl(t);for(;Nd(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Rp;let i=r.pow(n,e);const o=(e+gt)/qn;return function(c,l){if(c.is0(l))return l;if(Nd(c,l)!==1)throw new Error("Cannot find square root");let d=s,u=c.mul(c.ONE,i),h=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let g=1,f=c.sqr(h);for(;!c.eql(f,c.ONE);)if(g++,f=c.sqr(f),g===d)throw new Error("Cannot find square root");const w=gt<<BigInt(d-g-1),E=c.pow(u,w);d=g,u=c.sqr(E),h=c.mul(h,u),p=c.mul(p,E)}return p}}function yb(t){return t%Np===gb?Rp:t%Op===Tp?mb:wb(t)}const bb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Eb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},s=bb.reduce((n,r)=>(n[r]="function",n),e);return ea(t,s)}function Cb(t,e,s){if(s<Tt)throw new Error("invalid exponent, negatives unsupported");if(s===Tt)return t.ONE;if(s===gt)return e;let n=t.ONE,r=e;for(;s>Tt;)s>&&(n=t.mul(n,r)),r=t.sqr(r),s>>=gt;return n}function Pp(t,e,s=!1){const n=new Array(e.length).fill(s?t.ZERO:void 0),r=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(r);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function Nd(t,e){const s=(t.ORDER-gt)/qn,n=t.pow(e,s),r=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function xp(t,e){e!==void 0&&Ei(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function vl(t,e,s=!1,n={}){if(t<=Tt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:r,nByteLength:i}=xp(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:s,BITS:r,BYTES:i,MASK:Qo(r),ZERO:Tt,ONE:gt,create:c=>It(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Tt<=c&&c<t},is0:c=>c===Tt,isOdd:c=>(c>)===gt,neg:c=>It(-c,t),eql:(c,l)=>c===l,sqr:c=>It(c*c,t),add:(c,l)=>It(c+l,t),sub:(c,l)=>It(c-l,t),mul:(c,l)=>It(c*l,t),pow:(c,l)=>Cb(a,c,l),div:(c,l)=>It(c*_c(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>_c(c,t),sqrt:n.sqrt||(c=>(o||(o=yb(t)),o(a,c))),toBytes:c=>s?gp(c,i):$i(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return s?fp(c):Yn(c)},invertBatch:c=>Pp(a,c),cmov:(c,l,d)=>d?l:c});return Object.freeze(a)}function kp(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function $p(t){const e=kp(t);return e+Math.ceil(e/2)}function vb(t,e,s=!1){const n=t.length,r=kp(e),i=$p(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?fp(t):Yn(t),a=It(o,e-gt)+gt;return s?gp(a,r):$i(a,r)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Td=BigInt(0),Ic=BigInt(1);function Ta(t,e){const s=e.negate();return t?s:e}function Up(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Oa(t,e){Up(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=Qo(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function Od(t,e,s){const{windowSize:n,mask:r,maxNumber:i,shiftBy:o}=s;let a=Number(t&r),c=t>>o;a>n&&(a-=i,c+=Ic);const l=e*n,d=l+Math.abs(a)-1,u=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:l}}function Ab(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,n)=>{if(!(s instanceof e))throw new Error("invalid point at index "+n)})}function _b(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,n)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+n)})}const Ra=new WeakMap,Dp=new WeakMap;function Pa(t){return Dp.get(t)||1}function Ib(t,e){return{constTimeNegate:Ta,hasPrecomputes(s){return Pa(s)!==1},unsafeLadder(s,n,r=t.ZERO){let i=s;for(;n>Td;)n&Ic&&(r=r.add(i)),i=i.double(),n>>=Ic;return r},precomputeWindow(s,n){const{windows:r,windowSize:i}=Oa(n,e),o=[];let a=s,c=a;for(let l=0;l<r;l++){c=a,o.push(c);for(let d=1;d<i;d++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(s,n,r){let i=t.ZERO,o=t.BASE;const a=Oa(s,e);for(let c=0;c<a.windows;c++){const{nextN:l,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:g}=Od(r,c,a);r=l,u?o=o.add(Ta(p,n[g])):i=i.add(Ta(h,n[d]))}return{p:i,f:o}},wNAFUnsafe(s,n,r,i=t.ZERO){const o=Oa(s,e);for(let a=0;a<o.windows&&r!==Td;a++){const{nextN:c,offset:l,isZero:d,isNeg:u}=Od(r,a,o);if(r=c,!d){const h=n[l];i=i.add(u?h.negate():h)}}return i},getPrecomputes(s,n,r){let i=Ra.get(n);return i||(i=this.precomputeWindow(n,s),s!==1&&Ra.set(n,r(i))),i},wNAFCached(s,n,r){const i=Pa(s);return this.wNAF(i,this.getPrecomputes(i,s,r),n)},wNAFCachedUnsafe(s,n,r,i){const o=Pa(s);return o===1?this.unsafeLadder(s,n,i):this.wNAFUnsafe(o,this.getPrecomputes(o,s,r),n,i)},setWindowSize(s,n){Up(n,e),Dp.set(s,n),Ra.delete(s)}}}function Sb(t,e,s,n){Ab(s,t),_b(n,e);const r=s.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=O0(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Qo(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=u;p>=0;p-=c){d.fill(o);for(let f=0;f<i;f++){const w=n[f],E=Number(w>>BigInt(p)&l);d[E]=d[E].add(s[f])}let g=o;for(let f=d.length-1,w=o;f>0;f--)w=w.add(d[f]),g=g.add(w);if(h=h.add(g),p!==0)for(let f=0;f<c;f++)h=h.double()}return h}function Lp(t){return Eb(t.Fp),ea(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...xp(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Rd(t){t.lowS!==void 0&&Ci("lowS",t.lowS),t.prehash!==void 0&&Ci("prehash",t.prehash)}function Nb(t){const e=Lp(t);ea(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:s,Fp:n,a:r}=e;if(s){if(!n.eql(r,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof s!="object"||typeof s.beta!="bigint"||typeof s.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class Tb extends Error{constructor(e=""){super(e)}}const Ms={Err:Tb,_tlv:{encode:(t,e)=>{const{Err:s}=Ms;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const n=e.length/2,r=Xi(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?Xi(r.length/2|128):"";return Xi(t)+i+r+e},decode(t,e){const{Err:s}=Ms;let n=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new s("tlv.decode: wrong tlv");const r=e[n++],i=!!(r&128);let o=0;if(!i)o=r;else{const c=r&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(n+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=Ms;if(t<qs)throw new e("integer: negative integers are not allowed");let s=Xi(t);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(t){const{Err:e}=Ms;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Yn(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=Ms,r=Jt("signature",t),{v:i,l:o}=n.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=Ms,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}};function xa(t,e){return vi($i(t,e))}const qs=BigInt(0),Je=BigInt(1);BigInt(2);const ka=BigInt(3),Ob=BigInt(4);function Rb(t){const e=Nb(t),{Fp:s}=e,n=vl(e.n,e.nBitLength),r=e.toBytes||((_,v,T)=>{const P=v.toAffine();return Po(Uint8Array.from([4]),s.toBytes(P.x),s.toBytes(P.y))}),i=e.fromBytes||(_=>{const v=_.subarray(1),T=s.fromBytes(v.subarray(0,s.BYTES)),P=s.fromBytes(v.subarray(s.BYTES,2*s.BYTES));return{x:T,y:P}});function o(_){const{a:v,b:T}=e,P=s.sqr(_),D=s.mul(P,_);return s.add(s.add(D,s.mul(_,v)),T)}function a(_,v){const T=s.sqr(v),P=o(_);return s.eql(T,P)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=s.mul(s.pow(e.a,ka),Ob),l=s.mul(s.sqr(e.b),BigInt(27));if(s.is0(s.add(c,l)))throw new Error("bad curve params: a or b");function d(_){return bl(_,Je,e.n)}function u(_){const{allowedPrivateKeyLengths:v,nByteLength:T,wrapPrivateKey:P,n:D}=e;if(v&&typeof _!="bigint"){if(ki(_)&&(_=vi(_)),typeof _!="string"||!v.includes(_.length))throw new Error("invalid private key");_=_.padStart(T*2,"0")}let F;try{F=typeof _=="bigint"?_:Yn(Jt("private key",_,T))}catch{throw new Error("invalid private key, expected hex or "+T+" bytes, got "+typeof _)}return P&&(F=It(F,D)),Sr("private key",F,Je,D),F}function h(_){if(!(_ instanceof f))throw new Error("ProjectivePoint expected")}const p=Ed((_,v)=>{const{px:T,py:P,pz:D}=_;if(s.eql(D,s.ONE))return{x:T,y:P};const F=_.is0();v==null&&(v=F?s.ONE:s.inv(D));const x=s.mul(T,v),K=s.mul(P,v),j=s.mul(D,v);if(F)return{x:s.ZERO,y:s.ZERO};if(!s.eql(j,s.ONE))throw new Error("invZ was invalid");return{x,y:K}}),g=Ed(_=>{if(_.is0()){if(e.allowInfinityPoint&&!s.is0(_.py))return;throw new Error("bad point: ZERO")}const{x:v,y:T}=_.toAffine();if(!s.isValid(v)||!s.isValid(T))throw new Error("bad point: x or y not FE");if(!a(v,T))throw new Error("bad point: equation left != right");if(!_.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(v,T,P){if(v==null||!s.isValid(v))throw new Error("x required");if(T==null||!s.isValid(T)||s.is0(T))throw new Error("y required");if(P==null||!s.isValid(P))throw new Error("z required");this.px=v,this.py=T,this.pz=P,Object.freeze(this)}static fromAffine(v){const{x:T,y:P}=v||{};if(!v||!s.isValid(T)||!s.isValid(P))throw new Error("invalid affine point");if(v instanceof f)throw new Error("projective point not allowed");const D=F=>s.eql(F,s.ZERO);return D(T)&&D(P)?f.ZERO:new f(T,P,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const T=Pp(s,v.map(P=>P.pz));return v.map((P,D)=>P.toAffine(T[D])).map(f.fromAffine)}static fromHex(v){const T=f.fromAffine(i(Jt("pointHex",v)));return T.assertValidity(),T}static fromPrivateKey(v){return f.BASE.multiply(u(v))}static msm(v,T){return Sb(f,n,v,T)}_setWindowSize(v){I.setWindowSize(this,v)}assertValidity(){g(this)}hasEvenY(){const{y:v}=this.toAffine();if(s.isOdd)return!s.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){h(v);const{px:T,py:P,pz:D}=this,{px:F,py:x,pz:K}=v,j=s.eql(s.mul(T,K),s.mul(F,D)),R=s.eql(s.mul(P,K),s.mul(x,D));return j&&R}negate(){return new f(this.px,s.neg(this.py),this.pz)}double(){const{a:v,b:T}=e,P=s.mul(T,ka),{px:D,py:F,pz:x}=this;let K=s.ZERO,j=s.ZERO,R=s.ZERO,C=s.mul(D,D),S=s.mul(F,F),y=s.mul(x,x),b=s.mul(D,F);return b=s.add(b,b),R=s.mul(D,x),R=s.add(R,R),K=s.mul(v,R),j=s.mul(P,y),j=s.add(K,j),K=s.sub(S,j),j=s.add(S,j),j=s.mul(K,j),K=s.mul(b,K),R=s.mul(P,R),y=s.mul(v,y),b=s.sub(C,y),b=s.mul(v,b),b=s.add(b,R),R=s.add(C,C),C=s.add(R,C),C=s.add(C,y),C=s.mul(C,b),j=s.add(j,C),y=s.mul(F,x),y=s.add(y,y),C=s.mul(y,b),K=s.sub(K,C),R=s.mul(y,S),R=s.add(R,R),R=s.add(R,R),new f(K,j,R)}add(v){h(v);const{px:T,py:P,pz:D}=this,{px:F,py:x,pz:K}=v;let j=s.ZERO,R=s.ZERO,C=s.ZERO;const S=e.a,y=s.mul(e.b,ka);let b=s.mul(T,F),N=s.mul(P,x),$=s.mul(D,K),A=s.add(T,P),O=s.add(F,x);A=s.mul(A,O),O=s.add(b,N),A=s.sub(A,O),O=s.add(T,D);let M=s.add(F,K);return O=s.mul(O,M),M=s.add(b,$),O=s.sub(O,M),M=s.add(P,D),j=s.add(x,K),M=s.mul(M,j),j=s.add(N,$),M=s.sub(M,j),C=s.mul(S,O),j=s.mul(y,$),C=s.add(j,C),j=s.sub(N,C),C=s.add(N,C),R=s.mul(j,C),N=s.add(b,b),N=s.add(N,b),$=s.mul(S,$),O=s.mul(y,O),N=s.add(N,$),$=s.sub(b,$),$=s.mul(S,$),O=s.add(O,$),b=s.mul(N,O),R=s.add(R,b),b=s.mul(M,O),j=s.mul(A,j),j=s.sub(j,b),b=s.mul(A,N),C=s.mul(M,C),C=s.add(C,b),new f(j,R,C)}subtract(v){return this.add(v.negate())}is0(){return this.equals(f.ZERO)}wNAF(v){return I.wNAFCached(this,v,f.normalizeZ)}multiplyUnsafe(v){const{endo:T,n:P}=e;Sr("scalar",v,qs,P);const D=f.ZERO;if(v===qs)return D;if(this.is0()||v===Je)return this;if(!T||I.hasPrecomputes(this))return I.wNAFCachedUnsafe(this,v,f.normalizeZ);let{k1neg:F,k1:x,k2neg:K,k2:j}=T.splitScalar(v),R=D,C=D,S=this;for(;x>qs||j>qs;)x&Je&&(R=R.add(S)),j&Je&&(C=C.add(S)),S=S.double(),x>>=Je,j>>=Je;return F&&(R=R.negate()),K&&(C=C.negate()),C=new f(s.mul(C.px,T.beta),C.py,C.pz),R.add(C)}multiply(v){const{endo:T,n:P}=e;Sr("scalar",v,Je,P);let D,F;if(T){const{k1neg:x,k1:K,k2neg:j,k2:R}=T.splitScalar(v);let{p:C,f:S}=this.wNAF(K),{p:y,f:b}=this.wNAF(R);C=I.constTimeNegate(x,C),y=I.constTimeNegate(j,y),y=new f(s.mul(y.px,T.beta),y.py,y.pz),D=C.add(y),F=S.add(b)}else{const{p:x,f:K}=this.wNAF(v);D=x,F=K}return f.normalizeZ([D,F])[0]}multiplyAndAddUnsafe(v,T,P){const D=f.BASE,F=(K,j)=>j===qs||j===Je||!K.equals(D)?K.multiplyUnsafe(j):K.multiply(j),x=F(this,T).add(F(v,P));return x.is0()?void 0:x}toAffine(v){return p(this,v)}isTorsionFree(){const{h:v,isTorsionFree:T}=e;if(v===Je)return!0;if(T)return T(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:T}=e;return v===Je?this:T?T(f,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return Ci("isCompressed",v),this.assertValidity(),r(f,this,v)}toHex(v=!0){return Ci("isCompressed",v),vi(this.toRawBytes(v))}}f.BASE=new f(e.Gx,e.Gy,s.ONE),f.ZERO=new f(s.ZERO,s.ONE,s.ZERO);const{endo:w,nBitLength:E}=e,I=Ib(f,w?Math.ceil(E/2):E);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:u,weierstrassEquation:o,isWithinCurveOrder:d}}function Pb(t){const e=Lp(t);return ea(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function xb(t){const e=Pb(t),{Fp:s,n,nByteLength:r,nBitLength:i}=e,o=s.BYTES+1,a=2*s.BYTES+1;function c(y){return It(y,n)}function l(y){return _c(y,n)}const{ProjectivePoint:d,normPrivateKeyToScalar:u,weierstrassEquation:h,isWithinCurveOrder:p}=Rb({...e,toBytes(y,b,N){const $=b.toAffine(),A=s.toBytes($.x),O=Po;return Ci("isCompressed",N),N?O(Uint8Array.from([b.hasEvenY()?2:3]),A):O(Uint8Array.from([4]),A,s.toBytes($.y))},fromBytes(y){const b=y.length,N=y[0],$=y.subarray(1);if(b===o&&(N===2||N===3)){const A=Yn($);if(!bl(A,Je,s.ORDER))throw new Error("Point is not on curve");const O=h(A);let M;try{M=s.sqrt(O)}catch(se){const X=se instanceof Error?": "+se.message:"";throw new Error("Point is not on curve"+X)}const W=(M&Je)===Je;return(N&1)===1!==W&&(M=s.neg(M)),{x:A,y:M}}else if(b===a&&N===4){const A=s.fromBytes($.subarray(0,s.BYTES)),O=s.fromBytes($.subarray(s.BYTES,2*s.BYTES));return{x:A,y:O}}else{const A=o,O=a;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+O+", got "+b)}}});function g(y){const b=n>>Je;return y>b}function f(y){return g(y)?c(-y):y}const w=(y,b,N)=>Yn(y.slice(b,N));class E{constructor(b,N,$){Sr("r",b,Je,n),Sr("s",N,Je,n),this.r=b,this.s=N,$!=null&&(this.recovery=$),Object.freeze(this)}static fromCompact(b){const N=r;return b=Jt("compactSignature",b,N*2),new E(w(b,0,N),w(b,N,2*N))}static fromDER(b){const{r:N,s:$}=Ms.toSig(Jt("DER",b));return new E(N,$)}assertValidity(){}addRecoveryBit(b){return new E(this.r,this.s,b)}recoverPublicKey(b){const{r:N,s:$,recovery:A}=this,O=D(Jt("msgHash",b));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");const M=A===2||A===3?N+e.n:N;if(M>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const W=A&1?"03":"02",ae=d.fromHex(W+xa(M,s.BYTES)),se=l(M),X=c(-O*se),le=c($*se),ie=d.BASE.multiplyAndAddUnsafe(ae,X,le);if(!ie)throw new Error("point at infinify");return ie.assertValidity(),ie}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new E(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Ro(this.toDERHex())}toDERHex(){return Ms.hexFromSig(this)}toCompactRawBytes(){return Ro(this.toCompactHex())}toCompactHex(){const b=r;return xa(this.r,b)+xa(this.s,b)}}const I={isValidPrivateKey(y){try{return u(y),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const y=$p(e.n);return vb(e.randomBytes(y),e.n)},precompute(y=8,b=d.BASE){return b._setWindowSize(y),b.multiply(BigInt(3)),b}};function _(y,b=!0){return d.fromPrivateKey(y).toRawBytes(b)}function v(y){if(typeof y=="bigint")return!1;if(y instanceof d)return!0;const N=Jt("key",y).length,$=s.BYTES,A=$+1,O=2*$+1;if(!(e.allowedPrivateKeyLengths||r===A))return N===A||N===O}function T(y,b,N=!0){if(v(y)===!0)throw new Error("first arg must be private key");if(v(b)===!1)throw new Error("second arg must be public key");return d.fromHex(b).multiply(u(y)).toRawBytes(N)}const P=e.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const b=Yn(y),N=y.length*8-i;return N>0?b>>BigInt(N):b},D=e.bits2int_modN||function(y){return c(P(y))},F=Qo(i);function x(y){return Sr("num < 2^"+i,y,qs,F),$i(y,r)}function K(y,b,N=j){if(["recovered","canonical"].some(ce=>ce in N))throw new Error("sign() legacy options not supported");const{hash:$,randomBytes:A}=e;let{lowS:O,prehash:M,extraEntropy:W}=N;O==null&&(O=!0),y=Jt("msgHash",y),Rd(N),M&&(y=Jt("prehashed msgHash",$(y)));const ae=D(y),se=u(b),X=[x(se),x(ae)];if(W!=null&&W!==!1){const ce=W===!0?A(s.BYTES):W;X.push(Jt("extraEntropy",ce))}const le=Po(...X),ie=ae;function Se(ce){const Oe=P(ce);if(!p(Oe))return;const ht=l(Oe),yt=d.BASE.multiply(Oe).toAffine(),pt=c(yt.x);if(pt===qs)return;const jt=c(ht*c(ie+pt*se));if(jt===qs)return;let Tn=(yt.x===pt?0:2)|Number(yt.y&Je),dr=jt;return O&&g(jt)&&(dr=f(jt),Tn^=1),new E(pt,dr,Tn)}return{seed:le,k2sig:Se}}const j={lowS:e.lowS,prehash:!1},R={lowS:e.lowS,prehash:!1};function C(y,b,N=j){const{seed:$,k2sig:A}=K(y,b,N),O=e;return R0(O.hash.outputLen,O.nByteLength,O.hmac)($,A)}d.BASE._setWindowSize(8);function S(y,b,N,$=R){var Tn;const A=y;b=Jt("msgHash",b),N=Jt("publicKey",N);const{lowS:O,prehash:M,format:W}=$;if(Rd($),"strict"in $)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");const ae=typeof A=="string"||ki(A),se=!ae&&!W&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!ae&&!se)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,le;try{if(se&&(X=new E(A.r,A.s)),ae){try{W!=="compact"&&(X=E.fromDER(A))}catch(dr){if(!(dr instanceof Ms.Err))throw dr}!X&&W!=="der"&&(X=E.fromCompact(A))}le=d.fromHex(N)}catch{return!1}if(!X||O&&X.hasHighS())return!1;M&&(b=e.hash(b));const{r:ie,s:Se}=X,ce=D(b),Oe=l(Se),ht=c(ce*Oe),yt=c(ie*Oe),pt=(Tn=d.BASE.multiplyAndAddUnsafe(le,ht,yt))==null?void 0:Tn.toAffine();return pt?c(pt.x)===ie:!1}return{CURVE:e,getPublicKey:_,getSharedSecret:T,sign:C,verify:S,ProjectivePoint:d,Signature:E,utils:I}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function kb(t){return{hash:t,hmac:(e,...s)=>Sp(t,e,n0(...s)),randomBytes:r0}}function $b(t,e){const s=n=>xb({...t,...kb(n)});return{...s(e),create:s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Bp=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Pd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ub=BigInt(0),Db=BigInt(1),Sc=BigInt(2),xd=(t,e)=>(t+e/Sc)/e;function Lb(t){const e=Bp,s=BigInt(3),n=BigInt(6),r=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=Wt(d,s,e)*d%e,h=Wt(u,s,e)*d%e,p=Wt(h,Sc,e)*l%e,g=Wt(p,r,e)*p%e,f=Wt(g,i,e)*g%e,w=Wt(f,a,e)*f%e,E=Wt(w,c,e)*w%e,I=Wt(E,a,e)*f%e,_=Wt(I,s,e)*d%e,v=Wt(_,o,e)*g%e,T=Wt(v,n,e)*l%e,P=Wt(T,Sc,e);if(!Nc.eql(Nc.sqr(P),t))throw new Error("Cannot find square root");return P}const Nc=vl(Bp,void 0,void 0,{sqrt:Lb}),Bb=$b({a:Ub,b:BigInt(7),Fp:Nc,n:Pd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Pd,s=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Db*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=s,o=BigInt("0x100000000000000000000000000000000"),a=xd(i*t,e),c=xd(-n*t,e);let l=It(t-a*s-c*r,e),d=It(-a*n-c*i,e);const u=l>o,h=d>o;if(u&&(l=e-l),h&&(d=e-d),l>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}}},N0);function Mb(t){if(t.length!==130&&t.length!==132)throw new jb({signature:t});const e=BigInt(Ls(t,0,32)),s=BigInt(Ls(t,32,64)),n=(()=>{const r=+`0x${t.slice(130)}`;if(!Number.isNaN(r))try{return Fb(r)}catch{throw new qb({value:r})}})();return typeof n>"u"?{r:e,s}:{r:e,s,yParity:n}}function Fb(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new Wb({value:t})}class jb extends Le{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${_n(Cl(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class qb extends Le{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class Wb extends Le{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function Hb(t){return hb(Kb(t))}function Kb(t){const{payload:e,signature:s}=t,{r:n,s:r,yParity:i}=s,a=new Bb.Signature(BigInt(n),BigInt(r)).addRecoveryBit(i).recoverPublicKey(Cl(e).substring(2));return nb(a)}const zb=":";function zs(t){const[e,s]=t.split(zb);return{namespace:e,reference:s}}function Mp(t,e){return t.includes(":")?[t]:e.chains||[]}var Vb=Object.defineProperty,Gb=Object.defineProperties,Yb=Object.getOwnPropertyDescriptors,kd=Object.getOwnPropertySymbols,Jb=Object.prototype.hasOwnProperty,Xb=Object.prototype.propertyIsEnumerable,Tc=(t,e,s)=>e in t?Vb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$d=(t,e)=>{for(var s in e||(e={}))Jb.call(e,s)&&Tc(t,s,e[s]);if(kd)for(var s of kd(e))Xb.call(e,s)&&Tc(t,s,e[s]);return t},Zb=(t,e)=>Gb(t,Yb(e)),Ud=(t,e,s)=>Tc(t,typeof e!="symbol"?e+"":e,s);const Qb="ReactNative",Mt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},eE="js";function ko(){return typeof Ks<"u"&&typeof Ks.versions<"u"&&typeof Ks.versions.node<"u"}function Sn(){return!xr()&&!!Mh()&&navigator.product===Qb}function tE(){return Sn()&&typeof de<"u"&&typeof(de==null?void 0:de.Platform)<"u"&&(de==null?void 0:de.Platform.OS)==="android"}function sE(){return Sn()&&typeof de<"u"&&typeof(de==null?void 0:de.Platform)<"u"&&(de==null?void 0:de.Platform.OS)==="ios"}function qr(){return!ko()&&!!Mh()&&!!xr()}function Ui(){return Sn()?Mt.reactNative:ko()?Mt.node:qr()?Mt.browser:Mt.unknown}function Dd(){var t;try{return Sn()&&typeof de<"u"&&typeof(de==null?void 0:de.Application)<"u"?(t=de.Application)==null?void 0:t.applicationId:void 0}catch{return}}function nE(t,e){const s=new URLSearchParams(t);return Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!=null&&s.set(n,String(r))}),s.toString()}function rE(t){var e,s;const n=Fp();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(r=>r!=="")),Zb($d($d({},n),t),{url:(t==null?void 0:t.url)||n.url,name:(t==null?void 0:t.name)||n.name,description:(t==null?void 0:t.description)||n.description,icons:(s=t==null?void 0:t.icons)!=null&&s.length&&t.icons.length>0?t.icons:n.icons})}catch(r){return console.warn("Error populating app metadata",r),t||n}}function Fp(){return Mg()||{name:"",description:"",url:"",icons:[""]}}function iE(){if(Ui()===Mt.reactNative&&typeof de<"u"&&typeof(de==null?void 0:de.Platform)<"u"){const{OS:s,Version:n}=de.Platform;return[s,n].join("-")}const t=Hg();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function oE(){var t;const e=Ui();return e===Mt.browser?[e,((t=Kg())==null?void 0:t.host)||"unknown"].join(":"):e}function jp(t,e,s){const n=iE(),r=oE();return[[t,e].join("-"),[eE,s].join("-"),n,r].join("/")}function aE({protocol:t,version:e,relayUrl:s,sdkVersion:n,auth:r,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d=jp(t,e,n),u={auth:r,ua:d,projectId:i,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=nE(l[1]||"",u);return l[0]+"?"+h}function Wn(t,e){return t.filter(s=>e.includes(s)).length===t.length}function Oc(t){return Object.fromEntries(t.entries())}function Rc(t){return new Map(Object.entries(t))}function Ln(t=V.FIVE_MINUTES,e){const s=V.toMiliseconds(t||V.FIVE_MINUTES);let n,r,i,o;return{resolve:a=>{i&&n&&(clearTimeout(i),n(a),o=Promise.resolve(a))},reject:a=>{i&&r&&(clearTimeout(i),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);i=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),n=a,r=c})}}function As(t,e,s){return new Promise(async(n,r)=>{const i=setTimeout(()=>r(new Error(s)),e);try{const o=await t;n(o)}catch(o){r(o)}clearTimeout(i)})}function qp(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function cE(t){return qp("topic",t)}function lE(t){return qp("id",t)}function Wp(t){const[e,s]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")n.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))n.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return n}function qe(t,e){return V.fromMiliseconds((e||Date.now())+V.toMiliseconds(t))}function Cs(t){return Date.now()>=V.toMiliseconds(t)}function Ie(t,e){return`${t}${e?`:${e}`:""}`}function Ss(t=[],e=[]){return[...new Set([...t,...e])]}async function dE({id:t,topic:e,wcDeepLink:s}){var n;try{if(!s)return;const r=typeof s=="string"?JSON.parse(s):s,i=r==null?void 0:r.href;if(typeof i!="string")return;const o=uE(i,t,e),a=Ui();if(a===Mt.browser){if(!((n=xr())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}hE(o)}else a===Mt.reactNative&&typeof(de==null?void 0:de.Linking)<"u"&&await de.Linking.openURL(o)}catch(r){console.error(r)}}function uE(t,e,s){const n=`requestId=${e}&sessionTopic=${s}`;t.endsWith("/")&&(t=t.slice(0,-1));let r=`${t}`;if(t.startsWith("https://t.me")){const i=t.includes("?")?"&startapp=":"?startapp=";r=`${r}${i}${mE(n,!0)}`}else r=`${r}/wc?${n}`;return r}function hE(t){let e="_self";gE()?e="_top":(fE()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function pE(t,e){let s="";try{if(qr()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(n){console.error(n)}return s}function Ld(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),n=s.indexOf(e);return s[n+2]}function Bd(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Al(){return typeof Ks<"u"&&{}.IS_VITEST==="true"}function fE(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function gE(){try{return window.self!==window.top}catch{return!1}}function mE(t,e=!1){const s=Ee.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function Hp(t){return Ee.from(t,"base64").toString("utf-8")}function wE(t){return new Promise(e=>setTimeout(e,t))}let yE=class{constructor({limit:e}){Ud(this,"limit"),Ud(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const s=this.set.values().next().value;s&&this.set.delete(s)}this.set.add(e)}}has(e){return this.set.has(e)}};const Qi=BigInt(2**32-1),Md=BigInt(32);function Kp(t,e=!1){return e?{h:Number(t&Qi),l:Number(t>>Md&Qi)}:{h:Number(t>>Md&Qi)|0,l:Number(t&Qi)|0}}function zp(t,e=!1){const s=t.length;let n=new Uint32Array(s),r=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=Kp(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const Fd=(t,e,s)=>t>>>s,jd=(t,e,s)=>t<<32-s|e>>>s,ln=(t,e,s)=>t>>>s|e<<32-s,dn=(t,e,s)=>t<<32-s|e>>>s,ni=(t,e,s)=>t<<64-s|e>>>s-32,ri=(t,e,s)=>t>>>s-32|e<<64-s,bE=(t,e)=>e,EE=(t,e)=>t,CE=(t,e,s)=>t<<s|e>>>32-s,vE=(t,e,s)=>e<<s|t>>>32-s,AE=(t,e,s)=>e<<s-32|t>>>64-s,_E=(t,e,s)=>t<<s-32|e>>>64-s;function cs(t,e,s,n){const r=(e>>>0)+(n>>>0);return{h:t+s+(r/2**32|0)|0,l:r|0}}const _l=(t,e,s)=>(t>>>0)+(e>>>0)+(s>>>0),Il=(t,e,s,n)=>e+s+n+(t/2**32|0)|0,IE=(t,e,s,n)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0),SE=(t,e,s,n,r)=>e+s+n+r+(t/2**32|0)|0,NE=(t,e,s,n,r)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0)+(r>>>0),TE=(t,e,s,n,r,i)=>e+s+n+r+i+(t/2**32|0)|0,pr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ta(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Js(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ps(t,...e){if(!ta(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function sa(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Js(t.outputLen),Js(t.blockLen)}function In(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Sl(t,e){ps(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Ai(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function ss(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function $a(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function gs(t,e){return t<<32-e|t>>>e}const Vp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Gp(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const $s=Vp?t=>t:t=>Gp(t);function OE(t){for(let e=0;e<t.length;e++)t[e]=Gp(t[e]);return t}const un=Vp?t=>t:OE,Yp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",RE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Nr(t){if(ps(t),Yp)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=RE[t[s]];return e}const xs={_0:48,_9:57,A:65,F:70,a:97,f:102};function qd(t){if(t>=xs._0&&t<=xs._9)return t-xs._0;if(t>=xs.A&&t<=xs.F)return t-(xs.A-10);if(t>=xs.a&&t<=xs.f)return t-(xs.a-10)}function $o(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Yp)return Uint8Array.fromHex(t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=qd(t.charCodeAt(i)),a=qd(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[r]=o*16+a}return n}function Jp(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function hs(t){return typeof t=="string"&&(t=Jp(t)),ps(t),t}function pn(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];ps(r),e+=r.length}const s=new Uint8Array(e);for(let n=0,r=0;n<t.length;n++){const i=t[n];s.set(i,r),r+=i.length}return s}class na{}function Di(t){const e=n=>t().update(hs(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function PE(t){const e=(n,r)=>t(r).update(hs(n)).digest(),s=t({});return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}function cr(t=32){if(pr&&typeof pr.getRandomValues=="function")return pr.getRandomValues(new Uint8Array(t));if(pr&&typeof pr.randomBytes=="function")return Uint8Array.from(pr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const xE=BigInt(0),Vr=BigInt(1),kE=BigInt(2),$E=BigInt(7),UE=BigInt(256),DE=BigInt(113),Xp=[],Zp=[],Qp=[];for(let t=0,e=Vr,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],Xp.push(2*(5*n+s)),Zp.push((t+1)*(t+2)/2%64);let r=xE;for(let i=0;i<7;i++)e=(e<<Vr^(e>>$E)*DE)%UE,e&kE&&(r^=Vr<<(Vr<<BigInt(i))-Vr);Qp.push(r)}const ef=zp(Qp,!0),LE=ef[0],BE=ef[1],Wd=(t,e,s)=>s>32?AE(t,e,s):CE(t,e,s),Hd=(t,e,s)=>s>32?_E(t,e,s):vE(t,e,s);function ME(t,e=24){const s=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],d=s[c+1],u=Wd(l,d,1)^s[a],h=Hd(l,d,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=Zp[o],c=Wd(r,i,a),l=Hd(r,i,a),d=Xp[o];r=t[d],i=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=LE[n],t[1]^=BE[n]}ss(s)}let FE=class tf extends na{constructor(e,s,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=s,this.outputLen=n,this.enableXOF=r,this.rounds=i,Js(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ai(this.state)}clone(){return this._cloneInto()}keccak(){un(this.state32),ME(this.state32,this.rounds),un(this.state32),this.posOut=0,this.pos=0}update(e){In(this),e=hs(e),ps(e);const{blockLen:s,state:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:n,blockLen:r}=this;e[n]^=s,s&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){In(this,!1),ps(e),this.finish();const s=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(s.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Js(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Sl(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,ss(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new tf(s,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const jE=(t,e,s)=>Di(()=>new FE(e,t,s)),qE=jE(1,136,256/8);function WE(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function HE(t,e,s){return t&e^~t&s}function KE(t,e,s){return t&e^t&s^e&s}let sf=class extends na{constructor(e,s,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=s,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=$a(this.buffer)}update(e){In(this),e=hs(e),ps(e);const{view:s,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(r-this.pos,i-o);if(a===r){const c=$a(e);for(;r<=i-o;o+=r)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){In(this),Sl(e,this),this.finished=!0;const{buffer:s,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,ss(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)s[u]=0;WE(n,r-8,BigInt(this.length*8),i),this.process(n,0);const a=$a(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=a,r%s&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const sn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),it=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),ot=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),zE=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),nn=new Uint32Array(64);class VE extends sf{constructor(e=32){super(64,e,8,!1),this.A=sn[0]|0,this.B=sn[1]|0,this.C=sn[2]|0,this.D=sn[3]|0,this.E=sn[4]|0,this.F=sn[5]|0,this.G=sn[6]|0,this.H=sn[7]|0}get(){const{A:e,B:s,C:n,D:r,E:i,F:o,G:a,H:c}=this;return[e,s,n,r,i,o,a,c]}set(e,s,n,r,i,o,a,c){this.A=e|0,this.B=s|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let u=0;u<16;u++,s+=4)nn[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const h=nn[u-15],p=nn[u-2],g=gs(h,7)^gs(h,18)^h>>>3,f=gs(p,17)^gs(p,19)^p>>>10;nn[u]=f+nn[u-7]+g+nn[u-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=gs(a,6)^gs(a,11)^gs(a,25),p=d+h+HE(a,c,l)+zE[u]+nn[u]|0,g=(gs(n,2)^gs(n,13)^gs(n,22))+KE(n,r,i)|0;d=l,l=c,c=a,a=o+p|0,o=i,i=r,r=n,n=p+g|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,r,i,o,a,c,l,d)}roundClean(){ss(nn)}destroy(){this.set(0,0,0,0,0,0,0,0),ss(this.buffer)}}const nf=zp(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),GE=nf[0],YE=nf[1],rn=new Uint32Array(80),on=new Uint32Array(80);let Nl=class extends sf{constructor(e=64){super(128,e,16,!1),this.Ah=ot[0]|0,this.Al=ot[1]|0,this.Bh=ot[2]|0,this.Bl=ot[3]|0,this.Ch=ot[4]|0,this.Cl=ot[5]|0,this.Dh=ot[6]|0,this.Dl=ot[7]|0,this.Eh=ot[8]|0,this.El=ot[9]|0,this.Fh=ot[10]|0,this.Fl=ot[11]|0,this.Gh=ot[12]|0,this.Gl=ot[13]|0,this.Hh=ot[14]|0,this.Hl=ot[15]|0}get(){const{Ah:e,Al:s,Bh:n,Bl:r,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:h,Gh:p,Gl:g,Hh:f,Hl:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w){this.Ah=e|0,this.Al=s|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=h|0,this.Gh=p|0,this.Gl=g|0,this.Hh=f|0,this.Hl=w|0}process(e,s){for(let _=0;_<16;_++,s+=4)rn[_]=e.getUint32(s),on[_]=e.getUint32(s+=4);for(let _=16;_<80;_++){const v=rn[_-15]|0,T=on[_-15]|0,P=ln(v,T,1)^ln(v,T,8)^Fd(v,T,7),D=dn(v,T,1)^dn(v,T,8)^jd(v,T,7),F=rn[_-2]|0,x=on[_-2]|0,K=ln(F,x,19)^ni(F,x,61)^Fd(F,x,6),j=dn(F,x,19)^ri(F,x,61)^jd(F,x,6),R=IE(D,j,on[_-7],on[_-16]),C=SE(R,P,K,rn[_-7],rn[_-16]);rn[_]=C|0,on[_]=R|0}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:h,Fh:p,Fl:g,Gh:f,Gl:w,Hh:E,Hl:I}=this;for(let _=0;_<80;_++){const v=ln(u,h,14)^ln(u,h,18)^ni(u,h,41),T=dn(u,h,14)^dn(u,h,18)^ri(u,h,41),P=u&p^~u&f,D=h&g^~h&w,F=NE(I,T,D,YE[_],on[_]),x=TE(F,E,v,P,GE[_],rn[_]),K=F|0,j=ln(n,r,28)^ni(n,r,34)^ni(n,r,39),R=dn(n,r,28)^ri(n,r,34)^ri(n,r,39),C=n&i^n&a^i&a,S=r&o^r&c^o&c;E=f|0,I=w|0,f=p|0,w=g|0,p=u|0,g=h|0,{h:u,l:h}=cs(l|0,d|0,x|0,K|0),l=a|0,d=c|0,a=i|0,c=o|0,i=n|0,o=r|0;const y=_l(K,R,S);n=Il(y,x,j,C),r=y|0}({h:n,l:r}=cs(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:o}=cs(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=cs(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=cs(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:h}=cs(this.Eh|0,this.El|0,u|0,h|0),{h:p,l:g}=cs(this.Fh|0,this.Fl|0,p|0,g|0),{h:f,l:w}=cs(this.Gh|0,this.Gl|0,f|0,w|0),{h:E,l:I}=cs(this.Hh|0,this.Hl|0,E|0,I|0),this.set(n,r,i,o,a,c,l,d,u,h,p,g,f,w,E,I)}roundClean(){ss(rn,on)}destroy(){ss(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class JE extends Nl{constructor(){super(48),this.Ah=it[0]|0,this.Al=it[1]|0,this.Bh=it[2]|0,this.Bl=it[3]|0,this.Ch=it[4]|0,this.Cl=it[5]|0,this.Dh=it[6]|0,this.Dl=it[7]|0,this.Eh=it[8]|0,this.El=it[9]|0,this.Fh=it[10]|0,this.Fl=it[11]|0,this.Gh=it[12]|0,this.Gl=it[13]|0,this.Hh=it[14]|0,this.Hl=it[15]|0}}const at=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class XE extends Nl{constructor(){super(32),this.Ah=at[0]|0,this.Al=at[1]|0,this.Bh=at[2]|0,this.Bl=at[3]|0,this.Ch=at[4]|0,this.Cl=at[5]|0,this.Dh=at[6]|0,this.Dl=at[7]|0,this.Eh=at[8]|0,this.El=at[9]|0,this.Fh=at[10]|0,this.Fl=at[11]|0,this.Gh=at[12]|0,this.Gl=at[13]|0,this.Hh=at[14]|0,this.Hl=at[15]|0}}const ra=Di(()=>new VE),ZE=Di(()=>new Nl),QE=Di(()=>new JE),e1=Di(()=>new XE),t1=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Ke=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Y=new Uint32Array(32);function an(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=Y[2*t],l=Y[2*t+1],d=Y[2*e],u=Y[2*e+1],h=Y[2*s],p=Y[2*s+1],g=Y[2*n],f=Y[2*n+1],w=_l(c,d,o);l=Il(w,l,u,a),c=w|0,{Dh:f,Dl:g}={Dh:f^l,Dl:g^c},{Dh:f,Dl:g}={Dh:bE(f,g),Dl:EE(f)},{h:p,l:h}=cs(p,h,f,g),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:ln(u,d,24),Bl:dn(u,d,24)},Y[2*t]=c,Y[2*t+1]=l,Y[2*e]=d,Y[2*e+1]=u,Y[2*s]=h,Y[2*s+1]=p,Y[2*n]=g,Y[2*n+1]=f}function cn(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=Y[2*t],l=Y[2*t+1],d=Y[2*e],u=Y[2*e+1],h=Y[2*s],p=Y[2*s+1],g=Y[2*n],f=Y[2*n+1],w=_l(c,d,o);l=Il(w,l,u,a),c=w|0,{Dh:f,Dl:g}={Dh:f^l,Dl:g^c},{Dh:f,Dl:g}={Dh:ln(f,g,16),Dl:dn(f,g,16)},{h:p,l:h}=cs(p,h,f,g),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:ni(u,d,63),Bl:ri(u,d,63)},Y[2*t]=c,Y[2*t+1]=l,Y[2*e]=d,Y[2*e+1]=u,Y[2*s]=h,Y[2*s+1]=p,Y[2*n]=g,Y[2*n+1]=f}function s1(t,e={},s,n,r){if(Js(s),t<0||t>s)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.length>s))throw new Error("key length must be undefined or 1.."+s);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==r)throw new Error("personalization must be undefined or "+r)}class n1 extends na{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Js(e),Js(s),this.blockLen=e,this.outputLen=s,this.buffer=new Uint8Array(e),this.buffer32=Ai(this.buffer)}update(e){In(this),e=hs(e),ps(e);const{blockLen:s,buffer:n,buffer32:r}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===s&&(un(r),this.compress(r,0,!1),un(r),this.pos=0);const l=Math.min(s-this.pos,i-c),d=o+c;if(l===s&&!(d%4)&&c+l<i){const u=new Uint32Array(a,d,Math.floor((i-c)/4));un(u);for(let h=0;c+s<i;h+=r.length,c+=s)this.length+=s,this.compress(u,h,!1);un(u);continue}n.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){In(this),Sl(e,this);const{pos:s,buffer32:n}=this;this.finished=!0,ss(this.buffer.subarray(s)),un(n),this.compress(n,0,!0),un(n);const r=Ai(e);this.get().forEach((i,o)=>r[o]=$s(i))}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){const{buffer:s,length:n,finished:r,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(s),e.destroyed=i,e.finished=r,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class r1 extends n1{constructor(e={}){const s=e.dkLen===void 0?64:e.dkLen;super(128,s),this.v0l=Ke[0]|0,this.v0h=Ke[1]|0,this.v1l=Ke[2]|0,this.v1h=Ke[3]|0,this.v2l=Ke[4]|0,this.v2h=Ke[5]|0,this.v3l=Ke[6]|0,this.v3h=Ke[7]|0,this.v4l=Ke[8]|0,this.v4h=Ke[9]|0,this.v5l=Ke[10]|0,this.v5h=Ke[11]|0,this.v6l=Ke[12]|0,this.v6h=Ke[13]|0,this.v7l=Ke[14]|0,this.v7h=Ke[15]|0,s1(s,e,64,16,16);let{key:n,personalization:r,salt:i}=e,o=0;if(n!==void 0&&(n=hs(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=hs(i);const a=Ai(i);this.v4l^=$s(a[0]),this.v4h^=$s(a[1]),this.v5l^=$s(a[2]),this.v5h^=$s(a[3])}if(r!==void 0){r=hs(r);const a=Ai(r);this.v6l^=$s(a[0]),this.v6h^=$s(a[1]),this.v7l^=$s(a[2]),this.v7h^=$s(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:s,v1l:n,v1h:r,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:d,v5l:u,v5h:h,v6l:p,v6h:g,v7l:f,v7h:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w){this.v0l=e|0,this.v0h=s|0,this.v1l=n|0,this.v1h=r|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=d|0,this.v5l=u|0,this.v5h=h|0,this.v6l=p|0,this.v6h=g|0,this.v7l=f|0,this.v7h=w|0}compress(e,s,n){this.get().forEach((c,l)=>Y[l]=c),Y.set(Ke,16);let{h:r,l:i}=Kp(BigInt(this.length));Y[24]=Ke[8]^i,Y[25]=Ke[9]^r,n&&(Y[28]=~Y[28],Y[29]=~Y[29]);let o=0;const a=t1;for(let c=0;c<12;c++)an(0,4,8,12,e,s+2*a[o++]),cn(0,4,8,12,e,s+2*a[o++]),an(1,5,9,13,e,s+2*a[o++]),cn(1,5,9,13,e,s+2*a[o++]),an(2,6,10,14,e,s+2*a[o++]),cn(2,6,10,14,e,s+2*a[o++]),an(3,7,11,15,e,s+2*a[o++]),cn(3,7,11,15,e,s+2*a[o++]),an(0,5,10,15,e,s+2*a[o++]),cn(0,5,10,15,e,s+2*a[o++]),an(1,6,11,12,e,s+2*a[o++]),cn(1,6,11,12,e,s+2*a[o++]),an(2,7,8,13,e,s+2*a[o++]),cn(2,7,8,13,e,s+2*a[o++]),an(3,4,9,14,e,s+2*a[o++]),cn(3,4,9,14,e,s+2*a[o++]);this.v0l^=Y[0]^Y[16],this.v0h^=Y[1]^Y[17],this.v1l^=Y[2]^Y[18],this.v1h^=Y[3]^Y[19],this.v2l^=Y[4]^Y[20],this.v2h^=Y[5]^Y[21],this.v3l^=Y[6]^Y[22],this.v3h^=Y[7]^Y[23],this.v4l^=Y[8]^Y[24],this.v4h^=Y[9]^Y[25],this.v5l^=Y[10]^Y[26],this.v5h^=Y[11]^Y[27],this.v6l^=Y[12]^Y[28],this.v6h^=Y[13]^Y[29],this.v7l^=Y[14]^Y[30],this.v7h^=Y[15]^Y[31],ss(Y)}destroy(){this.destroyed=!0,ss(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const i1=PE(t=>new r1(t)),o1="https://rpc.walletconnect.org/v1";function rf(t){const e=`Ethereum Signed Message:
|
|
7
|
-
${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Ee.from(qE(s)).toString("hex")}async function
|
|
8
|
-
- ${f}`).join("")}`:void 0,g=wo(t.resources);if(g){const f=_i(g);r=
|
|
9
|
-
`)};function I1(t){return Ee.from(JSON.stringify(t)).toString("base64")}function S1(t){return JSON.parse(Ee.from(t,"base64").toString("utf-8"))}function tr(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(s=>{const n=t.att[s];if(Array.isArray(n))throw new Error(`Resource must be an object: ${s}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${s}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${s}`);Object.keys(n).forEach(r=>{const i=n[r];if(!Array.isArray(i))throw new Error(`Ability limits ${r} must be an array of objects, found: ${i}`);if(!i.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);i.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function N1(t,e,s,n={}){return s==null||s.sort((r,i)=>r.localeCompare(i)),{att:{[t]:T1(e,s,n)}}}function T1(t,e,s={}){e=e==null?void 0:e.sort((r,i)=>r.localeCompare(i));const n=e.map(r=>({[`${t}/${r}`]:[s]}));return Object.assign({},...n)}function af(t){return tr(t),`urn:recap:${I1(t).replace(/=/g,"")}`}function _i(t){const e=S1(t.replace("urn:recap:",""));return tr(e),e}function O1(t,e,s){const n=N1(t,e,s);return af(n)}function R1(t){return t&&t.includes("urn:recap:")}function P1(t,e){const s=_i(t),n=_i(e),r=x1(s,n);return af(r)}function x1(t,e){tr(t),tr(e);const s=Object.keys(t.att).concat(Object.keys(e.att)).sort((r,i)=>r.localeCompare(i)),n={att:{}};return s.forEach(r=>{var i,o;Object.keys(((i=t.att)==null?void 0:i[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;n.att[r]=v1(C1({},n.att[r]),{[a]:((c=t.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),n}function k1(t="",e){tr(e);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(s))return t;const n=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,h)=>u.action.localeCompare(h.action));const l={};c.forEach(u=>{l[u.ability]||(l[u.ability]=[]),l[u.ability].push(u.action)});const d=Object.keys(l).map(u=>(r++,`(${r}) '${u}': '${l[u].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});const i=n.join(" "),o=`${s}${i}`;return`${t?t+" ":""}${o}`}function Jd(t){var e;const s=_i(t);tr(s);const n=(e=s.att)==null?void 0:e.eip155;return n?Object.keys(n).map(r=>r.split("/")[1]):[]}function Xd(t){const e=_i(t);tr(e);const s=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(r=>{var i;(i=r==null?void 0:r[0])!=null&&i.chains&&s.push(r[0].chains)})}),[...new Set(s.flat())]}function wo(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return R1(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function cf(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Da(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function St(t,...e){if(!cf(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Zd(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function $1(t,e){St(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Cn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ur(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function U1(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const D1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function L1(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function kc(t){if(typeof t=="string")t=L1(t);else if(cf(t))t=$c(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function B1(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function M1(t,e){if(t.length!==e.length)return!1;let s=0;for(let n=0;n<t.length;n++)s|=t[n]^e[n];return s===0}const F1=(t,e)=>{function s(n,...r){if(St(n),!D1)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?St(l):St(l,t.nonceLength)}const i=t.tagLength;i&&r[1]!==void 0&&St(r[1]);const o=e(n,...r),a=(l,d)=>{if(d!==void 0){if(l!==2)throw new Error("cipher output not supported");St(d)}};let c=!1;return{encrypt(l,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,St(l),a(o.encrypt.length,d),o.encrypt(l,d)},decrypt(l,d){if(St(l),i&&l.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return a(o.decrypt.length,d),o.decrypt(l,d)}}}return Object.assign(s,t),s};function Qd(t,e,s=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(s&&!q1(e))throw new Error("invalid output, must be aligned");return e}function eu(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function j1(t,e,s){xc(s);const n=new Uint8Array(16),r=U1(n);return eu(r,0,BigInt(e),s),eu(r,8,BigInt(t),s),n}function q1(t){return t.byteOffset%4===0}function $c(t){return Uint8Array.from(t)}const lf=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),W1=lf("expand 16-byte k"),H1=lf("expand 32-byte k"),K1=Cn(W1),z1=Cn(H1);function ve(t,e){return t<<e|t>>>32-e}function Uc(t){return t.byteOffset%4===0}const eo=64,V1=16,df=2**32-1,tu=new Uint32Array;function G1(t,e,s,n,r,i,o,a){const c=r.length,l=new Uint8Array(eo),d=Cn(l),u=Uc(r)&&Uc(i),h=u?Cn(r):tu,p=u?Cn(i):tu;for(let g=0;g<c;o++){if(t(e,s,n,d,o,a),o>=df)throw new Error("arx: counter overflow");const f=Math.min(eo,c-g);if(u&&f===eo){const w=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let E=0,I;E<V1;E++)I=w+E,p[I]=h[I]^d[E];g+=eo;continue}for(let w=0,E;w<f;w++)E=g+w,i[E]=r[E]^l[w];g+=f}}function Y1(t,e){const{allowShortKeys:s,extendNonceFn:n,counterLength:r,counterRight:i,rounds:o}=B1({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Da(r),Da(o),xc(i),xc(s),(a,c,l,d,u=0)=>{St(a),St(c),St(l);const h=l.length;if(d===void 0&&(d=new Uint8Array(h)),St(d),Da(u),u<0||u>=df)throw new Error("arx: counter overflow");if(d.length<h)throw new Error(`arx: output (${d.length}) is shorter than data (${h})`);const p=[];let g=a.length,f,w;if(g===32)p.push(f=$c(a)),w=z1;else if(g===16&&s)f=new Uint8Array(32),f.set(a),f.set(a,16),w=K1,p.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Uc(c)||p.push(c=$c(c));const E=Cn(f);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(w,E,Cn(c.subarray(0,16)),E),c=c.subarray(16)}const I=16-r;if(I!==c.length)throw new Error(`arx: nonce must be ${I} or 16 bytes`);if(I!==12){const v=new Uint8Array(12);v.set(c,i?0:12-c.length),c=v,p.push(c)}const _=Cn(c);return G1(t,w,E,_,l,d,u,o),Ur(...p),d}}const Ze=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class J1{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=kc(e),St(e,32);const s=Ze(e,0),n=Ze(e,2),r=Ze(e,4),i=Ze(e,6),o=Ze(e,8),a=Ze(e,10),c=Ze(e,12),l=Ze(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Ze(e,16+2*d)}process(e,s,n=!1){const r=n?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],d=o[3],u=o[4],h=o[5],p=o[6],g=o[7],f=o[8],w=o[9],E=Ze(e,s+0),I=Ze(e,s+2),_=Ze(e,s+4),v=Ze(e,s+6),T=Ze(e,s+8),P=Ze(e,s+10),D=Ze(e,s+12),F=Ze(e,s+14);let x=i[0]+(E&8191),K=i[1]+((E>>>13|I<<3)&8191),j=i[2]+((I>>>10|_<<6)&8191),R=i[3]+((_>>>7|v<<9)&8191),C=i[4]+((v>>>4|T<<12)&8191),S=i[5]+(T>>>1&8191),y=i[6]+((T>>>14|P<<2)&8191),b=i[7]+((P>>>11|D<<5)&8191),N=i[8]+((D>>>8|F<<8)&8191),$=i[9]+(F>>>5|r),A=0,O=A+x*a+K*(5*w)+j*(5*f)+R*(5*g)+C*(5*p);A=O>>>13,O&=8191,O+=S*(5*h)+y*(5*u)+b*(5*d)+N*(5*l)+$*(5*c),A+=O>>>13,O&=8191;let M=A+x*c+K*a+j*(5*w)+R*(5*f)+C*(5*g);A=M>>>13,M&=8191,M+=S*(5*p)+y*(5*h)+b*(5*u)+N*(5*d)+$*(5*l),A+=M>>>13,M&=8191;let W=A+x*l+K*c+j*a+R*(5*w)+C*(5*f);A=W>>>13,W&=8191,W+=S*(5*g)+y*(5*p)+b*(5*h)+N*(5*u)+$*(5*d),A+=W>>>13,W&=8191;let ae=A+x*d+K*l+j*c+R*a+C*(5*w);A=ae>>>13,ae&=8191,ae+=S*(5*f)+y*(5*g)+b*(5*p)+N*(5*h)+$*(5*u),A+=ae>>>13,ae&=8191;let se=A+x*u+K*d+j*l+R*c+C*a;A=se>>>13,se&=8191,se+=S*(5*w)+y*(5*f)+b*(5*g)+N*(5*p)+$*(5*h),A+=se>>>13,se&=8191;let X=A+x*h+K*u+j*d+R*l+C*c;A=X>>>13,X&=8191,X+=S*a+y*(5*w)+b*(5*f)+N*(5*g)+$*(5*p),A+=X>>>13,X&=8191;let le=A+x*p+K*h+j*u+R*d+C*l;A=le>>>13,le&=8191,le+=S*c+y*a+b*(5*w)+N*(5*f)+$*(5*g),A+=le>>>13,le&=8191;let ie=A+x*g+K*p+j*h+R*u+C*d;A=ie>>>13,ie&=8191,ie+=S*l+y*c+b*a+N*(5*w)+$*(5*f),A+=ie>>>13,ie&=8191;let Se=A+x*f+K*g+j*p+R*h+C*u;A=Se>>>13,Se&=8191,Se+=S*d+y*l+b*c+N*a+$*(5*w),A+=Se>>>13,Se&=8191;let ce=A+x*w+K*f+j*g+R*p+C*h;A=ce>>>13,ce&=8191,ce+=S*u+y*d+b*l+N*c+$*a,A+=ce>>>13,ce&=8191,A=(A<<2)+A|0,A=A+O|0,O=A&8191,A=A>>>13,M+=A,i[0]=O,i[1]=M,i[2]=W,i[3]=ae,i[4]=se,i[5]=X,i[6]=le,i[7]=ie,i[8]=Se,i[9]=ce}finalize(){const{h:e,pad:s}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+r,r=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(r^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+s[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+s[a]|0)+(o>>>16)|0,e[a]=o&65535;Ur(n)}update(e){Zd(this),e=kc(e),St(e);const{buffer:s,blockLen:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(n-this.pos,r-i);if(o===n){for(;n<=r-i;i+=n)this.process(e,i);continue}s.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){Ur(this.h,this.r,this.buffer,this.pad)}digestInto(e){Zd(this),$1(e,this),this.finished=!0;const{buffer:s,h:n}=this;let{pos:r}=this;if(r){for(s[r++]=1;r<16;r++)s[r]=0;this.process(s,0,!0)}this.finalize();let i=0;for(let o=0;o<8;o++)e[i++]=n[o]>>>0,e[i++]=n[o]>>>8;return e}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}}function X1(t){const e=(n,r)=>t(r).update(kc(n)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}const Z1=X1(t=>new J1(t));function Q1(t,e,s,n,r,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],h=e[2],p=e[3],g=e[4],f=e[5],w=e[6],E=e[7],I=r,_=s[0],v=s[1],T=s[2],P=o,D=a,F=c,x=l,K=d,j=u,R=h,C=p,S=g,y=f,b=w,N=E,$=I,A=_,O=v,M=T;for(let ae=0;ae<i;ae+=2)P=P+K|0,$=ve($^P,16),S=S+$|0,K=ve(K^S,12),P=P+K|0,$=ve($^P,8),S=S+$|0,K=ve(K^S,7),D=D+j|0,A=ve(A^D,16),y=y+A|0,j=ve(j^y,12),D=D+j|0,A=ve(A^D,8),y=y+A|0,j=ve(j^y,7),F=F+R|0,O=ve(O^F,16),b=b+O|0,R=ve(R^b,12),F=F+R|0,O=ve(O^F,8),b=b+O|0,R=ve(R^b,7),x=x+C|0,M=ve(M^x,16),N=N+M|0,C=ve(C^N,12),x=x+C|0,M=ve(M^x,8),N=N+M|0,C=ve(C^N,7),P=P+j|0,M=ve(M^P,16),b=b+M|0,j=ve(j^b,12),P=P+j|0,M=ve(M^P,8),b=b+M|0,j=ve(j^b,7),D=D+R|0,$=ve($^D,16),N=N+$|0,R=ve(R^N,12),D=D+R|0,$=ve($^D,8),N=N+$|0,R=ve(R^N,7),F=F+C|0,A=ve(A^F,16),S=S+A|0,C=ve(C^S,12),F=F+C|0,A=ve(A^F,8),S=S+A|0,C=ve(C^S,7),x=x+K|0,O=ve(O^x,16),y=y+O|0,K=ve(K^y,12),x=x+K|0,O=ve(O^x,8),y=y+O|0,K=ve(K^y,7);let W=0;n[W++]=o+P|0,n[W++]=a+D|0,n[W++]=c+F|0,n[W++]=l+x|0,n[W++]=d+K|0,n[W++]=u+j|0,n[W++]=h+R|0,n[W++]=p+C|0,n[W++]=g+S|0,n[W++]=f+y|0,n[W++]=w+b|0,n[W++]=E+N|0,n[W++]=I+$|0,n[W++]=_+A|0,n[W++]=v+O|0,n[W++]=T+M|0}const eC=Y1(Q1,{counterRight:!1,counterLength:4,allowShortKeys:!1}),tC=new Uint8Array(16),su=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(tC.subarray(s))},sC=new Uint8Array(32);function nu(t,e,s,n,r){const i=t(e,s,sC),o=Z1.create(i);r&&su(o,r),su(o,n);const a=j1(n.length,r?r.length:0,!0);o.update(a);const c=o.digest();return Ur(i,a),c}const nC=t=>(e,s,n)=>({encrypt(r,i){const o=r.length;i=Qd(o+16,i,!1),i.set(r);const a=i.subarray(0,-16);t(e,s,a,a,1);const c=nu(t,e,s,a,n);return i.set(c,o),Ur(c),i},decrypt(r,i){i=Qd(r.length-16,i,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=nu(t,e,s,o,n);if(!M1(a,c))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),t(e,s,i,i,1),Ur(c),i}}),uf=F1({blockSize:64,nonceLength:12,tagLength:16},nC(eC));let hf=class extends na{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,sa(e);const n=hs(s);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),ss(i)}update(e){return In(this),this.iHash.update(e),this}digestInto(e){In(this),ps(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const ia=(t,e,s)=>new hf(t,e).update(s).digest();ia.create=(t,e)=>new hf(t,e);function rC(t,e,s){return sa(t),s===void 0&&(s=new Uint8Array(t.outputLen)),ia(t,hs(s),hs(e))}const La=Uint8Array.from([0]),ru=Uint8Array.of();function iC(t,e,s,n=32){sa(t),Js(n);const r=t.outputLen;if(n>255*r)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/r);s===void 0&&(s=ru);const o=new Uint8Array(i*r),a=ia.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)La[0]=d+1,c.update(d===0?ru:l).update(s).update(La).digestInto(l),o.set(l,r*d),a._cloneInto(c);return a.destroy(),c.destroy(),ss(l,La),o.slice(0,n)}const oC=(t,e,s,n,r)=>iC(t,rC(t,e,s),n,r),oa=ra,Ol=BigInt(0),Dc=BigInt(1);function Do(t,e=""){if(typeof t!="boolean"){const s=e&&`"${e}"`;throw new Error(s+"expected boolean, got type="+typeof t)}return t}function Hn(t,e,s=""){const n=ta(t),r=t==null?void 0:t.length,i=e!==void 0;if(!n||i&&r!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=n?`length=${r}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function to(t){const e=t.toString(16);return e.length&1?"0"+e:e}function pf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ol:BigInt("0x"+t)}function aa(t){return pf(Nr(t))}function Lo(t){return ps(t),pf(Nr(Uint8Array.from(t).reverse()))}function Rl(t,e){return $o(t.toString(16).padStart(e*2,"0"))}function Pl(t,e){return Rl(t,e).reverse()}function dt(t,e,s){let n;if(typeof e=="string")try{n=$o(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(ta(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const r=n.length;if(typeof s=="number"&&r!==s)throw new Error(t+" of length "+s+" expected, got "+r);return n}const Ba=t=>typeof t=="bigint"&&Ol<=t;function aC(t,e,s){return Ba(t)&&Ba(e)&&Ba(s)&&e<=t&&t<s}function Lc(t,e,s,n){if(!aC(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function ff(t){let e;for(e=0;t>Ol;t>>=Dc,e+=1);return e}const Li=t=>(Dc<<BigInt(t))-Dc;function cC(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),r=h=>Uint8Array.of(h);let i=n(t),o=n(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...h)=>s(o,i,...h),d=(h=n(0))=>{o=l(r(0),h),i=l(),h.length!==0&&(o=l(r(1),h),i=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const p=[];for(;h<e;){i=l();const g=i.slice();p.push(g),h+=i.length}return pn(...p)};return(h,p)=>{c(),d(h);let g;for(;!(g=p(u()));)d();return c(),g}}function ca(t,e,s={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(r,i,o){const a=t[r];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${r}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([r,i])=>n(r,i,!1)),Object.entries(s).forEach(([r,i])=>n(r,i,!0))}function iu(t){const e=new WeakMap;return(s,...n)=>{const r=e.get(s);if(r!==void 0)return r;const i=t(s,...n);return e.set(s,i),i}}const Ot=BigInt(0),mt=BigInt(1),Kn=BigInt(2),gf=BigInt(3),mf=BigInt(4),wf=BigInt(5),lC=BigInt(7),yf=BigInt(8),dC=BigInt(9),bf=BigInt(16);function Lt(t,e){const s=t%e;return s>=Ot?s:e+s}function as(t,e,s){let n=t;for(;e-- >Ot;)n*=n,n%=s;return n}function ou(t,e){if(t===Ot)throw new Error("invert: expected non-zero number");if(e<=Ot)throw new Error("invert: expected positive modulus, got "+e);let s=Lt(t,e),n=e,r=Ot,i=mt;for(;s!==Ot;){const o=n/s,a=n%s,c=r-i*o;n=s,s=a,r=i,i=c}if(n!==mt)throw new Error("invert: does not exist");return Lt(r,e)}function xl(t,e,s){if(!t.eql(t.sqr(e),s))throw new Error("Cannot find square root")}function Ef(t,e){const s=(t.ORDER+mt)/mf,n=t.pow(e,s);return xl(t,n,e),n}function uC(t,e){const s=(t.ORDER-wf)/yf,n=t.mul(e,Kn),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,Kn),r),a=t.mul(i,t.sub(o,t.ONE));return xl(t,a,e),a}function hC(t){const e=Nn(t),s=Cf(t),n=s(e,e.neg(e.ONE)),r=s(e,n),i=s(e,e.neg(n)),o=(t+lC)/bf;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,n);const u=a.mul(l,r),h=a.mul(l,i),p=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,p),d=a.cmov(h,u,g);const f=a.eql(a.sqr(d),c),w=a.cmov(l,d,f);return xl(a,w,c),w}}function Cf(t){if(t<gf)throw new Error("sqrt is not defined for small field");let e=t-mt,s=0;for(;e%Kn===Ot;)e/=Kn,s++;let n=Kn;const r=Nn(t);for(;au(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Ef;let i=r.pow(n,e);const o=(e+mt)/Kn;return function(a,c){if(a.is0(c))return c;if(au(a,c)!==1)throw new Error("Cannot find square root");let l=s,d=a.mul(a.ONE,i),u=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(u,a.ONE);){if(a.is0(u))return a.ZERO;let p=1,g=a.sqr(u);for(;!a.eql(g,a.ONE);)if(p++,g=a.sqr(g),p===l)throw new Error("Cannot find square root");const f=mt<<BigInt(l-p-1),w=a.pow(d,f);l=p,d=a.sqr(w),u=a.mul(u,d),h=a.mul(h,w)}return h}}function pC(t){return t%mf===gf?Ef:t%yf===wf?uC:t%bf===dC?hC(t):Cf(t)}const fC=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gC(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},s=fC.reduce((n,r)=>(n[r]="function",n),e);return ca(t,s),t}function mC(t,e,s){if(s<Ot)throw new Error("invalid exponent, negatives unsupported");if(s===Ot)return t.ONE;if(s===mt)return e;let n=t.ONE,r=e;for(;s>Ot;)s&mt&&(n=t.mul(n,r)),r=t.sqr(r),s>>=mt;return n}function vf(t,e,s=!1){const n=new Array(e.length).fill(s?t.ZERO:void 0),r=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(r);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function au(t,e){const s=(t.ORDER-mt)/Kn,n=t.pow(e,s),r=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function Af(t,e){e!==void 0&&Js(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function Nn(t,e,s=!1,n={}){if(t<=Ot)throw new Error("invalid field: expected ORDER > 0, got "+t);let r,i,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||s)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(r=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(s=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(r=e),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=Af(t,r);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:s,BITS:c,BYTES:l,MASK:Li(c),ZERO:Ot,ONE:mt,allowedLengths:a,create:h=>Lt(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Ot<=h&&h<t},is0:h=>h===Ot,isValidNot0:h=>!u.is0(h)&&u.isValid(h),isOdd:h=>(h&mt)===mt,neg:h=>Lt(-h,t),eql:(h,p)=>h===p,sqr:h=>Lt(h*h,t),add:(h,p)=>Lt(h+p,t),sub:(h,p)=>Lt(h-p,t),mul:(h,p)=>Lt(h*p,t),pow:(h,p)=>mC(u,h,p),div:(h,p)=>Lt(h*ou(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>ou(h,t),sqrt:i||(h=>(d||(d=pC(t)),d(u,h))),toBytes:h=>s?Pl(h,l):Rl(h,l),fromBytes:(h,p=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const f=new Uint8Array(l);f.set(h,s?0:f.length-h.length),h=f}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let g=s?Lo(h):aa(h);if(o&&(g=Lt(g,t)),!p&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>vf(u,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(u)}function _f(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function If(t){const e=_f(t);return e+Math.ceil(e/2)}function wC(t,e,s=!1){const n=t.length,r=_f(e),i=If(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?Lo(t):aa(t),a=Lt(o,e-mt)+mt;return s?Pl(a,r):Rl(a,r)}const Dr=BigInt(0),zn=BigInt(1);function Bo(t,e){const s=e.negate();return t?s:e}function Ma(t,e){const s=vf(t.Fp,e.map(n=>n.Z));return e.map((n,r)=>t.fromAffine(n.toAffine(s[r])))}function Sf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Fa(t,e){Sf(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=Li(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function cu(t,e,s){const{windowSize:n,mask:r,maxNumber:i,shiftBy:o}=s;let a=Number(t&r),c=t>>o;a>n&&(a-=i,c+=zn);const l=e*n,d=l+Math.abs(a)-1,u=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:l}}function yC(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,n)=>{if(!(s instanceof e))throw new Error("invalid point at index "+n)})}function bC(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,n)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+n)})}const ja=new WeakMap,Nf=new WeakMap;function qa(t){return Nf.get(t)||1}function lu(t){if(t!==Dr)throw new Error("invalid wNAF")}class EC{constructor(e,s){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,n=this.ZERO){let r=e;for(;s>Dr;)s&zn&&(n=n.add(r)),r=r.double(),s>>=zn;return n}precomputeWindow(e,s){const{windows:n,windowSize:r}=Fa(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<n;c++){a=o,i.push(a);for(let l=1;l<r;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=Fa(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:h,offsetF:p}=cu(n,a,o);n=c,d?i=i.add(Bo(h,s[p])):r=r.add(Bo(u,s[l]))}return lu(n),{p:r,f:i}}wNAFUnsafe(e,s,n,r=this.ZERO){const i=Fa(e,this.bits);for(let o=0;o<i.windows&&n!==Dr;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=cu(n,o,i);if(n=a,!l){const u=s[c];r=r.add(d?u.negate():u)}}return lu(n),r}getPrecomputes(e,s,n){let r=ja.get(s);return r||(r=this.precomputeWindow(s,e),e!==1&&(typeof n=="function"&&(r=n(r)),ja.set(s,r))),r}cached(e,s,n){const r=qa(e);return this.wNAF(r,this.getPrecomputes(r,e,n),s)}unsafe(e,s,n,r){const i=qa(e);return i===1?this._unsafeLadder(e,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),s,r)}createCache(e,s){Sf(s,this.bits),Nf.set(e,s),ja.delete(e)}hasCache(e){return qa(e)!==1}}function CC(t,e,s,n){let r=e,i=t.ZERO,o=t.ZERO;for(;s>Dr||n>Dr;)s&zn&&(i=i.add(r)),n&zn&&(o=o.add(r)),r=r.double(),s>>=zn,n>>=zn;return{p1:i,p2:o}}function vC(t,e,s,n){yC(s,t),bC(n,e);const r=s.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=ff(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Li(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=u;p>=0;p-=c){d.fill(o);for(let f=0;f<i;f++){const w=n[f],E=Number(w>>BigInt(p)&l);d[E]=d[E].add(s[f])}let g=o;for(let f=d.length-1,w=o;f>0;f--)w=w.add(d[f]),g=g.add(w);if(h=h.add(g),p!==0)for(let f=0;f<c;f++)h=h.double()}return h}function du(t,e,s){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return gC(e),e}else return Nn(t,{isLE:s})}function AC(t,e,s={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>Dr))throw new Error(`CURVE.${a} must be positive bigint`)}const r=du(e.p,s.Fp,n),i=du(e.n,s.Fn,n),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:i}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Jp("HashToScalar-");const Gr=BigInt(0),fr=BigInt(1),so=BigInt(2);function _C(t){return ca(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function IC(t){const e=_C(t),{P:s,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:o}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");const c=o||cr,l=a?255:448,d=a?32:56,u=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?so**BigInt(254):so**BigInt(447),g=a?BigInt(8)*so**BigInt(251)-fr:BigInt(4)*so**BigInt(445)-fr,f=p+g+fr,w=R=>Lt(R,s),E=I(u);function I(R){return Pl(w(R),d)}function _(R){const C=dt("u coordinate",R,d);return a&&(C[31]&=127),w(Lo(C))}function v(R){return Lo(r(dt("scalar",R,d)))}function T(R,C){const S=F(_(C),v(R));if(S===Gr)throw new Error("invalid private or public key received");return I(S)}function P(R){return T(R,E)}function D(R,C,S){const y=w(R*(C-S));return C=w(C-y),S=w(S+y),{x_2:C,x_3:S}}function F(R,C){Lc("u",R,Gr,s),Lc("scalar",C,p,f);const S=C,y=R;let b=fr,N=Gr,$=R,A=fr,O=Gr;for(let W=BigInt(l-1);W>=Gr;W--){const ae=S>>W&fr;O^=ae,{x_2:b,x_3:$}=D(O,b,$),{x_2:N,x_3:A}=D(O,N,A),O=ae;const se=b+N,X=w(se*se),le=b-N,ie=w(le*le),Se=X-ie,ce=$+A,Oe=$-A,ht=w(Oe*se),yt=w(ce*le),pt=ht+yt,jt=ht-yt;$=w(pt*pt),A=w(y*w(jt*jt)),b=w(X*ie),N=w(Se*(X+w(h*Se)))}({x_2:b,x_3:$}=D(O,b,$)),{x_2:N,x_3:A}=D(O,N,A);const M=i(N);return w(b*M)}const x={secretKey:d,publicKey:d,seed:d},K=(R=c(d))=>(ps(R,x.seed),R);function j(R){const C=K(R);return{secretKey:C,publicKey:P(C)}}return{keygen:j,getSharedSecret:(R,C)=>T(R,C),getPublicKey:R=>P(R),scalarMult:T,scalarMultBase:P,utils:{randomSecretKey:K,randomPrivateKey:K},GuBytes:E.slice(),lengths:x}}const SC=BigInt(1),uu=BigInt(2),NC=BigInt(3),TC=BigInt(5),OC=BigInt(8),Tf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),RC={p:Tf,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:OC,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function PC(t){const e=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=Tf,o=t*t%i*t%i,a=as(o,uu,i)*o%i,c=as(a,SC,i)*t%i,l=as(c,TC,i)*c%i,d=as(l,e,i)*l%i,u=as(d,s,i)*d%i,h=as(u,n,i)*u%i,p=as(h,r,i)*h%i,g=as(p,r,i)*h%i,f=as(g,e,i)*l%i;return{pow_p_5_8:as(f,uu,i)*t%i,b2:o}}function xC(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const kC=Nn(RC.p,{isLE:!0}),Bc=(()=>{const t=kC.ORDER;return IC({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:s,b2:n}=PC(e);return Lt(as(s,NC,t)*n,t)},adjustScalarBytes:xC})})(),hu=(t,e)=>(t+(t>=0?e:-e)/Of)/e;function $C(t,e,s){const[[n,r],[i,o]]=e,a=hu(o*t,s),c=hu(-r*t,s);let l=t-a*n-c*i,d=-a*r-c*o;const u=l<Hs,h=d<Hs;u&&(l=-l),h&&(d=-d);const p=Li(Math.ceil(ff(s)/2))+Tr;if(l<Hs||l>=p||d<Hs||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}function Mc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Wa(t,e){const s={};for(let n of Object.keys(e))s[n]=t[n]===void 0?e[n]:t[n];return Do(s.lowS,"lowS"),Do(s.prehash,"prehash"),s.format!==void 0&&Mc(s.format),s}class UC extends Error{constructor(e=""){super(e)}}const Fs={Err:UC,_tlv:{encode:(t,e)=>{const{Err:s}=Fs;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const n=e.length/2,r=to(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?to(r.length/2|128):"";return to(t)+i+r+e},decode(t,e){const{Err:s}=Fs;let n=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new s("tlv.decode: wrong tlv");const r=e[n++],i=!!(r&128);let o=0;if(!i)o=r;else{const c=r&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(n+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=Fs;if(t<Hs)throw new e("integer: negative integers are not allowed");let s=to(t);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(t){const{Err:e}=Fs;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return aa(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=Fs,r=dt("signature",t),{v:i,l:o}=n.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=Fs,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}},Hs=BigInt(0),Tr=BigInt(1),Of=BigInt(2),no=BigInt(3),DC=BigInt(4);function Cr(t,e){const{BYTES:s}=t;let n;if(typeof e=="bigint")n=e;else{let r=dt("private key",e);try{n=t.fromBytes(r)}catch{throw new Error(`invalid private key: expected ui8a of size ${s}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function LC(t,e={}){const s=AC("weierstrass",t,e),{Fp:n,Fn:r}=s;let i=s.CURVE;const{h:o,n:a}=i;ca(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Pf(n,r);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(R,C,S){const{x:y,y:b}=C.toAffine(),N=n.toBytes(y);if(Do(S,"isCompressed"),S){d();const $=!n.isOdd(b);return pn(Rf($),N)}else return pn(Uint8Array.of(4),N,n.toBytes(b))}function h(R){Hn(R,void 0,"Point");const{publicKey:C,publicKeyUncompressed:S}=l,y=R.length,b=R[0],N=R.subarray(1);if(y===C&&(b===2||b===3)){const $=n.fromBytes(N);if(!n.isValid($))throw new Error("bad point: is not on curve, wrong x");const A=f($);let O;try{O=n.sqrt(A)}catch(W){const ae=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+ae)}d();const M=n.isOdd(O);return(b&1)===1!==M&&(O=n.neg(O)),{x:$,y:O}}else if(y===S&&b===4){const $=n.BYTES,A=n.fromBytes(N.subarray(0,$)),O=n.fromBytes(N.subarray($,$*2));if(!w(A,O))throw new Error("bad point: is not on curve");return{x:A,y:O}}else throw new Error(`bad point: got length ${y}, expected compressed=${C} or uncompressed=${S}`)}const p=e.toBytes||u,g=e.fromBytes||h;function f(R){const C=n.sqr(R),S=n.mul(C,R);return n.add(n.add(S,n.mul(R,i.a)),i.b)}function w(R,C){const S=n.sqr(C),y=f(R);return n.eql(S,y)}if(!w(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const E=n.mul(n.pow(i.a,no),DC),I=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(E,I)))throw new Error("bad curve params: a or b");function _(R,C,S=!1){if(!n.isValid(C)||S&&n.is0(C))throw new Error(`bad point coordinate ${R}`);return C}function v(R){if(!(R instanceof x))throw new Error("ProjectivePoint expected")}function T(R){if(!c||!c.basises)throw new Error("no endo");return $C(R,c.basises,r.ORDER)}const P=iu((R,C)=>{const{X:S,Y:y,Z:b}=R;if(n.eql(b,n.ONE))return{x:S,y};const N=R.is0();C==null&&(C=N?n.ONE:n.inv(b));const $=n.mul(S,C),A=n.mul(y,C),O=n.mul(b,C);if(N)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:$,y:A}}),D=iu(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}const{x:C,y:S}=R.toAffine();if(!n.isValid(C)||!n.isValid(S))throw new Error("bad point: x or y not field elements");if(!w(C,S))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F(R,C,S,y,b){return S=new x(n.mul(S.X,R),S.Y,S.Z),C=Bo(y,C),S=Bo(b,S),C.add(S)}class x{constructor(C,S,y){this.X=_("x",C),this.Y=_("y",S,!0),this.Z=_("z",y),Object.freeze(this)}static CURVE(){return i}static fromAffine(C){const{x:S,y}=C||{};if(!C||!n.isValid(S)||!n.isValid(y))throw new Error("invalid affine point");if(C instanceof x)throw new Error("projective point not allowed");return n.is0(S)&&n.is0(y)?x.ZERO:new x(S,y,n.ONE)}static fromBytes(C){const S=x.fromAffine(g(Hn(C,void 0,"point")));return S.assertValidity(),S}static fromHex(C){return x.fromBytes(dt("pointHex",C))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(C=8,S=!0){return j.createCache(this,C),S||this.multiply(no),this}assertValidity(){D(this)}hasEvenY(){const{y:C}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(C)}equals(C){v(C);const{X:S,Y:y,Z:b}=this,{X:N,Y:$,Z:A}=C,O=n.eql(n.mul(S,A),n.mul(N,b)),M=n.eql(n.mul(y,A),n.mul($,b));return O&&M}negate(){return new x(this.X,n.neg(this.Y),this.Z)}double(){const{a:C,b:S}=i,y=n.mul(S,no),{X:b,Y:N,Z:$}=this;let A=n.ZERO,O=n.ZERO,M=n.ZERO,W=n.mul(b,b),ae=n.mul(N,N),se=n.mul($,$),X=n.mul(b,N);return X=n.add(X,X),M=n.mul(b,$),M=n.add(M,M),A=n.mul(C,M),O=n.mul(y,se),O=n.add(A,O),A=n.sub(ae,O),O=n.add(ae,O),O=n.mul(A,O),A=n.mul(X,A),M=n.mul(y,M),se=n.mul(C,se),X=n.sub(W,se),X=n.mul(C,X),X=n.add(X,M),M=n.add(W,W),W=n.add(M,W),W=n.add(W,se),W=n.mul(W,X),O=n.add(O,W),se=n.mul(N,$),se=n.add(se,se),W=n.mul(se,X),A=n.sub(A,W),M=n.mul(se,ae),M=n.add(M,M),M=n.add(M,M),new x(A,O,M)}add(C){v(C);const{X:S,Y:y,Z:b}=this,{X:N,Y:$,Z:A}=C;let O=n.ZERO,M=n.ZERO,W=n.ZERO;const ae=i.a,se=n.mul(i.b,no);let X=n.mul(S,N),le=n.mul(y,$),ie=n.mul(b,A),Se=n.add(S,y),ce=n.add(N,$);Se=n.mul(Se,ce),ce=n.add(X,le),Se=n.sub(Se,ce),ce=n.add(S,b);let Oe=n.add(N,A);return ce=n.mul(ce,Oe),Oe=n.add(X,ie),ce=n.sub(ce,Oe),Oe=n.add(y,b),O=n.add($,A),Oe=n.mul(Oe,O),O=n.add(le,ie),Oe=n.sub(Oe,O),W=n.mul(ae,ce),O=n.mul(se,ie),W=n.add(O,W),O=n.sub(le,W),W=n.add(le,W),M=n.mul(O,W),le=n.add(X,X),le=n.add(le,X),ie=n.mul(ae,ie),ce=n.mul(se,ce),le=n.add(le,ie),ie=n.sub(X,ie),ie=n.mul(ae,ie),ce=n.add(ce,ie),X=n.mul(le,ce),M=n.add(M,X),X=n.mul(Oe,ce),O=n.mul(Se,O),O=n.sub(O,X),X=n.mul(Se,le),W=n.mul(Oe,W),W=n.add(W,X),new x(O,M,W)}subtract(C){return this.add(C.negate())}is0(){return this.equals(x.ZERO)}multiply(C){const{endo:S}=e;if(!r.isValidNot0(C))throw new Error("invalid scalar: out of range");let y,b;const N=$=>j.cached(this,$,A=>Ma(x,A));if(S){const{k1neg:$,k1:A,k2neg:O,k2:M}=T(C),{p:W,f:ae}=N(A),{p:se,f:X}=N(M);b=ae.add(X),y=F(S.beta,W,se,$,O)}else{const{p:$,f:A}=N(C);y=$,b=A}return Ma(x,[y,b])[0]}multiplyUnsafe(C){const{endo:S}=e,y=this;if(!r.isValid(C))throw new Error("invalid scalar: out of range");if(C===Hs||y.is0())return x.ZERO;if(C===Tr)return y;if(j.hasCache(this))return this.multiply(C);if(S){const{k1neg:b,k1:N,k2neg:$,k2:A}=T(C),{p1:O,p2:M}=CC(x,y,N,A);return F(S.beta,O,M,b,$)}else return j.unsafe(y,C)}multiplyAndAddUnsafe(C,S,y){const b=this.multiplyUnsafe(S).add(C.multiplyUnsafe(y));return b.is0()?void 0:b}toAffine(C){return P(this,C)}isTorsionFree(){const{isTorsionFree:C}=e;return o===Tr?!0:C?C(x,this):j.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:C}=e;return o===Tr?this:C?C(x,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(C=!0){return Do(C,"isCompressed"),this.assertValidity(),p(x,this,C)}toHex(C=!0){return Nr(this.toBytes(C))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(C=!0){return this.toBytes(C)}_setWindowSize(C){this.precompute(C)}static normalizeZ(C){return Ma(x,C)}static msm(C,S){return vC(x,r,C,S)}static fromPrivateKey(C){return x.BASE.multiply(Cr(r,C))}}x.BASE=new x(i.Gx,i.Gy,n.ONE),x.ZERO=new x(n.ZERO,n.ONE,n.ZERO),x.Fp=n,x.Fn=r;const K=r.BITS,j=new EC(x,e.endo?Math.ceil(K/2):K);return x.BASE.precompute(8),x}function Rf(t){return Uint8Array.of(t?2:3)}function Pf(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function BC(t,e={}){const{Fn:s}=t,n=e.randomBytes||cr,r=Object.assign(Pf(t.Fp,s),{seed:If(s.ORDER)});function i(h){try{return!!Cr(s,h)}catch{return!1}}function o(h,p){const{publicKey:g,publicKeyUncompressed:f}=r;try{const w=h.length;return p===!0&&w!==g||p===!1&&w!==f?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(r.seed)){return wC(Hn(h,r.seed,"seed"),s.ORDER)}function c(h,p=!0){return t.BASE.multiply(Cr(s,h)).toBytes(p)}function l(h){const p=a(h);return{secretKey:p,publicKey:c(p)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:p,publicKey:g,publicKeyUncompressed:f}=r;if(s.allowedLengths||p===g)return;const w=dt("key",h).length;return w===g||w===f}function u(h,p,g=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(p)===!1)throw new Error("second arg must be public key");const f=Cr(s,h);return t.fromHex(p).multiply(f).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>Cr(s,h),precompute(h=8,p=t.BASE){return p.precompute(h,!1)}},lengths:r})}function MC(t,e,s={}){sa(e),ca(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=s.randomBytes||cr,r=s.hmac||((S,...y)=>ia(e,S,pn(...y))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p}=BC(t,s),g={prehash:!1,lowS:typeof s.lowS=="boolean"?s.lowS:!1,format:void 0,extraEntropy:!1},f="compact";function w(S){const y=a>>Tr;return S>y}function E(S,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return y}function I(S,y){Mc(y);const b=p.signature,N=y==="compact"?b:y==="recovered"?b+1:void 0;return Hn(S,N,`${y} signature`)}class _{constructor(y,b,N){this.r=E("r",y),this.s=E("s",b),N!=null&&(this.recovery=N),Object.freeze(this)}static fromBytes(y,b=f){I(y,b);let N;if(b==="der"){const{r:M,s:W}=Fs.toSig(Hn(y));return new _(M,W)}b==="recovered"&&(N=y[0],b="compact",y=y.subarray(1));const $=o.BYTES,A=y.subarray(0,$),O=y.subarray($,$*2);return new _(o.fromBytes(A),o.fromBytes(O),N)}static fromHex(y,b){return this.fromBytes($o(y),b)}addRecoveryBit(y){return new _(this.r,this.s,y)}recoverPublicKey(y){const b=i.ORDER,{r:N,s:$,recovery:A}=this;if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");if(a*Of<b&&A>1)throw new Error("recovery id is ambiguous for h>1 curve");const O=A===2||A===3?N+a:N;if(!i.isValid(O))throw new Error("recovery id 2 or 3 invalid");const M=i.toBytes(O),W=t.fromBytes(pn(Rf((A&1)===0),M)),ae=o.inv(O),se=T(dt("msgHash",y)),X=o.create(-se*ae),le=o.create($*ae),ie=t.BASE.multiplyUnsafe(X).add(W.multiplyUnsafe(le));if(ie.is0())throw new Error("point at infinify");return ie.assertValidity(),ie}hasHighS(){return w(this.s)}toBytes(y=f){if(Mc(y),y==="der")return $o(Fs.hexFromSig(this));const b=o.toBytes(this.r),N=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return pn(Uint8Array.of(this.recovery),b,N)}return pn(b,N)}toHex(y){return Nr(this.toBytes(y))}assertValidity(){}static fromCompact(y){return _.fromBytes(dt("sig",y),"compact")}static fromDER(y){return _.fromBytes(dt("sig",y),"der")}normalizeS(){return this.hasHighS()?new _(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Nr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Nr(this.toBytes("compact"))}}const v=s.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");const y=aa(S),b=S.length*8-c;return b>0?y>>BigInt(b):y},T=s.bits2int_modN||function(S){return o.create(v(S))},P=Li(c);function D(S){return Lc("num < 2^"+c,S,Hs,P),o.toBytes(S)}function F(S,y){return Hn(S,void 0,"message"),y?Hn(e(S),void 0,"prehashed message"):S}function x(S,y,b){if(["recovered","canonical"].some(le=>le in b))throw new Error("sign() legacy options not supported");const{lowS:N,prehash:$,extraEntropy:A}=Wa(b,g);S=F(S,$);const O=T(S),M=Cr(o,y),W=[D(M),D(O)];if(A!=null&&A!==!1){const le=A===!0?n(p.secretKey):A;W.push(dt("extraEntropy",le))}const ae=pn(...W),se=O;function X(le){const ie=v(le);if(!o.isValidNot0(ie))return;const Se=o.inv(ie),ce=t.BASE.multiply(ie).toAffine(),Oe=o.create(ce.x);if(Oe===Hs)return;const ht=o.create(Se*o.create(se+Oe*M));if(ht===Hs)return;let yt=(ce.x===Oe?0:2)|Number(ce.y&Tr),pt=ht;return N&&w(ht)&&(pt=o.neg(ht),yt^=1),new _(Oe,pt,yt)}return{seed:ae,k2sig:X}}function K(S,y,b={}){S=dt("message",S);const{seed:N,k2sig:$}=x(S,y,b);return cC(e.outputLen,o.BYTES,r)(N,$)}function j(S){let y;const b=typeof S=="string"||ta(S),N=!b&&S!==null&&typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!b&&!N)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(N)y=new _(S.r,S.s);else if(b){try{y=_.fromBytes(dt("sig",S),"der")}catch($){if(!($ instanceof Fs.Err))throw $}if(!y)try{y=_.fromBytes(dt("sig",S),"compact")}catch{return!1}}return y||!1}function R(S,y,b,N={}){const{lowS:$,prehash:A,format:O}=Wa(N,g);if(b=dt("publicKey",b),y=F(dt("message",y),A),"strict"in N)throw new Error("options.strict was renamed to lowS");const M=O===void 0?j(S):_.fromBytes(dt("sig",S),O);if(M===!1)return!1;try{const W=t.fromBytes(b);if($&&M.hasHighS())return!1;const{r:ae,s:se}=M,X=T(y),le=o.inv(se),ie=o.create(X*le),Se=o.create(ae*le),ce=t.BASE.multiplyUnsafe(ie).add(W.multiplyUnsafe(Se));return ce.is0()?!1:o.create(ce.x)===ae}catch{return!1}}function C(S,y,b={}){const{prehash:N}=Wa(b,g);return y=F(y,N),_.fromBytes(S,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p,Point:t,sign:K,verify:R,recoverPublicKey:C,Signature:_,hash:e})}function FC(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},s=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const r=Nn(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),i={Fp:s,Fn:r,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function jC(t){const{CURVE:e,curveOpts:s}=FC(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:s,hash:t.hash,ecdsaOpts:n}}function qC(t,e){const s=e.Point;return Object.assign({},e,{ProjectivePoint:s,CURVE:Object.assign({},t,Af(s.Fn.ORDER,s.Fn.BITS))})}function WC(t){const{CURVE:e,curveOpts:s,hash:n,ecdsaOpts:r}=jC(t),i=LC(e,s),o=MC(i,n,r);return qC(t,o)}function Fc(t,e){const s=n=>WC({...t,hash:n});return{...s(e),create:s}}const xf={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},kf={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},$f={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},HC=Nn(xf.p),KC=Nn(kf.p),zC=Nn($f.p),VC=Fc({...xf,Fp:HC,lowS:!1},ra);Fc({...kf,Fp:KC,lowS:!1},QE),Fc({...$f,Fp:zC,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},ZE);const GC=VC,Uf="base10",wt="base16",Nt="base64pad",fn="base64url",Bi="utf8",Df=0,Vs=1,Mi=2,YC=0,pu=1,di=12,kl=32;function JC(){const t=Bc.utils.randomPrivateKey(),e=Bc.getPublicKey(t);return{privateKey:Rt(t,wt),publicKey:Rt(e,wt)}}function jc(){const t=cr(kl);return Rt(t,wt)}function XC(t,e){const s=Bc.getSharedSecret(es(t,wt),es(e,wt)),n=oC(oa,s,void 0,void 0,kl);return Rt(n,wt)}function yo(t){const e=oa(es(t,wt));return Rt(e,wt)}function Xt(t){const e=oa(es(t,Bi));return Rt(e,wt)}function Lf(t){return es(`${t}`,Uf)}function sr(t){return Number(Rt(t,Uf))}function Bf(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Mf(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function ZC(t){const e=Lf(typeof t.type<"u"?t.type:Df);if(sr(e)===Vs&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?es(t.senderPublicKey,wt):void 0,n=typeof t.iv<"u"?es(t.iv,wt):cr(di),r=es(t.symKey,wt),i=uf(r,n).encrypt(es(t.message,Bi)),o=Ff({type:e,sealed:i,iv:n,senderPublicKey:s});return t.encoding===fn?Bf(o):o}function QC(t){const e=es(t.symKey,wt),{sealed:s,iv:n}=Ii({encoded:t.encoded,encoding:t.encoding}),r=uf(e,n).decrypt(s);if(r===null)throw new Error("Failed to decrypt");return Rt(r,Bi)}function ev(t,e){const s=Lf(Mi),n=cr(di),r=es(t,Bi),i=Ff({type:s,sealed:r,iv:n});return e===fn?Bf(i):i}function tv(t,e){const{sealed:s}=Ii({encoded:t,encoding:e});return Rt(s,Bi)}function Ff(t){if(sr(t.type)===Mi)return Rt(ai([t.type,t.sealed]),Nt);if(sr(t.type)===Vs){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Rt(ai([t.type,t.senderPublicKey,t.iv,t.sealed]),Nt)}return Rt(ai([t.type,t.iv,t.sealed]),Nt)}function Ii(t){const e=(t.encoding||Nt)===fn?Mf(t.encoded):t.encoded,s=es(e,Nt),n=s.slice(YC,pu),r=pu;if(sr(n)===Vs){const c=r+kl,l=c+di,d=s.slice(r,c),u=s.slice(c,l),h=s.slice(l);return{type:n,sealed:h,iv:u,senderPublicKey:d}}if(sr(n)===Mi){const c=s.slice(r),l=cr(di);return{type:n,sealed:c,iv:l}}const i=r+di,o=s.slice(r,i),a=s.slice(i);return{type:n,sealed:a,iv:o}}function sv(t,e){const s=Ii({encoded:t,encoding:e==null?void 0:e.encoding});return jf({type:sr(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?Rt(s.senderPublicKey,wt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function jf(t){const e=(t==null?void 0:t.type)||Df;if(e===Vs){if(typeof(t==null?void 0:t.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(t==null?void 0:t.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t==null?void 0:t.senderPublicKey,receiverPublicKey:t==null?void 0:t.receiverPublicKey}}function fu(t){return t.type===Vs&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function gu(t){return t.type===Mi}function nv(t){const e=Ee.from(t.x,"base64"),s=Ee.from(t.y,"base64");return ai([new Uint8Array([4]),e,s])}function rv(t,e){const[s,n,r]=t.split("."),i=Ee.from(Mf(r),"base64");if(i.length!==64)throw new Error("Invalid signature length");const o=i.slice(0,32),a=i.slice(32,64),c=`${s}.${n}`,l=oa(c),d=nv(e);if(!GC.verify(ai([o,a]),l,d))throw new Error("Invalid signature");return uc(t).payload}const iv="irn";function Mo(t){return(t==null?void 0:t.relay)||{protocol:iv}}function vr(t){const e=zg[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var ov=Object.defineProperty,av=Object.defineProperties,cv=Object.getOwnPropertyDescriptors,mu=Object.getOwnPropertySymbols,lv=Object.prototype.hasOwnProperty,dv=Object.prototype.propertyIsEnumerable,wu=(t,e,s)=>e in t?ov(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ha=(t,e)=>{for(var s in e||(e={}))lv.call(e,s)&&wu(t,s,e[s]);if(mu)for(var s of mu(e))dv.call(e,s)&&wu(t,s,e[s]);return t},uv=(t,e)=>av(t,cv(e));function hv(t,e="-"){const s={},n="relay"+e;return Object.keys(t).forEach(r=>{if(r.startsWith(n)){const i=r.replace(n,""),o=t[r];s[i]=o}}),s}function yu(t){if(!t.includes("wc:")){const l=Hp(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),s=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),r=t.substring(e+1,s).split("@"),i=typeof s<"u"?t.substring(s):"",o=new URLSearchParams(i),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:pv(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:hv(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function pv(t){return t.startsWith("//")?t.substring(2):t}function fv(t,e="-"){const s="relay",n={};return Object.keys(t).forEach(r=>{const i=r,o=s+e+i;t[i]&&(n[o]=t[i])}),n}function bu(t){const e=new URLSearchParams,s=Ha(Ha(uv(Ha({},fv(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(s).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!==void 0&&e.append(n,String(r))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function ro(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var gv=Object.defineProperty,mv=Object.defineProperties,wv=Object.getOwnPropertyDescriptors,Eu=Object.getOwnPropertySymbols,yv=Object.prototype.hasOwnProperty,bv=Object.prototype.propertyIsEnumerable,Cu=(t,e,s)=>e in t?gv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ev=(t,e)=>{for(var s in e||(e={}))yv.call(e,s)&&Cu(t,s,e[s]);if(Eu)for(var s of Eu(e))bv.call(e,s)&&Cu(t,s,e[s]);return t},Cv=(t,e)=>mv(t,wv(e));function Wr(t){const e=[];return t.forEach(s=>{const[n,r]=s.split(":");e.push(`${n}:${r}`)}),e}function vv(t){const e=[];return Object.values(t).forEach(s=>{e.push(...Wr(s.accounts))}),e}function Av(t,e){const s=[];return Object.values(t).forEach(n=>{Wr(n.accounts).includes(e)&&s.push(...n.methods)}),s}function _v(t,e){const s=[];return Object.values(t).forEach(n=>{Wr(n.accounts).includes(e)&&s.push(...n.events)}),s}function la(t){return t.includes(":")}function Ar(t){return la(t)?t.split(":")[0]:t}function vu(t){var e,s,n;const r={};if(!Ns(t))return r;for(const[i,o]of Object.entries(t)){const a=la(i)?[i]:o.chains,c=o.methods||[],l=o.events||[],d=Ar(i);r[d]=Cv(Ev({},r[d]),{chains:Ss(a,(e=r[d])==null?void 0:e.chains),methods:Ss(c,(s=r[d])==null?void 0:s.methods),events:Ss(l,(n=r[d])==null?void 0:n.events)})}return r}function Iv(t){const e={};return t==null||t.forEach(s=>{var n;const[r,i]=s.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(s),(n=e[r].chains)==null||n.push(`${r}:${i}`)}),e}function Au(t,e){e=e.map(n=>n.replace("did:pkh:",""));const s=Iv(e);for(const[n,r]of Object.entries(s))r.methods?r.methods=Ss(r.methods,t):r.methods=t,r.events=["chainChanged","accountsChanged"];return s}function Sv(t,e){var s,n,r,i,o,a;const c=vu(t),l=vu(e),d={},u=Object.keys(c).concat(Object.keys(l));for(const h of u)d[h]={chains:Ss((s=c[h])==null?void 0:s.chains,(n=l[h])==null?void 0:n.chains),methods:Ss((r=c[h])==null?void 0:r.methods,(i=l[h])==null?void 0:i.methods),events:Ss((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return d}const Nv={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}},Tv={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 H(t,e){const{message:s,code:n}=Tv[t];return{message:e?`${s} ${e}`:s,code:n}}function De(t,e){const{message:s,code:n}=Nv[t];return{message:e?`${s} ${e}`:s,code:n}}function Gs(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Ns(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function ze(t){return typeof t>"u"}function We(t,e){return e&&ze(t)?!0:typeof t=="string"&&!!t.trim().length}function $l(t,e){return e&&ze(t)?!0:typeof t=="number"&&!isNaN(t)}function Ov(t,e){const{requiredNamespaces:s}=e,n=Object.keys(t.namespaces),r=Object.keys(s);let i=!0;return Wn(r,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],d=Wr(a),u=s[o];(!Wn(Mp(o,u),d)||!Wn(u.methods,c)||!Wn(u.events,l))&&(i=!1)}),i):!1}function Fo(t){return We(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function Rv(t){if(We(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&Fo(s)}}return!1}function Pv(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(We(t,!1)){if(e(t))return!0;const s=Hp(t);return e(s)}}catch{}return!1}function xv(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function kv(t){return t==null?void 0:t.topic}function $v(t,e){let s=null;return We(t==null?void 0:t.publicKey,!1)||(s=H("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function _u(t){let e=!0;return Gs(t)?t.length&&(e=t.every(s=>We(s,!1))):e=!1,e}function Uv(t,e,s){let n=null;return Gs(e)&&e.length?e.forEach(r=>{n||Fo(r)||(n=De("UNSUPPORTED_CHAINS",`${s}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Fo(t)||(n=De("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function Dv(t,e,s){let n=null;return Object.entries(t).forEach(([r,i])=>{if(n)return;const o=Uv(r,Mp(r,i),`${e} ${s}`);o&&(n=o)}),n}function Lv(t,e){let s=null;return Gs(t)?t.forEach(n=>{s||Rv(n)||(s=De("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):s=De("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function Bv(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=Lv(n==null?void 0:n.accounts,`${e} namespace`);r&&(s=r)}),s}function Mv(t,e){let s=null;return _u(t==null?void 0:t.methods)?_u(t==null?void 0:t.events)||(s=De("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=De("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function qf(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=Mv(n,`${e}, namespace`);r&&(s=r)}),s}function Fv(t,e,s){let n=null;if(t&&Ns(t)){const r=qf(t,e);r&&(n=r);const i=Dv(t,e,s);i&&(n=i)}else n=H("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return n}function Ka(t,e){let s=null;if(t&&Ns(t)){const n=qf(t,e);n&&(s=n);const r=Bv(t,e);r&&(s=r)}else s=H("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function Wf(t){return We(t.protocol,!0)}function jv(t,e){let s=!1;return e&&!t?s=!0:t&&Gs(t)&&t.length&&t.forEach(n=>{s=Wf(n)}),s}function qv(t){return typeof t=="number"}function _t(t){return typeof t<"u"&&typeof t!==null}function Wv(t){return!(!t||typeof t!="object"||!t.code||!$l(t.code,!1)||!t.message||!We(t.message,!1))}function Hv(t){return!(ze(t)||!We(t.method,!1))}function Kv(t){return!(ze(t)||ze(t.result)&&ze(t.error)||!$l(t.id,!1)||!We(t.jsonrpc,!1))}function zv(t){return!(ze(t)||!We(t.name,!1))}function Iu(t,e){return!(!Fo(e)||!vv(t).includes(e))}function Vv(t,e,s){return We(s,!1)?Av(t,e).includes(s):!1}function Gv(t,e,s){return We(s,!1)?_v(t,e).includes(s):!1}function Su(t,e,s){let n=null;const r=Yv(t),i=Jv(e),o=Object.keys(r),a=Object.keys(i),c=Nu(Object.keys(t)),l=Nu(Object.keys(e)),d=c.filter(u=>!l.includes(u));return d.length&&(n=H("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
|
|
6
|
+
`);super(a,s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Yy()}`}),this.cause=s.cause,this.details=n,this.docs=o,this.docsPath=r,this.shortMessage=e}walk(e){return ip(this,e)}}function ip(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?ip(t.cause,e):e?null:t}const hr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Jy(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ei(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function er(t,...e){if(!Jy(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Xy(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ei(t.outputLen),Ei(t.blockLen)}function kr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function op(t,e){er(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Zy(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function $r(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Aa(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function fs(t,e){return t<<32-e|t>>>e}const Qy=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function e0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function t0(t){for(let e=0;e<t.length;e++)t[e]=e0(t[e]);return t}const fd=Qy?t=>t:t0;function s0(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Zo(t){return typeof t=="string"&&(t=s0(t)),er(t),t}function n0(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];er(r),e+=r.length}const s=new Uint8Array(e);for(let n=0,r=0;n<t.length;n++){const i=t[n];s.set(i,r),r+=i.length}return s}class gl{}function ap(t){const e=n=>t().update(Zo(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function r0(t=32){if(hr&&typeof hr.getRandomValues=="function")return hr.getRandomValues(new Uint8Array(t));if(hr&&typeof hr.randomBytes=="function")return Uint8Array.from(hr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function i0(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function o0(t,e,s){return t&e^~t&s}function a0(t,e,s){return t&e^t&s^e&s}class c0 extends gl{constructor(e,s,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=s,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Aa(this.buffer)}update(e){kr(this),e=Zo(e),er(e);const{view:s,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(r-this.pos,i-o);if(a===r){const c=Aa(e);for(;r<=i-o;o+=r)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){kr(this),op(e,this),this.finished=!0;const{buffer:s,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,$r(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)s[u]=0;i0(n,r-8,BigInt(this.length*8),i),this.process(n,0);const a=Aa(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=a,r%s&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const en=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ji=BigInt(2**32-1),gd=BigInt(32);function l0(t,e=!1){return e?{h:Number(t&Ji),l:Number(t>>gd&Ji)}:{h:Number(t>>gd&Ji)|0,l:Number(t&Ji)|0}}function d0(t,e=!1){const s=t.length;let n=new Uint32Array(s),r=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=l0(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const u0=(t,e,s)=>t<<s|e>>>32-s,h0=(t,e,s)=>e<<s|t>>>32-s,p0=(t,e,s)=>e<<s-32|t>>>64-s,f0=(t,e,s)=>t<<s-32|e>>>64-s,g0=BigInt(0),zr=BigInt(1),m0=BigInt(2),w0=BigInt(7),y0=BigInt(256),b0=BigInt(113),cp=[],lp=[],dp=[];for(let t=0,e=zr,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],cp.push(2*(5*n+s)),lp.push((t+1)*(t+2)/2%64);let r=g0;for(let i=0;i<7;i++)e=(e<<zr^(e>>w0)*b0)%y0,e&m0&&(r^=zr<<(zr<<BigInt(i))-zr);dp.push(r)}const up=d0(dp,!0),E0=up[0],C0=up[1],md=(t,e,s)=>s>32?p0(t,e,s):u0(t,e,s),wd=(t,e,s)=>s>32?f0(t,e,s):h0(t,e,s);function v0(t,e=24){const s=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],d=s[c+1],u=md(l,d,1)^s[a],h=wd(l,d,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=lp[o],c=md(r,i,a),l=wd(r,i,a),d=cp[o];r=t[d],i=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=E0[n],t[1]^=C0[n]}$r(s)}class ml extends gl{constructor(e,s,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=s,this.outputLen=n,this.enableXOF=r,this.rounds=i,Ei(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Zy(this.state)}clone(){return this._cloneInto()}keccak(){fd(this.state32),v0(this.state32,this.rounds),fd(this.state32),this.posOut=0,this.pos=0}update(e){kr(this),e=Zo(e),er(e);const{blockLen:s,state:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:n,blockLen:r}=this;e[n]^=s,s&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){kr(this,!1),er(e),this.finish();const s=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(s.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ei(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(op(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,$r(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new ml(s,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const A0=(t,e,s)=>ap(()=>new ml(e,t,s)),_0=(()=>A0(1,136,256/8))(),I0=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),tn=new Uint32Array(64);class S0 extends c0{constructor(e=32){super(64,e,8,!1),this.A=en[0]|0,this.B=en[1]|0,this.C=en[2]|0,this.D=en[3]|0,this.E=en[4]|0,this.F=en[5]|0,this.G=en[6]|0,this.H=en[7]|0}get(){const{A:e,B:s,C:n,D:r,E:i,F:o,G:a,H:c}=this;return[e,s,n,r,i,o,a,c]}set(e,s,n,r,i,o,a,c){this.A=e|0,this.B=s|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let u=0;u<16;u++,s+=4)tn[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const h=tn[u-15],p=tn[u-2],g=fs(h,7)^fs(h,18)^h>>>3,f=fs(p,17)^fs(p,19)^p>>>10;tn[u]=f+tn[u-7]+g+tn[u-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=fs(a,6)^fs(a,11)^fs(a,25),p=d+h+o0(a,c,l)+I0[u]+tn[u]|0,f=(fs(n,2)^fs(n,13)^fs(n,22))+a0(n,r,i)|0;d=l,l=c,c=a,a=o+p|0,o=i,i=r,r=n,n=p+f|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,r,i,o,a,c,l,d)}roundClean(){$r(tn)}destroy(){this.set(0,0,0,0,0,0,0,0),$r(this.buffer)}}const N0=ap(()=>new S0);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wl=BigInt(0),Ac=BigInt(1);function ki(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function yl(t){if(!ki(t))throw new Error("Uint8Array expected")}function Ci(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Xi(t){const e=t.toString(16);return e.length&1?"0"+e:e}function hp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?wl:BigInt("0x"+t)}const pp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",T0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function vi(t){if(yl(t),pp)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=T0[t[s]];return e}const Rs={_0:48,_9:57,A:65,F:70,a:97,f:102};function yd(t){if(t>=Rs._0&&t<=Rs._9)return t-Rs._0;if(t>=Rs.A&&t<=Rs.F)return t-(Rs.A-10);if(t>=Rs.a&&t<=Rs.f)return t-(Rs.a-10)}function Ro(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(pp)return Uint8Array.fromHex(t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=yd(t.charCodeAt(i)),a=yd(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[r]=o*16+a}return n}function Yn(t){return hp(vi(t))}function fp(t){return yl(t),hp(vi(Uint8Array.from(t).reverse()))}function $i(t,e){return Ro(t.toString(16).padStart(e*2,"0"))}function gp(t,e){return $i(t,e).reverse()}function Jt(t,e,s){let n;if(typeof e=="string")try{n=Ro(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(ki(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const r=n.length;if(typeof s=="number"&&r!==s)throw new Error(t+" of length "+s+" expected, got "+r);return n}function Po(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];yl(r),e+=r.length}const s=new Uint8Array(e);for(let n=0,r=0;n<t.length;n++){const i=t[n];s.set(i,r),r+=i.length}return s}const _a=t=>typeof t=="bigint"&&wl<=t;function bl(t,e,s){return _a(t)&&_a(e)&&_a(s)&&e<=t&&t<s}function Sr(t,e,s,n){if(!bl(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function O0(t){let e;for(e=0;t>wl;t>>=Ac,e+=1);return e}const Qo=t=>(Ac<<BigInt(t))-Ac,Ia=t=>new Uint8Array(t),bd=t=>Uint8Array.from(t);function R0(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");let n=Ia(t),r=Ia(t),i=0;const o=()=>{n.fill(1),r.fill(0),i=0},a=(...u)=>s(r,n,...u),c=(u=Ia(0))=>{r=a(bd([0]),u),n=a(),u.length!==0&&(r=a(bd([1]),u),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const h=[];for(;u<e;){n=a();const p=n.slice();h.push(p),u+=n.length}return Po(...h)};return(u,h)=>{o(),c(u);let p;for(;!(p=h(l()));)c();return o(),p}}const P0={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||ki(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function ea(t,e,s={}){const n=(r,i,o)=>{const a=P0[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[r];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(r)+" is invalid. Expected "+i+", got "+c)};for(const[r,i]of Object.entries(e))n(r,i,!1);for(const[r,i]of Object.entries(s))n(r,i,!0);return t}function Ed(t){const e=new WeakMap;return(s,...n)=>{const r=e.get(s);if(r!==void 0)return r;const i=t(s,...n);return e.set(s,i),i}}function x0(t,e){if(_d(t)>e)throw new Q0({givenSize:_d(t),maxSize:e})}const Ps={zero:48,nine:57,A:65,F:70,a:97,f:102};function Cd(t){if(t>=Ps.zero&&t<=Ps.nine)return t-Ps.zero;if(t>=Ps.A&&t<=Ps.F)return t-(Ps.A-10);if(t>=Ps.a&&t<=Ps.f)return t-(Ps.a-10)}function k0(t,e={}){const{dir:s,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new eb({size:t.length,targetSize:n,type:"Bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const o=s==="right";r[o?i:n-i-1]=t[o?i:t.length-i-1]}return r}function mp(t,e){if(_n(t)>e)throw new W0({givenSize:_n(t),maxSize:e})}function $0(t,e){if(typeof e=="number"&&e>0&&e>_n(t)-1)throw new bp({offset:e,position:"start",size:_n(t)})}function U0(t,e,s){if(typeof e=="number"&&typeof s=="number"&&_n(t)!==s-e)throw new bp({offset:s,position:"end",size:_n(t)})}function wp(t,e={}){const{dir:s,size:n=32}=e;if(n===0)return t;const r=t.replace("0x","");if(r.length>n*2)throw new H0({size:Math.ceil(r.length/2),targetSize:n,type:"Hex"});return`0x${r[s==="right"?"padEnd":"padStart"](n*2,"0")}`}const D0="#__bigint";function El(t,e,s){return JSON.stringify(t,(n,r)=>typeof e=="function"?e(n,r):typeof r=="bigint"?r.toString()+D0:r,s)}const L0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function B0(t,e={}){const{strict:s=!1}=e;if(!t)throw new vd(t);if(typeof t!="string")throw new vd(t);if(s&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Ad(t);if(!t.startsWith("0x"))throw new Ad(t)}function M0(...t){return`0x${t.reduce((e,s)=>e+s.replace("0x",""),"")}`}function Cl(t){return t instanceof Uint8Array?xo(t):Array.isArray(t)?xo(new Uint8Array(t)):t}function xo(t,e={}){let s="";for(let r=0;r<t.length;r++)s+=L0[t[r]];const n=`0x${s}`;return typeof e.size=="number"?(mp(n,e.size),yp(n,e.size)):n}function Sa(t,e={}){const{signed:s,size:n}=e,r=BigInt(t);let i;n?s?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&s?-i-1n:0;if(i&&r>i||r<o){const l=typeof t=="bigint"?"n":"";throw new q0({max:i?`${i}${l}`:void 0,min:`${o}${l}`,signed:s,size:n,value:`${t}${l}`})}const c=`0x${(s&&r<0?(1n<<BigInt(n*8))+BigInt(r):r).toString(16)}`;return n?F0(c,n):c}function F0(t,e){return wp(t,{dir:"left",size:e})}function yp(t,e){return wp(t,{dir:"right",size:e})}function Ls(t,e,s,n={}){const{strict:r}=n;$0(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(s??t.length)*2)}`;return r&&U0(i,e,s),i}function _n(t){return Math.ceil((t.length-2)/2)}function j0(t,e={}){const{strict:s=!1}=e;try{return B0(t,{strict:s}),!0}catch{return!1}}class q0 extends Le{constructor({max:e,min:s,signed:n,size:r,value:i}){super(`Number \`${i}\` is not in safe${r?` ${r*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${s}\` to \`${e}\`)`:`(above \`${s}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class vd extends Le{constructor(e){super(`Value \`${typeof e=="object"?El(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Ad extends Le{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}let W0=class extends Le{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed \`${s}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class bp extends Le{constructor({offset:e,position:s,size:n}){super(`Slice ${s==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let H0=class extends Le{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${s}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const K0=new TextEncoder;function z0(t){if(!(t instanceof Uint8Array)){if(!t)throw new Zi(t);if(typeof t!="object")throw new Zi(t);if(!("BYTES_PER_ELEMENT"in t))throw new Zi(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new Zi(t)}}function V0(t){return t instanceof Uint8Array?t:typeof t=="string"?Y0(t):G0(t)}function G0(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Y0(t,e={}){const{size:s}=e;let n=t;s&&(mp(t,s),n=yp(t,s));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,o=new Uint8Array(i);for(let a=0,c=0;a<i;a++){const l=Cd(r.charCodeAt(c++)),d=Cd(r.charCodeAt(c++));if(l===void 0||d===void 0)throw new Le(`Invalid byte sequence ("${r[c-2]}${r[c-1]}" in "${r}").`);o[a]=l*16+d}return o}function J0(t,e={}){const{size:s}=e,n=K0.encode(t);return typeof s=="number"?(x0(n,s),X0(n,s)):n}function X0(t,e){return k0(t,{dir:"right",size:e})}function _d(t){return t.length}function Z0(t){try{return z0(t),!0}catch{return!1}}class Zi extends Le{constructor(e){super(`Value \`${typeof e=="object"?El(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class Q0 extends Le{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed \`${s}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class eb extends Le{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${s}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function Ep(t,e={}){const{as:s=typeof t=="string"?"Hex":"Bytes"}=e,n=_0(V0(t));return s==="Bytes"?n:xo(n)}class tb extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const s=super.get(e);return super.has(e)&&s!==void 0&&(this.delete(e),super.set(e,s)),s}set(e,s){if(super.set(e,s),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const sb={checksum:new tb(8192)},Na=sb.checksum;function Cp(t,e={}){const{compressed:s}=e,{prefix:n,x:r,y:i}=t;if(s===!1||typeof r=="bigint"&&typeof i=="bigint"){if(n!==4)throw new Id({prefix:n,cause:new cb});return}if(s===!0||typeof r=="bigint"&&typeof i>"u"){if(n!==3&&n!==2)throw new Id({prefix:n,cause:new ab});return}throw new ob({publicKey:t})}function nb(t){const e=(()=>{if(j0(t))return vp(t);if(Z0(t))return rb(t);const{prefix:s,x:n,y:r}=t;return typeof n=="bigint"&&typeof r=="bigint"?{prefix:s??4,x:n,y:r}:{prefix:s,x:n}})();return Cp(e),e}function rb(t){return vp(xo(t))}function vp(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new lb({publicKey:t});if(t.length===130){const n=BigInt(Ls(t,0,32)),r=BigInt(Ls(t,32,64));return{prefix:4,x:n,y:r}}if(t.length===132){const n=Number(Ls(t,0,1)),r=BigInt(Ls(t,1,33)),i=BigInt(Ls(t,33,65));return{prefix:n,x:r,y:i}}const e=Number(Ls(t,0,1)),s=BigInt(Ls(t,1,33));return{prefix:e,x:s}}function ib(t,e={}){Cp(t);const{prefix:s,x:n,y:r}=t,{includePrefix:i=!0}=e;return M0(i?Sa(s,{size:1}):"0x",Sa(n,{size:32}),typeof r=="bigint"?Sa(r,{size:32}):"0x")}class ob extends Le{constructor({publicKey:e}){super(`Value \`${El(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class Id extends Le{constructor({prefix:e,cause:s}){super(`Prefix "${e}" is invalid.`,{cause:s}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class ab extends Le{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class cb extends Le{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let lb=class extends Le{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${_n(Cl(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const db=/^0x[a-fA-F0-9]{40}$/;function Ap(t,e={}){const{strict:s=!0}=e;if(!db.test(t))throw new Sd({address:t,cause:new pb});if(s){if(t.toLowerCase()===t)return;if(_p(t)!==t)throw new Sd({address:t,cause:new fb})}}function _p(t){if(Na.has(t))return Na.get(t);Ap(t,{strict:!1});const e=t.substring(2).toLowerCase(),s=Ep(J0(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)s[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(s[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const r=`0x${n.join("")}`;return Na.set(t,r),r}function ub(t,e={}){const{checksum:s=!1}=e;return Ap(t),s?_p(t):t}function hb(t,e={}){const s=Ep(`0x${ib(t).slice(4)}`).substring(26);return ub(`0x${s}`,e)}class Sd extends Le{constructor({address:e,cause:s}){super(`Address "${e}" is invalid.`,{cause:s}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class pb extends Le{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class fb extends Le{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class Ip extends gl{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,Xy(e);const n=Zo(s);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),$r(i)}update(e){return kr(this),this.iHash.update(e),this}digestInto(e){kr(this),er(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Sp=(t,e,s)=>new Ip(t,e).update(s).digest();Sp.create=(t,e)=>new Ip(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Tt=BigInt(0),gt=BigInt(1),qn=BigInt(2),gb=BigInt(3),Np=BigInt(4),Tp=BigInt(5),Op=BigInt(8);function It(t,e){const s=t%e;return s>=Tt?s:e+s}function Wt(t,e,s){let n=t;for(;e-- >Tt;)n*=n,n%=s;return n}function _c(t,e){if(t===Tt)throw new Error("invert: expected non-zero number");if(e<=Tt)throw new Error("invert: expected positive modulus, got "+e);let s=It(t,e),n=e,r=Tt,i=gt;for(;s!==Tt;){const a=n/s,c=n%s,l=r-i*a;n=s,s=c,r=i,i=l}if(n!==gt)throw new Error("invert: does not exist");return It(r,e)}function Rp(t,e){const s=(t.ORDER+gt)/Np,n=t.pow(e,s);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function mb(t,e){const s=(t.ORDER-Tp)/Op,n=t.mul(e,qn),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,qn),r),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function wb(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-gt,s=0;for(;e%qn===Tt;)e/=qn,s++;let n=qn;const r=vl(t);for(;Nd(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Rp;let i=r.pow(n,e);const o=(e+gt)/qn;return function(c,l){if(c.is0(l))return l;if(Nd(c,l)!==1)throw new Error("Cannot find square root");let d=s,u=c.mul(c.ONE,i),h=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let g=1,f=c.sqr(h);for(;!c.eql(f,c.ONE);)if(g++,f=c.sqr(f),g===d)throw new Error("Cannot find square root");const w=gt<<BigInt(d-g-1),E=c.pow(u,w);d=g,u=c.sqr(E),h=c.mul(h,u),p=c.mul(p,E)}return p}}function yb(t){return t%Np===gb?Rp:t%Op===Tp?mb:wb(t)}const bb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Eb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},s=bb.reduce((n,r)=>(n[r]="function",n),e);return ea(t,s)}function Cb(t,e,s){if(s<Tt)throw new Error("invalid exponent, negatives unsupported");if(s===Tt)return t.ONE;if(s===gt)return e;let n=t.ONE,r=e;for(;s>Tt;)s>&&(n=t.mul(n,r)),r=t.sqr(r),s>>=gt;return n}function Pp(t,e,s=!1){const n=new Array(e.length).fill(s?t.ZERO:void 0),r=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(r);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function Nd(t,e){const s=(t.ORDER-gt)/qn,n=t.pow(e,s),r=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function xp(t,e){e!==void 0&&Ei(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function vl(t,e,s=!1,n={}){if(t<=Tt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:r,nByteLength:i}=xp(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:s,BITS:r,BYTES:i,MASK:Qo(r),ZERO:Tt,ONE:gt,create:c=>It(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Tt<=c&&c<t},is0:c=>c===Tt,isOdd:c=>(c>)===gt,neg:c=>It(-c,t),eql:(c,l)=>c===l,sqr:c=>It(c*c,t),add:(c,l)=>It(c+l,t),sub:(c,l)=>It(c-l,t),mul:(c,l)=>It(c*l,t),pow:(c,l)=>Cb(a,c,l),div:(c,l)=>It(c*_c(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>_c(c,t),sqrt:n.sqrt||(c=>(o||(o=yb(t)),o(a,c))),toBytes:c=>s?gp(c,i):$i(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return s?fp(c):Yn(c)},invertBatch:c=>Pp(a,c),cmov:(c,l,d)=>d?l:c});return Object.freeze(a)}function kp(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function $p(t){const e=kp(t);return e+Math.ceil(e/2)}function vb(t,e,s=!1){const n=t.length,r=kp(e),i=$p(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?fp(t):Yn(t),a=It(o,e-gt)+gt;return s?gp(a,r):$i(a,r)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Td=BigInt(0),Ic=BigInt(1);function Ta(t,e){const s=e.negate();return t?s:e}function Up(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Oa(t,e){Up(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=Qo(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function Od(t,e,s){const{windowSize:n,mask:r,maxNumber:i,shiftBy:o}=s;let a=Number(t&r),c=t>>o;a>n&&(a-=i,c+=Ic);const l=e*n,d=l+Math.abs(a)-1,u=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:l}}function Ab(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,n)=>{if(!(s instanceof e))throw new Error("invalid point at index "+n)})}function _b(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,n)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+n)})}const Ra=new WeakMap,Dp=new WeakMap;function Pa(t){return Dp.get(t)||1}function Ib(t,e){return{constTimeNegate:Ta,hasPrecomputes(s){return Pa(s)!==1},unsafeLadder(s,n,r=t.ZERO){let i=s;for(;n>Td;)n&Ic&&(r=r.add(i)),i=i.double(),n>>=Ic;return r},precomputeWindow(s,n){const{windows:r,windowSize:i}=Oa(n,e),o=[];let a=s,c=a;for(let l=0;l<r;l++){c=a,o.push(c);for(let d=1;d<i;d++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(s,n,r){let i=t.ZERO,o=t.BASE;const a=Oa(s,e);for(let c=0;c<a.windows;c++){const{nextN:l,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:g}=Od(r,c,a);r=l,u?o=o.add(Ta(p,n[g])):i=i.add(Ta(h,n[d]))}return{p:i,f:o}},wNAFUnsafe(s,n,r,i=t.ZERO){const o=Oa(s,e);for(let a=0;a<o.windows&&r!==Td;a++){const{nextN:c,offset:l,isZero:d,isNeg:u}=Od(r,a,o);if(r=c,!d){const h=n[l];i=i.add(u?h.negate():h)}}return i},getPrecomputes(s,n,r){let i=Ra.get(n);return i||(i=this.precomputeWindow(n,s),s!==1&&Ra.set(n,r(i))),i},wNAFCached(s,n,r){const i=Pa(s);return this.wNAF(i,this.getPrecomputes(i,s,r),n)},wNAFCachedUnsafe(s,n,r,i){const o=Pa(s);return o===1?this.unsafeLadder(s,n,i):this.wNAFUnsafe(o,this.getPrecomputes(o,s,r),n,i)},setWindowSize(s,n){Up(n,e),Dp.set(s,n),Ra.delete(s)}}}function Sb(t,e,s,n){Ab(s,t),_b(n,e);const r=s.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=O0(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Qo(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=u;p>=0;p-=c){d.fill(o);for(let f=0;f<i;f++){const w=n[f],E=Number(w>>BigInt(p)&l);d[E]=d[E].add(s[f])}let g=o;for(let f=d.length-1,w=o;f>0;f--)w=w.add(d[f]),g=g.add(w);if(h=h.add(g),p!==0)for(let f=0;f<c;f++)h=h.double()}return h}function Lp(t){return Eb(t.Fp),ea(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...xp(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Rd(t){t.lowS!==void 0&&Ci("lowS",t.lowS),t.prehash!==void 0&&Ci("prehash",t.prehash)}function Nb(t){const e=Lp(t);ea(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:s,Fp:n,a:r}=e;if(s){if(!n.eql(r,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof s!="object"||typeof s.beta!="bigint"||typeof s.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class Tb extends Error{constructor(e=""){super(e)}}const Ms={Err:Tb,_tlv:{encode:(t,e)=>{const{Err:s}=Ms;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const n=e.length/2,r=Xi(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?Xi(r.length/2|128):"";return Xi(t)+i+r+e},decode(t,e){const{Err:s}=Ms;let n=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new s("tlv.decode: wrong tlv");const r=e[n++],i=!!(r&128);let o=0;if(!i)o=r;else{const c=r&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(n+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=Ms;if(t<qs)throw new e("integer: negative integers are not allowed");let s=Xi(t);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(t){const{Err:e}=Ms;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Yn(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=Ms,r=Jt("signature",t),{v:i,l:o}=n.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=Ms,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}};function xa(t,e){return vi($i(t,e))}const qs=BigInt(0),Je=BigInt(1);BigInt(2);const ka=BigInt(3),Ob=BigInt(4);function Rb(t){const e=Nb(t),{Fp:s}=e,n=vl(e.n,e.nBitLength),r=e.toBytes||((_,v,T)=>{const P=v.toAffine();return Po(Uint8Array.from([4]),s.toBytes(P.x),s.toBytes(P.y))}),i=e.fromBytes||(_=>{const v=_.subarray(1),T=s.fromBytes(v.subarray(0,s.BYTES)),P=s.fromBytes(v.subarray(s.BYTES,2*s.BYTES));return{x:T,y:P}});function o(_){const{a:v,b:T}=e,P=s.sqr(_),D=s.mul(P,_);return s.add(s.add(D,s.mul(_,v)),T)}function a(_,v){const T=s.sqr(v),P=o(_);return s.eql(T,P)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=s.mul(s.pow(e.a,ka),Ob),l=s.mul(s.sqr(e.b),BigInt(27));if(s.is0(s.add(c,l)))throw new Error("bad curve params: a or b");function d(_){return bl(_,Je,e.n)}function u(_){const{allowedPrivateKeyLengths:v,nByteLength:T,wrapPrivateKey:P,n:D}=e;if(v&&typeof _!="bigint"){if(ki(_)&&(_=vi(_)),typeof _!="string"||!v.includes(_.length))throw new Error("invalid private key");_=_.padStart(T*2,"0")}let F;try{F=typeof _=="bigint"?_:Yn(Jt("private key",_,T))}catch{throw new Error("invalid private key, expected hex or "+T+" bytes, got "+typeof _)}return P&&(F=It(F,D)),Sr("private key",F,Je,D),F}function h(_){if(!(_ instanceof f))throw new Error("ProjectivePoint expected")}const p=Ed((_,v)=>{const{px:T,py:P,pz:D}=_;if(s.eql(D,s.ONE))return{x:T,y:P};const F=_.is0();v==null&&(v=F?s.ONE:s.inv(D));const x=s.mul(T,v),K=s.mul(P,v),j=s.mul(D,v);if(F)return{x:s.ZERO,y:s.ZERO};if(!s.eql(j,s.ONE))throw new Error("invZ was invalid");return{x,y:K}}),g=Ed(_=>{if(_.is0()){if(e.allowInfinityPoint&&!s.is0(_.py))return;throw new Error("bad point: ZERO")}const{x:v,y:T}=_.toAffine();if(!s.isValid(v)||!s.isValid(T))throw new Error("bad point: x or y not FE");if(!a(v,T))throw new Error("bad point: equation left != right");if(!_.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(v,T,P){if(v==null||!s.isValid(v))throw new Error("x required");if(T==null||!s.isValid(T)||s.is0(T))throw new Error("y required");if(P==null||!s.isValid(P))throw new Error("z required");this.px=v,this.py=T,this.pz=P,Object.freeze(this)}static fromAffine(v){const{x:T,y:P}=v||{};if(!v||!s.isValid(T)||!s.isValid(P))throw new Error("invalid affine point");if(v instanceof f)throw new Error("projective point not allowed");const D=F=>s.eql(F,s.ZERO);return D(T)&&D(P)?f.ZERO:new f(T,P,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const T=Pp(s,v.map(P=>P.pz));return v.map((P,D)=>P.toAffine(T[D])).map(f.fromAffine)}static fromHex(v){const T=f.fromAffine(i(Jt("pointHex",v)));return T.assertValidity(),T}static fromPrivateKey(v){return f.BASE.multiply(u(v))}static msm(v,T){return Sb(f,n,v,T)}_setWindowSize(v){I.setWindowSize(this,v)}assertValidity(){g(this)}hasEvenY(){const{y:v}=this.toAffine();if(s.isOdd)return!s.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){h(v);const{px:T,py:P,pz:D}=this,{px:F,py:x,pz:K}=v,j=s.eql(s.mul(T,K),s.mul(F,D)),R=s.eql(s.mul(P,K),s.mul(x,D));return j&&R}negate(){return new f(this.px,s.neg(this.py),this.pz)}double(){const{a:v,b:T}=e,P=s.mul(T,ka),{px:D,py:F,pz:x}=this;let K=s.ZERO,j=s.ZERO,R=s.ZERO,C=s.mul(D,D),S=s.mul(F,F),y=s.mul(x,x),b=s.mul(D,F);return b=s.add(b,b),R=s.mul(D,x),R=s.add(R,R),K=s.mul(v,R),j=s.mul(P,y),j=s.add(K,j),K=s.sub(S,j),j=s.add(S,j),j=s.mul(K,j),K=s.mul(b,K),R=s.mul(P,R),y=s.mul(v,y),b=s.sub(C,y),b=s.mul(v,b),b=s.add(b,R),R=s.add(C,C),C=s.add(R,C),C=s.add(C,y),C=s.mul(C,b),j=s.add(j,C),y=s.mul(F,x),y=s.add(y,y),C=s.mul(y,b),K=s.sub(K,C),R=s.mul(y,S),R=s.add(R,R),R=s.add(R,R),new f(K,j,R)}add(v){h(v);const{px:T,py:P,pz:D}=this,{px:F,py:x,pz:K}=v;let j=s.ZERO,R=s.ZERO,C=s.ZERO;const S=e.a,y=s.mul(e.b,ka);let b=s.mul(T,F),N=s.mul(P,x),$=s.mul(D,K),A=s.add(T,P),O=s.add(F,x);A=s.mul(A,O),O=s.add(b,N),A=s.sub(A,O),O=s.add(T,D);let M=s.add(F,K);return O=s.mul(O,M),M=s.add(b,$),O=s.sub(O,M),M=s.add(P,D),j=s.add(x,K),M=s.mul(M,j),j=s.add(N,$),M=s.sub(M,j),C=s.mul(S,O),j=s.mul(y,$),C=s.add(j,C),j=s.sub(N,C),C=s.add(N,C),R=s.mul(j,C),N=s.add(b,b),N=s.add(N,b),$=s.mul(S,$),O=s.mul(y,O),N=s.add(N,$),$=s.sub(b,$),$=s.mul(S,$),O=s.add(O,$),b=s.mul(N,O),R=s.add(R,b),b=s.mul(M,O),j=s.mul(A,j),j=s.sub(j,b),b=s.mul(A,N),C=s.mul(M,C),C=s.add(C,b),new f(j,R,C)}subtract(v){return this.add(v.negate())}is0(){return this.equals(f.ZERO)}wNAF(v){return I.wNAFCached(this,v,f.normalizeZ)}multiplyUnsafe(v){const{endo:T,n:P}=e;Sr("scalar",v,qs,P);const D=f.ZERO;if(v===qs)return D;if(this.is0()||v===Je)return this;if(!T||I.hasPrecomputes(this))return I.wNAFCachedUnsafe(this,v,f.normalizeZ);let{k1neg:F,k1:x,k2neg:K,k2:j}=T.splitScalar(v),R=D,C=D,S=this;for(;x>qs||j>qs;)x&Je&&(R=R.add(S)),j&Je&&(C=C.add(S)),S=S.double(),x>>=Je,j>>=Je;return F&&(R=R.negate()),K&&(C=C.negate()),C=new f(s.mul(C.px,T.beta),C.py,C.pz),R.add(C)}multiply(v){const{endo:T,n:P}=e;Sr("scalar",v,Je,P);let D,F;if(T){const{k1neg:x,k1:K,k2neg:j,k2:R}=T.splitScalar(v);let{p:C,f:S}=this.wNAF(K),{p:y,f:b}=this.wNAF(R);C=I.constTimeNegate(x,C),y=I.constTimeNegate(j,y),y=new f(s.mul(y.px,T.beta),y.py,y.pz),D=C.add(y),F=S.add(b)}else{const{p:x,f:K}=this.wNAF(v);D=x,F=K}return f.normalizeZ([D,F])[0]}multiplyAndAddUnsafe(v,T,P){const D=f.BASE,F=(K,j)=>j===qs||j===Je||!K.equals(D)?K.multiplyUnsafe(j):K.multiply(j),x=F(this,T).add(F(v,P));return x.is0()?void 0:x}toAffine(v){return p(this,v)}isTorsionFree(){const{h:v,isTorsionFree:T}=e;if(v===Je)return!0;if(T)return T(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:T}=e;return v===Je?this:T?T(f,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return Ci("isCompressed",v),this.assertValidity(),r(f,this,v)}toHex(v=!0){return Ci("isCompressed",v),vi(this.toRawBytes(v))}}f.BASE=new f(e.Gx,e.Gy,s.ONE),f.ZERO=new f(s.ZERO,s.ONE,s.ZERO);const{endo:w,nBitLength:E}=e,I=Ib(f,w?Math.ceil(E/2):E);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:u,weierstrassEquation:o,isWithinCurveOrder:d}}function Pb(t){const e=Lp(t);return ea(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function xb(t){const e=Pb(t),{Fp:s,n,nByteLength:r,nBitLength:i}=e,o=s.BYTES+1,a=2*s.BYTES+1;function c(y){return It(y,n)}function l(y){return _c(y,n)}const{ProjectivePoint:d,normPrivateKeyToScalar:u,weierstrassEquation:h,isWithinCurveOrder:p}=Rb({...e,toBytes(y,b,N){const $=b.toAffine(),A=s.toBytes($.x),O=Po;return Ci("isCompressed",N),N?O(Uint8Array.from([b.hasEvenY()?2:3]),A):O(Uint8Array.from([4]),A,s.toBytes($.y))},fromBytes(y){const b=y.length,N=y[0],$=y.subarray(1);if(b===o&&(N===2||N===3)){const A=Yn($);if(!bl(A,Je,s.ORDER))throw new Error("Point is not on curve");const O=h(A);let M;try{M=s.sqrt(O)}catch(se){const X=se instanceof Error?": "+se.message:"";throw new Error("Point is not on curve"+X)}const W=(M&Je)===Je;return(N&1)===1!==W&&(M=s.neg(M)),{x:A,y:M}}else if(b===a&&N===4){const A=s.fromBytes($.subarray(0,s.BYTES)),O=s.fromBytes($.subarray(s.BYTES,2*s.BYTES));return{x:A,y:O}}else{const A=o,O=a;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+O+", got "+b)}}});function g(y){const b=n>>Je;return y>b}function f(y){return g(y)?c(-y):y}const w=(y,b,N)=>Yn(y.slice(b,N));class E{constructor(b,N,$){Sr("r",b,Je,n),Sr("s",N,Je,n),this.r=b,this.s=N,$!=null&&(this.recovery=$),Object.freeze(this)}static fromCompact(b){const N=r;return b=Jt("compactSignature",b,N*2),new E(w(b,0,N),w(b,N,2*N))}static fromDER(b){const{r:N,s:$}=Ms.toSig(Jt("DER",b));return new E(N,$)}assertValidity(){}addRecoveryBit(b){return new E(this.r,this.s,b)}recoverPublicKey(b){const{r:N,s:$,recovery:A}=this,O=D(Jt("msgHash",b));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");const M=A===2||A===3?N+e.n:N;if(M>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const W=A&1?"03":"02",ae=d.fromHex(W+xa(M,s.BYTES)),se=l(M),X=c(-O*se),le=c($*se),ie=d.BASE.multiplyAndAddUnsafe(ae,X,le);if(!ie)throw new Error("point at infinify");return ie.assertValidity(),ie}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new E(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Ro(this.toDERHex())}toDERHex(){return Ms.hexFromSig(this)}toCompactRawBytes(){return Ro(this.toCompactHex())}toCompactHex(){const b=r;return xa(this.r,b)+xa(this.s,b)}}const I={isValidPrivateKey(y){try{return u(y),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const y=$p(e.n);return vb(e.randomBytes(y),e.n)},precompute(y=8,b=d.BASE){return b._setWindowSize(y),b.multiply(BigInt(3)),b}};function _(y,b=!0){return d.fromPrivateKey(y).toRawBytes(b)}function v(y){if(typeof y=="bigint")return!1;if(y instanceof d)return!0;const N=Jt("key",y).length,$=s.BYTES,A=$+1,O=2*$+1;if(!(e.allowedPrivateKeyLengths||r===A))return N===A||N===O}function T(y,b,N=!0){if(v(y)===!0)throw new Error("first arg must be private key");if(v(b)===!1)throw new Error("second arg must be public key");return d.fromHex(b).multiply(u(y)).toRawBytes(N)}const P=e.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const b=Yn(y),N=y.length*8-i;return N>0?b>>BigInt(N):b},D=e.bits2int_modN||function(y){return c(P(y))},F=Qo(i);function x(y){return Sr("num < 2^"+i,y,qs,F),$i(y,r)}function K(y,b,N=j){if(["recovered","canonical"].some(ce=>ce in N))throw new Error("sign() legacy options not supported");const{hash:$,randomBytes:A}=e;let{lowS:O,prehash:M,extraEntropy:W}=N;O==null&&(O=!0),y=Jt("msgHash",y),Rd(N),M&&(y=Jt("prehashed msgHash",$(y)));const ae=D(y),se=u(b),X=[x(se),x(ae)];if(W!=null&&W!==!1){const ce=W===!0?A(s.BYTES):W;X.push(Jt("extraEntropy",ce))}const le=Po(...X),ie=ae;function Se(ce){const Oe=P(ce);if(!p(Oe))return;const ht=l(Oe),yt=d.BASE.multiply(Oe).toAffine(),pt=c(yt.x);if(pt===qs)return;const jt=c(ht*c(ie+pt*se));if(jt===qs)return;let Tn=(yt.x===pt?0:2)|Number(yt.y&Je),dr=jt;return O&&g(jt)&&(dr=f(jt),Tn^=1),new E(pt,dr,Tn)}return{seed:le,k2sig:Se}}const j={lowS:e.lowS,prehash:!1},R={lowS:e.lowS,prehash:!1};function C(y,b,N=j){const{seed:$,k2sig:A}=K(y,b,N),O=e;return R0(O.hash.outputLen,O.nByteLength,O.hmac)($,A)}d.BASE._setWindowSize(8);function S(y,b,N,$=R){var Tn;const A=y;b=Jt("msgHash",b),N=Jt("publicKey",N);const{lowS:O,prehash:M,format:W}=$;if(Rd($),"strict"in $)throw new Error("options.strict was renamed to lowS");if(W!==void 0&&W!=="compact"&&W!=="der")throw new Error("format must be compact or der");const ae=typeof A=="string"||ki(A),se=!ae&&!W&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!ae&&!se)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let X,le;try{if(se&&(X=new E(A.r,A.s)),ae){try{W!=="compact"&&(X=E.fromDER(A))}catch(dr){if(!(dr instanceof Ms.Err))throw dr}!X&&W!=="der"&&(X=E.fromCompact(A))}le=d.fromHex(N)}catch{return!1}if(!X||O&&X.hasHighS())return!1;M&&(b=e.hash(b));const{r:ie,s:Se}=X,ce=D(b),Oe=l(Se),ht=c(ce*Oe),yt=c(ie*Oe),pt=(Tn=d.BASE.multiplyAndAddUnsafe(le,ht,yt))==null?void 0:Tn.toAffine();return pt?c(pt.x)===ie:!1}return{CURVE:e,getPublicKey:_,getSharedSecret:T,sign:C,verify:S,ProjectivePoint:d,Signature:E,utils:I}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function kb(t){return{hash:t,hmac:(e,...s)=>Sp(t,e,n0(...s)),randomBytes:r0}}function $b(t,e){const s=n=>xb({...t,...kb(n)});return{...s(e),create:s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Bp=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Pd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ub=BigInt(0),Db=BigInt(1),Sc=BigInt(2),xd=(t,e)=>(t+e/Sc)/e;function Lb(t){const e=Bp,s=BigInt(3),n=BigInt(6),r=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=Wt(d,s,e)*d%e,h=Wt(u,s,e)*d%e,p=Wt(h,Sc,e)*l%e,g=Wt(p,r,e)*p%e,f=Wt(g,i,e)*g%e,w=Wt(f,a,e)*f%e,E=Wt(w,c,e)*w%e,I=Wt(E,a,e)*f%e,_=Wt(I,s,e)*d%e,v=Wt(_,o,e)*g%e,T=Wt(v,n,e)*l%e,P=Wt(T,Sc,e);if(!Nc.eql(Nc.sqr(P),t))throw new Error("Cannot find square root");return P}const Nc=vl(Bp,void 0,void 0,{sqrt:Lb}),Bb=$b({a:Ub,b:BigInt(7),Fp:Nc,n:Pd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Pd,s=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Db*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=s,o=BigInt("0x100000000000000000000000000000000"),a=xd(i*t,e),c=xd(-n*t,e);let l=It(t-a*s-c*r,e),d=It(-a*n-c*i,e);const u=l>o,h=d>o;if(u&&(l=e-l),h&&(d=e-d),l>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}}},N0);function Mb(t){if(t.length!==130&&t.length!==132)throw new jb({signature:t});const e=BigInt(Ls(t,0,32)),s=BigInt(Ls(t,32,64)),n=(()=>{const r=+`0x${t.slice(130)}`;if(!Number.isNaN(r))try{return Fb(r)}catch{throw new qb({value:r})}})();return typeof n>"u"?{r:e,s}:{r:e,s,yParity:n}}function Fb(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new Wb({value:t})}class jb extends Le{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${_n(Cl(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class qb extends Le{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class Wb extends Le{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function Hb(t){return hb(Kb(t))}function Kb(t){const{payload:e,signature:s}=t,{r:n,s:r,yParity:i}=s,a=new Bb.Signature(BigInt(n),BigInt(r)).addRecoveryBit(i).recoverPublicKey(Cl(e).substring(2));return nb(a)}const zb=":";function zs(t){const[e,s]=t.split(zb);return{namespace:e,reference:s}}function Mp(t,e){return t.includes(":")?[t]:e.chains||[]}var Vb=Object.defineProperty,Gb=Object.defineProperties,Yb=Object.getOwnPropertyDescriptors,kd=Object.getOwnPropertySymbols,Jb=Object.prototype.hasOwnProperty,Xb=Object.prototype.propertyIsEnumerable,Tc=(t,e,s)=>e in t?Vb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$d=(t,e)=>{for(var s in e||(e={}))Jb.call(e,s)&&Tc(t,s,e[s]);if(kd)for(var s of kd(e))Xb.call(e,s)&&Tc(t,s,e[s]);return t},Zb=(t,e)=>Gb(t,Yb(e)),Ud=(t,e,s)=>Tc(t,typeof e!="symbol"?e+"":e,s);const Qb="ReactNative",Mt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},eE="js";function ko(){return typeof Ks<"u"&&typeof Ks.versions<"u"&&typeof Ks.versions.node<"u"}function Sn(){return!xr()&&!!Mh()&&navigator.product===Qb}function tE(){return Sn()&&typeof de<"u"&&typeof(de==null?void 0:de.Platform)<"u"&&(de==null?void 0:de.Platform.OS)==="android"}function sE(){return Sn()&&typeof de<"u"&&typeof(de==null?void 0:de.Platform)<"u"&&(de==null?void 0:de.Platform.OS)==="ios"}function qr(){return!ko()&&!!Mh()&&!!xr()}function Ui(){return Sn()?Mt.reactNative:ko()?Mt.node:qr()?Mt.browser:Mt.unknown}function Dd(){var t;try{return Sn()&&typeof de<"u"&&typeof(de==null?void 0:de.Application)<"u"?(t=de.Application)==null?void 0:t.applicationId:void 0}catch{return}}function nE(t,e){const s=new URLSearchParams(t);return Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!=null&&s.set(n,String(r))}),s.toString()}function rE(t){var e,s;const n=Fp();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(r=>r!=="")),Zb($d($d({},n),t),{url:(t==null?void 0:t.url)||n.url,name:(t==null?void 0:t.name)||n.name,description:(t==null?void 0:t.description)||n.description,icons:(s=t==null?void 0:t.icons)!=null&&s.length&&t.icons.length>0?t.icons:n.icons})}catch(r){return console.warn("Error populating app metadata",r),t||n}}function Fp(){return Mg()||{name:"",description:"",url:"",icons:[""]}}function iE(){if(Ui()===Mt.reactNative&&typeof de<"u"&&typeof(de==null?void 0:de.Platform)<"u"){const{OS:s,Version:n}=de.Platform;return[s,n].join("-")}const t=Hg();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function oE(){var t;const e=Ui();return e===Mt.browser?[e,((t=Kg())==null?void 0:t.host)||"unknown"].join(":"):e}function jp(t,e,s){const n=iE(),r=oE();return[[t,e].join("-"),[eE,s].join("-"),n,r].join("/")}function aE({protocol:t,version:e,relayUrl:s,sdkVersion:n,auth:r,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d=jp(t,e,n),u={auth:r,ua:d,projectId:i,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=nE(l[1]||"",u);return l[0]+"?"+h}function Wn(t,e){return t.filter(s=>e.includes(s)).length===t.length}function Oc(t){return Object.fromEntries(t.entries())}function Rc(t){return new Map(Object.entries(t))}function Ln(t=V.FIVE_MINUTES,e){const s=V.toMiliseconds(t||V.FIVE_MINUTES);let n,r,i,o;return{resolve:a=>{i&&n&&(clearTimeout(i),n(a),o=Promise.resolve(a))},reject:a=>{i&&r&&(clearTimeout(i),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);i=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),n=a,r=c})}}function As(t,e,s){return new Promise(async(n,r)=>{const i=setTimeout(()=>r(new Error(s)),e);try{const o=await t;n(o)}catch(o){r(o)}clearTimeout(i)})}function qp(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function cE(t){return qp("topic",t)}function lE(t){return qp("id",t)}function Wp(t){const[e,s]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")n.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))n.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return n}function qe(t,e){return V.fromMiliseconds((e||Date.now())+V.toMiliseconds(t))}function Cs(t){return Date.now()>=V.toMiliseconds(t)}function Ie(t,e){return`${t}${e?`:${e}`:""}`}function Ss(t=[],e=[]){return[...new Set([...t,...e])]}async function dE({id:t,topic:e,wcDeepLink:s}){var n;try{if(!s)return;const r=typeof s=="string"?JSON.parse(s):s,i=r==null?void 0:r.href;if(typeof i!="string")return;const o=uE(i,t,e),a=Ui();if(a===Mt.browser){if(!((n=xr())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}hE(o)}else a===Mt.reactNative&&typeof(de==null?void 0:de.Linking)<"u"&&await de.Linking.openURL(o)}catch(r){console.error(r)}}function uE(t,e,s){const n=`requestId=${e}&sessionTopic=${s}`;t.endsWith("/")&&(t=t.slice(0,-1));let r=`${t}`;if(t.startsWith("https://t.me")){const i=t.includes("?")?"&startapp=":"?startapp=";r=`${r}${i}${mE(n,!0)}`}else r=`${r}/wc?${n}`;return r}function hE(t){let e="_self";gE()?e="_top":(fE()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function pE(t,e){let s="";try{if(qr()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(n){console.error(n)}return s}function Ld(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),n=s.indexOf(e);return s[n+2]}function Bd(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Al(){return typeof Ks<"u"&&{}.IS_VITEST==="true"}function fE(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function gE(){try{return window.self!==window.top}catch{return!1}}function mE(t,e=!1){const s=Ee.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function Hp(t){return Ee.from(t,"base64").toString("utf-8")}function wE(t){return new Promise(e=>setTimeout(e,t))}let yE=class{constructor({limit:e}){Ud(this,"limit"),Ud(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const s=this.set.values().next().value;s&&this.set.delete(s)}this.set.add(e)}}has(e){return this.set.has(e)}};const Qi=BigInt(2**32-1),Md=BigInt(32);function Kp(t,e=!1){return e?{h:Number(t&Qi),l:Number(t>>Md&Qi)}:{h:Number(t>>Md&Qi)|0,l:Number(t&Qi)|0}}function zp(t,e=!1){const s=t.length;let n=new Uint32Array(s),r=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=Kp(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const Fd=(t,e,s)=>t>>>s,jd=(t,e,s)=>t<<32-s|e>>>s,ln=(t,e,s)=>t>>>s|e<<32-s,dn=(t,e,s)=>t<<32-s|e>>>s,ni=(t,e,s)=>t<<64-s|e>>>s-32,ri=(t,e,s)=>t>>>s-32|e<<64-s,bE=(t,e)=>e,EE=(t,e)=>t,CE=(t,e,s)=>t<<s|e>>>32-s,vE=(t,e,s)=>e<<s|t>>>32-s,AE=(t,e,s)=>e<<s-32|t>>>64-s,_E=(t,e,s)=>t<<s-32|e>>>64-s;function cs(t,e,s,n){const r=(e>>>0)+(n>>>0);return{h:t+s+(r/2**32|0)|0,l:r|0}}const _l=(t,e,s)=>(t>>>0)+(e>>>0)+(s>>>0),Il=(t,e,s,n)=>e+s+n+(t/2**32|0)|0,IE=(t,e,s,n)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0),SE=(t,e,s,n,r)=>e+s+n+r+(t/2**32|0)|0,NE=(t,e,s,n,r)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0)+(r>>>0),TE=(t,e,s,n,r,i)=>e+s+n+r+i+(t/2**32|0)|0,pr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ta(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Js(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ps(t,...e){if(!ta(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function sa(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Js(t.outputLen),Js(t.blockLen)}function In(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Sl(t,e){ps(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Ai(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function ss(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function $a(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function gs(t,e){return t<<32-e|t>>>e}const Vp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Gp(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const $s=Vp?t=>t:t=>Gp(t);function OE(t){for(let e=0;e<t.length;e++)t[e]=Gp(t[e]);return t}const un=Vp?t=>t:OE,Yp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",RE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Nr(t){if(ps(t),Yp)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=RE[t[s]];return e}const xs={_0:48,_9:57,A:65,F:70,a:97,f:102};function qd(t){if(t>=xs._0&&t<=xs._9)return t-xs._0;if(t>=xs.A&&t<=xs.F)return t-(xs.A-10);if(t>=xs.a&&t<=xs.f)return t-(xs.a-10)}function $o(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Yp)return Uint8Array.fromHex(t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=qd(t.charCodeAt(i)),a=qd(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[r]=o*16+a}return n}function Jp(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function hs(t){return typeof t=="string"&&(t=Jp(t)),ps(t),t}function pn(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];ps(r),e+=r.length}const s=new Uint8Array(e);for(let n=0,r=0;n<t.length;n++){const i=t[n];s.set(i,r),r+=i.length}return s}class na{}function Di(t){const e=n=>t().update(hs(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function PE(t){const e=(n,r)=>t(r).update(hs(n)).digest(),s=t({});return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}function cr(t=32){if(pr&&typeof pr.getRandomValues=="function")return pr.getRandomValues(new Uint8Array(t));if(pr&&typeof pr.randomBytes=="function")return Uint8Array.from(pr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const xE=BigInt(0),Vr=BigInt(1),kE=BigInt(2),$E=BigInt(7),UE=BigInt(256),DE=BigInt(113),Xp=[],Zp=[],Qp=[];for(let t=0,e=Vr,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],Xp.push(2*(5*n+s)),Zp.push((t+1)*(t+2)/2%64);let r=xE;for(let i=0;i<7;i++)e=(e<<Vr^(e>>$E)*DE)%UE,e&kE&&(r^=Vr<<(Vr<<BigInt(i))-Vr);Qp.push(r)}const ef=zp(Qp,!0),LE=ef[0],BE=ef[1],Wd=(t,e,s)=>s>32?AE(t,e,s):CE(t,e,s),Hd=(t,e,s)=>s>32?_E(t,e,s):vE(t,e,s);function ME(t,e=24){const s=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],d=s[c+1],u=Wd(l,d,1)^s[a],h=Hd(l,d,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=Zp[o],c=Wd(r,i,a),l=Hd(r,i,a),d=Xp[o];r=t[d],i=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=LE[n],t[1]^=BE[n]}ss(s)}let FE=class tf extends na{constructor(e,s,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=s,this.outputLen=n,this.enableXOF=r,this.rounds=i,Js(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ai(this.state)}clone(){return this._cloneInto()}keccak(){un(this.state32),ME(this.state32,this.rounds),un(this.state32),this.posOut=0,this.pos=0}update(e){In(this),e=hs(e),ps(e);const{blockLen:s,state:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:n,blockLen:r}=this;e[n]^=s,s&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){In(this,!1),ps(e),this.finish();const s=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(s.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Js(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Sl(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,ss(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new tf(s,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const jE=(t,e,s)=>Di(()=>new FE(e,t,s)),qE=jE(1,136,256/8);function WE(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function HE(t,e,s){return t&e^~t&s}function KE(t,e,s){return t&e^t&s^e&s}let sf=class extends na{constructor(e,s,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=s,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=$a(this.buffer)}update(e){In(this),e=hs(e),ps(e);const{view:s,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(r-this.pos,i-o);if(a===r){const c=$a(e);for(;r<=i-o;o+=r)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){In(this),Sl(e,this),this.finished=!0;const{buffer:s,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,ss(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)s[u]=0;WE(n,r-8,BigInt(this.length*8),i),this.process(n,0);const a=$a(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=a,r%s&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const sn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),it=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),ot=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),zE=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),nn=new Uint32Array(64);class VE extends sf{constructor(e=32){super(64,e,8,!1),this.A=sn[0]|0,this.B=sn[1]|0,this.C=sn[2]|0,this.D=sn[3]|0,this.E=sn[4]|0,this.F=sn[5]|0,this.G=sn[6]|0,this.H=sn[7]|0}get(){const{A:e,B:s,C:n,D:r,E:i,F:o,G:a,H:c}=this;return[e,s,n,r,i,o,a,c]}set(e,s,n,r,i,o,a,c){this.A=e|0,this.B=s|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let u=0;u<16;u++,s+=4)nn[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const h=nn[u-15],p=nn[u-2],g=gs(h,7)^gs(h,18)^h>>>3,f=gs(p,17)^gs(p,19)^p>>>10;nn[u]=f+nn[u-7]+g+nn[u-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=gs(a,6)^gs(a,11)^gs(a,25),p=d+h+HE(a,c,l)+zE[u]+nn[u]|0,g=(gs(n,2)^gs(n,13)^gs(n,22))+KE(n,r,i)|0;d=l,l=c,c=a,a=o+p|0,o=i,i=r,r=n,n=p+g|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,r,i,o,a,c,l,d)}roundClean(){ss(nn)}destroy(){this.set(0,0,0,0,0,0,0,0),ss(this.buffer)}}const nf=zp(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),GE=nf[0],YE=nf[1],rn=new Uint32Array(80),on=new Uint32Array(80);let Nl=class extends sf{constructor(e=64){super(128,e,16,!1),this.Ah=ot[0]|0,this.Al=ot[1]|0,this.Bh=ot[2]|0,this.Bl=ot[3]|0,this.Ch=ot[4]|0,this.Cl=ot[5]|0,this.Dh=ot[6]|0,this.Dl=ot[7]|0,this.Eh=ot[8]|0,this.El=ot[9]|0,this.Fh=ot[10]|0,this.Fl=ot[11]|0,this.Gh=ot[12]|0,this.Gl=ot[13]|0,this.Hh=ot[14]|0,this.Hl=ot[15]|0}get(){const{Ah:e,Al:s,Bh:n,Bl:r,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:h,Gh:p,Gl:g,Hh:f,Hl:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w){this.Ah=e|0,this.Al=s|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=h|0,this.Gh=p|0,this.Gl=g|0,this.Hh=f|0,this.Hl=w|0}process(e,s){for(let _=0;_<16;_++,s+=4)rn[_]=e.getUint32(s),on[_]=e.getUint32(s+=4);for(let _=16;_<80;_++){const v=rn[_-15]|0,T=on[_-15]|0,P=ln(v,T,1)^ln(v,T,8)^Fd(v,T,7),D=dn(v,T,1)^dn(v,T,8)^jd(v,T,7),F=rn[_-2]|0,x=on[_-2]|0,K=ln(F,x,19)^ni(F,x,61)^Fd(F,x,6),j=dn(F,x,19)^ri(F,x,61)^jd(F,x,6),R=IE(D,j,on[_-7],on[_-16]),C=SE(R,P,K,rn[_-7],rn[_-16]);rn[_]=C|0,on[_]=R|0}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:h,Fh:p,Fl:g,Gh:f,Gl:w,Hh:E,Hl:I}=this;for(let _=0;_<80;_++){const v=ln(u,h,14)^ln(u,h,18)^ni(u,h,41),T=dn(u,h,14)^dn(u,h,18)^ri(u,h,41),P=u&p^~u&f,D=h&g^~h&w,F=NE(I,T,D,YE[_],on[_]),x=TE(F,E,v,P,GE[_],rn[_]),K=F|0,j=ln(n,r,28)^ni(n,r,34)^ni(n,r,39),R=dn(n,r,28)^ri(n,r,34)^ri(n,r,39),C=n&i^n&a^i&a,S=r&o^r&c^o&c;E=f|0,I=w|0,f=p|0,w=g|0,p=u|0,g=h|0,{h:u,l:h}=cs(l|0,d|0,x|0,K|0),l=a|0,d=c|0,a=i|0,c=o|0,i=n|0,o=r|0;const y=_l(K,R,S);n=Il(y,x,j,C),r=y|0}({h:n,l:r}=cs(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:o}=cs(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=cs(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=cs(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:h}=cs(this.Eh|0,this.El|0,u|0,h|0),{h:p,l:g}=cs(this.Fh|0,this.Fl|0,p|0,g|0),{h:f,l:w}=cs(this.Gh|0,this.Gl|0,f|0,w|0),{h:E,l:I}=cs(this.Hh|0,this.Hl|0,E|0,I|0),this.set(n,r,i,o,a,c,l,d,u,h,p,g,f,w,E,I)}roundClean(){ss(rn,on)}destroy(){ss(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class JE extends Nl{constructor(){super(48),this.Ah=it[0]|0,this.Al=it[1]|0,this.Bh=it[2]|0,this.Bl=it[3]|0,this.Ch=it[4]|0,this.Cl=it[5]|0,this.Dh=it[6]|0,this.Dl=it[7]|0,this.Eh=it[8]|0,this.El=it[9]|0,this.Fh=it[10]|0,this.Fl=it[11]|0,this.Gh=it[12]|0,this.Gl=it[13]|0,this.Hh=it[14]|0,this.Hl=it[15]|0}}const at=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class XE extends Nl{constructor(){super(32),this.Ah=at[0]|0,this.Al=at[1]|0,this.Bh=at[2]|0,this.Bl=at[3]|0,this.Ch=at[4]|0,this.Cl=at[5]|0,this.Dh=at[6]|0,this.Dl=at[7]|0,this.Eh=at[8]|0,this.El=at[9]|0,this.Fh=at[10]|0,this.Fl=at[11]|0,this.Gh=at[12]|0,this.Gl=at[13]|0,this.Hh=at[14]|0,this.Hl=at[15]|0}}const ra=Di(()=>new VE),ZE=Di(()=>new Nl),QE=Di(()=>new JE),eC=Di(()=>new XE),tC=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Ke=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Y=new Uint32Array(32);function an(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=Y[2*t],l=Y[2*t+1],d=Y[2*e],u=Y[2*e+1],h=Y[2*s],p=Y[2*s+1],g=Y[2*n],f=Y[2*n+1],w=_l(c,d,o);l=Il(w,l,u,a),c=w|0,{Dh:f,Dl:g}={Dh:f^l,Dl:g^c},{Dh:f,Dl:g}={Dh:bE(f,g),Dl:EE(f)},{h:p,l:h}=cs(p,h,f,g),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:ln(u,d,24),Bl:dn(u,d,24)},Y[2*t]=c,Y[2*t+1]=l,Y[2*e]=d,Y[2*e+1]=u,Y[2*s]=h,Y[2*s+1]=p,Y[2*n]=g,Y[2*n+1]=f}function cn(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=Y[2*t],l=Y[2*t+1],d=Y[2*e],u=Y[2*e+1],h=Y[2*s],p=Y[2*s+1],g=Y[2*n],f=Y[2*n+1],w=_l(c,d,o);l=Il(w,l,u,a),c=w|0,{Dh:f,Dl:g}={Dh:f^l,Dl:g^c},{Dh:f,Dl:g}={Dh:ln(f,g,16),Dl:dn(f,g,16)},{h:p,l:h}=cs(p,h,f,g),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:ni(u,d,63),Bl:ri(u,d,63)},Y[2*t]=c,Y[2*t+1]=l,Y[2*e]=d,Y[2*e+1]=u,Y[2*s]=h,Y[2*s+1]=p,Y[2*n]=g,Y[2*n+1]=f}function sC(t,e={},s,n,r){if(Js(s),t<0||t>s)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.length>s))throw new Error("key length must be undefined or 1.."+s);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==r)throw new Error("personalization must be undefined or "+r)}class nC extends na{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Js(e),Js(s),this.blockLen=e,this.outputLen=s,this.buffer=new Uint8Array(e),this.buffer32=Ai(this.buffer)}update(e){In(this),e=hs(e),ps(e);const{blockLen:s,buffer:n,buffer32:r}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===s&&(un(r),this.compress(r,0,!1),un(r),this.pos=0);const l=Math.min(s-this.pos,i-c),d=o+c;if(l===s&&!(d%4)&&c+l<i){const u=new Uint32Array(a,d,Math.floor((i-c)/4));un(u);for(let h=0;c+s<i;h+=r.length,c+=s)this.length+=s,this.compress(u,h,!1);un(u);continue}n.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){In(this),Sl(e,this);const{pos:s,buffer32:n}=this;this.finished=!0,ss(this.buffer.subarray(s)),un(n),this.compress(n,0,!0),un(n);const r=Ai(e);this.get().forEach((i,o)=>r[o]=$s(i))}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){const{buffer:s,length:n,finished:r,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(s),e.destroyed=i,e.finished=r,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class rC extends nC{constructor(e={}){const s=e.dkLen===void 0?64:e.dkLen;super(128,s),this.v0l=Ke[0]|0,this.v0h=Ke[1]|0,this.v1l=Ke[2]|0,this.v1h=Ke[3]|0,this.v2l=Ke[4]|0,this.v2h=Ke[5]|0,this.v3l=Ke[6]|0,this.v3h=Ke[7]|0,this.v4l=Ke[8]|0,this.v4h=Ke[9]|0,this.v5l=Ke[10]|0,this.v5h=Ke[11]|0,this.v6l=Ke[12]|0,this.v6h=Ke[13]|0,this.v7l=Ke[14]|0,this.v7h=Ke[15]|0,sC(s,e,64,16,16);let{key:n,personalization:r,salt:i}=e,o=0;if(n!==void 0&&(n=hs(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=hs(i);const a=Ai(i);this.v4l^=$s(a[0]),this.v4h^=$s(a[1]),this.v5l^=$s(a[2]),this.v5h^=$s(a[3])}if(r!==void 0){r=hs(r);const a=Ai(r);this.v6l^=$s(a[0]),this.v6h^=$s(a[1]),this.v7l^=$s(a[2]),this.v7h^=$s(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:s,v1l:n,v1h:r,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:d,v5l:u,v5h:h,v6l:p,v6h:g,v7l:f,v7h:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w){this.v0l=e|0,this.v0h=s|0,this.v1l=n|0,this.v1h=r|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=d|0,this.v5l=u|0,this.v5h=h|0,this.v6l=p|0,this.v6h=g|0,this.v7l=f|0,this.v7h=w|0}compress(e,s,n){this.get().forEach((c,l)=>Y[l]=c),Y.set(Ke,16);let{h:r,l:i}=Kp(BigInt(this.length));Y[24]=Ke[8]^i,Y[25]=Ke[9]^r,n&&(Y[28]=~Y[28],Y[29]=~Y[29]);let o=0;const a=tC;for(let c=0;c<12;c++)an(0,4,8,12,e,s+2*a[o++]),cn(0,4,8,12,e,s+2*a[o++]),an(1,5,9,13,e,s+2*a[o++]),cn(1,5,9,13,e,s+2*a[o++]),an(2,6,10,14,e,s+2*a[o++]),cn(2,6,10,14,e,s+2*a[o++]),an(3,7,11,15,e,s+2*a[o++]),cn(3,7,11,15,e,s+2*a[o++]),an(0,5,10,15,e,s+2*a[o++]),cn(0,5,10,15,e,s+2*a[o++]),an(1,6,11,12,e,s+2*a[o++]),cn(1,6,11,12,e,s+2*a[o++]),an(2,7,8,13,e,s+2*a[o++]),cn(2,7,8,13,e,s+2*a[o++]),an(3,4,9,14,e,s+2*a[o++]),cn(3,4,9,14,e,s+2*a[o++]);this.v0l^=Y[0]^Y[16],this.v0h^=Y[1]^Y[17],this.v1l^=Y[2]^Y[18],this.v1h^=Y[3]^Y[19],this.v2l^=Y[4]^Y[20],this.v2h^=Y[5]^Y[21],this.v3l^=Y[6]^Y[22],this.v3h^=Y[7]^Y[23],this.v4l^=Y[8]^Y[24],this.v4h^=Y[9]^Y[25],this.v5l^=Y[10]^Y[26],this.v5h^=Y[11]^Y[27],this.v6l^=Y[12]^Y[28],this.v6h^=Y[13]^Y[29],this.v7l^=Y[14]^Y[30],this.v7h^=Y[15]^Y[31],ss(Y)}destroy(){this.destroyed=!0,ss(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const iC=PE(t=>new rC(t)),oC="https://rpc.walletconnect.org/v1";function rf(t){const e=`Ethereum Signed Message:
|
|
7
|
+
${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Ee.from(qE(s)).toString("hex")}async function aC(t,e,s,n,r,i){switch(s.t){case"eip191":return await cC(t,e,s.s);case"eip1271":return await lC(t,e,s.s,n,r,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}function cC(t,e,s){const n=Mb(s);return Hb({payload:rf(e),signature:n}).toLowerCase()===t.toLowerCase()}async function lC(t,e,s,n,r,i){const o=zs(n);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l=s.substring(2),d=(l.length/2).toString(16).padStart(64,"0"),u=(e.startsWith("0x")?e:rf(e)).substring(2),h=a+u+c+d+l,p=await fetch(`${i||oC}/?chainId=${n}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:dC(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:g}=await p.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function dC(){return Date.now()+Math.floor(Math.random()*1e3)}function uC(t){const e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);const n=s[0];if(n===0)throw new Error("No signatures found");const r=1+n*64;if(s.length<r)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const i=Ee.from(t,"base64").slice(1,65);return Fr.encode(i)}function hC(t){const e=new Uint8Array(Ee.from(t,"base64")),s=Array.from("TransactionData::").map(i=>i.charCodeAt(0)),n=new Uint8Array(s.length+e.length);n.set(s),n.set(e,s.length);const r=iC(n,{dkLen:32});return Fr.encode(r)}function Kd(t){const e=new Uint8Array(ra(pC(t)));return Fr.encode(e)}function pC(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function zd(t){const e=Ee.from(t,"base64"),s=Fg(e).txn;if(!s)throw new Error("Invalid signed transaction: missing 'txn' field");const n=jg(s),r=Ee.from("TX"),i=Ee.concat([r,Ee.from(n)]),o=eC(i);return qg.encode(o).replace(/=+$/,"")}function Ua(t){const e=[];let s=BigInt(t);for(;s>=BigInt(128);)e.push(Number(s&BigInt(127)|BigInt(128))),s>>=BigInt(7);return e.push(Number(s)),Ee.from(e)}function fC(t){const e=Ee.from(t.signed.bodyBytes,"base64"),s=Ee.from(t.signed.authInfoBytes,"base64"),n=Ee.from(t.signature.signature,"base64"),r=[];r.push(Ee.from([10])),r.push(Ua(e.length)),r.push(e),r.push(Ee.from([18])),r.push(Ua(s.length)),r.push(s),r.push(Ee.from([26])),r.push(Ua(n.length)),r.push(n);const i=Ee.concat(r),o=ra(i);return Ee.from(o).toString("hex").toUpperCase()}function gC(t){var e,s;const n=[];try{if(typeof t=="string")return n.push(t),n;if(typeof t!="object")return n;t!=null&&t.id&&n.push(t.id);const r=(s=(e=t==null?void 0:t.capabilities)==null?void 0:e.caip345)==null?void 0:s.transactionHashes;r&&n.push(...r)}catch(r){console.warn("getWalletSendCallsHashes failed: ",r)}return n}var mC=Object.defineProperty,wC=Object.defineProperties,yC=Object.getOwnPropertyDescriptors,Vd=Object.getOwnPropertySymbols,bC=Object.prototype.hasOwnProperty,EC=Object.prototype.propertyIsEnumerable,Gd=(t,e,s)=>e in t?mC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,CC=(t,e)=>{for(var s in e||(e={}))bC.call(e,s)&&Gd(t,s,e[s]);if(Vd)for(var s of Vd(e))EC.call(e,s)&&Gd(t,s,e[s]);return t},vC=(t,e)=>wC(t,yC(e));const AC="did:pkh:",Tl=t=>t==null?void 0:t.split(":"),_C=t=>{const e=t&&Tl(t);if(e)return t.includes(AC)?e[3]:e[1]},Pc=t=>{const e=t&&Tl(t);if(e)return e[2]+":"+e[3]},Uo=t=>{const e=t&&Tl(t);if(e)return e.pop()};async function Yd(t){const{cacao:e,projectId:s}=t,{s:n,p:r}=e,i=of(r,r.iss),o=Uo(r.iss);return await aC(o,i,n,Pc(r.iss),s)}const of=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,n=Uo(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=t.statement||void 0;const i=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${_C(e)}`,c=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,d=t.exp?`Expiration Time: ${t.exp}`:void 0,u=t.nbf?`Not Before: ${t.nbf}`:void 0,h=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(f=>`
|
|
8
|
+
- ${f}`).join("")}`:void 0,g=wo(t.resources);if(g){const f=_i(g);r=kC(r,f)}return[s,n,"",r,"",i,o,a,c,l,d,u,h,p].filter(f=>f!=null).join(`
|
|
9
|
+
`)};function IC(t){return Ee.from(JSON.stringify(t)).toString("base64")}function SC(t){return JSON.parse(Ee.from(t,"base64").toString("utf-8"))}function tr(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(s=>{const n=t.att[s];if(Array.isArray(n))throw new Error(`Resource must be an object: ${s}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${s}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${s}`);Object.keys(n).forEach(r=>{const i=n[r];if(!Array.isArray(i))throw new Error(`Ability limits ${r} must be an array of objects, found: ${i}`);if(!i.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);i.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function NC(t,e,s,n={}){return s==null||s.sort((r,i)=>r.localeCompare(i)),{att:{[t]:TC(e,s,n)}}}function TC(t,e,s={}){e=e==null?void 0:e.sort((r,i)=>r.localeCompare(i));const n=e.map(r=>({[`${t}/${r}`]:[s]}));return Object.assign({},...n)}function af(t){return tr(t),`urn:recap:${IC(t).replace(/=/g,"")}`}function _i(t){const e=SC(t.replace("urn:recap:",""));return tr(e),e}function OC(t,e,s){const n=NC(t,e,s);return af(n)}function RC(t){return t&&t.includes("urn:recap:")}function PC(t,e){const s=_i(t),n=_i(e),r=xC(s,n);return af(r)}function xC(t,e){tr(t),tr(e);const s=Object.keys(t.att).concat(Object.keys(e.att)).sort((r,i)=>r.localeCompare(i)),n={att:{}};return s.forEach(r=>{var i,o;Object.keys(((i=t.att)==null?void 0:i[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;n.att[r]=vC(CC({},n.att[r]),{[a]:((c=t.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),n}function kC(t="",e){tr(e);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(s))return t;const n=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,h)=>u.action.localeCompare(h.action));const l={};c.forEach(u=>{l[u.ability]||(l[u.ability]=[]),l[u.ability].push(u.action)});const d=Object.keys(l).map(u=>(r++,`(${r}) '${u}': '${l[u].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});const i=n.join(" "),o=`${s}${i}`;return`${t?t+" ":""}${o}`}function Jd(t){var e;const s=_i(t);tr(s);const n=(e=s.att)==null?void 0:e.eip155;return n?Object.keys(n).map(r=>r.split("/")[1]):[]}function Xd(t){const e=_i(t);tr(e);const s=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(r=>{var i;(i=r==null?void 0:r[0])!=null&&i.chains&&s.push(r[0].chains)})}),[...new Set(s.flat())]}function wo(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return RC(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function cf(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Da(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function St(t,...e){if(!cf(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Zd(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function $C(t,e){St(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Cn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ur(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function UC(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const DC=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function LC(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function kc(t){if(typeof t=="string")t=LC(t);else if(cf(t))t=$c(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function BC(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function MC(t,e){if(t.length!==e.length)return!1;let s=0;for(let n=0;n<t.length;n++)s|=t[n]^e[n];return s===0}const FC=(t,e)=>{function s(n,...r){if(St(n),!DC)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?St(l):St(l,t.nonceLength)}const i=t.tagLength;i&&r[1]!==void 0&&St(r[1]);const o=e(n,...r),a=(l,d)=>{if(d!==void 0){if(l!==2)throw new Error("cipher output not supported");St(d)}};let c=!1;return{encrypt(l,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,St(l),a(o.encrypt.length,d),o.encrypt(l,d)},decrypt(l,d){if(St(l),i&&l.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return a(o.decrypt.length,d),o.decrypt(l,d)}}}return Object.assign(s,t),s};function Qd(t,e,s=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(s&&!qC(e))throw new Error("invalid output, must be aligned");return e}function eu(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function jC(t,e,s){xc(s);const n=new Uint8Array(16),r=UC(n);return eu(r,0,BigInt(e),s),eu(r,8,BigInt(t),s),n}function qC(t){return t.byteOffset%4===0}function $c(t){return Uint8Array.from(t)}const lf=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),WC=lf("expand 16-byte k"),HC=lf("expand 32-byte k"),KC=Cn(WC),zC=Cn(HC);function ve(t,e){return t<<e|t>>>32-e}function Uc(t){return t.byteOffset%4===0}const eo=64,VC=16,df=2**32-1,tu=new Uint32Array;function GC(t,e,s,n,r,i,o,a){const c=r.length,l=new Uint8Array(eo),d=Cn(l),u=Uc(r)&&Uc(i),h=u?Cn(r):tu,p=u?Cn(i):tu;for(let g=0;g<c;o++){if(t(e,s,n,d,o,a),o>=df)throw new Error("arx: counter overflow");const f=Math.min(eo,c-g);if(u&&f===eo){const w=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let E=0,I;E<VC;E++)I=w+E,p[I]=h[I]^d[E];g+=eo;continue}for(let w=0,E;w<f;w++)E=g+w,i[E]=r[E]^l[w];g+=f}}function YC(t,e){const{allowShortKeys:s,extendNonceFn:n,counterLength:r,counterRight:i,rounds:o}=BC({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Da(r),Da(o),xc(i),xc(s),(a,c,l,d,u=0)=>{St(a),St(c),St(l);const h=l.length;if(d===void 0&&(d=new Uint8Array(h)),St(d),Da(u),u<0||u>=df)throw new Error("arx: counter overflow");if(d.length<h)throw new Error(`arx: output (${d.length}) is shorter than data (${h})`);const p=[];let g=a.length,f,w;if(g===32)p.push(f=$c(a)),w=zC;else if(g===16&&s)f=new Uint8Array(32),f.set(a),f.set(a,16),w=KC,p.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Uc(c)||p.push(c=$c(c));const E=Cn(f);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(w,E,Cn(c.subarray(0,16)),E),c=c.subarray(16)}const I=16-r;if(I!==c.length)throw new Error(`arx: nonce must be ${I} or 16 bytes`);if(I!==12){const v=new Uint8Array(12);v.set(c,i?0:12-c.length),c=v,p.push(c)}const _=Cn(c);return GC(t,w,E,_,l,d,u,o),Ur(...p),d}}const Ze=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class JC{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=kc(e),St(e,32);const s=Ze(e,0),n=Ze(e,2),r=Ze(e,4),i=Ze(e,6),o=Ze(e,8),a=Ze(e,10),c=Ze(e,12),l=Ze(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Ze(e,16+2*d)}process(e,s,n=!1){const r=n?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],d=o[3],u=o[4],h=o[5],p=o[6],g=o[7],f=o[8],w=o[9],E=Ze(e,s+0),I=Ze(e,s+2),_=Ze(e,s+4),v=Ze(e,s+6),T=Ze(e,s+8),P=Ze(e,s+10),D=Ze(e,s+12),F=Ze(e,s+14);let x=i[0]+(E&8191),K=i[1]+((E>>>13|I<<3)&8191),j=i[2]+((I>>>10|_<<6)&8191),R=i[3]+((_>>>7|v<<9)&8191),C=i[4]+((v>>>4|T<<12)&8191),S=i[5]+(T>>>1&8191),y=i[6]+((T>>>14|P<<2)&8191),b=i[7]+((P>>>11|D<<5)&8191),N=i[8]+((D>>>8|F<<8)&8191),$=i[9]+(F>>>5|r),A=0,O=A+x*a+K*(5*w)+j*(5*f)+R*(5*g)+C*(5*p);A=O>>>13,O&=8191,O+=S*(5*h)+y*(5*u)+b*(5*d)+N*(5*l)+$*(5*c),A+=O>>>13,O&=8191;let M=A+x*c+K*a+j*(5*w)+R*(5*f)+C*(5*g);A=M>>>13,M&=8191,M+=S*(5*p)+y*(5*h)+b*(5*u)+N*(5*d)+$*(5*l),A+=M>>>13,M&=8191;let W=A+x*l+K*c+j*a+R*(5*w)+C*(5*f);A=W>>>13,W&=8191,W+=S*(5*g)+y*(5*p)+b*(5*h)+N*(5*u)+$*(5*d),A+=W>>>13,W&=8191;let ae=A+x*d+K*l+j*c+R*a+C*(5*w);A=ae>>>13,ae&=8191,ae+=S*(5*f)+y*(5*g)+b*(5*p)+N*(5*h)+$*(5*u),A+=ae>>>13,ae&=8191;let se=A+x*u+K*d+j*l+R*c+C*a;A=se>>>13,se&=8191,se+=S*(5*w)+y*(5*f)+b*(5*g)+N*(5*p)+$*(5*h),A+=se>>>13,se&=8191;let X=A+x*h+K*u+j*d+R*l+C*c;A=X>>>13,X&=8191,X+=S*a+y*(5*w)+b*(5*f)+N*(5*g)+$*(5*p),A+=X>>>13,X&=8191;let le=A+x*p+K*h+j*u+R*d+C*l;A=le>>>13,le&=8191,le+=S*c+y*a+b*(5*w)+N*(5*f)+$*(5*g),A+=le>>>13,le&=8191;let ie=A+x*g+K*p+j*h+R*u+C*d;A=ie>>>13,ie&=8191,ie+=S*l+y*c+b*a+N*(5*w)+$*(5*f),A+=ie>>>13,ie&=8191;let Se=A+x*f+K*g+j*p+R*h+C*u;A=Se>>>13,Se&=8191,Se+=S*d+y*l+b*c+N*a+$*(5*w),A+=Se>>>13,Se&=8191;let ce=A+x*w+K*f+j*g+R*p+C*h;A=ce>>>13,ce&=8191,ce+=S*u+y*d+b*l+N*c+$*a,A+=ce>>>13,ce&=8191,A=(A<<2)+A|0,A=A+O|0,O=A&8191,A=A>>>13,M+=A,i[0]=O,i[1]=M,i[2]=W,i[3]=ae,i[4]=se,i[5]=X,i[6]=le,i[7]=ie,i[8]=Se,i[9]=ce}finalize(){const{h:e,pad:s}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+r,r=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(r^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+s[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+s[a]|0)+(o>>>16)|0,e[a]=o&65535;Ur(n)}update(e){Zd(this),e=kc(e),St(e);const{buffer:s,blockLen:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(n-this.pos,r-i);if(o===n){for(;n<=r-i;i+=n)this.process(e,i);continue}s.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){Ur(this.h,this.r,this.buffer,this.pad)}digestInto(e){Zd(this),$C(e,this),this.finished=!0;const{buffer:s,h:n}=this;let{pos:r}=this;if(r){for(s[r++]=1;r<16;r++)s[r]=0;this.process(s,0,!0)}this.finalize();let i=0;for(let o=0;o<8;o++)e[i++]=n[o]>>>0,e[i++]=n[o]>>>8;return e}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}}function XC(t){const e=(n,r)=>t(r).update(kc(n)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}const ZC=XC(t=>new JC(t));function QC(t,e,s,n,r,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],h=e[2],p=e[3],g=e[4],f=e[5],w=e[6],E=e[7],I=r,_=s[0],v=s[1],T=s[2],P=o,D=a,F=c,x=l,K=d,j=u,R=h,C=p,S=g,y=f,b=w,N=E,$=I,A=_,O=v,M=T;for(let ae=0;ae<i;ae+=2)P=P+K|0,$=ve($^P,16),S=S+$|0,K=ve(K^S,12),P=P+K|0,$=ve($^P,8),S=S+$|0,K=ve(K^S,7),D=D+j|0,A=ve(A^D,16),y=y+A|0,j=ve(j^y,12),D=D+j|0,A=ve(A^D,8),y=y+A|0,j=ve(j^y,7),F=F+R|0,O=ve(O^F,16),b=b+O|0,R=ve(R^b,12),F=F+R|0,O=ve(O^F,8),b=b+O|0,R=ve(R^b,7),x=x+C|0,M=ve(M^x,16),N=N+M|0,C=ve(C^N,12),x=x+C|0,M=ve(M^x,8),N=N+M|0,C=ve(C^N,7),P=P+j|0,M=ve(M^P,16),b=b+M|0,j=ve(j^b,12),P=P+j|0,M=ve(M^P,8),b=b+M|0,j=ve(j^b,7),D=D+R|0,$=ve($^D,16),N=N+$|0,R=ve(R^N,12),D=D+R|0,$=ve($^D,8),N=N+$|0,R=ve(R^N,7),F=F+C|0,A=ve(A^F,16),S=S+A|0,C=ve(C^S,12),F=F+C|0,A=ve(A^F,8),S=S+A|0,C=ve(C^S,7),x=x+K|0,O=ve(O^x,16),y=y+O|0,K=ve(K^y,12),x=x+K|0,O=ve(O^x,8),y=y+O|0,K=ve(K^y,7);let W=0;n[W++]=o+P|0,n[W++]=a+D|0,n[W++]=c+F|0,n[W++]=l+x|0,n[W++]=d+K|0,n[W++]=u+j|0,n[W++]=h+R|0,n[W++]=p+C|0,n[W++]=g+S|0,n[W++]=f+y|0,n[W++]=w+b|0,n[W++]=E+N|0,n[W++]=I+$|0,n[W++]=_+A|0,n[W++]=v+O|0,n[W++]=T+M|0}const e1=YC(QC,{counterRight:!1,counterLength:4,allowShortKeys:!1}),t1=new Uint8Array(16),su=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(t1.subarray(s))},s1=new Uint8Array(32);function nu(t,e,s,n,r){const i=t(e,s,s1),o=ZC.create(i);r&&su(o,r),su(o,n);const a=jC(n.length,r?r.length:0,!0);o.update(a);const c=o.digest();return Ur(i,a),c}const n1=t=>(e,s,n)=>({encrypt(r,i){const o=r.length;i=Qd(o+16,i,!1),i.set(r);const a=i.subarray(0,-16);t(e,s,a,a,1);const c=nu(t,e,s,a,n);return i.set(c,o),Ur(c),i},decrypt(r,i){i=Qd(r.length-16,i,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=nu(t,e,s,o,n);if(!MC(a,c))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),t(e,s,i,i,1),Ur(c),i}}),uf=FC({blockSize:64,nonceLength:12,tagLength:16},n1(e1));let hf=class extends na{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,sa(e);const n=hs(s);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),ss(i)}update(e){return In(this),this.iHash.update(e),this}digestInto(e){In(this),ps(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const ia=(t,e,s)=>new hf(t,e).update(s).digest();ia.create=(t,e)=>new hf(t,e);function r1(t,e,s){return sa(t),s===void 0&&(s=new Uint8Array(t.outputLen)),ia(t,hs(s),hs(e))}const La=Uint8Array.from([0]),ru=Uint8Array.of();function i1(t,e,s,n=32){sa(t),Js(n);const r=t.outputLen;if(n>255*r)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/r);s===void 0&&(s=ru);const o=new Uint8Array(i*r),a=ia.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)La[0]=d+1,c.update(d===0?ru:l).update(s).update(La).digestInto(l),o.set(l,r*d),a._cloneInto(c);return a.destroy(),c.destroy(),ss(l,La),o.slice(0,n)}const o1=(t,e,s,n,r)=>i1(t,r1(t,e,s),n,r),oa=ra,Ol=BigInt(0),Dc=BigInt(1);function Do(t,e=""){if(typeof t!="boolean"){const s=e&&`"${e}"`;throw new Error(s+"expected boolean, got type="+typeof t)}return t}function Hn(t,e,s=""){const n=ta(t),r=t==null?void 0:t.length,i=e!==void 0;if(!n||i&&r!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=n?`length=${r}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function to(t){const e=t.toString(16);return e.length&1?"0"+e:e}function pf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ol:BigInt("0x"+t)}function aa(t){return pf(Nr(t))}function Lo(t){return ps(t),pf(Nr(Uint8Array.from(t).reverse()))}function Rl(t,e){return $o(t.toString(16).padStart(e*2,"0"))}function Pl(t,e){return Rl(t,e).reverse()}function dt(t,e,s){let n;if(typeof e=="string")try{n=$o(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(ta(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const r=n.length;if(typeof s=="number"&&r!==s)throw new Error(t+" of length "+s+" expected, got "+r);return n}const Ba=t=>typeof t=="bigint"&&Ol<=t;function a1(t,e,s){return Ba(t)&&Ba(e)&&Ba(s)&&e<=t&&t<s}function Lc(t,e,s,n){if(!a1(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function ff(t){let e;for(e=0;t>Ol;t>>=Dc,e+=1);return e}const Li=t=>(Dc<<BigInt(t))-Dc;function c1(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),r=h=>Uint8Array.of(h);let i=n(t),o=n(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...h)=>s(o,i,...h),d=(h=n(0))=>{o=l(r(0),h),i=l(),h.length!==0&&(o=l(r(1),h),i=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const p=[];for(;h<e;){i=l();const g=i.slice();p.push(g),h+=i.length}return pn(...p)};return(h,p)=>{c(),d(h);let g;for(;!(g=p(u()));)d();return c(),g}}function ca(t,e,s={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(r,i,o){const a=t[r];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${r}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([r,i])=>n(r,i,!1)),Object.entries(s).forEach(([r,i])=>n(r,i,!0))}function iu(t){const e=new WeakMap;return(s,...n)=>{const r=e.get(s);if(r!==void 0)return r;const i=t(s,...n);return e.set(s,i),i}}const Ot=BigInt(0),mt=BigInt(1),Kn=BigInt(2),gf=BigInt(3),mf=BigInt(4),wf=BigInt(5),l1=BigInt(7),yf=BigInt(8),d1=BigInt(9),bf=BigInt(16);function Lt(t,e){const s=t%e;return s>=Ot?s:e+s}function as(t,e,s){let n=t;for(;e-- >Ot;)n*=n,n%=s;return n}function ou(t,e){if(t===Ot)throw new Error("invert: expected non-zero number");if(e<=Ot)throw new Error("invert: expected positive modulus, got "+e);let s=Lt(t,e),n=e,r=Ot,i=mt;for(;s!==Ot;){const o=n/s,a=n%s,c=r-i*o;n=s,s=a,r=i,i=c}if(n!==mt)throw new Error("invert: does not exist");return Lt(r,e)}function xl(t,e,s){if(!t.eql(t.sqr(e),s))throw new Error("Cannot find square root")}function Ef(t,e){const s=(t.ORDER+mt)/mf,n=t.pow(e,s);return xl(t,n,e),n}function u1(t,e){const s=(t.ORDER-wf)/yf,n=t.mul(e,Kn),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,Kn),r),a=t.mul(i,t.sub(o,t.ONE));return xl(t,a,e),a}function h1(t){const e=Nn(t),s=Cf(t),n=s(e,e.neg(e.ONE)),r=s(e,n),i=s(e,e.neg(n)),o=(t+l1)/bf;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,n);const u=a.mul(l,r),h=a.mul(l,i),p=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,p),d=a.cmov(h,u,g);const f=a.eql(a.sqr(d),c),w=a.cmov(l,d,f);return xl(a,w,c),w}}function Cf(t){if(t<gf)throw new Error("sqrt is not defined for small field");let e=t-mt,s=0;for(;e%Kn===Ot;)e/=Kn,s++;let n=Kn;const r=Nn(t);for(;au(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Ef;let i=r.pow(n,e);const o=(e+mt)/Kn;return function(a,c){if(a.is0(c))return c;if(au(a,c)!==1)throw new Error("Cannot find square root");let l=s,d=a.mul(a.ONE,i),u=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(u,a.ONE);){if(a.is0(u))return a.ZERO;let p=1,g=a.sqr(u);for(;!a.eql(g,a.ONE);)if(p++,g=a.sqr(g),p===l)throw new Error("Cannot find square root");const f=mt<<BigInt(l-p-1),w=a.pow(d,f);l=p,d=a.sqr(w),u=a.mul(u,d),h=a.mul(h,w)}return h}}function p1(t){return t%mf===gf?Ef:t%yf===wf?u1:t%bf===d1?h1(t):Cf(t)}const f1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function g1(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},s=f1.reduce((n,r)=>(n[r]="function",n),e);return ca(t,s),t}function m1(t,e,s){if(s<Ot)throw new Error("invalid exponent, negatives unsupported");if(s===Ot)return t.ONE;if(s===mt)return e;let n=t.ONE,r=e;for(;s>Ot;)s&mt&&(n=t.mul(n,r)),r=t.sqr(r),s>>=mt;return n}function vf(t,e,s=!1){const n=new Array(e.length).fill(s?t.ZERO:void 0),r=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(r);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function au(t,e){const s=(t.ORDER-mt)/Kn,n=t.pow(e,s),r=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function Af(t,e){e!==void 0&&Js(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function Nn(t,e,s=!1,n={}){if(t<=Ot)throw new Error("invalid field: expected ORDER > 0, got "+t);let r,i,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||s)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(r=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(s=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(r=e),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=Af(t,r);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:s,BITS:c,BYTES:l,MASK:Li(c),ZERO:Ot,ONE:mt,allowedLengths:a,create:h=>Lt(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Ot<=h&&h<t},is0:h=>h===Ot,isValidNot0:h=>!u.is0(h)&&u.isValid(h),isOdd:h=>(h&mt)===mt,neg:h=>Lt(-h,t),eql:(h,p)=>h===p,sqr:h=>Lt(h*h,t),add:(h,p)=>Lt(h+p,t),sub:(h,p)=>Lt(h-p,t),mul:(h,p)=>Lt(h*p,t),pow:(h,p)=>m1(u,h,p),div:(h,p)=>Lt(h*ou(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>ou(h,t),sqrt:i||(h=>(d||(d=p1(t)),d(u,h))),toBytes:h=>s?Pl(h,l):Rl(h,l),fromBytes:(h,p=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const f=new Uint8Array(l);f.set(h,s?0:f.length-h.length),h=f}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let g=s?Lo(h):aa(h);if(o&&(g=Lt(g,t)),!p&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>vf(u,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(u)}function _f(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function If(t){const e=_f(t);return e+Math.ceil(e/2)}function w1(t,e,s=!1){const n=t.length,r=_f(e),i=If(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?Lo(t):aa(t),a=Lt(o,e-mt)+mt;return s?Pl(a,r):Rl(a,r)}const Dr=BigInt(0),zn=BigInt(1);function Bo(t,e){const s=e.negate();return t?s:e}function Ma(t,e){const s=vf(t.Fp,e.map(n=>n.Z));return e.map((n,r)=>t.fromAffine(n.toAffine(s[r])))}function Sf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Fa(t,e){Sf(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=Li(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function cu(t,e,s){const{windowSize:n,mask:r,maxNumber:i,shiftBy:o}=s;let a=Number(t&r),c=t>>o;a>n&&(a-=i,c+=zn);const l=e*n,d=l+Math.abs(a)-1,u=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:l}}function y1(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,n)=>{if(!(s instanceof e))throw new Error("invalid point at index "+n)})}function b1(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,n)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+n)})}const ja=new WeakMap,Nf=new WeakMap;function qa(t){return Nf.get(t)||1}function lu(t){if(t!==Dr)throw new Error("invalid wNAF")}class E1{constructor(e,s){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,n=this.ZERO){let r=e;for(;s>Dr;)s&zn&&(n=n.add(r)),r=r.double(),s>>=zn;return n}precomputeWindow(e,s){const{windows:n,windowSize:r}=Fa(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<n;c++){a=o,i.push(a);for(let l=1;l<r;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=Fa(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:h,offsetF:p}=cu(n,a,o);n=c,d?i=i.add(Bo(h,s[p])):r=r.add(Bo(u,s[l]))}return lu(n),{p:r,f:i}}wNAFUnsafe(e,s,n,r=this.ZERO){const i=Fa(e,this.bits);for(let o=0;o<i.windows&&n!==Dr;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=cu(n,o,i);if(n=a,!l){const u=s[c];r=r.add(d?u.negate():u)}}return lu(n),r}getPrecomputes(e,s,n){let r=ja.get(s);return r||(r=this.precomputeWindow(s,e),e!==1&&(typeof n=="function"&&(r=n(r)),ja.set(s,r))),r}cached(e,s,n){const r=qa(e);return this.wNAF(r,this.getPrecomputes(r,e,n),s)}unsafe(e,s,n,r){const i=qa(e);return i===1?this._unsafeLadder(e,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),s,r)}createCache(e,s){Sf(s,this.bits),Nf.set(e,s),ja.delete(e)}hasCache(e){return qa(e)!==1}}function C1(t,e,s,n){let r=e,i=t.ZERO,o=t.ZERO;for(;s>Dr||n>Dr;)s&zn&&(i=i.add(r)),n&zn&&(o=o.add(r)),r=r.double(),s>>=zn,n>>=zn;return{p1:i,p2:o}}function v1(t,e,s,n){y1(s,t),b1(n,e);const r=s.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=ff(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Li(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=u;p>=0;p-=c){d.fill(o);for(let f=0;f<i;f++){const w=n[f],E=Number(w>>BigInt(p)&l);d[E]=d[E].add(s[f])}let g=o;for(let f=d.length-1,w=o;f>0;f--)w=w.add(d[f]),g=g.add(w);if(h=h.add(g),p!==0)for(let f=0;f<c;f++)h=h.double()}return h}function du(t,e,s){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return g1(e),e}else return Nn(t,{isLE:s})}function A1(t,e,s={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>Dr))throw new Error(`CURVE.${a} must be positive bigint`)}const r=du(e.p,s.Fp,n),i=du(e.n,s.Fn,n),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:i}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Jp("HashToScalar-");const Gr=BigInt(0),fr=BigInt(1),so=BigInt(2);function _1(t){return ca(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function I1(t){const e=_1(t),{P:s,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:o}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");const c=o||cr,l=a?255:448,d=a?32:56,u=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?so**BigInt(254):so**BigInt(447),g=a?BigInt(8)*so**BigInt(251)-fr:BigInt(4)*so**BigInt(445)-fr,f=p+g+fr,w=R=>Lt(R,s),E=I(u);function I(R){return Pl(w(R),d)}function _(R){const C=dt("u coordinate",R,d);return a&&(C[31]&=127),w(Lo(C))}function v(R){return Lo(r(dt("scalar",R,d)))}function T(R,C){const S=F(_(C),v(R));if(S===Gr)throw new Error("invalid private or public key received");return I(S)}function P(R){return T(R,E)}function D(R,C,S){const y=w(R*(C-S));return C=w(C-y),S=w(S+y),{x_2:C,x_3:S}}function F(R,C){Lc("u",R,Gr,s),Lc("scalar",C,p,f);const S=C,y=R;let b=fr,N=Gr,$=R,A=fr,O=Gr;for(let W=BigInt(l-1);W>=Gr;W--){const ae=S>>W&fr;O^=ae,{x_2:b,x_3:$}=D(O,b,$),{x_2:N,x_3:A}=D(O,N,A),O=ae;const se=b+N,X=w(se*se),le=b-N,ie=w(le*le),Se=X-ie,ce=$+A,Oe=$-A,ht=w(Oe*se),yt=w(ce*le),pt=ht+yt,jt=ht-yt;$=w(pt*pt),A=w(y*w(jt*jt)),b=w(X*ie),N=w(Se*(X+w(h*Se)))}({x_2:b,x_3:$}=D(O,b,$)),{x_2:N,x_3:A}=D(O,N,A);const M=i(N);return w(b*M)}const x={secretKey:d,publicKey:d,seed:d},K=(R=c(d))=>(ps(R,x.seed),R);function j(R){const C=K(R);return{secretKey:C,publicKey:P(C)}}return{keygen:j,getSharedSecret:(R,C)=>T(R,C),getPublicKey:R=>P(R),scalarMult:T,scalarMultBase:P,utils:{randomSecretKey:K,randomPrivateKey:K},GuBytes:E.slice(),lengths:x}}const S1=BigInt(1),uu=BigInt(2),N1=BigInt(3),T1=BigInt(5),O1=BigInt(8),Tf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),R1={p:Tf,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:O1,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function P1(t){const e=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=Tf,o=t*t%i*t%i,a=as(o,uu,i)*o%i,c=as(a,S1,i)*t%i,l=as(c,T1,i)*c%i,d=as(l,e,i)*l%i,u=as(d,s,i)*d%i,h=as(u,n,i)*u%i,p=as(h,r,i)*h%i,g=as(p,r,i)*h%i,f=as(g,e,i)*l%i;return{pow_p_5_8:as(f,uu,i)*t%i,b2:o}}function x1(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const k1=Nn(R1.p,{isLE:!0}),Bc=(()=>{const t=k1.ORDER;return I1({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:s,b2:n}=P1(e);return Lt(as(s,N1,t)*n,t)},adjustScalarBytes:x1})})(),hu=(t,e)=>(t+(t>=0?e:-e)/Of)/e;function $1(t,e,s){const[[n,r],[i,o]]=e,a=hu(o*t,s),c=hu(-r*t,s);let l=t-a*n-c*i,d=-a*r-c*o;const u=l<Hs,h=d<Hs;u&&(l=-l),h&&(d=-d);const p=Li(Math.ceil(ff(s)/2))+Tr;if(l<Hs||l>=p||d<Hs||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}function Mc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Wa(t,e){const s={};for(let n of Object.keys(e))s[n]=t[n]===void 0?e[n]:t[n];return Do(s.lowS,"lowS"),Do(s.prehash,"prehash"),s.format!==void 0&&Mc(s.format),s}class U1 extends Error{constructor(e=""){super(e)}}const Fs={Err:U1,_tlv:{encode:(t,e)=>{const{Err:s}=Fs;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const n=e.length/2,r=to(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?to(r.length/2|128):"";return to(t)+i+r+e},decode(t,e){const{Err:s}=Fs;let n=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new s("tlv.decode: wrong tlv");const r=e[n++],i=!!(r&128);let o=0;if(!i)o=r;else{const c=r&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(n+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=Fs;if(t<Hs)throw new e("integer: negative integers are not allowed");let s=to(t);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(t){const{Err:e}=Fs;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return aa(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=Fs,r=dt("signature",t),{v:i,l:o}=n.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=Fs,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}},Hs=BigInt(0),Tr=BigInt(1),Of=BigInt(2),no=BigInt(3),D1=BigInt(4);function Cr(t,e){const{BYTES:s}=t;let n;if(typeof e=="bigint")n=e;else{let r=dt("private key",e);try{n=t.fromBytes(r)}catch{throw new Error(`invalid private key: expected ui8a of size ${s}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function L1(t,e={}){const s=A1("weierstrass",t,e),{Fp:n,Fn:r}=s;let i=s.CURVE;const{h:o,n:a}=i;ca(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Pf(n,r);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(R,C,S){const{x:y,y:b}=C.toAffine(),N=n.toBytes(y);if(Do(S,"isCompressed"),S){d();const $=!n.isOdd(b);return pn(Rf($),N)}else return pn(Uint8Array.of(4),N,n.toBytes(b))}function h(R){Hn(R,void 0,"Point");const{publicKey:C,publicKeyUncompressed:S}=l,y=R.length,b=R[0],N=R.subarray(1);if(y===C&&(b===2||b===3)){const $=n.fromBytes(N);if(!n.isValid($))throw new Error("bad point: is not on curve, wrong x");const A=f($);let O;try{O=n.sqrt(A)}catch(W){const ae=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+ae)}d();const M=n.isOdd(O);return(b&1)===1!==M&&(O=n.neg(O)),{x:$,y:O}}else if(y===S&&b===4){const $=n.BYTES,A=n.fromBytes(N.subarray(0,$)),O=n.fromBytes(N.subarray($,$*2));if(!w(A,O))throw new Error("bad point: is not on curve");return{x:A,y:O}}else throw new Error(`bad point: got length ${y}, expected compressed=${C} or uncompressed=${S}`)}const p=e.toBytes||u,g=e.fromBytes||h;function f(R){const C=n.sqr(R),S=n.mul(C,R);return n.add(n.add(S,n.mul(R,i.a)),i.b)}function w(R,C){const S=n.sqr(C),y=f(R);return n.eql(S,y)}if(!w(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const E=n.mul(n.pow(i.a,no),D1),I=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(E,I)))throw new Error("bad curve params: a or b");function _(R,C,S=!1){if(!n.isValid(C)||S&&n.is0(C))throw new Error(`bad point coordinate ${R}`);return C}function v(R){if(!(R instanceof x))throw new Error("ProjectivePoint expected")}function T(R){if(!c||!c.basises)throw new Error("no endo");return $1(R,c.basises,r.ORDER)}const P=iu((R,C)=>{const{X:S,Y:y,Z:b}=R;if(n.eql(b,n.ONE))return{x:S,y};const N=R.is0();C==null&&(C=N?n.ONE:n.inv(b));const $=n.mul(S,C),A=n.mul(y,C),O=n.mul(b,C);if(N)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:$,y:A}}),D=iu(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}const{x:C,y:S}=R.toAffine();if(!n.isValid(C)||!n.isValid(S))throw new Error("bad point: x or y not field elements");if(!w(C,S))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F(R,C,S,y,b){return S=new x(n.mul(S.X,R),S.Y,S.Z),C=Bo(y,C),S=Bo(b,S),C.add(S)}class x{constructor(C,S,y){this.X=_("x",C),this.Y=_("y",S,!0),this.Z=_("z",y),Object.freeze(this)}static CURVE(){return i}static fromAffine(C){const{x:S,y}=C||{};if(!C||!n.isValid(S)||!n.isValid(y))throw new Error("invalid affine point");if(C instanceof x)throw new Error("projective point not allowed");return n.is0(S)&&n.is0(y)?x.ZERO:new x(S,y,n.ONE)}static fromBytes(C){const S=x.fromAffine(g(Hn(C,void 0,"point")));return S.assertValidity(),S}static fromHex(C){return x.fromBytes(dt("pointHex",C))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(C=8,S=!0){return j.createCache(this,C),S||this.multiply(no),this}assertValidity(){D(this)}hasEvenY(){const{y:C}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(C)}equals(C){v(C);const{X:S,Y:y,Z:b}=this,{X:N,Y:$,Z:A}=C,O=n.eql(n.mul(S,A),n.mul(N,b)),M=n.eql(n.mul(y,A),n.mul($,b));return O&&M}negate(){return new x(this.X,n.neg(this.Y),this.Z)}double(){const{a:C,b:S}=i,y=n.mul(S,no),{X:b,Y:N,Z:$}=this;let A=n.ZERO,O=n.ZERO,M=n.ZERO,W=n.mul(b,b),ae=n.mul(N,N),se=n.mul($,$),X=n.mul(b,N);return X=n.add(X,X),M=n.mul(b,$),M=n.add(M,M),A=n.mul(C,M),O=n.mul(y,se),O=n.add(A,O),A=n.sub(ae,O),O=n.add(ae,O),O=n.mul(A,O),A=n.mul(X,A),M=n.mul(y,M),se=n.mul(C,se),X=n.sub(W,se),X=n.mul(C,X),X=n.add(X,M),M=n.add(W,W),W=n.add(M,W),W=n.add(W,se),W=n.mul(W,X),O=n.add(O,W),se=n.mul(N,$),se=n.add(se,se),W=n.mul(se,X),A=n.sub(A,W),M=n.mul(se,ae),M=n.add(M,M),M=n.add(M,M),new x(A,O,M)}add(C){v(C);const{X:S,Y:y,Z:b}=this,{X:N,Y:$,Z:A}=C;let O=n.ZERO,M=n.ZERO,W=n.ZERO;const ae=i.a,se=n.mul(i.b,no);let X=n.mul(S,N),le=n.mul(y,$),ie=n.mul(b,A),Se=n.add(S,y),ce=n.add(N,$);Se=n.mul(Se,ce),ce=n.add(X,le),Se=n.sub(Se,ce),ce=n.add(S,b);let Oe=n.add(N,A);return ce=n.mul(ce,Oe),Oe=n.add(X,ie),ce=n.sub(ce,Oe),Oe=n.add(y,b),O=n.add($,A),Oe=n.mul(Oe,O),O=n.add(le,ie),Oe=n.sub(Oe,O),W=n.mul(ae,ce),O=n.mul(se,ie),W=n.add(O,W),O=n.sub(le,W),W=n.add(le,W),M=n.mul(O,W),le=n.add(X,X),le=n.add(le,X),ie=n.mul(ae,ie),ce=n.mul(se,ce),le=n.add(le,ie),ie=n.sub(X,ie),ie=n.mul(ae,ie),ce=n.add(ce,ie),X=n.mul(le,ce),M=n.add(M,X),X=n.mul(Oe,ce),O=n.mul(Se,O),O=n.sub(O,X),X=n.mul(Se,le),W=n.mul(Oe,W),W=n.add(W,X),new x(O,M,W)}subtract(C){return this.add(C.negate())}is0(){return this.equals(x.ZERO)}multiply(C){const{endo:S}=e;if(!r.isValidNot0(C))throw new Error("invalid scalar: out of range");let y,b;const N=$=>j.cached(this,$,A=>Ma(x,A));if(S){const{k1neg:$,k1:A,k2neg:O,k2:M}=T(C),{p:W,f:ae}=N(A),{p:se,f:X}=N(M);b=ae.add(X),y=F(S.beta,W,se,$,O)}else{const{p:$,f:A}=N(C);y=$,b=A}return Ma(x,[y,b])[0]}multiplyUnsafe(C){const{endo:S}=e,y=this;if(!r.isValid(C))throw new Error("invalid scalar: out of range");if(C===Hs||y.is0())return x.ZERO;if(C===Tr)return y;if(j.hasCache(this))return this.multiply(C);if(S){const{k1neg:b,k1:N,k2neg:$,k2:A}=T(C),{p1:O,p2:M}=C1(x,y,N,A);return F(S.beta,O,M,b,$)}else return j.unsafe(y,C)}multiplyAndAddUnsafe(C,S,y){const b=this.multiplyUnsafe(S).add(C.multiplyUnsafe(y));return b.is0()?void 0:b}toAffine(C){return P(this,C)}isTorsionFree(){const{isTorsionFree:C}=e;return o===Tr?!0:C?C(x,this):j.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:C}=e;return o===Tr?this:C?C(x,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(C=!0){return Do(C,"isCompressed"),this.assertValidity(),p(x,this,C)}toHex(C=!0){return Nr(this.toBytes(C))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(C=!0){return this.toBytes(C)}_setWindowSize(C){this.precompute(C)}static normalizeZ(C){return Ma(x,C)}static msm(C,S){return v1(x,r,C,S)}static fromPrivateKey(C){return x.BASE.multiply(Cr(r,C))}}x.BASE=new x(i.Gx,i.Gy,n.ONE),x.ZERO=new x(n.ZERO,n.ONE,n.ZERO),x.Fp=n,x.Fn=r;const K=r.BITS,j=new E1(x,e.endo?Math.ceil(K/2):K);return x.BASE.precompute(8),x}function Rf(t){return Uint8Array.of(t?2:3)}function Pf(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function B1(t,e={}){const{Fn:s}=t,n=e.randomBytes||cr,r=Object.assign(Pf(t.Fp,s),{seed:If(s.ORDER)});function i(h){try{return!!Cr(s,h)}catch{return!1}}function o(h,p){const{publicKey:g,publicKeyUncompressed:f}=r;try{const w=h.length;return p===!0&&w!==g||p===!1&&w!==f?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(r.seed)){return w1(Hn(h,r.seed,"seed"),s.ORDER)}function c(h,p=!0){return t.BASE.multiply(Cr(s,h)).toBytes(p)}function l(h){const p=a(h);return{secretKey:p,publicKey:c(p)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:p,publicKey:g,publicKeyUncompressed:f}=r;if(s.allowedLengths||p===g)return;const w=dt("key",h).length;return w===g||w===f}function u(h,p,g=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(p)===!1)throw new Error("second arg must be public key");const f=Cr(s,h);return t.fromHex(p).multiply(f).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>Cr(s,h),precompute(h=8,p=t.BASE){return p.precompute(h,!1)}},lengths:r})}function M1(t,e,s={}){sa(e),ca(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=s.randomBytes||cr,r=s.hmac||((S,...y)=>ia(e,S,pn(...y))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p}=B1(t,s),g={prehash:!1,lowS:typeof s.lowS=="boolean"?s.lowS:!1,format:void 0,extraEntropy:!1},f="compact";function w(S){const y=a>>Tr;return S>y}function E(S,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return y}function I(S,y){Mc(y);const b=p.signature,N=y==="compact"?b:y==="recovered"?b+1:void 0;return Hn(S,N,`${y} signature`)}class _{constructor(y,b,N){this.r=E("r",y),this.s=E("s",b),N!=null&&(this.recovery=N),Object.freeze(this)}static fromBytes(y,b=f){I(y,b);let N;if(b==="der"){const{r:M,s:W}=Fs.toSig(Hn(y));return new _(M,W)}b==="recovered"&&(N=y[0],b="compact",y=y.subarray(1));const $=o.BYTES,A=y.subarray(0,$),O=y.subarray($,$*2);return new _(o.fromBytes(A),o.fromBytes(O),N)}static fromHex(y,b){return this.fromBytes($o(y),b)}addRecoveryBit(y){return new _(this.r,this.s,y)}recoverPublicKey(y){const b=i.ORDER,{r:N,s:$,recovery:A}=this;if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");if(a*Of<b&&A>1)throw new Error("recovery id is ambiguous for h>1 curve");const O=A===2||A===3?N+a:N;if(!i.isValid(O))throw new Error("recovery id 2 or 3 invalid");const M=i.toBytes(O),W=t.fromBytes(pn(Rf((A&1)===0),M)),ae=o.inv(O),se=T(dt("msgHash",y)),X=o.create(-se*ae),le=o.create($*ae),ie=t.BASE.multiplyUnsafe(X).add(W.multiplyUnsafe(le));if(ie.is0())throw new Error("point at infinify");return ie.assertValidity(),ie}hasHighS(){return w(this.s)}toBytes(y=f){if(Mc(y),y==="der")return $o(Fs.hexFromSig(this));const b=o.toBytes(this.r),N=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return pn(Uint8Array.of(this.recovery),b,N)}return pn(b,N)}toHex(y){return Nr(this.toBytes(y))}assertValidity(){}static fromCompact(y){return _.fromBytes(dt("sig",y),"compact")}static fromDER(y){return _.fromBytes(dt("sig",y),"der")}normalizeS(){return this.hasHighS()?new _(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Nr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Nr(this.toBytes("compact"))}}const v=s.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");const y=aa(S),b=S.length*8-c;return b>0?y>>BigInt(b):y},T=s.bits2int_modN||function(S){return o.create(v(S))},P=Li(c);function D(S){return Lc("num < 2^"+c,S,Hs,P),o.toBytes(S)}function F(S,y){return Hn(S,void 0,"message"),y?Hn(e(S),void 0,"prehashed message"):S}function x(S,y,b){if(["recovered","canonical"].some(le=>le in b))throw new Error("sign() legacy options not supported");const{lowS:N,prehash:$,extraEntropy:A}=Wa(b,g);S=F(S,$);const O=T(S),M=Cr(o,y),W=[D(M),D(O)];if(A!=null&&A!==!1){const le=A===!0?n(p.secretKey):A;W.push(dt("extraEntropy",le))}const ae=pn(...W),se=O;function X(le){const ie=v(le);if(!o.isValidNot0(ie))return;const Se=o.inv(ie),ce=t.BASE.multiply(ie).toAffine(),Oe=o.create(ce.x);if(Oe===Hs)return;const ht=o.create(Se*o.create(se+Oe*M));if(ht===Hs)return;let yt=(ce.x===Oe?0:2)|Number(ce.y&Tr),pt=ht;return N&&w(ht)&&(pt=o.neg(ht),yt^=1),new _(Oe,pt,yt)}return{seed:ae,k2sig:X}}function K(S,y,b={}){S=dt("message",S);const{seed:N,k2sig:$}=x(S,y,b);return c1(e.outputLen,o.BYTES,r)(N,$)}function j(S){let y;const b=typeof S=="string"||ta(S),N=!b&&S!==null&&typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!b&&!N)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(N)y=new _(S.r,S.s);else if(b){try{y=_.fromBytes(dt("sig",S),"der")}catch($){if(!($ instanceof Fs.Err))throw $}if(!y)try{y=_.fromBytes(dt("sig",S),"compact")}catch{return!1}}return y||!1}function R(S,y,b,N={}){const{lowS:$,prehash:A,format:O}=Wa(N,g);if(b=dt("publicKey",b),y=F(dt("message",y),A),"strict"in N)throw new Error("options.strict was renamed to lowS");const M=O===void 0?j(S):_.fromBytes(dt("sig",S),O);if(M===!1)return!1;try{const W=t.fromBytes(b);if($&&M.hasHighS())return!1;const{r:ae,s:se}=M,X=T(y),le=o.inv(se),ie=o.create(X*le),Se=o.create(ae*le),ce=t.BASE.multiplyUnsafe(ie).add(W.multiplyUnsafe(Se));return ce.is0()?!1:o.create(ce.x)===ae}catch{return!1}}function C(S,y,b={}){const{prehash:N}=Wa(b,g);return y=F(y,N),_.fromBytes(S,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p,Point:t,sign:K,verify:R,recoverPublicKey:C,Signature:_,hash:e})}function F1(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},s=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const r=Nn(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),i={Fp:s,Fn:r,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function j1(t){const{CURVE:e,curveOpts:s}=F1(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:s,hash:t.hash,ecdsaOpts:n}}function q1(t,e){const s=e.Point;return Object.assign({},e,{ProjectivePoint:s,CURVE:Object.assign({},t,Af(s.Fn.ORDER,s.Fn.BITS))})}function W1(t){const{CURVE:e,curveOpts:s,hash:n,ecdsaOpts:r}=j1(t),i=L1(e,s),o=M1(i,n,r);return q1(t,o)}function Fc(t,e){const s=n=>W1({...t,hash:n});return{...s(e),create:s}}const xf={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},kf={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},$f={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},H1=Nn(xf.p),K1=Nn(kf.p),z1=Nn($f.p),V1=Fc({...xf,Fp:H1,lowS:!1},ra);Fc({...kf,Fp:K1,lowS:!1},QE),Fc({...$f,Fp:z1,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},ZE);const G1=V1,Uf="base10",wt="base16",Nt="base64pad",fn="base64url",Bi="utf8",Df=0,Vs=1,Mi=2,Y1=0,pu=1,di=12,kl=32;function J1(){const t=Bc.utils.randomPrivateKey(),e=Bc.getPublicKey(t);return{privateKey:Rt(t,wt),publicKey:Rt(e,wt)}}function jc(){const t=cr(kl);return Rt(t,wt)}function X1(t,e){const s=Bc.getSharedSecret(es(t,wt),es(e,wt)),n=o1(oa,s,void 0,void 0,kl);return Rt(n,wt)}function yo(t){const e=oa(es(t,wt));return Rt(e,wt)}function Xt(t){const e=oa(es(t,Bi));return Rt(e,wt)}function Lf(t){return es(`${t}`,Uf)}function sr(t){return Number(Rt(t,Uf))}function Bf(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Mf(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function Z1(t){const e=Lf(typeof t.type<"u"?t.type:Df);if(sr(e)===Vs&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?es(t.senderPublicKey,wt):void 0,n=typeof t.iv<"u"?es(t.iv,wt):cr(di),r=es(t.symKey,wt),i=uf(r,n).encrypt(es(t.message,Bi)),o=Ff({type:e,sealed:i,iv:n,senderPublicKey:s});return t.encoding===fn?Bf(o):o}function Q1(t){const e=es(t.symKey,wt),{sealed:s,iv:n}=Ii({encoded:t.encoded,encoding:t.encoding}),r=uf(e,n).decrypt(s);if(r===null)throw new Error("Failed to decrypt");return Rt(r,Bi)}function ev(t,e){const s=Lf(Mi),n=cr(di),r=es(t,Bi),i=Ff({type:s,sealed:r,iv:n});return e===fn?Bf(i):i}function tv(t,e){const{sealed:s}=Ii({encoded:t,encoding:e});return Rt(s,Bi)}function Ff(t){if(sr(t.type)===Mi)return Rt(ai([t.type,t.sealed]),Nt);if(sr(t.type)===Vs){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Rt(ai([t.type,t.senderPublicKey,t.iv,t.sealed]),Nt)}return Rt(ai([t.type,t.iv,t.sealed]),Nt)}function Ii(t){const e=(t.encoding||Nt)===fn?Mf(t.encoded):t.encoded,s=es(e,Nt),n=s.slice(Y1,pu),r=pu;if(sr(n)===Vs){const c=r+kl,l=c+di,d=s.slice(r,c),u=s.slice(c,l),h=s.slice(l);return{type:n,sealed:h,iv:u,senderPublicKey:d}}if(sr(n)===Mi){const c=s.slice(r),l=cr(di);return{type:n,sealed:c,iv:l}}const i=r+di,o=s.slice(r,i),a=s.slice(i);return{type:n,sealed:a,iv:o}}function sv(t,e){const s=Ii({encoded:t,encoding:e==null?void 0:e.encoding});return jf({type:sr(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?Rt(s.senderPublicKey,wt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function jf(t){const e=(t==null?void 0:t.type)||Df;if(e===Vs){if(typeof(t==null?void 0:t.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(t==null?void 0:t.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t==null?void 0:t.senderPublicKey,receiverPublicKey:t==null?void 0:t.receiverPublicKey}}function fu(t){return t.type===Vs&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function gu(t){return t.type===Mi}function nv(t){const e=Ee.from(t.x,"base64"),s=Ee.from(t.y,"base64");return ai([new Uint8Array([4]),e,s])}function rv(t,e){const[s,n,r]=t.split("."),i=Ee.from(Mf(r),"base64");if(i.length!==64)throw new Error("Invalid signature length");const o=i.slice(0,32),a=i.slice(32,64),c=`${s}.${n}`,l=oa(c),d=nv(e);if(!G1.verify(ai([o,a]),l,d))throw new Error("Invalid signature");return uc(t).payload}const iv="irn";function Mo(t){return(t==null?void 0:t.relay)||{protocol:iv}}function vr(t){const e=zg[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var ov=Object.defineProperty,av=Object.defineProperties,cv=Object.getOwnPropertyDescriptors,mu=Object.getOwnPropertySymbols,lv=Object.prototype.hasOwnProperty,dv=Object.prototype.propertyIsEnumerable,wu=(t,e,s)=>e in t?ov(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ha=(t,e)=>{for(var s in e||(e={}))lv.call(e,s)&&wu(t,s,e[s]);if(mu)for(var s of mu(e))dv.call(e,s)&&wu(t,s,e[s]);return t},uv=(t,e)=>av(t,cv(e));function hv(t,e="-"){const s={},n="relay"+e;return Object.keys(t).forEach(r=>{if(r.startsWith(n)){const i=r.replace(n,""),o=t[r];s[i]=o}}),s}function yu(t){if(!t.includes("wc:")){const l=Hp(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),s=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),r=t.substring(e+1,s).split("@"),i=typeof s<"u"?t.substring(s):"",o=new URLSearchParams(i),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:pv(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:hv(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function pv(t){return t.startsWith("//")?t.substring(2):t}function fv(t,e="-"){const s="relay",n={};return Object.keys(t).forEach(r=>{const i=r,o=s+e+i;t[i]&&(n[o]=t[i])}),n}function bu(t){const e=new URLSearchParams,s=Ha(Ha(uv(Ha({},fv(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(s).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!==void 0&&e.append(n,String(r))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function ro(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var gv=Object.defineProperty,mv=Object.defineProperties,wv=Object.getOwnPropertyDescriptors,Eu=Object.getOwnPropertySymbols,yv=Object.prototype.hasOwnProperty,bv=Object.prototype.propertyIsEnumerable,Cu=(t,e,s)=>e in t?gv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ev=(t,e)=>{for(var s in e||(e={}))yv.call(e,s)&&Cu(t,s,e[s]);if(Eu)for(var s of Eu(e))bv.call(e,s)&&Cu(t,s,e[s]);return t},Cv=(t,e)=>mv(t,wv(e));function Wr(t){const e=[];return t.forEach(s=>{const[n,r]=s.split(":");e.push(`${n}:${r}`)}),e}function vv(t){const e=[];return Object.values(t).forEach(s=>{e.push(...Wr(s.accounts))}),e}function Av(t,e){const s=[];return Object.values(t).forEach(n=>{Wr(n.accounts).includes(e)&&s.push(...n.methods)}),s}function _v(t,e){const s=[];return Object.values(t).forEach(n=>{Wr(n.accounts).includes(e)&&s.push(...n.events)}),s}function la(t){return t.includes(":")}function Ar(t){return la(t)?t.split(":")[0]:t}function vu(t){var e,s,n;const r={};if(!Ns(t))return r;for(const[i,o]of Object.entries(t)){const a=la(i)?[i]:o.chains,c=o.methods||[],l=o.events||[],d=Ar(i);r[d]=Cv(Ev({},r[d]),{chains:Ss(a,(e=r[d])==null?void 0:e.chains),methods:Ss(c,(s=r[d])==null?void 0:s.methods),events:Ss(l,(n=r[d])==null?void 0:n.events)})}return r}function Iv(t){const e={};return t==null||t.forEach(s=>{var n;const[r,i]=s.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(s),(n=e[r].chains)==null||n.push(`${r}:${i}`)}),e}function Au(t,e){e=e.map(n=>n.replace("did:pkh:",""));const s=Iv(e);for(const[n,r]of Object.entries(s))r.methods?r.methods=Ss(r.methods,t):r.methods=t,r.events=["chainChanged","accountsChanged"];return s}function Sv(t,e){var s,n,r,i,o,a;const c=vu(t),l=vu(e),d={},u=Object.keys(c).concat(Object.keys(l));for(const h of u)d[h]={chains:Ss((s=c[h])==null?void 0:s.chains,(n=l[h])==null?void 0:n.chains),methods:Ss((r=c[h])==null?void 0:r.methods,(i=l[h])==null?void 0:i.methods),events:Ss((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return d}const Nv={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}},Tv={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 H(t,e){const{message:s,code:n}=Tv[t];return{message:e?`${s} ${e}`:s,code:n}}function De(t,e){const{message:s,code:n}=Nv[t];return{message:e?`${s} ${e}`:s,code:n}}function Gs(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Ns(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function ze(t){return typeof t>"u"}function We(t,e){return e&&ze(t)?!0:typeof t=="string"&&!!t.trim().length}function $l(t,e){return e&&ze(t)?!0:typeof t=="number"&&!isNaN(t)}function Ov(t,e){const{requiredNamespaces:s}=e,n=Object.keys(t.namespaces),r=Object.keys(s);let i=!0;return Wn(r,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],d=Wr(a),u=s[o];(!Wn(Mp(o,u),d)||!Wn(u.methods,c)||!Wn(u.events,l))&&(i=!1)}),i):!1}function Fo(t){return We(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function Rv(t){if(We(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&Fo(s)}}return!1}function Pv(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(We(t,!1)){if(e(t))return!0;const s=Hp(t);return e(s)}}catch{}return!1}function xv(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function kv(t){return t==null?void 0:t.topic}function $v(t,e){let s=null;return We(t==null?void 0:t.publicKey,!1)||(s=H("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function _u(t){let e=!0;return Gs(t)?t.length&&(e=t.every(s=>We(s,!1))):e=!1,e}function Uv(t,e,s){let n=null;return Gs(e)&&e.length?e.forEach(r=>{n||Fo(r)||(n=De("UNSUPPORTED_CHAINS",`${s}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Fo(t)||(n=De("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function Dv(t,e,s){let n=null;return Object.entries(t).forEach(([r,i])=>{if(n)return;const o=Uv(r,Mp(r,i),`${e} ${s}`);o&&(n=o)}),n}function Lv(t,e){let s=null;return Gs(t)?t.forEach(n=>{s||Rv(n)||(s=De("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):s=De("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function Bv(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=Lv(n==null?void 0:n.accounts,`${e} namespace`);r&&(s=r)}),s}function Mv(t,e){let s=null;return _u(t==null?void 0:t.methods)?_u(t==null?void 0:t.events)||(s=De("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=De("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function qf(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=Mv(n,`${e}, namespace`);r&&(s=r)}),s}function Fv(t,e,s){let n=null;if(t&&Ns(t)){const r=qf(t,e);r&&(n=r);const i=Dv(t,e,s);i&&(n=i)}else n=H("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return n}function Ka(t,e){let s=null;if(t&&Ns(t)){const n=qf(t,e);n&&(s=n);const r=Bv(t,e);r&&(s=r)}else s=H("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function Wf(t){return We(t.protocol,!0)}function jv(t,e){let s=!1;return e&&!t?s=!0:t&&Gs(t)&&t.length&&t.forEach(n=>{s=Wf(n)}),s}function qv(t){return typeof t=="number"}function _t(t){return typeof t<"u"&&typeof t!==null}function Wv(t){return!(!t||typeof t!="object"||!t.code||!$l(t.code,!1)||!t.message||!We(t.message,!1))}function Hv(t){return!(ze(t)||!We(t.method,!1))}function Kv(t){return!(ze(t)||ze(t.result)&&ze(t.error)||!$l(t.id,!1)||!We(t.jsonrpc,!1))}function zv(t){return!(ze(t)||!We(t.name,!1))}function Iu(t,e){return!(!Fo(e)||!vv(t).includes(e))}function Vv(t,e,s){return We(s,!1)?Av(t,e).includes(s):!1}function Gv(t,e,s){return We(s,!1)?_v(t,e).includes(s):!1}function Su(t,e,s){let n=null;const r=Yv(t),i=Jv(e),o=Object.keys(r),a=Object.keys(i),c=Nu(Object.keys(t)),l=Nu(Object.keys(e)),d=c.filter(u=>!l.includes(u));return d.length&&(n=H("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
|
|
10
10
|
Required: ${d.toString()}
|
|
11
11
|
Received: ${Object.keys(e).toString()}`)),Wn(o,a)||(n=H("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.
|
|
12
12
|
Required: ${o.toString()}
|
|
13
13
|
Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||n)return;const h=Wr(e[u].accounts);h.includes(u)||(n=H("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${u}
|
|
14
14
|
Required: ${u}
|
|
15
|
-
Approved: ${h.toString()}`))}),o.forEach(u=>{n||(Wn(r[u].methods,i[u].methods)?Wn(r[u].events,i[u].events)||(n=H("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${u}`)):n=H("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${u}`))}),n}function Yv(t){const e={};return Object.keys(t).forEach(s=>{var n;s.includes(":")?e[s]=t[s]:(n=t[s].chains)==null||n.forEach(r=>{e[r]={methods:t[s].methods,events:t[s].events}})}),e}function Nu(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Jv(t){const e={};return Object.keys(t).forEach(s=>{if(s.includes(":"))e[s]=t[s];else{const n=Wr(t[s].accounts);n==null||n.forEach(r=>{e[r]={accounts:t[s].accounts.filter(i=>i.includes(`${r}:`)),methods:t[s].methods,events:t[s].events}})}}),e}function Xv(t,e){return $l(t,!1)&&t<=e.max&&t>=e.min}function Tu(){const t=Ui();return new Promise(e=>{switch(t){case Mt.browser:e(Zv());break;case Mt.reactNative:e(Qv());break;case Mt.node:e(eA());break;default:e(!0)}})}function Zv(){return qr()&&(navigator==null?void 0:navigator.onLine)}async function Qv(){if(Sn()&&typeof de<"u"&&de!=null&&de.NetInfo){const t=await(de==null?void 0:de.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function eA(){return!0}function tA(t){switch(Ui()){case Mt.browser:sA(t);break;case Mt.reactNative:nA(t);break}}function sA(t){!Sn()&&qr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function nA(t){var e;Sn()&&typeof de<"u"&&de!=null&&de.NetInfo&&((e=de)==null||e.NetInfo.addEventListener(s=>t(s==null?void 0:s.isConnected)))}function rA(){var t;return qr()&&xr()?((t=xr())==null?void 0:t.visibilityState)==="visible":!0}const za={};class Yr{static get(e){return za[e]}static set(e,s){za[e]=s}static delete(e){delete za[e]}}function iA(t){const e=Fr.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function oA({publicKey:t,signature:e,payload:s}){var n;const r=qc(s.method),i=128|parseInt(((n=s.version)==null?void 0:n.toString())||"4"),o=lA(s.address),a=s.era==="00"?new Uint8Array([0]):qc(s.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(s.nonce,16),l=new Uint8Array([c&255,c>>8&255]),d=BigInt(`0x${cA(s.tip)}`),u=uA(d),h=new Uint8Array([0,...t,o,...e,...a,...l,...u,...r]),p=dA(h.length+1);return new Uint8Array([...p,i,...h])}function aA(t){const e=qc(t),s=Wg.blake2b(e,void 0,32);return"0x"+Ee.from(s).toString("hex")}function qc(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function cA(t){return t.startsWith("0x")?t.slice(2):t}function lA(t){const e=Fr.decode(t)[0];return e===42?0:e===60?2:1}function dA(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function uA(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function hA(t){const e=Uint8Array.from(Ee.from(t.signature,"hex")),s=iA(t.transaction.address),n=oA({publicKey:s,signature:e,payload:t.transaction}),r=Ee.from(n).toString("hex");return aA(r)}function Ul({logger:t,name:e}){const s=typeof t=="string"?rp({opts:{level:t,name:e}}).logger:t;return s.level=typeof t=="string"?t:t.level,s}const Hf="wc",Kf=2,jo="core",Ts=`${Hf}@2:${jo}:`,pA={name:jo,logger:"error"},fA={database:":memory:"},gA="crypto",Ou="client_ed25519_seed",mA=V.ONE_DAY,wA="keychain",yA="0.3",bA="messages",EA="0.3",CA=V.SIX_HOURS,vA="publisher",zf="irn",AA="error",Vf="wss://relay.walletconnect.org",_A="relayer",Fe={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},IA="_subscription",Ht={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},SA=.1,Wc="2.22.4",xe={link_mode:"link_mode",relay:"relay"},bo={inbound:"inbound",outbound:"outbound"},NA="0.3",TA="WALLETCONNECT_CLIENT_ID",Ru="WALLETCONNECT_LINK_MODE_APPS",Ut={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},OA="subscription",RA="0.3",PA="pairing",xA="0.3",Jr={wc_pairingDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:V.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:V.ONE_DAY,prompt:!1,tag:0},res:{ttl:V.ONE_DAY,prompt:!1,tag:0}}},Bn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},is={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},kA="history",$A="0.3",UA="expirer",Yt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},DA="0.3",LA="verify-api",BA="https://verify.walletconnect.com",Gf="https://verify.walletconnect.org",ui=Gf,MA=`${ui}/v3`,FA=[BA,Gf],jA="echo",qA="https://echo.walletconnect.com",ys={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Us={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},os={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},xn={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},kn={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Xr={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},WA=.1,HA="event-client",KA=86400,zA="https://pulse.walletconnect.org/batch";function VA(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),n=0;n<s.length;n++)s[n]=255;for(var r=0;r<t.length;r++){var i=t.charAt(r),o=i.charCodeAt(0);if(s[o]!==255)throw new TypeError(i+" is ambiguous");s[o]=r}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var f=0,w=0,E=0,I=g.length;E!==I&&g[E]===0;)E++,f++;for(var _=(I-E)*d+1>>>0,v=new Uint8Array(_);E!==I;){for(var T=g[E],P=0,D=_-1;(T!==0||P<w)&&D!==-1;D--,P++)T+=256*v[D]>>>0,v[D]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");w=P,E++}for(var F=_-w;F!==_&&v[F]===0;)F++;for(var x=c.repeat(f);F<_;++F)x+=t.charAt(v[F]);return x}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var f=0;if(g[f]!==" "){for(var w=0,E=0;g[f]===c;)w++,f++;for(var I=(g.length-f)*l+1>>>0,_=new Uint8Array(I);g[f];){var v=s[g.charCodeAt(f)];if(v===255)return;for(var T=0,P=I-1;(v!==0||T<E)&&P!==-1;P--,T++)v+=a*_[P]>>>0,_[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");E=T,f++}if(g[f]!==" "){for(var D=I-E;D!==I&&_[D]===0;)D++;for(var F=new Uint8Array(w+(I-D)),x=w;D!==I;)F[x++]=_[D++];return F}}}function p(g){var f=h(g);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:p}}var GA=VA,YA=GA;const Yf=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},JA=t=>new TextEncoder().encode(t),XA=t=>new TextDecoder().decode(t);class ZA{constructor(e,s,n){this.name=e,this.prefix=s,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class QA{constructor(e,s,n){if(this.name=e,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Jf(this,e)}}class e_{constructor(e){this.decoders=e}or(e){return Jf(this,e)}decode(e){const s=e[0],n=this.decoders[s];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Jf=(t,e)=>new e_({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class t_{constructor(e,s,n,r){this.name=e,this.prefix=s,this.baseEncode=n,this.baseDecode=r,this.encoder=new ZA(e,s,n),this.decoder=new QA(e,s,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const da=({name:t,prefix:e,encode:s,decode:n})=>new t_(t,e,s,n),Fi=({prefix:t,name:e,alphabet:s})=>{const{encode:n,decode:r}=YA(s,e);return da({prefix:t,name:e,encode:n,decode:i=>Yf(r(i))})},s_=(t,e,s,n)=>{const r={};for(let d=0;d<e.length;++d)r[e[d]]=d;let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*s/8|0);let a=0,c=0,l=0;for(let d=0;d<i;++d){const u=r[t[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<s|u,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},n_=(t,e,s)=>{const n=e[e.length-1]==="=",r=(1<<s)-1;let i="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,i+=e[r&a>>o];if(o&&(i+=e[r&a<<s-o]),n)for(;i.length*s&7;)i+="=";return i},rt=({name:t,prefix:e,bitsPerChar:s,alphabet:n})=>da({prefix:e,name:t,encode(r){return n_(r,n,s)},decode(r){return s_(r,n,s,t)}}),r_=da({prefix:"\0",name:"identity",encode:t=>XA(t),decode:t=>JA(t)});var i_=Object.freeze({__proto__:null,identity:r_});const o_=rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var a_=Object.freeze({__proto__:null,base2:o_});const c_=rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var l_=Object.freeze({__proto__:null,base8:c_});const d_=Fi({prefix:"9",name:"base10",alphabet:"0123456789"});var u_=Object.freeze({__proto__:null,base10:d_});const h_=rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),p_=rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var f_=Object.freeze({__proto__:null,base16:h_,base16upper:p_});const g_=rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),m_=rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),w_=rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),y_=rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),b_=rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),E_=rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),C_=rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),v_=rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),A_=rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var __=Object.freeze({__proto__:null,base32:g_,base32upper:m_,base32pad:w_,base32padupper:y_,base32hex:b_,base32hexupper:E_,base32hexpad:C_,base32hexpadupper:v_,base32z:A_});const I_=Fi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),S_=Fi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var N_=Object.freeze({__proto__:null,base36:I_,base36upper:S_});const T_=Fi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),O_=Fi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var R_=Object.freeze({__proto__:null,base58btc:T_,base58flickr:O_});const P_=rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),x_=rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),k_=rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$_=rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var U_=Object.freeze({__proto__:null,base64:P_,base64pad:x_,base64url:k_,base64urlpad:$_});const Xf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),D_=Xf.reduce((t,e,s)=>(t[s]=e,t),[]),L_=Xf.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function B_(t){return t.reduce((e,s)=>(e+=D_[s],e),"")}function M_(t){const e=[];for(const s of t){const n=L_[s.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(n)}return new Uint8Array(e)}const F_=da({prefix:"🚀",name:"base256emoji",encode:B_,decode:M_});var j_=Object.freeze({__proto__:null,base256emoji:F_}),q_=Zf,Pu=128,W_=127,H_=~W_,K_=Math.pow(2,31);function Zf(t,e,s){e=e||[],s=s||0;for(var n=s;t>=K_;)e[s++]=t&255|Pu,t/=128;for(;t&H_;)e[s++]=t&255|Pu,t>>>=7;return e[s]=t|0,Zf.bytes=s-n+1,e}var z_=Hc,V_=128,xu=127;function Hc(t,n){var s=0,n=n||0,r=0,i=n,o,a=t.length;do{if(i>=a)throw Hc.bytes=0,new RangeError("Could not decode varint");o=t[i++],s+=r<28?(o&xu)<<r:(o&xu)*Math.pow(2,r),r+=7}while(o>=V_);return Hc.bytes=i-n,s}var G_=Math.pow(2,7),Y_=Math.pow(2,14),J_=Math.pow(2,21),X_=Math.pow(2,28),Z_=Math.pow(2,35),Q_=Math.pow(2,42),eI=Math.pow(2,49),tI=Math.pow(2,56),sI=Math.pow(2,63),nI=function(t){return t<G_?1:t<Y_?2:t<J_?3:t<X_?4:t<Z_?5:t<Q_?6:t<eI?7:t<tI?8:t<sI?9:10},rI={encode:q_,decode:z_,encodingLength:nI},Qf=rI;const ku=(t,e,s=0)=>(Qf.encode(t,e,s),e),$u=t=>Qf.encodingLength(t),Kc=(t,e)=>{const s=e.byteLength,n=$u(t),r=n+$u(s),i=new Uint8Array(r+s);return ku(t,i,0),ku(s,i,n),i.set(e,r),new iI(t,s,e,i)};class iI{constructor(e,s,n,r){this.code=e,this.size=s,this.digest=n,this.bytes=r}}const eg=({name:t,code:e,encode:s})=>new oI(t,e,s);class oI{constructor(e,s,n){this.name=e,this.code=s,this.encode=n}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?Kc(this.code,s):s.then(n=>Kc(this.code,n))}else throw Error("Unknown type, must be binary type")}}const tg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),aI=eg({name:"sha2-256",code:18,encode:tg("SHA-256")}),cI=eg({name:"sha2-512",code:19,encode:tg("SHA-512")});var lI=Object.freeze({__proto__:null,sha256:aI,sha512:cI});const sg=0,dI="identity",ng=Yf,uI=t=>Kc(sg,ng(t)),hI={code:sg,name:dI,encode:ng,digest:uI};var pI=Object.freeze({__proto__:null,identity:hI});new TextEncoder,new TextDecoder;const Uu={...i_,...a_,...l_,...u_,...f_,...__,...N_,...R_,...U_,...j_};({...lI,...pI});function rg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function fI(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?rg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function ig(t,e,s,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:n}}}const Du=ig("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Va=ig("ascii","a",t=>{let e="a";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return e},t=>{t=t.substring(1);const e=fI(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),gI={utf8:Du,"utf-8":Du,hex:Uu.base16,latin1:Va,ascii:Va,binary:Va,...Uu};function mI(t,e="utf8"){const s=gI[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?rg(globalThis.Buffer.from(t,"utf-8")):s.decoder.decode(`${s.prefix}${t}`)}var wI=Object.defineProperty,yI=(t,e,s)=>e in t?wI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ms=(t,e,s)=>yI(t,typeof e!="symbol"?e+"":e,s);class bI{constructor(e,s){this.core=e,this.logger=s,ms(this,"keychain",new Map),ms(this,"name",wA),ms(this,"version",yA),ms(this,"initialized",!1),ms(this,"storagePrefix",Ts),ms(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),ms(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),ms(this,"set",async(n,r)=>{this.isInitialized(),this.keychain.set(n,r),await this.persist()}),ms(this,"get",n=>{this.isInitialized();const r=this.keychain.get(n);if(typeof r>"u"){const{message:i}=H("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(i)}return r}),ms(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=Ft(s,this.name)}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Oc(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Rc(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var EI=Object.defineProperty,CI=(t,e,s)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ve=(t,e,s)=>CI(t,typeof e!="symbol"?e+"":e,s);class vI{constructor(e,s,n){this.core=e,this.logger=s,Ve(this,"name",gA),Ve(this,"keychain"),Ve(this,"randomSessionIdentifier",jc()),Ve(this,"initialized",!1),Ve(this,"clientId"),Ve(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ve(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ve(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const r=await this.getClientSeed(),i=zl(r),o=Yg(i.publicKey);return this.clientId=o,o}),Ve(this,"generateKeyPair",()=>{this.isInitialized();const r=JC();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ve(this,"signJWT",async r=>{this.isInitialized();const i=await this.getClientSeed(),o=zl(i),a=this.randomSessionIdentifier;return await Jg(a,r,mA,o)}),Ve(this,"generateSharedKey",(r,i,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=XC(a,i);return this.setSymKey(c,o)}),Ve(this,"setSymKey",async(r,i)=>{this.isInitialized();const o=i||yo(r);return await this.keychain.set(o,r),o}),Ve(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"encode",async(r,i,o)=>{this.isInitialized();const a=jf(o),c=Xn(i);if(gu(a))return ev(c,o==null?void 0:o.encoding);if(fu(a)){const h=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(h,p)}const l=this.getSymKey(r),{type:d,senderPublicKey:u}=a;return ZC({type:d,symKey:l,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Ve(this,"decode",async(r,i,o)=>{this.isInitialized();const a=sv(i,o);if(gu(a)){const c=tv(i,o==null?void 0:o.encoding);return _o(c)}if(fu(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=QC({symKey:c,encoded:i,encoding:o==null?void 0:o.encoding});return _o(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ve(this,"getPayloadType",(r,i=Nt)=>{const o=Ii({encoded:r,encoding:i});return sr(o.type)}),Ve(this,"getPayloadSenderPublicKey",(r,i=Nt)=>{const o=Ii({encoded:r,encoding:i});return o.senderPublicKey?Rt(o.senderPublicKey,wt):void 0}),this.core=e,this.logger=Ft(s,this.name),this.keychain=n||new bI(this.core,this.logger)}get context(){return Pt(this.logger)}async setPrivateKey(e,s){return await this.keychain.set(e,s),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ou)}catch{e=jc(),await this.keychain.set(Ou,e)}return mI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var AI=Object.defineProperty,_I=Object.defineProperties,II=Object.getOwnPropertyDescriptors,Lu=Object.getOwnPropertySymbols,SI=Object.prototype.hasOwnProperty,NI=Object.prototype.propertyIsEnumerable,zc=(t,e,s)=>e in t?AI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,TI=(t,e)=>{for(var s in e||(e={}))SI.call(e,s)&&zc(t,s,e[s]);if(Lu)for(var s of Lu(e))NI.call(e,s)&&zc(t,s,e[s]);return t},OI=(t,e)=>_I(t,II(e)),kt=(t,e,s)=>zc(t,typeof e!="symbol"?e+"":e,s);class RI extends Uy{constructor(e,s){super(e,s),this.logger=e,this.core=s,kt(this,"messages",new Map),kt(this,"messagesWithoutClientAck",new Map),kt(this,"name",bA),kt(this,"version",EA),kt(this,"initialized",!1),kt(this,"storagePrefix",Ts),kt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),kt(this,"set",async(n,r,i)=>{this.isInitialized();const o=Xt(r);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(n,a),i===bo.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,OI(TI({},c),{[o]:r}))}return await this.persist(),o}),kt(this,"get",n=>{this.isInitialized();let r=this.messages.get(n);return typeof r>"u"&&(r={}),r}),kt(this,"getWithoutAck",n=>{this.isInitialized();const r={};for(const i of n){const o=this.messagesWithoutClientAck.get(i)||{};r[i]=Object.values(o)}return r}),kt(this,"has",(n,r)=>{this.isInitialized();const i=this.get(n),o=Xt(r);return typeof i[o]<"u"}),kt(this,"ack",async(n,r)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(n);if(typeof i>"u")return;const o=Xt(r);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,i),await this.persist()}),kt(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Ft(e,this.name),this.core=s}get context(){return Pt(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,Oc(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Oc(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Rc(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Rc(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var PI=Object.defineProperty,xI=Object.defineProperties,kI=Object.getOwnPropertyDescriptors,Bu=Object.getOwnPropertySymbols,$I=Object.prototype.hasOwnProperty,UI=Object.prototype.propertyIsEnumerable,Vc=(t,e,s)=>e in t?PI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,gr=(t,e)=>{for(var s in e||(e={}))$I.call(e,s)&&Vc(t,s,e[s]);if(Bu)for(var s of Bu(e))UI.call(e,s)&&Vc(t,s,e[s]);return t},Mu=(t,e)=>xI(t,kI(e)),Kt=(t,e,s)=>Vc(t,typeof e!="symbol"?e+"":e,s);class DI extends Dy{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Kt(this,"events",new rr.EventEmitter),Kt(this,"name",vA),Kt(this,"queue",new Map),Kt(this,"publishTimeout",V.toMiliseconds(V.ONE_MINUTE)),Kt(this,"initialPublishTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Kt(this,"needsTransportRestart",!1),Kt(this,"publish",async(n,r,i)=>{var o,a,c,l,d;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:r,opts:i}});const u=(i==null?void 0:i.ttl)||CA,h=(i==null?void 0:i.prompt)||!1,p=(i==null?void 0:i.tag)||0,g=(i==null?void 0:i.id)||jn().toString(),f=vr(Mo().protocol),w={id:g,method:(i==null?void 0:i.publishMethod)||f.publish,params:gr({topic:n,message:r,ttl:u,prompt:h,tag:p,attestation:i==null?void 0:i.attestation},i==null?void 0:i.tvf)},E=`Failed to publish payload, please try again. id:${g} tag:${p}`;try{ze((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),ze((c=w.params)==null?void 0:c.tag)&&((l=w.params)==null||delete l.tag);const I=new Promise(async _=>{const v=({id:P})=>{var D;((D=w.id)==null?void 0:D.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(Fe.publish,v),_())};this.relayer.events.on(Fe.publish,v);const T=As(new Promise((P,D)=>{this.rpcPublish(w,i).then(P).catch(F=>{this.logger.warn(F,F==null?void 0:F.message),D(F)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${g} tag:${p}`);try{await T,this.events.removeListener(Fe.publish,v)}catch(P){this.queue.set(g,{request:w,opts:i,attempt:1}),this.logger.warn(P,P==null?void 0:P.message)}});this.logger.trace({type:"method",method:"publish",params:{id:g,topic:n,message:r,opts:i}}),await As(I,this.publishTimeout,E)}catch(I){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(I),(d=i==null?void 0:i.internal)!=null&&d.throwOnFailedPublish)throw I}finally{this.queue.delete(g)}}),Kt(this,"publishCustom",async n=>{var r,i,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:l,opts:d={}}=n,{attestation:u,tvf:h,publishMethod:p,prompt:g,tag:f,ttl:w=V.FIVE_MINUTES}=d,E=d.id||jn().toString(),I=vr(Mo().protocol),_=p||I.publish,v={id:E,method:_,params:gr(Mu(gr({},l),{ttl:w,prompt:g,tag:f,attestation:u}),h)},T=`Failed to publish custom payload, please try again. id:${E} tag:${f}`;try{ze((r=v.params)==null?void 0:r.prompt)&&((i=v.params)==null||delete i.prompt),ze((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const P=new Promise(async D=>{const F=({id:K})=>{var j;((j=v.id)==null?void 0:j.toString())===K.toString()&&(this.removeRequestFromQueue(K),this.relayer.events.removeListener(Fe.publish,F),D())};this.relayer.events.on(Fe.publish,F);const x=As(new Promise((K,j)=>{this.rpcPublish(v,d).then(K).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),j(R)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${_} id:${E} tag:${f}`);try{await x,this.events.removeListener(Fe.publish,F)}catch(K){this.queue.set(E,{request:v,opts:d,attempt:1}),this.logger.warn(K,K==null?void 0:K.message)}});this.logger.trace({type:"method",method:"publish",params:{id:E,payload:l,opts:d}}),await As(P,this.publishTimeout,T)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=d==null?void 0:d.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(E)}}),Kt(this,"on",(n,r)=>{this.events.on(n,r)}),Kt(this,"once",(n,r)=>{this.events.once(n,r)}),Kt(this,"off",(n,r)=>{this.events.off(n,r)}),Kt(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.relayer=e,this.logger=Ft(s,this.name),this.registerEventListeners()}get context(){return Pt(this.logger)}async rpcPublish(e,s){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(Fe.publish,gr(gr({},e),s)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{var n;const r=e.attempt+1;this.queue.set(s,Mu(gr({},e),{attempt:r})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${r}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(jr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Fe.connection_stalled);return}this.checkQueue()}),this.relayer.on(Fe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var LI=Object.defineProperty,BI=(t,e,s)=>e in t?LI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mr=(t,e,s)=>BI(t,typeof e!="symbol"?e+"":e,s);class MI{constructor(){mr(this,"map",new Map),mr(this,"set",(e,s)=>{const n=this.get(e);this.exists(e,s)||this.map.set(e,[...n,s])}),mr(this,"get",e=>this.map.get(e)||[]),mr(this,"exists",(e,s)=>this.get(e).includes(s)),mr(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,s))return;const r=n.filter(i=>i!==s);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),mr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var FI=Object.defineProperty,jI=Object.defineProperties,qI=Object.getOwnPropertyDescriptors,Fu=Object.getOwnPropertySymbols,WI=Object.prototype.hasOwnProperty,HI=Object.prototype.propertyIsEnumerable,Gc=(t,e,s)=>e in t?FI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Zr=(t,e)=>{for(var s in e||(e={}))WI.call(e,s)&&Gc(t,s,e[s]);if(Fu)for(var s of Fu(e))HI.call(e,s)&&Gc(t,s,e[s]);return t},Ga=(t,e)=>jI(t,qI(e)),Re=(t,e,s)=>Gc(t,typeof e!="symbol"?e+"":e,s);class KI extends My{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Re(this,"subscriptions",new Map),Re(this,"topicMap",new MI),Re(this,"events",new rr.EventEmitter),Re(this,"name",OA),Re(this,"version",RA),Re(this,"pending",new Map),Re(this,"cached",[]),Re(this,"initialized",!1),Re(this,"storagePrefix",Ts),Re(this,"subscribeTimeout",V.toMiliseconds(V.ONE_MINUTE)),Re(this,"initialSubscribeTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Re(this,"clientId"),Re(this,"batchSubscribeTopicsLimit",500),Re(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Re(this,"subscribe",async(n,r)=>{var i;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}});try{const o=Mo(r),a={topic:n,relay:o,transportType:r==null?void 0:r.transportType};(i=r==null?void 0:r.internal)!=null&&i.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,r);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),Re(this,"unsubscribe",async(n,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(n,r.id,r):await this.unsubscribeByTopic(n,r)}),Re(this,"isSubscribed",n=>new Promise(r=>{r(this.topicMap.topics.includes(n))})),Re(this,"isKnownTopic",n=>new Promise(r=>{r(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(i=>i.topic===n))})),Re(this,"on",(n,r)=>{this.events.on(n,r)}),Re(this,"once",(n,r)=>{this.events.once(n,r)}),Re(this,"off",(n,r)=>{this.events.off(n,r)}),Re(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),Re(this,"start",async()=>{await this.onConnect()}),Re(this,"stop",async()=>{await this.onDisconnect()}),Re(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Re(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(r=>{n.push(r)}),await this.batchSubscribe(n)}),Re(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(jr.pulse,async()=>{await this.checkPending()}),this.events.on(Ut.created,async n=>{const r=Ut.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()}),this.events.on(Ut.deleted,async n=>{const r=Ut.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()})}),this.relayer=e,this.logger=Ft(s,this.name),this.clientId=""}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,s){let n=!1;try{n=this.getSubscription(e).topic===s}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,s){const n=this.topicMap.get(e);await Promise.all(n.map(async r=>await this.unsubscribeById(e,r,s)))}async unsubscribeById(e,s,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}});try{const r=Mo(n);await this.restartToComplete({topic:e,id:s,relay:r}),await this.rpcUnsubscribe(e,s,r);const i=De("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,s,n){var r,i;const o=await this.getSubscriptionId(e);if((r=n==null?void 0:n.internal)!=null&&r.skipSubscribe)return o;(!n||(n==null?void 0:n.transportType)===xe.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const a={method:vr(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(i=n==null?void 0:n.internal)==null?void 0:i.throwOnFailedPublish;try{if((n==null?void 0:n.transportType)===xe.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(u=>this.logger.warn(u))},V.toMiliseconds(V.ONE_SECOND)),o;const l=new Promise(async u=>{const h=p=>{p.topic===e&&(this.events.removeListener(Ut.created,h),u(p.id))};this.events.on(Ut.created,h);try{const p=await As(new Promise((g,f)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),f(w)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ut.created,h),u(p)}catch{}}),d=await As(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!d&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return d?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Fe.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,n={method:vr(s.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await As(new Promise(r=>{this.relayer.request(n).catch(i=>this.logger.warn(i)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Fe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,n={method:vr(s.protocol).batchFetchMessages,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let r;try{r=await await As(new Promise((i,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Fe.connection_stalled)}return r}rpcUnsubscribe(e,s,n){const r={method:vr(n.protocol).unsubscribe,params:{topic:e,id:s}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,s){this.setSubscription(e,Ga(Zr({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,Zr({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,n){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,s){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:s}),this.addSubscription(e,s)}addSubscription(e,s){this.subscriptions.set(e,Zr({},s)),this.topicMap.set(s.topic,e),this.events.emit(Ut.created,s)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const s=this.subscriptions.get(e);if(!s){const{message:n}=H("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Ut.deleted,Ga(Zr({},n),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ut.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<s;n++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(Ut.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(s=>{var n;return s.topic===((n=this.subscriptions.get(s.id))==null?void 0:n.topic)})){const{message:s}=H("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async s=>Ga(Zr({},s),{id:await this.getSubscriptionId(s.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const s=await this.rpcBatchFetchMessages(e);s&&s.messages&&(await wE(V.toMiliseconds(V.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(s.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=H("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 Xt(e+await this.getClientId())}}var zI=Object.defineProperty,ju=Object.getOwnPropertySymbols,VI=Object.prototype.hasOwnProperty,GI=Object.prototype.propertyIsEnumerable,Yc=(t,e,s)=>e in t?zI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qu=(t,e)=>{for(var s in e||(e={}))VI.call(e,s)&&Yc(t,s,e[s]);if(ju)for(var s of ju(e))GI.call(e,s)&&Yc(t,s,e[s]);return t},Ae=(t,e,s)=>Yc(t,typeof e!="symbol"?e+"":e,s);class YI extends Ly{constructor(e){var s;super(e),Ae(this,"protocol","wc"),Ae(this,"version",2),Ae(this,"core"),Ae(this,"logger"),Ae(this,"events",new rr.EventEmitter),Ae(this,"provider"),Ae(this,"messages"),Ae(this,"subscriber"),Ae(this,"publisher"),Ae(this,"name",_A),Ae(this,"transportExplicitlyClosed",!1),Ae(this,"initialized",!1),Ae(this,"connectionAttemptInProgress",!1),Ae(this,"relayUrl"),Ae(this,"projectId"),Ae(this,"packageName"),Ae(this,"bundleId"),Ae(this,"hasExperiencedNetworkDisruption",!1),Ae(this,"pingTimeout"),Ae(this,"heartBeatTimeout",V.toMiliseconds(V.THIRTY_SECONDS+V.FIVE_SECONDS)),Ae(this,"reconnectTimeout"),Ae(this,"connectPromise"),Ae(this,"reconnectInProgress",!1),Ae(this,"requestsInFlight",[]),Ae(this,"connectTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Ae(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const o=n.id||jn().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const a=`${o}:${((i=n.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),Ae(this,"resetPingTimeout",()=>{ko()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,i,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||o.call(i)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),Ae(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),Ae(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Fe.connect)}),Ae(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ae(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(Fe.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ae(this,"registerProviderListeners",()=>{this.provider.on(Ht.payload,this.onPayloadHandler),this.provider.on(Ht.connect,this.onConnectHandler),this.provider.on(Ht.disconnect,this.onDisconnectHandler),this.provider.on(Ht.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Ul({logger:(s=e.logger)!=null?s:AA,name:this.name}),this.messages=new RI(this.logger,e.core),this.subscriber=new KI(this,this.logger),this.publisher=new DI(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Vf,tE()?this.packageName=Dd():sE()&&(this.bundleId=Dd()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e==null?void 0:e.message))}get context(){return Pt(this.logger)}get connected(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,n){this.isInitialized(),await this.publisher.publish(e,s,n),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:xe.relay},bo.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,s){var n,r,i;this.isInitialized(),(!(s!=null&&s.transportType)||(s==null?void 0:s.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((n=s==null?void 0:s.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(r=s==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",c;const l=d=>{d.topic===e&&(this.subscriber.off(Ut.created,l),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(Ut.created,l)}),new Promise(async(d,u)=>{a=await this.subscriber.subscribe(e,qu({internal:{throwOnFailedPublish:o}},s)).catch(h=>{o&&u(h)})||a,d()})]),a}async unsubscribe(e,s){this.isInitialized(),await this.subscriber.unsubscribe(e,s)}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}off(e,s){this.events.off(e,s)}removeListener(e,s){this.events.removeListener(e,s)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await As(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(s,n)=>{await this.connect(e).then(s).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Tu())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const s=e.sort((n,r)=>n.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const n of s)try{await this.onMessageEvent(n)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:n}=e;if(!s.sessionExists){const r=qe(V.FIVE_MINUTES),i={topic:n,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,i)}this.events.emit(Fe.message,e),await this.recordMessageEvent(e,bo.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let s=1;for(;s<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${s}...`),await this.createProvider(),await new Promise(async(n,r)=>{const i=()=>{r(new Error("Connection interrupted while trying to connect"))};this.provider.once(Ht.disconnect,i),await As(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(Ht.disconnect,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ht.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Ht.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const r=n;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${s}`);break}await new Promise(n=>setTimeout(n,V.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,n,r,i;if(ko())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null||i.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new al(new Gg(aE({sdkVersion:Wc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,s){const{topic:n,message:r}=e;await this.messages.set(n,r,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const r=this.messages.has(s,n);return r&&this.logger.warn(`Ignoring duplicate message: ${n}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),cl(e)){if(!e.method.endsWith(IA))return;const s=e.params,{topic:n,message:r,publishedAt:i,attestation:o}=s.data,a={topic:n,message:r,publishedAt:i,transportType:xe.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(qu({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ll(e)&&this.events.emit(Fe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,bo.inbound),this.events.emit(Fe.message,e))}async acknowledgePayload(e){const s=gi(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Ht.payload,this.onPayloadHandler),this.provider.off(Ht.connect,this.onConnectHandler),this.provider.off(Ht.disconnect,this.onDisconnectHandler),this.provider.off(Ht.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Tu();tA(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(n=>this.logger.error(n,n==null?void 0:n.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(jr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&rA())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s==null?void 0:s.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Fe.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},V.toMiliseconds(SA)))))}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function JI(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Wu(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Hu(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const XI="[object RegExp]",ZI="[object String]",QI="[object Number]",eS="[object Boolean]",Ku="[object Arguments]",tS="[object Symbol]",sS="[object Date]",nS="[object Map]",rS="[object Set]",iS="[object Array]",oS="[object Function]",aS="[object ArrayBuffer]",Ya="[object Object]",cS="[object Error]",lS="[object DataView]",dS="[object Uint8Array]",uS="[object Uint8ClampedArray]",hS="[object Uint16Array]",pS="[object Uint32Array]",fS="[object BigUint64Array]",gS="[object Int8Array]",mS="[object Int16Array]",wS="[object Int32Array]",yS="[object BigInt64Array]",bS="[object Float32Array]",ES="[object Float64Array]";function CS(){}function zu(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function vS(t,e,s){return ii(t,e,void 0,void 0,void 0,void 0,s)}function ii(t,e,s,n,r,i,o){const a=o(t,e,s,n,r,i);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return hi(t,e,i,o)}return hi(t,e,i,o)}function hi(t,e,s,n){if(Object.is(t,e))return!0;let r=Hu(t),i=Hu(e);if(r===Ku&&(r=Ya),i===Ku&&(i=Ya),r!==i)return!1;switch(r){case ZI:return t.toString()===e.toString();case QI:{const c=t.valueOf(),l=e.valueOf();return JI(c,l)}case eS:case sS:case tS:return Object.is(t.valueOf(),e.valueOf());case XI:return t.source===e.source&&t.flags===e.flags;case oS:return t===e}s=s??new Map;const o=s.get(t),a=s.get(e);if(o!=null&&a!=null)return o===e;s.set(t,e),s.set(e,t);try{switch(r){case nS:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!ii(l,e.get(c),c,t,e,s,n))return!1;return!0}case rS:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let d=0;d<c.length;d++){const u=c[d],h=l.findIndex(p=>ii(u,p,void 0,t,e,s,n));if(h===-1)return!1;l.splice(h,1)}return!0}case iS:case dS:case uS:case hS:case pS:case fS:case gS:case mS:case wS:case yS:case bS:case ES:{if(typeof Ee<"u"&&Ee.isBuffer(t)!==Ee.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!ii(t[c],e[c],c,t,e,s,n))return!1;return!0}case aS:return t.byteLength!==e.byteLength?!1:hi(new Uint8Array(t),new Uint8Array(e),s,n);case lS:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:hi(new Uint8Array(t),new Uint8Array(e),s,n);case cS:return t.name===e.name&&t.message===e.message;case Ya:{if(!(hi(t.constructor,e.constructor,s,n)||zu(t)&&zu(e)))return!1;const c=[...Object.keys(t),...Wu(t)],l=[...Object.keys(e),...Wu(e)];if(c.length!==l.length)return!1;for(let d=0;d<c.length;d++){const u=c[d],h=t[u];if(!Object.hasOwn(e,u))return!1;const p=e[u];if(!ii(h,p,u,t,e,s,n))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function AS(t,e){return vS(t,e,CS)}var _S=Object.defineProperty,Vu=Object.getOwnPropertySymbols,IS=Object.prototype.hasOwnProperty,SS=Object.prototype.propertyIsEnumerable,Jc=(t,e,s)=>e in t?_S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Gu=(t,e)=>{for(var s in e||(e={}))IS.call(e,s)&&Jc(t,s,e[s]);if(Vu)for(var s of Vu(e))SS.call(e,s)&&Jc(t,s,e[s]);return t},vt=(t,e,s)=>Jc(t,typeof e!="symbol"?e+"":e,s);class lr extends By{constructor(e,s,n,r=Ts,i=void 0){super(e,s,n,r),this.core=e,this.logger=s,this.name=n,vt(this,"map",new Map),vt(this,"version",NA),vt(this,"cached",[]),vt(this,"initialized",!1),vt(this,"getKey"),vt(this,"storagePrefix",Ts),vt(this,"recentlyDeleted",[]),vt(this,"recentlyDeletedLimit",200),vt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ze(o)?this.map.set(this.getKey(o),o):xv(o)?this.map.set(o.id,o):kv(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),vt(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),vt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),vt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>AS(a[c],o[c]))):this.values)),vt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Gu(Gu({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),vt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ft(s,this.name),this.storagePrefix=r,this.getKey=i}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const s=this.map.get(e);if(!s){if(this.recentlyDeleted.includes(e)){const{message:r}=H("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:n}=H("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return s}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:s}=H("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var NS=Object.defineProperty,TS=(t,e,s)=>e in t?NS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fe=(t,e,s)=>TS(t,typeof e!="symbol"?e+"":e,s);class OS{constructor(e,s){this.core=e,this.logger=s,fe(this,"name",PA),fe(this,"version",xA),fe(this,"events",new ol),fe(this,"pairings"),fe(this,"initialized",!1),fe(this,"storagePrefix",Ts),fe(this,"ignoredPayloadTypes",[Vs]),fe(this,"registeredMethods",[]),fe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),fe(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),fe(this,"create",async n=>{this.isInitialized();const r=jc(),i=await this.core.crypto.setSymKey(r),o=qe(V.FIVE_MINUTES),a={protocol:zf},c={topic:i,expiry:o,relay:a,active:!1,methods:n==null?void 0:n.methods},l=bu({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:r,relay:a,expiryTimestamp:o,methods:n==null?void 0:n.methods});return this.events.emit(Bn.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:n==null?void 0:n.transportType,internal:n==null?void 0:n.internal}),{topic:i,uri:l}}),fe(this,"pair",async n=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:n==null?void 0:n.uri,trace:[ys.pairing_started]}});this.isValidPair(n,r);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=yu(n.uri);r.props.properties.topic=i,r.addTrace(ys.pairing_uri_validation_success),r.addTrace(ys.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(i)){if(d=this.pairings.get(i),r.addTrace(ys.existing_pairing),d.active)throw r.setError(Us.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);r.addTrace(ys.pairing_not_expired)}const u=c||qe(V.FIVE_MINUTES),h={topic:i,relay:a,expiry:u,active:!1,methods:l};this.core.expirer.set(i,u),await this.pairings.set(i,h),r.addTrace(ys.store_new_pairing),n.activatePairing&&await this.activate({topic:i}),this.events.emit(Bn.create,h),r.addTrace(ys.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),r.addTrace(ys.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(Us.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(p){throw r.setError(Us.subscribe_pairing_topic_failure),p}return r.addTrace(ys.subscribe_pairing_topic_success),h}),fe(this,"activate",async({topic:n})=>{this.isInitialized();const r=qe(V.FIVE_MINUTES);this.core.expirer.set(n,r),await this.pairings.update(n,{active:!0,expiry:r})}),fe(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=n;if(this.pairings.keys.includes(r)){const i=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ln();this.events.once(Ie("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}}),fe(this,"updateExpiry",async({topic:n,expiry:r})=>{this.isInitialized(),await this.pairings.update(n,{expiry:r})}),fe(this,"updateMetadata",async({topic:n,metadata:r})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:r})}),fe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),fe(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:r}=n;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",De("USER_DISCONNECTED")),await this.deletePairing(r))}),fe(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:r,relay:i,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(r);return bu({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:i,expiryTimestamp:o,methods:a})}),fe(this,"sendRequest",async(n,r,i)=>{const o=Es(r,i),a=await this.core.crypto.encode(n,o),c=Jr[r].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),fe(this,"sendResult",async(n,r,i)=>{const o=gi(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=Jr[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"sendError",async(n,r,i)=>{const o=Fh(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=Jr[c]?Jr[c].res:Jr.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"deletePairing",async(n,r)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,De("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),r?Promise.resolve():this.core.expirer.del(n)])}),fe(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(r=>Cs(r.expiry));await Promise.all(n.map(r=>this.deletePairing(r.topic)))}),fe(this,"onRelayEventRequest",async n=>{const{topic:r,payload:i}=n;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,i);default:return await this.onUnknownRpcMethodRequest(r,i)}}),fe(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i}=n,o=(await this.core.history.get(r,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,i);default:return this.onUnknownRpcMethodResponse(o)}}),fe(this,"onPairingPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult(i,n,!0),this.events.emit(Bn.ping,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),fe(this,"onPairingPingResponse",(n,r)=>{const{id:i}=r;setTimeout(()=>{ks(r)?this.events.emit(Ie("pairing_ping",i),{}):bs(r)&&this.events.emit(Ie("pairing_ping",i),{error:r.error})},500)}),fe(this,"onPairingDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Bn.delete,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),fe(this,"onUnknownRpcMethodRequest",async(n,r)=>{const{id:i,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=De("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,n,a),this.logger.error(a)}catch(a){await this.sendError(i,n,a),this.logger.error(a)}}),fe(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(De("WC_METHOD_UNSUPPORTED",n))}),fe(this,"isValidPair",(n,r)=>{var i;if(!_t(n)){const{message:a}=H("MISSING_OR_INVALID",`pair() params: ${n}`);throw r.setError(Us.malformed_pairing_uri),new Error(a)}if(!Pv(n.uri)){const{message:a}=H("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw r.setError(Us.malformed_pairing_uri),new Error(a)}const o=yu(n==null?void 0:n.uri);if(!((i=o==null?void 0:o.relay)!=null&&i.protocol)){const{message:a}=H("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(Us.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=H("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(Us.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&V.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(Us.pairing_expired);const{message:a}=H("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),fe(this,"isValidPing",async n=>{if(!_t(n)){const{message:i}=H("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),fe(this,"isValidDisconnect",async n=>{if(!_t(n)){const{message:i}=H("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),fe(this,"isValidPairingTopic",async n=>{if(!We(n,!1)){const{message:r}=H("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(r)}if(!this.pairings.keys.includes(n)){const{message:r}=H("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(r)}if(Cs(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:r}=H("EXPIRED",`pairing topic: ${n}`);throw new Error(r)}}),this.core=e,this.logger=Ft(s,this.name),this.pairings=new lr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Pt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Fe.message,async e=>{const{topic:s,message:n,transportType:r}=e;if(this.pairings.keys.includes(s)&&r!==xe.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const i=await this.core.crypto.decode(s,n);cl(i)?(this.core.history.set(s,i),await this.onRelayEventRequest({topic:s,payload:i})):ll(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:s,payload:i}),this.core.history.delete(s,i.id)),await this.core.relayer.messages.ack(s,n)}catch(i){this.logger.error(i)}})}registerExpirerEvents(){this.core.expirer.on(Yt.expired,async e=>{const{topic:s}=Wp(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(Bn.expire,{topic:s}))})}}var RS=Object.defineProperty,PS=(t,e,s)=>e in t?RS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qe=(t,e,s)=>PS(t,typeof e!="symbol"?e+"":e,s);class xS extends $y{constructor(e,s){super(e,s),this.core=e,this.logger=s,Qe(this,"records",new Map),Qe(this,"events",new rr.EventEmitter),Qe(this,"name",kA),Qe(this,"version",$A),Qe(this,"cached",[]),Qe(this,"initialized",!1),Qe(this,"storagePrefix",Ts),Qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Qe(this,"set",(n,r,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:r,chainId:i}),this.records.has(r.id))return;const o={id:r.id,topic:n,request:{method:r.method,params:r.params||null},chainId:i,expiry:qe(V.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(is.created,o)}),Qe(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const r=await this.getRecord(n.id);typeof r.response>"u"&&(r.response=bs(n)?{error:n.error}:{result:n.result},this.records.set(r.id,r),this.persist(),this.events.emit(is.updated,r))}),Qe(this,"get",async(n,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:r}),await this.getRecord(r))),Qe(this,"delete",(n,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(i=>{if(i.topic===n){if(typeof r<"u"&&i.id!==r)return;this.records.delete(i.id),this.events.emit(is.deleted,i)}}),this.persist()}),Qe(this,"exists",async(n,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===n:!1)),Qe(this,"on",(n,r)=>{this.events.on(n,r)}),Qe(this,"once",(n,r)=>{this.events.once(n,r)}),Qe(this,"off",(n,r)=>{this.events.off(n,r)}),Qe(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=Ft(s,this.name)}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(s=>{if(typeof s.response<"u")return;const n={topic:s.topic,request:Es(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const s=this.records.get(e);if(!s){const{message:n}=H("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(is.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=H("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(is.created,e=>{const s=is.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(is.updated,e=>{const s=is.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(is.deleted,e=>{const s=is.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(jr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{V.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(is.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var kS=Object.defineProperty,$S=(t,e,s)=>e in t?kS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ct=(t,e,s)=>$S(t,typeof e!="symbol"?e+"":e,s);class US extends Fy{constructor(e,s){super(e,s),this.core=e,this.logger=s,ct(this,"expirations",new Map),ct(this,"events",new rr.EventEmitter),ct(this,"name",UA),ct(this,"version",DA),ct(this,"cached",[]),ct(this,"initialized",!1),ct(this,"storagePrefix",Ts),ct(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ct(this,"has",n=>{try{const r=this.formatTarget(n);return typeof this.getExpiration(r)<"u"}catch{return!1}}),ct(this,"set",(n,r)=>{this.isInitialized();const i=this.formatTarget(n),o={target:i,expiry:r};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(Yt.created,{target:i,expiration:o})}),ct(this,"get",n=>{this.isInitialized();const r=this.formatTarget(n);return this.getExpiration(r)}),ct(this,"del",n=>{if(this.isInitialized(),this.has(n)){const r=this.formatTarget(n),i=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Yt.deleted,{target:r,expiration:i})}}),ct(this,"on",(n,r)=>{this.events.on(n,r)}),ct(this,"once",(n,r)=>{this.events.once(n,r)}),ct(this,"off",(n,r)=>{this.events.off(n,r)}),ct(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=Ft(s,this.name)}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return cE(e);if(typeof e=="number")return lE(e);const{message:s}=H("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(s)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Yt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=H("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const s=this.expirations.get(e);if(!s){const{message:n}=H("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return s}checkExpiry(e,s){const{expiry:n}=s;V.toMiliseconds(n)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(Yt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(jr.pulse,()=>this.checkExpirations()),this.events.on(Yt.created,e=>{const s=Yt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Yt.expired,e=>{const s=Yt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Yt.deleted,e=>{const s=Yt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var DS=Object.defineProperty,LS=(t,e,s)=>e in t?DS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,je=(t,e,s)=>LS(t,typeof e!="symbol"?e+"":e,s);class BS extends jy{constructor(e,s,n){super(e,s,n),this.core=e,this.logger=s,this.store=n,je(this,"name",LA),je(this,"abortController"),je(this,"isDevEnv"),je(this,"verifyUrlV3",MA),je(this,"storagePrefix",Ts),je(this,"version",Kf),je(this,"publicKey"),je(this,"fetchPromise"),je(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&V.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),je(this,"register",async r=>{if(!qr()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=xr(),d=this.startAbortTimer(V.ONE_SECOND*5),u=await new Promise((h,p)=>{const g=()=>{window.removeEventListener("message",w),l.body.removeChild(f),p("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const f=l.createElement("iframe");f.src=c,f.style.display="none",f.addEventListener("error",g,{signal:this.abortController.signal});const w=E=>{if(E.data&&typeof E.data=="string")try{const I=JSON.parse(E.data);if(I.type==="verify_attestation"){if(uc(I.attestation).payload.id!==o)return;clearInterval(d),l.body.removeChild(f),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",w),h(I.attestation===null?"":I.attestation)}}catch(I){this.logger.warn(I)}};l.body.appendChild(f),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(u,"jwt attestation"),u}catch(l){this.logger.warn(l)}return""}),je(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=r;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(uc(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),je(this,"fetchAttestation",async(r,i)=>{this.logger.debug(`resolving attestation: ${r} from url: ${i}`);const o=this.startAbortTimer(V.ONE_SECOND*5),a=await fetch(`${i}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),je(this,"getVerifyUrl",r=>{let i=r||ui;return FA.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${ui}`),i=ui),i}),je(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(V.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await i.json()}catch(r){this.logger.warn(r)}}),je(this,"persistPublicKey",async r=>{this.logger.debug(r,"persisting public key to local storage"),await this.store.setItem(this.storeKey,r),this.publicKey=r}),je(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),je(this,"isValidJwtAttestation",async r=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(r,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),je(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),je(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),je(this,"validateAttestation",(r,i)=>{const o=rv(r,i.publicKey),a={hasExpired:V.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ft(s,this.name),this.abortController=new AbortController,this.isDevEnv=Al(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Pt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),V.toMiliseconds(e))}}var MS=Object.defineProperty,FS=(t,e,s)=>e in t?MS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Yu=(t,e,s)=>FS(t,typeof e!="symbol"?e+"":e,s);class jS extends qy{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,Yu(this,"context",jA),Yu(this,"registerDeviceToken",async n=>{const{clientId:r,token:i,notificationType:o,enableEncrypted:a=!1}=n,c=`${qA}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:i,always_raw:a})})}),this.logger=Ft(s,this.context)}}var qS=Object.defineProperty,Ju=Object.getOwnPropertySymbols,WS=Object.prototype.hasOwnProperty,HS=Object.prototype.propertyIsEnumerable,Xc=(t,e,s)=>e in t?qS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qr=(t,e)=>{for(var s in e||(e={}))WS.call(e,s)&&Xc(t,s,e[s]);if(Ju)for(var s of Ju(e))HS.call(e,s)&&Xc(t,s,e[s]);return t},Ge=(t,e,s)=>Xc(t,typeof e!="symbol"?e+"":e,s);class KS extends Wy{constructor(e,s,n=!0){super(e,s,n),this.core=e,this.logger=s,Ge(this,"context",HA),Ge(this,"storagePrefix",Ts),Ge(this,"storageVersion",WA),Ge(this,"events",new Map),Ge(this,"shouldPersist",!1),Ge(this,"init",async()=>{if(!Al())try{const r={eventId:Bd(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:jp(this.core.relayer.protocol,this.core.relayer.version,Wc)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),Ge(this,"createEvent",r=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=Bd(),d=this.core.projectId||"",u=Date.now(),h=Qr({eventId:l,timestamp:u,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Ge(this,"getEvent",r=>{const{eventId:i,topic:o}=r;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Qr(Qr({},a),this.setMethods(a.eventId))}),Ge(this,"deleteEvent",r=>{const{eventId:i}=r;this.events.delete(i),this.shouldPersist=!0}),Ge(this,"setEventListeners",()=>{this.core.heartbeat.on(jr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{V.fromMiliseconds(Date.now())-V.fromMiliseconds(r.timestamp)>KA&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),Ge(this,"setMethods",r=>({addTrace:i=>this.addTrace(r,i),setError:i=>this.setError(r,i)})),Ge(this,"addTrace",(r,i)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(i),this.events.set(r,o),this.shouldPersist=!0)}),Ge(this,"setError",(r,i)=>{const o=this.events.get(r);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),Ge(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ge(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(i=>{this.events.set(i.eventId,Qr(Qr({},i),this.setMethods(i.eventId)))})}catch(r){this.logger.warn(r)}}),Ge(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[i,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const i of r)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}}),Ge(this,"sendEvent",async r=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${zA}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Wc}${i}`,{method:"POST",body:JSON.stringify(r)})}),Ge(this,"getAppDomain",()=>Fp().url),this.logger=Ft(s,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var zS=Object.defineProperty,Xu=Object.getOwnPropertySymbols,VS=Object.prototype.hasOwnProperty,GS=Object.prototype.propertyIsEnumerable,Zc=(t,e,s)=>e in t?zS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Zu=(t,e)=>{for(var s in e||(e={}))VS.call(e,s)&&Zc(t,s,e[s]);if(Xu)for(var s of Xu(e))GS.call(e,s)&&Zc(t,s,e[s]);return t},Pe=(t,e,s)=>Zc(t,typeof e!="symbol"?e+"":e,s);let YS=class og extends Ry{constructor(e){var s;super(e),Pe(this,"protocol",Hf),Pe(this,"version",Kf),Pe(this,"name",jo),Pe(this,"relayUrl"),Pe(this,"projectId"),Pe(this,"customStoragePrefix"),Pe(this,"events",new rr.EventEmitter),Pe(this,"logger"),Pe(this,"heartbeat"),Pe(this,"relayer"),Pe(this,"crypto"),Pe(this,"storage"),Pe(this,"history"),Pe(this,"expirer"),Pe(this,"pairing"),Pe(this,"verify"),Pe(this,"echoClient"),Pe(this,"linkModeSupportedApps"),Pe(this,"eventClient"),Pe(this,"initialized",!1),Pe(this,"logChunkController"),Pe(this,"on",(a,c)=>this.events.on(a,c)),Pe(this,"once",(a,c)=>this.events.once(a,c)),Pe(this,"off",(a,c)=>this.events.off(a,c)),Pe(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Pe(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const d={topic:a,message:c,publishedAt:Date.now(),transportType:xe.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:l})});const n=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Vf,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Ay({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:pA.logger,name:jo}),{logger:i,chunkLoggerController:o}=rp({opts:r,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(s=this.logChunkController)!=null&&s.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ft(i,this.name),this.heartbeat=new Vg,this.crypto=new vI(this,this.logger,e==null?void 0:e.keychain),this.history=new xS(this,this.logger),this.expirer=new US(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new ny(Zu(Zu({},fA),e==null?void 0:e.storageOptions)),this.relayer=new YI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new OS(this,this.logger),this.verify=new BS(this,this.logger,this.storage),this.echoClient=new jS(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new KS(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new og(e);await s.initialize();const n=await s.crypto.getClientId();return await s.storage.setItem(TA,n),s}get context(){return Pt(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Ru,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(Ru)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${e}`,n=`${s}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[s]}catch(s){console.warn("Failed to get global WalletConnect core",s);return}}setGlobalCore(e){var s;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof Ks<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const JS=YS,ag="wc",cg=2,lg="client",Dl=`${ag}@${cg}:${lg}:`,Ja={name:lg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Qu="WALLETCONNECT_DEEPLINK_CHOICE",XS="proposal",eh="Proposal expired",ZS="session",wr=V.SEVEN_DAYS,QS="engine",et={wc_sessionPropose:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1104},res:{ttl:V.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1106},res:{ttl:V.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1112},res:{ttl:V.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1114},res:{ttl:V.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:V.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:V.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1119}}},Xa={min:V.FIVE_MINUTES,max:V.SEVEN_DAYS},ws={idle:"IDLE",active:"ACTIVE"},eN={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},tN="request",sN=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],nN="wc",rN="auth",iN="authKeys",oN="pairingTopics",aN="requests",ua=`${nN}@${1.5}:${rN}:`,Eo=`${ua}:PUB_KEY`;var cN=Object.defineProperty,lN=Object.defineProperties,dN=Object.getOwnPropertyDescriptors,th=Object.getOwnPropertySymbols,uN=Object.prototype.hasOwnProperty,hN=Object.prototype.propertyIsEnumerable,Qc=(t,e,s)=>e in t?cN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ne=(t,e)=>{for(var s in e||(e={}))uN.call(e,s)&&Qc(t,s,e[s]);if(th)for(var s of th(e))hN.call(e,s)&&Qc(t,s,e[s]);return t},lt=(t,e)=>lN(t,dN(e)),L=(t,e,s)=>Qc(t,typeof e!="symbol"?e+"":e,s);class pN extends Vy{constructor(e){super(e),L(this,"name",QS),L(this,"events",new ol),L(this,"initialized",!1),L(this,"requestQueue",{state:ws.idle,queue:[]}),L(this,"sessionRequestQueue",{state:ws.idle,queue:[]}),L(this,"emittedSessionRequests",new yE({limit:500})),L(this,"requestQueueDelay",V.ONE_SECOND),L(this,"expectedPairingMethodMap",new Map),L(this,"recentlyDeletedMap",new Map),L(this,"recentlyDeletedLimit",200),L(this,"relayMessageCache",[]),L(this,"pendingSessions",new Map),L(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(et)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay)))}),L(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=lt(Ne({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=Sv(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=n;let d=r,u,h=!1;try{if(d){const P=this.client.core.pairing.pairings.get(d);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=P.active}}catch(P){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),P}if(!d||!h){const{topic:P,uri:D}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});d=P,u=D}if(!d){const{message:P}=H("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(P)}const p=await this.client.core.crypto.generateKeyPair(),g=et.wc_sessionPropose.req.ttl||V.FIVE_MINUTES,f=qe(g),w=lt(Ne(Ne({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:zf}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:f,pairingTopic:d},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Xs()}),E=Ie("session_connect",w.id),{reject:I,resolve:_,done:v}=Ln(g,eh),T=({id:P})=>{P===w.id&&(this.client.events.off("proposal_expire",T),this.pendingSessions.delete(w.id),this.events.emit(E,{error:{message:eh,code:0}}))};return this.client.events.on("proposal_expire",T),this.events.once(E,({error:P,session:D})=>{this.client.events.off("proposal_expire",T),P?I(P):D&&_(D)}),await this.sendProposeSession({proposal:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:w.id}}}),await this.setProposal(w.id,w),{uri:u,approval:v}}),L(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(n){throw this.client.logger.error("pair() failed"),n}}),L(this,"approve",async s=>{var n,r,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=s==null?void 0:s.id)==null?void 0:n.toString(),trace:[os.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(x){throw o.setError(xn.no_internet_connection),x}try{await this.isValidProposalId(s==null?void 0:s.id)}catch(x){throw this.client.logger.error(`approve() -> proposal.get(${s==null?void 0:s.id}) failed`),o.setError(xn.proposal_not_found),x}try{await this.isValidApprove(s)}catch(x){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(xn.session_approve_namespace_validation_failure),x}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=s,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:f,requiredNamespaces:w,optionalNamespaces:E}=p;let I=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});I||(I=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:os.session_approve_started,properties:{topic:g,trace:[os.session_approve_started,os.session_namespaces_validation_success]}}));const _=await this.client.core.crypto.generateKeyPair(),v=f.publicKey,T=await this.client.core.crypto.generateSharedKey(_,v),P=Ne(Ne(Ne({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:_,metadata:this.client.metadata},expiry:qe(wr)},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),D=xe.relay;I.addTrace(os.subscribing_session_topic);try{await this.client.core.relayer.subscribe(T,{transportType:D,internal:{skipSubscribe:!0}})}catch(x){throw I.setError(xn.subscribe_session_topic_failure),x}I.addTrace(os.subscribe_session_topic_success);const F=lt(Ne({},P),{topic:T,requiredNamespaces:w,optionalNamespaces:E,pairingTopic:g,acknowledged:!1,self:P.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:_,transportType:xe.relay});await this.client.session.set(T,F),I.addTrace(os.store_session);try{await this.sendApproveSession({sessionTopic:T,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:_},sessionSettleRequest:P,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),I.addTrace(os.session_approve_publish_success)}catch(x){throw this.client.logger.error(x),this.client.session.delete(T,De("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(T),x}return this.client.core.eventClient.deleteEvent({eventId:I.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:f.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(T,qe(wr)),{topic:T,acknowledged:()=>Promise.resolve(this.client.session.get(T))}}),L(this,"reject",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(s)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:r}=s;let i;try{i=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}i&&await this.sendError({id:n,topic:i,error:r,rpcOpts:et.wc_sessionPropose.reject}),await this.deleteProposal(n)}),L(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:n,namespaces:r}=s,{done:i,resolve:o,reject:a}=Ln(),c=Xs(),l=jn().toString(),d=this.client.session.get(n).namespaces;return this.events.once(Ie("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(n,{namespaces:r}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(u=>{this.client.logger.error(u),this.client.session.update(n,{namespaces:d}),a(u)}),{acknowledged:i}}),L(this,"extend",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(s)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=s,r=Xs(),{done:i,resolve:o,reject:a}=Ln();return this.events.once(Ie("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,qe(wr)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),L(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:r,topic:i,expiry:o=et.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(i);(a==null?void 0:a.transportType)===xe.relay&&await this.confirmOnlineStateOrThrow();const c=Xs(),l=jn().toString(),{done:d,resolve:u,reject:h}=Ln(o,"Request expired. Please try again.");this.events.once(Ie("session_request",c),({error:w,result:E})=>{w?h(w):u(E)});const p="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:{request:lt(Ne({},r),{expiryTimestamp:qe(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>h(w)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),await d();const f={request:lt(Ne({},r),{expiryTimestamp:qe(o)}),chainId:n};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:f,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,f)}).catch(E=>h(E)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),w()}),new Promise(async w=>{var E;if(!((E=a.sessionConfig)!=null&&E.disableDeepLink)){const I=await pE(this.client.core.storage,Qu);await dE({id:c,topic:i,wcDeepLink:I})}w()}),d()]).then(w=>w[2])}),L(this,"respond",async s=>{var n,r;this.isInitialized();const i=this.client.core.eventClient.createEvent({properties:{topic:(s==null?void 0:s.topic)||((r=(n=s==null?void 0:s.response)==null?void 0:n.id)==null?void 0:r.toString()),trace:[os.session_request_response_started]}});try{await this.isValidRespond(s)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(xn.session_request_response_validation_failure),u}i.addTrace(os.session_request_response_validation_success);const{topic:o,response:a}=s,{id:c}=a,l=this.client.session.get(o);l.transportType===xe.relay&&await this.confirmOnlineStateOrThrow();const d=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{i.addTrace(os.session_request_response_publish_started),ks(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:d}):bs(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:d}),this.cleanupAfterResponse(s)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(xn.session_request_response_publish_failure),u}}),L(this,"ping",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(s)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:n}=s;if(this.client.session.keys.includes(n)){const r=Xs(),i=jn().toString(),{done:o,resolve:a,reject:c}=Ln();this.events.once(Ie("session_ping",r),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:i}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))}),L(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:n,event:r,chainId:i}=s,o=jn().toString(),a=Xs();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:r,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),L(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:n}=s;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:De("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:r}=H("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(r)}}),L(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(n=>Ov(n,s)))),L(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),L(this,"authenticate",async(s,n)=>{var r;this.isInitialized(),this.isValidAuthenticate(s);const i=n&&this.client.core.linkModeSupportedApps.includes(n)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=i?xe.link_mode:xe.relay;o===xe.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:d,nonce:u,type:h,exp:p,nbf:g,methods:f=[],expiry:w}=s,E=[...s.resources||[]],{topic:I,uri:_}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:I,uri:_}});const v=await this.client.core.crypto.generateKeyPair(),T=yo(v);if(await Promise.all([this.client.auth.authKeys.set(Eo,{responseTopic:T,publicKey:v}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:I})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${I}`),f.length>0){const{namespace:A}=zs(a[0]);let O=O1(A,"request",f);wo(E)&&(O=P1(O,E.pop())),E.push(O)}const P=w&&w>et.wc_sessionAuthenticate.req.ttl?w:et.wc_sessionAuthenticate.req.ttl,D={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:d,version:"1",nonce:u,iat:new Date().toISOString(),exp:p,nbf:g,resources:E},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:qe(P)},F={eip155:{chains:a,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},x={requiredNamespaces:{},optionalNamespaces:F,relays:[{protocol:"irn"}],pairingTopic:I,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:qe(et.wc_sessionPropose.req.ttl),id:Xs()},{done:K,resolve:j,reject:R}=Ln(P,"Request expired"),C=Xs(),S=Ie("session_connect",x.id),y=Ie("session_request",C),b=async({error:A,session:O})=>{this.events.off(y,N),A?R(A):O&&j({session:O})},N=async A=>{var O,M,W;if(await this.deletePendingAuthRequest(C,{message:"fulfilled",code:0}),A.error){const ce=De("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return A.error.code===ce.code?void 0:(this.events.off(S,b),R(A.error.message))}await this.deleteProposal(x.id),this.events.off(S,b);const{cacaos:ae,responder:se}=A.result,X=[],le=[];for(const ce of ae){await Yd({cacao:ce,projectId:this.client.core.projectId})||(this.client.logger.error(ce,"Signature verification failed"),R(De("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Oe}=ce,ht=wo(Oe.resources),yt=[Pc(Oe.iss)],pt=Uo(Oe.iss);if(ht){const jt=Jd(ht),Tn=Xd(ht);X.push(...jt),yt.push(...Tn)}for(const jt of yt)le.push(`${jt}:${pt}`)}const ie=await this.client.core.crypto.generateSharedKey(v,se.publicKey);let Se;X.length>0&&(Se={topic:ie,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:se,controller:se.publicKey,expiry:qe(wr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:I,namespaces:Au([...new Set(X)],[...new Set(le)]),transportType:o},await this.client.core.relayer.subscribe(ie,{transportType:o}),await this.client.session.set(ie,Se),I&&await this.client.core.pairing.updateMetadata({topic:I,metadata:se.metadata}),Se=this.client.session.get(ie)),(O=this.client.metadata.redirect)!=null&&O.linkMode&&(M=se.metadata.redirect)!=null&&M.linkMode&&(W=se.metadata.redirect)!=null&&W.universal&&n&&(this.client.core.addLinkModeSupportedApp(se.metadata.redirect.universal),this.client.session.update(ie,{transportType:xe.link_mode})),j({auths:ae,session:Se})};this.events.once(S,b),this.events.once(y,N);let $;try{if(i){const A=Es("wc_sessionAuthenticate",D,C);this.client.core.history.set(I,A);const O=await this.client.core.crypto.encode("",A,{type:Mi,encoding:fn});$=ro(n,I,O)}else await Promise.all([this.sendRequest({topic:I,method:"wc_sessionAuthenticate",params:D,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:C}),this.sendRequest({topic:I,method:"wc_sessionPropose",params:x,expiry:et.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:x.id})])}catch(A){throw this.events.off(S,b),this.events.off(y,N),A}return await this.setProposal(x.id,x),await this.setAuthRequest(C,{request:lt(Ne({},D),{verifyContext:{}}),pairingTopic:I,transportType:o}),{uri:$??_,response:K}}),L(this,"approveSessionAuthenticate",async s=>{const{id:n,auths:r}=s,i=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[kn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw i.setError(Xr.no_internet_connection),w}const o=this.getPendingAuthRequest(n);if(!o)throw i.setError(Xr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||xe.relay;a===xe.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=yo(c),u={type:Vs,receiverPublicKey:c,senderPublicKey:l},h=[],p=[];for(const w of r){if(!await Yd({cacao:w,projectId:this.client.core.projectId})){i.setError(Xr.invalid_cacao);const T=De("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:T,encodeOpts:u}),new Error(T.message)}i.addTrace(kn.cacaos_verified);const{p:E}=w,I=wo(E.resources),_=[Pc(E.iss)],v=Uo(E.iss);if(I){const T=Jd(I),P=Xd(I);h.push(...T),_.push(...P)}for(const T of _)p.push(`${T}:${v}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(kn.create_authenticated_session_topic);let f;if((h==null?void 0:h.length)>0){f={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:qe(wr),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Au([...new Set(h)],[...new Set(p)]),transportType:a},i.addTrace(kn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(w){throw i.setError(Xr.subscribe_authenticated_session_topic_failure),w}i.addTrace(kn.subscribe_authenticated_session_topic_success),await this.client.session.set(g,f),i.addTrace(kn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(kn.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw i.setError(Xr.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:f}}),L(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:n,reason:r}=s,i=this.getPendingAuthRequest(n);if(!i)throw new Error(`Could not find pending auth request with id ${n}`);i.transportType===xe.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=yo(o),l={type:Vs,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:r,encodeOpts:l,rpcOpts:et.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),L(this,"formatAuthMessage",s=>{this.isInitialized();const{request:n,iss:r}=s;return of(n,r)}),L(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const s=this.relayMessageCache.shift();s&&await this.onRelayMessage(s)}catch(s){this.client.logger.error(s)}},50)}),L(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const n=this.client.core.pairing.pairings.get(s.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter(i=>{var o,a;return((o=i.peerMetadata)==null?void 0:o.url)&&((a=i.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&i.topic&&i.topic!==n.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),L(this,"deleteSession",async s=>{var n;const{topic:r,expirerHasDeleted:i=!1,emitEvent:o=!0,id:a=0}=s,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,De("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),i||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Qu).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,De("USER_DISCONNECTED"))}),r===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=ws.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),L(this,"deleteProposal",async(s,n)=>{if(n)try{const r=this.client.proposal.get(s),i=this.client.core.eventClient.getEvent({topic:r.pairingTopic});i==null||i.setError(xn.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,De("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),L(this,"deletePendingSessionRequest",async(s,n,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==s),r&&(this.sessionRequestQueue.state=ws.idle,this.client.events.emit("session_request_expire",{id:s}))}),L(this,"deletePendingAuthRequest",async(s,n,r=!1)=>{await Promise.all([this.client.auth.requests.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)])}),L(this,"setExpiry",async(s,n)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,n),await this.client.session.update(s,{expiry:n}))}),L(this,"setProposal",async(s,n)=>{this.client.core.expirer.set(s,qe(et.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,n)}),L(this,"setAuthRequest",async(s,n)=>{const{request:r,pairingTopic:i,transportType:o=xe.relay}=n;this.client.core.expirer.set(s,r.expiryTimestamp),await this.client.auth.requests.set(s,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:s,pairingTopic:i,verifyContext:r.verifyContext,transportType:o})}),L(this,"setPendingSessionRequest",async s=>{const{id:n,topic:r,params:i,verifyContext:o}=s,a=i.request.expiryTimestamp||qe(et.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:r,params:i,verifyContext:o})}),L(this,"sendRequest",async s=>{const{topic:n,method:r,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:d,tvf:u,publishOpts:h={}}=s,p=Es(r,i,c);let g;const f=!!d;try{const I=f?fn:Nt;g=await this.client.core.crypto.encode(n,p,{encoding:I})}catch(I){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),I}let w;if(sN.includes(r)){const I=Xt(JSON.stringify(p)),_=Xt(g);w=await this.client.core.verify.register({id:_,decryptedId:I})}const E=Ne(Ne({},et[r].req),h);if(E.attestation=w,o&&(E.ttl=o),a&&(E.id=a),this.client.core.history.set(n,p),f){const I=ro(d,n,g);await de.Linking.openURL(I,this.client.name)}else E.tvf=lt(Ne({},u),{correlationId:p.id}),l?(E.internal=lt(Ne({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,g,E)):this.client.core.relayer.publish(n,g,E).catch(I=>this.client.logger.error(I));return p.id}),L(this,"sendProposeSession",async s=>{const{proposal:n,publishOpts:r}=s,i=Es("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,i);const o=await this.client.core.crypto.encode(n.pairingTopic,i,{encoding:Nt}),a=Xt(JSON.stringify(i)),c=Xt(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:o},opts:lt(Ne({},r),{publishMethod:"wc_proposeSession",attestation:l})})}),L(this,"sendApproveSession",async s=>{const{sessionTopic:n,pairingProposalResponse:r,proposal:i,sessionSettleRequest:o,publishOpts:a}=s,c=gi(i.id,r),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:Nt}),d=Es("wc_sessionSettle",o,a==null?void 0:a.id),u=await this.client.core.crypto.encode(n,d,{encoding:Nt});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:u},opts:lt(Ne({},a),{publishMethod:"wc_approveSession"})})}),L(this,"sendResult",async s=>{const{id:n,topic:r,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=gi(n,i);let d;const u=c&&typeof(de==null?void 0:de.Linking)<"u";try{const g=u?fn:Nt;d=await this.client.core.crypto.encode(r,l,lt(Ne({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let h,p;try{h=await this.client.core.history.get(r,n);const g=h.request;try{p=this.getTVFParams(n,g.params,i)}catch(f){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${f==null?void 0:f.message}`)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${n}) failed`),g}if(u){const g=ro(c,r,d);await de.Linking.openURL(g,this.client.name)}else{const g=h.request.method,f=et[g].res;f.tvf=lt(Ne({},p),{correlationId:n}),o?(f.internal=lt(Ne({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,d,f)):this.client.core.relayer.publish(r,d,f).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(l)}),L(this,"sendError",async s=>{const{id:n,topic:r,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=Fh(n,i);let d;const u=c&&typeof(de==null?void 0:de.Linking)<"u";try{const p=u?fn:Nt;d=await this.client.core.crypto.encode(r,l,lt(Ne({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),p}let h;try{h=await this.client.core.history.get(r,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${r}, ${n}) failed`),p}if(u){const p=ro(c,r,d);await de.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=a||et[p].res;this.client.core.relayer.publish(r,d,g)}await this.client.core.history.resolve(l)}),L(this,"cleanup",async()=>{const s=[],n=[];this.client.session.getAll().forEach(r=>{let i=!1;Cs(r.expiry)&&(i=!0),this.client.core.crypto.keychain.has(r.topic)||(i=!0),i&&s.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Cs(r.expiryTimestamp)&&n.push(r.id)}),await Promise.all([...s.map(r=>this.deleteSession({topic:r})),...n.map(r=>this.deleteProposal(r))])}),L(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),L(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),L(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===ws.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=ws.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=ws.idle}),L(this,"processRequest",async s=>{const{topic:n,payload:r,attestation:i,transportType:o,encryptedId:a}=s,c=r.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:r,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,r);case"wc_sessionPing":return await this.onSessionPingRequest(n,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),L(this,"onRelayEventResponse",async s=>{const{topic:n,payload:r,transportType:i}=s,o=(await this.client.core.history.get(n,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,r,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,r);case"wc_sessionExtend":return this.onSessionExtendResponse(n,r);case"wc_sessionPing":return this.onSessionPingResponse(n,r);case"wc_sessionRequest":return this.onSessionRequestResponse(n,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),L(this,"onRelayEventUnknownPayload",s=>{const{topic:n}=s,{message:r}=H("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),L(this,"shouldIgnorePairingRequest",s=>{const{topic:n,requestMethod:r}=s,i=this.expectedPairingMethodMap.get(n);return!i||i.includes(r)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),L(this,"onSessionProposeRequest",async s=>{const{topic:n,payload:r,attestation:i,encryptedId:o}=s,{params:a,id:c}=r;try{const l=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(Us.proposal_listener_not_found)),this.isValidConnect(Ne({},r.params));const d=a.expiryTimestamp||qe(et.wc_sessionPropose.req.ttl),u=Ne({id:c,pairingTopic:n,expiryTimestamp:d,attestation:i,encryptedId:o},a);await this.setProposal(c,u);const h=await this.getVerifyContext({attestationId:i,hash:Xt(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});l==null||l.addTrace(ys.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:h})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:et.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),L(this,"onSessionProposeResponse",async(s,n,r)=>{const{id:i}=n;if(ks(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const d=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(i,{sessionTopic:d,pairingTopic:s,proposalId:i,publicKey:c});const u=await this.client.core.relayer.subscribe(d,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:s})}else if(bs(n)){await this.deleteProposal(i);const o=Ie("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),L(this,"onSessionSettleRequest",async(s,n)=>{const{id:r,params:i}=n;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=n.params,p=[...this.pendingSessions.values()].find(w=>w.sessionTopic===s);if(!p)return this.client.logger.error(`Pending session not found for topic ${s}`);const g=this.client.proposal.get(p.proposalId),f=lt(Ne(Ne(Ne({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),{transportType:xe.relay});await this.client.session.set(f.topic,f),await this.setExpiry(f.topic,f.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:f.peer.metadata}),this.client.events.emit("session_connect",{session:f}),this.events.emit(Ie("session_connect",p.proposalId),{session:f}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(f),await this.sendResult({id:n.id,topic:s,result:!0})}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),L(this,"onSessionSettleResponse",async(s,n)=>{const{id:r}=n;ks(n)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(Ie("session_approve",r),{})):bs(n)&&(await this.client.session.delete(s,De("USER_DISCONNECTED")),this.events.emit(Ie("session_approve",r),{error:n.error}))}),L(this,"onSessionUpdateRequest",async(s,n)=>{const{params:r,id:i}=n;try{const o=`${s}_session_update`,a=Yr.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:s,error:De("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ne({topic:s},r));try{Yr.set(o,i),await this.client.session.update(s,{namespaces:r.namespaces}),await this.sendResult({id:i,topic:s,result:!0})}catch(c){throw Yr.delete(o),c}this.client.events.emit("session_update",{id:i,topic:s,params:r})}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),L(this,"isRequestOutOfSync",(s,n)=>n.toString().slice(0,-3)<s.toString().slice(0,-3)),L(this,"onSessionUpdateResponse",(s,n)=>{const{id:r}=n,i=Ie("session_update",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);ks(n)?this.events.emit(Ie("session_update",r),{}):bs(n)&&this.events.emit(Ie("session_update",r),{error:n.error})}),L(this,"onSessionExtendRequest",async(s,n)=>{const{id:r}=n;try{this.isValidExtend({topic:s}),await this.setExpiry(s,qe(wr)),await this.sendResult({id:r,topic:s,result:!0}),this.client.events.emit("session_extend",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),L(this,"onSessionExtendResponse",(s,n)=>{const{id:r}=n,i=Ie("session_extend",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);ks(n)?this.events.emit(Ie("session_extend",r),{}):bs(n)&&this.events.emit(Ie("session_extend",r),{error:n.error})}),L(this,"onSessionPingRequest",async(s,n)=>{const{id:r}=n;try{this.isValidPing({topic:s}),await this.sendResult({id:r,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),L(this,"onSessionPingResponse",(s,n)=>{const{id:r}=n,i=Ie("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);ks(n)?this.events.emit(Ie("session_ping",r),{}):bs(n)&&this.events.emit(Ie("session_ping",r),{error:n.error})},500)}),L(this,"onSessionDeleteRequest",async(s,n)=>{const{id:r}=n;try{this.isValidDisconnect({topic:s,reason:n.params}),await Promise.all([new Promise(i=>{this.client.core.relayer.once(Fe.publish,async()=>{i(await this.deleteSession({topic:s,id:r}))})}),this.sendResult({id:r,topic:s,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:De("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),L(this,"onSessionRequest",async s=>{var n,r,i;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:d}=s,{id:u,params:h}=a;try{await this.isValidRequest(Ne({topic:o},h));const p=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:Xt(JSON.stringify(Es("wc_sessionRequest",h,u))),encryptedId:l,metadata:p.peer.metadata,transportType:d}),f={id:u,topic:o,params:h,verifyContext:g};await this.setPendingSessionRequest(f),d===xe.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((r=p.peer.metadata.redirect)==null?void 0:r.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(p){await this.sendError({id:u,topic:o,error:p}),this.client.logger.error(p)}}),L(this,"onSessionRequestResponse",(s,n)=>{const{id:r}=n,i=Ie("session_request",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);ks(n)?this.events.emit(Ie("session_request",r),{result:n.result}):bs(n)&&this.events.emit(Ie("session_request",r),{error:n.error})}),L(this,"onSessionEventRequest",async(s,n)=>{const{id:r,params:i}=n;try{const o=`${s}_session_event_${i.event.name}`,a=Yr.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Ne({topic:s},i)),this.client.events.emit("session_event",{id:r,topic:s,params:i}),Yr.set(o,r)}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),L(this,"onSessionAuthenticateResponse",(s,n)=>{const{id:r}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:n}),ks(n)?this.events.emit(Ie("session_request",r),{result:n.result}):bs(n)&&this.events.emit(Ie("session_request",r),{error:n.error})}),L(this,"onSessionAuthenticateRequest",async s=>{var n;const{topic:r,payload:i,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:d,expiryTimestamp:u}=i.params,h=await this.getVerifyContext({attestationId:o,hash:Xt(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:r,id:i.id,authPayload:d,verifyContext:h,expiryTimestamp:u};await this.setAuthRequest(i.id,{request:p,pairingTopic:r,transportType:c}),c===xe.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:i.params,id:i.id,verifyContext:h})}catch(l){this.client.logger.error(l);const d=i.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(i.params.requester.metadata,c),p={type:Vs,receiverPublicKey:d,senderPublicKey:u};await this.sendError({id:i.id,topic:r,error:l,encodeOpts:p,rpcOpts:et.wc_sessionAuthenticate.autoReject,appLink:h})}}),L(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),L(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ws.idle,this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay))}),L(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:n})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(i=>i.topic===s&&i.request.method==="wc_sessionRequest").forEach(i=>{const o=i.request.id,a=Ie("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ie("session_request",i.request.id),{error:n})})}),L(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===ws.active){this.client.logger.info("session request queue is already active.");return}const s=this.sessionRequestQueue.queue[0];if(!s){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(s)}catch(n){this.client.logger.error(n)}}),L(this,"emitSessionRequest",s=>{if(this.emittedSessionRequests.has(s.id)){this.client.logger.warn({id:s.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${s.id}`);return}this.sessionRequestQueue.state=ws.active,this.emittedSessionRequests.add(s.id),this.client.events.emit("session_request",s)}),L(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const n=this.client.proposal.getAll().find(r=>r.pairingTopic===s.topic);n&&this.onSessionProposeRequest({topic:s.topic,payload:Es("wc_sessionPropose",lt(Ne({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),L(this,"isValidConnect",async s=>{if(!_t(s)){const{message:l}=H("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:n,requiredNamespaces:r,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=s;if(ze(n)||await this.isValidPairingTopic(n),!jv(c,!0)){const{message:l}=H("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(r&&!ze(r)&&Ns(r)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(r,"requiredNamespaces")}if(i&&!ze(i)&&Ns(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),o&&!ze(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!ze(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(r||{}).concat(Object.keys(i||{}));if(!Object.keys(a).every(d=>l.includes(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),L(this,"validateNamespaces",(s,n)=>{const r=Fv(s,"connect()",n);if(r)throw new Error(r.message)}),L(this,"isValidApprove",async s=>{if(!_t(s))throw new Error(H("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:n,namespaces:r,relayProtocol:i,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),l=Ka(r,"approve()");if(l)throw new Error(l.message);const d=Su(c.requiredNamespaces,r,"approve()");if(d)throw new Error(d.message);if(!We(i,!0)){const{message:u}=H("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(u)}if(o&&!ze(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!ze(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(h=>u.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),L(this,"isValidReject",async s=>{if(!_t(s)){const{message:i}=H("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(i)}const{id:n,reason:r}=s;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!Wv(r)){const{message:i}=H("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(i)}}),L(this,"isValidSessionSettleRequest",s=>{if(!_t(s)){const{message:l}=H("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:n,controller:r,namespaces:i,expiry:o}=s;if(!Wf(n)){const{message:l}=H("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=$v(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Ka(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Cs(o)){const{message:l}=H("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),L(this,"isValidUpdate",async s=>{if(!_t(s)){const{message:c}=H("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:n,namespaces:r}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const i=this.client.session.get(n),o=Ka(r,"update()");if(o)throw new Error(o.message);const a=Su(i.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),L(this,"isValidExtend",async s=>{if(!_t(s)){const{message:r}=H("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(r)}const{topic:n}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),L(this,"isValidRequest",async s=>{if(!_t(s)){const{message:c}=H("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:n,request:r,chainId:i,expiry:o}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!Iu(a,i)){const{message:c}=H("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!Hv(r)){const{message:c}=H("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!Vv(a,i,r.method)){const{message:c}=H("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Xv(o,Xa)){const{message:c}=H("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Xa.min} and ${Xa.max}`);throw new Error(c)}}),L(this,"isValidRespond",async s=>{var n;if(!_t(s)){const{message:a}=H("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(a)}const{topic:r,response:i}=s;try{await this.isValidSessionTopic(r)}catch(a){throw(n=s==null?void 0:s.response)!=null&&n.id&&this.cleanupAfterResponse(s),a}if(!Kv(i)){const{message:a}=H("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(a)}const o=this.client.pendingRequest.get(i.id);if(o.topic!==r){const{message:a}=H("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${i.id}, expected topic: ${o.topic}, received topic: ${r}`);throw new Error(a)}}),L(this,"isValidPing",async s=>{if(!_t(s)){const{message:r}=H("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),L(this,"isValidEmit",async s=>{if(!_t(s)){const{message:a}=H("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}const{topic:n,event:r,chainId:i}=s;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!Iu(o,i)){const{message:a}=H("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!zv(r)){const{message:a}=H("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Gv(o,i,r.name)){const{message:a}=H("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),L(this,"isValidDisconnect",async s=>{if(!_t(s)){const{message:r}=H("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),L(this,"isValidAuthenticate",s=>{const{chains:n,uri:r,domain:i,nonce:o}=s;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!We(r,!1))throw new Error("uri is required parameter");if(!We(i,!1))throw new Error("domain is required parameter");if(!We(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>zs(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=zs(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),L(this,"getVerifyContext",async s=>{const{attestationId:n,hash:r,encryptedId:i,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||ui,validation:"UNKNOWN",origin:o.url||""}};try{if(a===xe.link_mode){const d=this.getAppLinkIfEnabled(o,a);return c.verified.validation=d&&new URL(d).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:n,hash:r,encryptedId:i,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),L(this,"validateSessionProps",(s,n)=>{Object.values(s).forEach((r,i)=>{if(r==null){const{message:o}=H("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${r} for key ${Object.keys(s)[i]}`);throw new Error(o)}})}),L(this,"getPendingAuthRequest",s=>{const n=this.client.auth.requests.get(s);return typeof n=="object"?n:void 0}),L(this,"addToRecentlyDeleted",(s,n)=>{if(this.recentlyDeletedMap.set(s,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=i)break;this.recentlyDeletedMap.delete(o)}}}),L(this,"checkRecentlyDeleted",s=>{const n=this.recentlyDeletedMap.get(s);if(n){const{message:r}=H("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${s}`);throw new Error(r)}}),L(this,"isLinkModeEnabled",(s,n)=>{var r,i,o,a,c,l,d,u,h;return!s||n!==xe.link_mode?!1:((i=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:i.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((d=s==null?void 0:s.redirect)==null?void 0:d.universal)!==void 0&&((u=s==null?void 0:s.redirect)==null?void 0:u.universal)!==""&&((h=s==null?void 0:s.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(de==null?void 0:de.Linking)<"u"}),L(this,"getAppLinkIfEnabled",(s,n)=>{var r;return this.isLinkModeEnabled(s,n)?(r=s==null?void 0:s.redirect)==null?void 0:r.universal:void 0}),L(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const n=Ld(s,"topic")||"",r=decodeURIComponent(Ld(s,"wc_ev")||""),i=this.client.session.keys.includes(n);i&&this.client.session.update(n,{transportType:xe.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:r,sessionExists:i})}),L(this,"registerLinkModeListeners",async()=>{var s;if(Al()||Sn()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const n=de==null?void 0:de.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await n.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),L(this,"getTVFParams",(s,n,r)=>{var i,o,a;if(!((i=n.request)!=null&&i.method))return{};const c={correlationId:s,rpcMethods:[n.request.method],chainId:n.chainId};try{const l=this.extractTxHashesFromResult(n.request,r);c.txHashes=l,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(o=n.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),L(this,"isValidContractData",s=>{var n;if(!s)return!1;try{const r=(s==null?void 0:s.data)||((n=s==null?void 0:s[0])==null?void 0:n.data);if(!r.startsWith("0x"))return!1;const i=r.slice(2);return/^[0-9a-fA-F]*$/.test(i)?i.length%2===0:!1}catch{}return!1}),L(this,"extractTxHashesFromResult",(s,n)=>{var r;try{if(!n)return[];const i=s.method,o=eN[i];if(i==="sui_signTransaction")return[h1(n.transactionBytes)];if(i==="near_signTransaction")return[Kd(n)];if(i==="near_signTransactions")return n.map(c=>Kd(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(r=n.tx_json)==null?void 0:r.hash];if(i==="polkadot_signTransaction")return[hA({transaction:s.params.transactionPayload,signature:n.signature})];if(i==="algo_signTxn")return Gs(n)?n.map(c=>zd(c)):[zd(n)];if(i==="cosmos_signDirect")return[f1(n)];if(i==="wallet_sendCalls")return g1(n);if(typeof n=="string")return[n];const a=n[o.key];if(Gs(a))return i==="solana_signAllTransactions"?a.map(c=>u1(c)):a;if(typeof a=="string")return[a]}catch(i){this.client.logger.warn(i,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,s=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,r]of Object.entries(s))for(const i of r)try{await this.onProviderMessageEvent({topic:n,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${i}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Fe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:n,attestation:r,transportType:i}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Eo)?this.client.auth.authKeys.get(Eo):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,n,{receiverPublicKey:o,encoding:i===xe.link_mode?fn:Nt});cl(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:r,transportType:i,encryptedId:Xt(n)})):ll(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:i}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:i}),await this.client.core.relayer.messages.ack(s,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Yt.expired,async e=>{const{topic:s,id:n}=Wp(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,H("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,H("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(Bn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Bn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!We(e,!1)){const{message:s}=H("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(s)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:s}=H("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(Cs(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=H("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!We(e,!1)){const{message:s}=H("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(s)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:s}=H("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(Cs(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=H("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=H("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(s)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(We(e,!1)){const{message:s}=H("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=H("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!qv(e)){const{message:s}=H("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=H("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(Cs(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=H("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class fN extends lr{constructor(e,s){super(e,s,XS,Dl),this.core=e,this.logger=s}}let gN=class extends lr{constructor(e,s){super(e,s,ZS,Dl),this.core=e,this.logger=s}};class mN extends lr{constructor(e,s){super(e,s,tN,Dl,n=>n.id),this.core=e,this.logger=s}}class wN extends lr{constructor(e,s){super(e,s,iN,ua,()=>Eo),this.core=e,this.logger=s}}class yN extends lr{constructor(e,s){super(e,s,oN,ua),this.core=e,this.logger=s}}class bN extends lr{constructor(e,s){super(e,s,aN,ua,n=>n.id),this.core=e,this.logger=s}}var EN=Object.defineProperty,CN=(t,e,s)=>e in t?EN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Za=(t,e,s)=>CN(t,typeof e!="symbol"?e+"":e,s);class vN{constructor(e,s){this.core=e,this.logger=s,Za(this,"authKeys"),Za(this,"pairingTopics"),Za(this,"requests"),this.authKeys=new wN(this.core,this.logger),this.pairingTopics=new yN(this.core,this.logger),this.requests=new bN(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var AN=Object.defineProperty,_N=(t,e,s)=>e in t?AN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ge=(t,e,s)=>_N(t,typeof e!="symbol"?e+"":e,s);let IN=class dg extends zy{constructor(e){super(e),ge(this,"protocol",ag),ge(this,"version",cg),ge(this,"name",Ja.name),ge(this,"metadata"),ge(this,"core"),ge(this,"logger"),ge(this,"events",new rr.EventEmitter),ge(this,"engine"),ge(this,"session"),ge(this,"proposal"),ge(this,"pendingRequest"),ge(this,"auth"),ge(this,"signConfig"),ge(this,"on",(n,r)=>this.events.on(n,r)),ge(this,"once",(n,r)=>this.events.once(n,r)),ge(this,"off",(n,r)=>this.events.off(n,r)),ge(this,"removeListener",(n,r)=>this.events.removeListener(n,r)),ge(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),ge(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"update",async n=>{try{return await this.engine.update(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"request",async n=>{try{return await this.engine.request(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"find",n=>{try{return this.engine.find(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),ge(this,"authenticate",async(n,r)=>{try{return await this.engine.authenticate(n,r)}catch(i){throw this.logger.error(i.message),i}}),ge(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||Ja.name,this.metadata=rE(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const s=Ul({logger:(e==null?void 0:e.logger)||Ja.logger,name:this.name});this.logger=s,this.core=(e==null?void 0:e.core)||new JS(e),this.session=new gN(this.core,this.logger),this.proposal=new fN(this.core,this.logger),this.pendingRequest=new mN(this.core,this.logger),this.engine=new pN(this),this.auth=new vN(this.core,this.logger)}static async init(e){const s=new dg(e);return await s.initialize(),s}get context(){return Pt(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const SN=IN;function Ll(t){return t==null||typeof t!="object"&&typeof t!="function"}function ug(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function hg(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const NN="[object RegExp]",pg="[object String]",fg="[object Number]",gg="[object Boolean]",mg="[object Arguments]",TN="[object Symbol]",ON="[object Date]",RN="[object Map]",PN="[object Set]",xN="[object Array]",kN="[object ArrayBuffer]",$N="[object Object]",UN="[object DataView]",DN="[object Uint8Array]",LN="[object Uint8ClampedArray]",BN="[object Uint16Array]",MN="[object Uint32Array]",FN="[object Int8Array]",jN="[object Int16Array]",qN="[object Int32Array]",WN="[object Float32Array]",HN="[object Float64Array]";function Bl(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function KN(t,e){return _r(t,void 0,t,new Map,e)}function _r(t,e,s,n=new Map,r=void 0){const i=r==null?void 0:r(t,e,s,n);if(i!=null)return i;if(Ll(t))return t;if(n.has(t))return n.get(t);if(Array.isArray(t)){const o=new Array(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=_r(t[a],a,s,n,r);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;n.set(t,o);for(const[a,c]of t)o.set(a,_r(c,a,s,n,r));return o}if(t instanceof Set){const o=new Set;n.set(t,o);for(const a of t)o.add(_r(a,void 0,s,n,r));return o}if(typeof Ee<"u"&&Ee.isBuffer(t))return t.subarray();if(Bl(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=_r(t[a],a,s,n,r);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return n.set(t,o),Mn(o,t,s,n,r),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return n.set(t,o),Mn(o,t,s,n,r),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),Mn(o,t,s,n,r),o}if(t instanceof Error){const o=new t.constructor;return n.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Mn(o,t,s,n,r),o}if(typeof t=="object"&&zN(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),Mn(o,t,s,n,r),o}return t}function Mn(t,e,s=t,n,r){const i=[...Object.keys(e),...ug(e)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=_r(e[a],a,s,n,r))}}function zN(t){switch(hg(t)){case mg:case xN:case kN:case UN:case gg:case ON:case WN:case HN:case FN:case jN:case qN:case RN:case fg:case $N:case NN:case PN:case pg:case TN:case DN:case LN:case BN:case MN:return!0;default:return!1}}function VN(t,e){return KN(t,(s,n,r,i)=>{const o=e==null?void 0:e(s,n,r,i);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case fg:case pg:case gg:{const a=new t.constructor(t==null?void 0:t.valueOf());return Mn(a,t),a}case mg:{const a={};return Mn(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function sh(t){return VN(t)}function nh(t){return t!==null&&typeof t=="object"&&hg(t)==="[object Arguments]"}function rh(t){return typeof t=="object"&&t!==null}function GN(){}function YN(t){return Bl(t)}function JN(t){var s;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const n=t[Symbol.toStringTag];return n==null||!((s=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&s.writable)?!1:t.toString()===`[object ${n}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function XN(t){if(Ll(t))return t;if(Array.isArray(t)||Bl(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),s=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new s(t);if(t instanceof RegExp){const n=new s(t);return n.lastIndex=t.lastIndex,n}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const n=new s(t.message);return n.stack=t.stack,n.name=t.name,n.cause=t.cause,n}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const n=Object.create(e);return Object.assign(n,t)}return t}function ZN(t,...e){const s=e.slice(0,-1),n=e[e.length-1];let r=t;for(let i=0;i<s.length;i++){const o=s[i];r=el(r,o,n,new Map)}return r}function el(t,e,s,n){if(Ll(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return XN(n.get(e));if(n.set(e,t),Array.isArray(e)){e=e.slice();for(let i=0;i<e.length;i++)e[i]=e[i]??void 0}const r=[...Object.keys(e),...ug(e)];for(let i=0;i<r.length;i++){const o=r[i];let a=e[o],c=t[o];if(nh(a)&&(a={...a}),nh(c)&&(c={...c}),typeof Ee<"u"&&Ee.isBuffer(a)&&(a=sh(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const d=[],u=Reflect.ownKeys(c);for(let h=0;h<u.length;h++){const p=u[h];d[p]=c[p]}c=d}else c=[];const l=s(c,a,o,t,e,n);l!=null?t[o]=l:Array.isArray(a)||rh(c)&&rh(a)?t[o]=el(c,a,s,n):c==null&&JN(a)?t[o]=el({},a,s,n):c==null&&YN(a)?t[o]=sh(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function QN(t,...e){return ZN(t,...e,GN)}const ih="error",eT="wss://relay.walletconnect.org",tT="wc",wg="universal_provider",io=`${tT}@2:${wg}:`,yg="https://rpc.walletconnect.org/v1/",bg="generic",sT=`${yg}bundler`,Or="call_status",nT=86400,Ml={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var rT=Object.defineProperty,iT=Object.defineProperties,oT=Object.getOwnPropertyDescriptors,oh=Object.getOwnPropertySymbols,aT=Object.prototype.hasOwnProperty,cT=Object.prototype.propertyIsEnumerable,ah=(t,e,s)=>e in t?rT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oo=(t,e)=>{for(var s in e||(e={}))aT.call(e,s)&&ah(t,s,e[s]);if(oh)for(var s of oh(e))cT.call(e,s)&&ah(t,s,e[s]);return t},lT=(t,e)=>iT(t,oT(e));function Eg(t,e,s){var n;const r=zs(t);return((n=e.rpcMap)==null?void 0:n[r.reference])||`${yg}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function dT(t){return t.includes(":")?t.split(":")[1]:t}function Cg(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function uT(t,e){const s=Object.keys(e.namespaces).filter(r=>r.includes(t));if(!s.length)return[];const n=[];return s.forEach(r=>{const i=e.namespaces[r].accounts;n.push(...i)}),n}function ch(t){return Object.fromEntries(Object.entries(t).filter(([e,s])=>{var n,r;return((n=s==null?void 0:s.chains)==null?void 0:n.length)&&((r=s==null?void 0:s.chains)==null?void 0:r.length)>0}))}function ao(t={},e={}){const s=ch(lh(t)),n=ch(lh(e));return QN(s,n)}function lh(t){var e,s,n,r,i;const o={};if(!Ns(t))return o;for(const[a,c]of Object.entries(t)){const l=la(a)?[a]:c.chains,d=c.methods||[],u=c.events||[],h=c.rpcMap||{},p=Ar(a);o[p]=lT(oo(oo({},o[p]),c),{chains:Ss(l,(e=o[p])==null?void 0:e.chains),methods:Ss(d,(s=o[p])==null?void 0:s.methods),events:Ss(u,(n=o[p])==null?void 0:n.events)}),(Ns(h)||Ns(((r=o[p])==null?void 0:r.rpcMap)||{}))&&(o[p].rpcMap=oo(oo({},h),(i=o[p])==null?void 0:i.rpcMap))}return o}function dh(t){return t.includes(":")?t.split(":")[2]:t}function uh(t){const e={};for(const[s,n]of Object.entries(t)){const r=n.methods||[],i=n.events||[],o=n.accounts||[],a=la(s)?[s]:n.chains?n.chains:Cg(n.accounts);e[s]={chains:a,methods:r,events:i,accounts:o}}return e}function Qa(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function hT(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const vg={},Rr=t=>vg[t],ec=(t,e)=>{vg[t]=e};var pT=Object.defineProperty,hh=Object.getOwnPropertySymbols,fT=Object.prototype.hasOwnProperty,gT=Object.prototype.propertyIsEnumerable,ph=(t,e,s)=>e in t?pT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fh=(t,e)=>{for(var s in e||(e={}))fT.call(e,s)&&ph(t,s,e[s]);if(hh)for(var s of hh(e))gT.call(e,s)&&ph(t,s,e[s]);return t};const gh="eip155",mT=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],wT=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,tc=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,mh=t=>Object.keys(t).filter(e=>mT.includes(e)).reduce((e,s)=>(e[s]=yT(t[s]),e),{}),yT=t=>typeof t=="string"&&hT(t)?JSON.parse(t):t,bT=(t,e,s)=>{const{sessionProperties:n={},scopedProperties:r={}}=t,i={};if(!Ns(r)&&!Ns(n))return;const o=mh(n);for(const a of s){const c=wT(a);if(!c)continue;i[tc(c)]=o;const l=r==null?void 0:r[`${gh}:${c}`];if(l){const d=l==null?void 0:l[`${gh}:${c}:${e}`];i[tc(c)]=fh(fh({},i[tc(c)]),mh(d||l))}}for(const[a,c]of Object.entries(i))Object.keys(c).length===0&&delete i[a];return Object.keys(i).length>0?i:void 0};var ET=Object.defineProperty,CT=(t,e,s)=>e in t?ET(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vT=(t,e,s)=>CT(t,typeof e!="symbol"?e+"":e,s);let sc;class Fl{constructor(e){vT(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,s){return await this.storage.setItem(e,s)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return sc||(sc=new Fl(e)),sc}}var AT=Object.defineProperty,_T=Object.defineProperties,IT=Object.getOwnPropertyDescriptors,wh=Object.getOwnPropertySymbols,ST=Object.prototype.hasOwnProperty,NT=Object.prototype.propertyIsEnumerable,yh=(t,e,s)=>e in t?AT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,TT=(t,e)=>{for(var s in e||(e={}))ST.call(e,s)&&yh(t,s,e[s]);if(wh)for(var s of wh(e))NT.call(e,s)&&yh(t,s,e[s]);return t},OT=(t,e)=>_T(t,IT(e));async function RT(t,e){const s=zs(t.result.capabilities.caip345.caip2),n=t.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(n.map(u=>PT(s.reference,u,e))),i=r.filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u);r.filter(u=>u.status==="rejected").forEach(u=>console.warn("Failed to fetch transaction receipt:",u.reason));const o=!i.length||i.some(u=>!u),a=i.every(u=>(u==null?void 0:u.status)==="0x1"),c=i.every(u=>(u==null?void 0:u.status)==="0x0"),l=i.some(u=>(u==null?void 0:u.status)==="0x0");let d;return o?d=100:a?d=200:c?d=500:l&&(d=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:i,status:d}}async function PT(t,e,s){return await s(parseInt(t)).request(Es("eth_getTransactionReceipt",[e]))}async function xT({sendCalls:t,storage:e}){const s=await e.getItem(Or);await e.setItem(Or,OT(TT({},s),{[t.result.id]:{request:t.request,result:t.result,expiry:qe(nT)}}))}async function kT({resultId:t,storage:e}){const s=await e.getItem(Or);if(s){delete s[t],await e.setItem(Or,s);for(const n in s)Cs(s[n].expiry)&&delete s[n];await e.setItem(Or,s)}}async function $T({resultId:t,storage:e}){const s=await e.getItem(Or),n=s==null?void 0:s[t];if(n&&!Cs(n.expiry))return n;await kT({resultId:t,storage:e})}var UT=Object.defineProperty,DT=Object.defineProperties,LT=Object.getOwnPropertyDescriptors,bh=Object.getOwnPropertySymbols,BT=Object.prototype.hasOwnProperty,MT=Object.prototype.propertyIsEnumerable,tl=(t,e,s)=>e in t?UT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,nc=(t,e)=>{for(var s in e||(e={}))BT.call(e,s)&&tl(t,s,e[s]);if(bh)for(var s of bh(e))MT.call(e,s)&&tl(t,s,e[s]);return t},rc=(t,e)=>DT(t,LT(e)),$n=(t,e,s)=>tl(t,typeof e!="symbol"?e+"":e,s);class FT{constructor(e){$n(this,"name","eip155"),$n(this,"client"),$n(this,"chainId"),$n(this,"namespace"),$n(this,"httpProviders"),$n(this,"events"),$n(this,"storage"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=Fl.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s);const n=this.chainId;this.chainId=parseInt(e),this.events.emit(Ml.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,s){const n=s||Eg(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new al(new jh(n,Rr("disableProviderPing")))}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var n;const r=parseInt(dT(s));e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[s])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}getHttpProvider(e){const s=e||this.chainId;return this.httpProviders[s]||(this.httpProviders=rc(nc({},this.httpProviders),{[s]:this.createHttpProvider(s)}),this.httpProviders[s])}async handleSwitchChain(e){var s,n;let r=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const i=parseInt(r,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${i}`);else throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,n,r,i,o;const a=(n=(s=e.request)==null?void 0:s.params)==null?void 0:n[0],c=((i=(r=e.request)==null?void 0:r.params)==null?void 0:i[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),d=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{},u=`${a}${c.join(",")}`,h=d==null?void 0:d[u];if(h)return h;let p;try{p=bT(l,a,c)}catch(f){console.warn("Failed to extract capabilities from session",f)}if(p)return p;const g=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:rc(nc({},l.sessionProperties||{}),{capabilities:rc(nc({},d||{}),{[u]:g})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return g}async getCallStatus(e){var s,n,r;const i=this.client.session.get(e.topic),o=(s=i.sessionProperties)==null?void 0:s.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(d){console.warn("Failed to fetch call status from bundler",d,l)}}const a=(n=i.sessionProperties)==null?void 0:n.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await $T({resultId:(r=e.request.params)==null?void 0:r[0],storage:this.storage});if(c)try{return await RT(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,s){var n;const r=new URL(e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Es("eth_getUserOperationReceipt",[(n=s.request.params)==null?void 0:n[0]]))});if(!i.ok)throw new Error(`Failed to fetch user operation receipt - ${i.status}`);return await i.json()}getBundlerUrl(e,s){return`${sT}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}async sendCalls(e){var s,n,r;const i=await this.client.request(e),o=(s=e.request.params)==null?void 0:s[0],a=i==null?void 0:i.id,c=(i==null?void 0:i.capabilities)||{},l=(n=c==null?void 0:c.caip345)==null?void 0:n.caip2,d=(r=c==null?void 0:c.caip345)==null?void 0:r.transactionHashes;return!a||!l||!(d!=null&&d.length)||await xT({sendCalls:{request:o,result:i},storage:this.storage}),i}}var jT=Object.defineProperty,qT=(t,e,s)=>e in t?jT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yr=(t,e,s)=>qT(t,typeof e!="symbol"?e+"":e,s);class WT{constructor(e){yr(this,"name",bg),yr(this,"client"),yr(this,"httpProviders"),yr(this,"events"),yr(this,"namespace"),yr(this,"chainId"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s);const n=this.chainId;this.chainId=e,this.events.emit(Ml.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return zs(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){var e,s;const n={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(r=>{var i,o;const a=zs(r),c=(o=(i=this.namespace)==null?void 0:i.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];n[a.reference]=this.createHttpProvider(r,c)}),n}getHttpProvider(e){const s=zs(e).reference,n=this.httpProviders[s];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProvider(e,s){const n=s||Eg(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new al(new jh(n,Rr("disableProviderPing")))}}var HT=Object.defineProperty,KT=Object.defineProperties,zT=Object.getOwnPropertyDescriptors,Eh=Object.getOwnPropertySymbols,VT=Object.prototype.hasOwnProperty,GT=Object.prototype.propertyIsEnumerable,sl=(t,e,s)=>e in t?HT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ei=(t,e)=>{for(var s in e||(e={}))VT.call(e,s)&&sl(t,s,e[s]);if(Eh)for(var s of Eh(e))GT.call(e,s)&&sl(t,s,e[s]);return t},co=(t,e)=>KT(t,zT(e)),zt=(t,e,s)=>sl(t,typeof e!="symbol"?e+"":e,s);let YT=class Ag{constructor(e){zt(this,"client"),zt(this,"namespaces"),zt(this,"optionalNamespaces"),zt(this,"sessionProperties"),zt(this,"scopedProperties"),zt(this,"events",new ol),zt(this,"rpcProviders",{}),zt(this,"session"),zt(this,"providerOpts"),zt(this,"logger"),zt(this,"uri"),zt(this,"disableProviderPing",!1);var s,n;this.providerOpts=e,this.logger=Ul({logger:(s=e.logger)!=null?s:ih,name:(n=this.providerOpts.name)!=null?n:wg}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const s=new Ag(e);return await s.initialize(),s}async request(e,s,n){const[r,i]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:ei({},e),chainId:`${r}:${i}`,topic:this.session.topic,expiry:n})}sendAsync(e,s,n,r){const i=new Date().getTime();this.request(e,n,r).then(o=>s(null,gi(i,o))).catch(o=>s(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:De("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,s){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:r}=await this.client.authenticate(e,s);n&&(this.uri=n,this.events.emit("display_uri",n));const i=await r();if(this.session=i.session,this.session){const o=uh(this.session.namespaces);this.namespaces=ao(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return i}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}removeListener(e,s){this.events.removeListener(e,s)}off(e,s){this.events.off(e,s)}get isWalletConnect(){return!0}async pair(e){const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});s&&(this.uri=s,this.events.emit("display_uri",s));const r=await n();this.session=r;const i=uh(r.namespaces);return this.namespaces=ao(this.namespaces,i),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,s){try{if(!this.session)return;const[n,r]=this.validateChain(e);this.getProvider(n).setDefaultChain(r,s)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(!Gs(s))return;for(const n of s)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}catch(s){this.logger.warn(s,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,s;if(this.client=this.providerOpts.client||await SN.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ih,relayUrl:this.providerOpts.relayUrl||eT,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(n){throw this.logger.error(n,"Failed to get session"),new Error(`The provided session: ${(s=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:s.topic} doesn't exist in the Sign client`)}else{const n=this.client.session.getAll();this.session=n[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(s=>Ar(s)))];ec("client",this.client),ec("events",this.events),ec("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const n=uT(s,this.session);if((n==null?void 0:n.length)===0)return;const r=Cg(n),i=ao(this.namespaces,this.optionalNamespaces),o=co(ei({},i[s]),{accounts:n,chains:r});switch(s){case"eip155":this.rpcProviders[s]=new FT({namespace:o});break;default:this.rpcProviders[s]=new WT({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var s;const{topic:n}=e;n===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:n,topic:r}=e;if(r!==((s=this.session)==null?void 0:s.topic))return;const{event:i}=n;if(i.name==="accountsChanged"){const o=i.data;o&&Gs(o)&&this.events.emit("accountsChanged",o.map(dh))}else if(i.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Ar(o),l=Qa(o)!==Qa(a)?`${c}:${Qa(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var n,r;if(e!==((n=this.session)==null?void 0:n.topic))return;const{namespaces:i}=s,o=(r=this.client)==null?void 0:r.session.get(e);this.session=co(ei({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:s})}),this.client.on("session_delete",async e=>{var s;e.topic===((s=this.session)==null?void 0:s.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",co(ei({},De("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Ml.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(co(ei({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[bg]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var s;this.getProvider(e).updateNamespace((s=this.session)==null?void 0:s.namespaces[e])})}setNamespaces(e){const{namespaces:s={},optionalNamespaces:n={},sessionProperties:r,scopedProperties:i}=e;this.optionalNamespaces=ao(s,n),this.sessionProperties=r,this.scopedProperties=i}validateChain(e){const[s,n]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,n];if(s&&!Object.keys(this.namespaces||{}).map(o=>Ar(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&n)return[s,n];const r=Ar(Object.keys(this.namespaces)[0]),i=this.rpcProviders[r].getDefaultChain();return[r,i]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:s,internal:n=!1}){if(!this.namespaces)return;const[r,i]=this.validateChain(e);i&&(this.updateNamespaceChain(r,i),n?(this.events.emit("chainChanged",i),this.emitAccountsChangedOnChainChange({namespace:r,currentCaipChainId:e,previousCaipChainId:s})):this.getProvider(r).setDefaultChain(i),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:s,previousCaipChainId:n}){var r,i;try{if(n===s)return;const o=(i=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:i.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(dh);if(!Gs(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,s){if(!this.namespaces)return;const n=this.namespaces[e]?e:`${e}:${s}`,r={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=s):this.namespaces[n]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,s){var n;const r=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${io}/${e}${r}`,s)}async getFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${io}/${e}${n}`)}async deleteFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${io}/${e}${n}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const s=await this.client.core.storage.getKeys();for(const n of s)n.startsWith(io)&&await this.client.core.storage.removeItem(n)}catch(s){this.logger.warn(s,"Failed to cleanup storage")}}};const Me={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",EIP155:U.CHAIN.EVM,ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH",getSDKVersionWarningMessage(t,e){return`
|
|
15
|
+
Approved: ${h.toString()}`))}),o.forEach(u=>{n||(Wn(r[u].methods,i[u].methods)?Wn(r[u].events,i[u].events)||(n=H("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${u}`)):n=H("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${u}`))}),n}function Yv(t){const e={};return Object.keys(t).forEach(s=>{var n;s.includes(":")?e[s]=t[s]:(n=t[s].chains)==null||n.forEach(r=>{e[r]={methods:t[s].methods,events:t[s].events}})}),e}function Nu(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Jv(t){const e={};return Object.keys(t).forEach(s=>{if(s.includes(":"))e[s]=t[s];else{const n=Wr(t[s].accounts);n==null||n.forEach(r=>{e[r]={accounts:t[s].accounts.filter(i=>i.includes(`${r}:`)),methods:t[s].methods,events:t[s].events}})}}),e}function Xv(t,e){return $l(t,!1)&&t<=e.max&&t>=e.min}function Tu(){const t=Ui();return new Promise(e=>{switch(t){case Mt.browser:e(Zv());break;case Mt.reactNative:e(Qv());break;case Mt.node:e(eA());break;default:e(!0)}})}function Zv(){return qr()&&(navigator==null?void 0:navigator.onLine)}async function Qv(){if(Sn()&&typeof de<"u"&&de!=null&&de.NetInfo){const t=await(de==null?void 0:de.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function eA(){return!0}function tA(t){switch(Ui()){case Mt.browser:sA(t);break;case Mt.reactNative:nA(t);break}}function sA(t){!Sn()&&qr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function nA(t){var e;Sn()&&typeof de<"u"&&de!=null&&de.NetInfo&&((e=de)==null||e.NetInfo.addEventListener(s=>t(s==null?void 0:s.isConnected)))}function rA(){var t;return qr()&&xr()?((t=xr())==null?void 0:t.visibilityState)==="visible":!0}const za={};class Yr{static get(e){return za[e]}static set(e,s){za[e]=s}static delete(e){delete za[e]}}function iA(t){const e=Fr.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function oA({publicKey:t,signature:e,payload:s}){var n;const r=qc(s.method),i=128|parseInt(((n=s.version)==null?void 0:n.toString())||"4"),o=lA(s.address),a=s.era==="00"?new Uint8Array([0]):qc(s.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(s.nonce,16),l=new Uint8Array([c&255,c>>8&255]),d=BigInt(`0x${cA(s.tip)}`),u=uA(d),h=new Uint8Array([0,...t,o,...e,...a,...l,...u,...r]),p=dA(h.length+1);return new Uint8Array([...p,i,...h])}function aA(t){const e=qc(t),s=Wg.blake2b(e,void 0,32);return"0x"+Ee.from(s).toString("hex")}function qc(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function cA(t){return t.startsWith("0x")?t.slice(2):t}function lA(t){const e=Fr.decode(t)[0];return e===42?0:e===60?2:1}function dA(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function uA(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function hA(t){const e=Uint8Array.from(Ee.from(t.signature,"hex")),s=iA(t.transaction.address),n=oA({publicKey:s,signature:e,payload:t.transaction}),r=Ee.from(n).toString("hex");return aA(r)}function Ul({logger:t,name:e}){const s=typeof t=="string"?rp({opts:{level:t,name:e}}).logger:t;return s.level=typeof t=="string"?t:t.level,s}const Hf="wc",Kf=2,jo="core",Ts=`${Hf}@2:${jo}:`,pA={name:jo,logger:"error"},fA={database:":memory:"},gA="crypto",Ou="client_ed25519_seed",mA=V.ONE_DAY,wA="keychain",yA="0.3",bA="messages",EA="0.3",CA=V.SIX_HOURS,vA="publisher",zf="irn",AA="error",Vf="wss://relay.walletconnect.org",_A="relayer",Fe={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},IA="_subscription",Ht={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},SA=.1,Wc="2.22.4",xe={link_mode:"link_mode",relay:"relay"},bo={inbound:"inbound",outbound:"outbound"},NA="0.3",TA="WALLETCONNECT_CLIENT_ID",Ru="WALLETCONNECT_LINK_MODE_APPS",Ut={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},OA="subscription",RA="0.3",PA="pairing",xA="0.3",Jr={wc_pairingDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:V.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:V.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:V.ONE_DAY,prompt:!1,tag:0},res:{ttl:V.ONE_DAY,prompt:!1,tag:0}}},Bn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},is={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},kA="history",$A="0.3",UA="expirer",Yt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},DA="0.3",LA="verify-api",BA="https://verify.walletconnect.com",Gf="https://verify.walletconnect.org",ui=Gf,MA=`${ui}/v3`,FA=[BA,Gf],jA="echo",qA="https://echo.walletconnect.com",ys={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Us={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},os={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},xn={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},kn={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Xr={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},WA=.1,HA="event-client",KA=86400,zA="https://pulse.walletconnect.org/batch";function VA(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),n=0;n<s.length;n++)s[n]=255;for(var r=0;r<t.length;r++){var i=t.charAt(r),o=i.charCodeAt(0);if(s[o]!==255)throw new TypeError(i+" is ambiguous");s[o]=r}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var f=0,w=0,E=0,I=g.length;E!==I&&g[E]===0;)E++,f++;for(var _=(I-E)*d+1>>>0,v=new Uint8Array(_);E!==I;){for(var T=g[E],P=0,D=_-1;(T!==0||P<w)&&D!==-1;D--,P++)T+=256*v[D]>>>0,v[D]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");w=P,E++}for(var F=_-w;F!==_&&v[F]===0;)F++;for(var x=c.repeat(f);F<_;++F)x+=t.charAt(v[F]);return x}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var f=0;if(g[f]!==" "){for(var w=0,E=0;g[f]===c;)w++,f++;for(var I=(g.length-f)*l+1>>>0,_=new Uint8Array(I);g[f];){var v=s[g.charCodeAt(f)];if(v===255)return;for(var T=0,P=I-1;(v!==0||T<E)&&P!==-1;P--,T++)v+=a*_[P]>>>0,_[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");E=T,f++}if(g[f]!==" "){for(var D=I-E;D!==I&&_[D]===0;)D++;for(var F=new Uint8Array(w+(I-D)),x=w;D!==I;)F[x++]=_[D++];return F}}}function p(g){var f=h(g);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:p}}var GA=VA,YA=GA;const Yf=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},JA=t=>new TextEncoder().encode(t),XA=t=>new TextDecoder().decode(t);class ZA{constructor(e,s,n){this.name=e,this.prefix=s,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class QA{constructor(e,s,n){if(this.name=e,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Jf(this,e)}}class e_{constructor(e){this.decoders=e}or(e){return Jf(this,e)}decode(e){const s=e[0],n=this.decoders[s];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Jf=(t,e)=>new e_({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class t_{constructor(e,s,n,r){this.name=e,this.prefix=s,this.baseEncode=n,this.baseDecode=r,this.encoder=new ZA(e,s,n),this.decoder=new QA(e,s,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const da=({name:t,prefix:e,encode:s,decode:n})=>new t_(t,e,s,n),Fi=({prefix:t,name:e,alphabet:s})=>{const{encode:n,decode:r}=YA(s,e);return da({prefix:t,name:e,encode:n,decode:i=>Yf(r(i))})},s_=(t,e,s,n)=>{const r={};for(let d=0;d<e.length;++d)r[e[d]]=d;let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*s/8|0);let a=0,c=0,l=0;for(let d=0;d<i;++d){const u=r[t[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<s|u,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},n_=(t,e,s)=>{const n=e[e.length-1]==="=",r=(1<<s)-1;let i="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,i+=e[r&a>>o];if(o&&(i+=e[r&a<<s-o]),n)for(;i.length*s&7;)i+="=";return i},rt=({name:t,prefix:e,bitsPerChar:s,alphabet:n})=>da({prefix:e,name:t,encode(r){return n_(r,n,s)},decode(r){return s_(r,n,s,t)}}),r_=da({prefix:"\0",name:"identity",encode:t=>XA(t),decode:t=>JA(t)});var i_=Object.freeze({__proto__:null,identity:r_});const o_=rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var a_=Object.freeze({__proto__:null,base2:o_});const c_=rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var l_=Object.freeze({__proto__:null,base8:c_});const d_=Fi({prefix:"9",name:"base10",alphabet:"0123456789"});var u_=Object.freeze({__proto__:null,base10:d_});const h_=rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),p_=rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var f_=Object.freeze({__proto__:null,base16:h_,base16upper:p_});const g_=rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),m_=rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),w_=rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),y_=rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),b_=rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),E_=rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),C_=rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),v_=rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),A_=rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var __=Object.freeze({__proto__:null,base32:g_,base32upper:m_,base32pad:w_,base32padupper:y_,base32hex:b_,base32hexupper:E_,base32hexpad:C_,base32hexpadupper:v_,base32z:A_});const I_=Fi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),S_=Fi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var N_=Object.freeze({__proto__:null,base36:I_,base36upper:S_});const T_=Fi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),O_=Fi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var R_=Object.freeze({__proto__:null,base58btc:T_,base58flickr:O_});const P_=rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),x_=rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),k_=rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$_=rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var U_=Object.freeze({__proto__:null,base64:P_,base64pad:x_,base64url:k_,base64urlpad:$_});const Xf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),D_=Xf.reduce((t,e,s)=>(t[s]=e,t),[]),L_=Xf.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function B_(t){return t.reduce((e,s)=>(e+=D_[s],e),"")}function M_(t){const e=[];for(const s of t){const n=L_[s.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(n)}return new Uint8Array(e)}const F_=da({prefix:"🚀",name:"base256emoji",encode:B_,decode:M_});var j_=Object.freeze({__proto__:null,base256emoji:F_}),q_=Zf,Pu=128,W_=127,H_=~W_,K_=Math.pow(2,31);function Zf(t,e,s){e=e||[],s=s||0;for(var n=s;t>=K_;)e[s++]=t&255|Pu,t/=128;for(;t&H_;)e[s++]=t&255|Pu,t>>>=7;return e[s]=t|0,Zf.bytes=s-n+1,e}var z_=Hc,V_=128,xu=127;function Hc(t,n){var s=0,n=n||0,r=0,i=n,o,a=t.length;do{if(i>=a)throw Hc.bytes=0,new RangeError("Could not decode varint");o=t[i++],s+=r<28?(o&xu)<<r:(o&xu)*Math.pow(2,r),r+=7}while(o>=V_);return Hc.bytes=i-n,s}var G_=Math.pow(2,7),Y_=Math.pow(2,14),J_=Math.pow(2,21),X_=Math.pow(2,28),Z_=Math.pow(2,35),Q_=Math.pow(2,42),eI=Math.pow(2,49),tI=Math.pow(2,56),sI=Math.pow(2,63),nI=function(t){return t<G_?1:t<Y_?2:t<J_?3:t<X_?4:t<Z_?5:t<Q_?6:t<eI?7:t<tI?8:t<sI?9:10},rI={encode:q_,decode:z_,encodingLength:nI},Qf=rI;const ku=(t,e,s=0)=>(Qf.encode(t,e,s),e),$u=t=>Qf.encodingLength(t),Kc=(t,e)=>{const s=e.byteLength,n=$u(t),r=n+$u(s),i=new Uint8Array(r+s);return ku(t,i,0),ku(s,i,n),i.set(e,r),new iI(t,s,e,i)};class iI{constructor(e,s,n,r){this.code=e,this.size=s,this.digest=n,this.bytes=r}}const eg=({name:t,code:e,encode:s})=>new oI(t,e,s);class oI{constructor(e,s,n){this.name=e,this.code=s,this.encode=n}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?Kc(this.code,s):s.then(n=>Kc(this.code,n))}else throw Error("Unknown type, must be binary type")}}const tg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),aI=eg({name:"sha2-256",code:18,encode:tg("SHA-256")}),cI=eg({name:"sha2-512",code:19,encode:tg("SHA-512")});var lI=Object.freeze({__proto__:null,sha256:aI,sha512:cI});const sg=0,dI="identity",ng=Yf,uI=t=>Kc(sg,ng(t)),hI={code:sg,name:dI,encode:ng,digest:uI};var pI=Object.freeze({__proto__:null,identity:hI});new TextEncoder,new TextDecoder;const Uu={...i_,...a_,...l_,...u_,...f_,...__,...N_,...R_,...U_,...j_};({...lI,...pI});function rg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function fI(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?rg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function ig(t,e,s,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:n}}}const Du=ig("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Va=ig("ascii","a",t=>{let e="a";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return e},t=>{t=t.substring(1);const e=fI(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),gI={utf8:Du,"utf-8":Du,hex:Uu.base16,latin1:Va,ascii:Va,binary:Va,...Uu};function mI(t,e="utf8"){const s=gI[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?rg(globalThis.Buffer.from(t,"utf-8")):s.decoder.decode(`${s.prefix}${t}`)}var wI=Object.defineProperty,yI=(t,e,s)=>e in t?wI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ms=(t,e,s)=>yI(t,typeof e!="symbol"?e+"":e,s);class bI{constructor(e,s){this.core=e,this.logger=s,ms(this,"keychain",new Map),ms(this,"name",wA),ms(this,"version",yA),ms(this,"initialized",!1),ms(this,"storagePrefix",Ts),ms(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),ms(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),ms(this,"set",async(n,r)=>{this.isInitialized(),this.keychain.set(n,r),await this.persist()}),ms(this,"get",n=>{this.isInitialized();const r=this.keychain.get(n);if(typeof r>"u"){const{message:i}=H("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(i)}return r}),ms(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=Ft(s,this.name)}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Oc(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Rc(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var EI=Object.defineProperty,CI=(t,e,s)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ve=(t,e,s)=>CI(t,typeof e!="symbol"?e+"":e,s);class vI{constructor(e,s,n){this.core=e,this.logger=s,Ve(this,"name",gA),Ve(this,"keychain"),Ve(this,"randomSessionIdentifier",jc()),Ve(this,"initialized",!1),Ve(this,"clientId"),Ve(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ve(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ve(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const r=await this.getClientSeed(),i=zl(r),o=Yg(i.publicKey);return this.clientId=o,o}),Ve(this,"generateKeyPair",()=>{this.isInitialized();const r=J1();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ve(this,"signJWT",async r=>{this.isInitialized();const i=await this.getClientSeed(),o=zl(i),a=this.randomSessionIdentifier;return await Jg(a,r,mA,o)}),Ve(this,"generateSharedKey",(r,i,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=X1(a,i);return this.setSymKey(c,o)}),Ve(this,"setSymKey",async(r,i)=>{this.isInitialized();const o=i||yo(r);return await this.keychain.set(o,r),o}),Ve(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"encode",async(r,i,o)=>{this.isInitialized();const a=jf(o),c=Xn(i);if(gu(a))return ev(c,o==null?void 0:o.encoding);if(fu(a)){const h=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(h,p)}const l=this.getSymKey(r),{type:d,senderPublicKey:u}=a;return Z1({type:d,symKey:l,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Ve(this,"decode",async(r,i,o)=>{this.isInitialized();const a=sv(i,o);if(gu(a)){const c=tv(i,o==null?void 0:o.encoding);return _o(c)}if(fu(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=Q1({symKey:c,encoded:i,encoding:o==null?void 0:o.encoding});return _o(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ve(this,"getPayloadType",(r,i=Nt)=>{const o=Ii({encoded:r,encoding:i});return sr(o.type)}),Ve(this,"getPayloadSenderPublicKey",(r,i=Nt)=>{const o=Ii({encoded:r,encoding:i});return o.senderPublicKey?Rt(o.senderPublicKey,wt):void 0}),this.core=e,this.logger=Ft(s,this.name),this.keychain=n||new bI(this.core,this.logger)}get context(){return Pt(this.logger)}async setPrivateKey(e,s){return await this.keychain.set(e,s),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ou)}catch{e=jc(),await this.keychain.set(Ou,e)}return mI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var AI=Object.defineProperty,_I=Object.defineProperties,II=Object.getOwnPropertyDescriptors,Lu=Object.getOwnPropertySymbols,SI=Object.prototype.hasOwnProperty,NI=Object.prototype.propertyIsEnumerable,zc=(t,e,s)=>e in t?AI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,TI=(t,e)=>{for(var s in e||(e={}))SI.call(e,s)&&zc(t,s,e[s]);if(Lu)for(var s of Lu(e))NI.call(e,s)&&zc(t,s,e[s]);return t},OI=(t,e)=>_I(t,II(e)),kt=(t,e,s)=>zc(t,typeof e!="symbol"?e+"":e,s);class RI extends Uy{constructor(e,s){super(e,s),this.logger=e,this.core=s,kt(this,"messages",new Map),kt(this,"messagesWithoutClientAck",new Map),kt(this,"name",bA),kt(this,"version",EA),kt(this,"initialized",!1),kt(this,"storagePrefix",Ts),kt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),kt(this,"set",async(n,r,i)=>{this.isInitialized();const o=Xt(r);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(n,a),i===bo.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,OI(TI({},c),{[o]:r}))}return await this.persist(),o}),kt(this,"get",n=>{this.isInitialized();let r=this.messages.get(n);return typeof r>"u"&&(r={}),r}),kt(this,"getWithoutAck",n=>{this.isInitialized();const r={};for(const i of n){const o=this.messagesWithoutClientAck.get(i)||{};r[i]=Object.values(o)}return r}),kt(this,"has",(n,r)=>{this.isInitialized();const i=this.get(n),o=Xt(r);return typeof i[o]<"u"}),kt(this,"ack",async(n,r)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(n);if(typeof i>"u")return;const o=Xt(r);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,i),await this.persist()}),kt(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Ft(e,this.name),this.core=s}get context(){return Pt(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,Oc(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Oc(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Rc(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Rc(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var PI=Object.defineProperty,xI=Object.defineProperties,kI=Object.getOwnPropertyDescriptors,Bu=Object.getOwnPropertySymbols,$I=Object.prototype.hasOwnProperty,UI=Object.prototype.propertyIsEnumerable,Vc=(t,e,s)=>e in t?PI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,gr=(t,e)=>{for(var s in e||(e={}))$I.call(e,s)&&Vc(t,s,e[s]);if(Bu)for(var s of Bu(e))UI.call(e,s)&&Vc(t,s,e[s]);return t},Mu=(t,e)=>xI(t,kI(e)),Kt=(t,e,s)=>Vc(t,typeof e!="symbol"?e+"":e,s);class DI extends Dy{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Kt(this,"events",new rr.EventEmitter),Kt(this,"name",vA),Kt(this,"queue",new Map),Kt(this,"publishTimeout",V.toMiliseconds(V.ONE_MINUTE)),Kt(this,"initialPublishTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Kt(this,"needsTransportRestart",!1),Kt(this,"publish",async(n,r,i)=>{var o,a,c,l,d;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:r,opts:i}});const u=(i==null?void 0:i.ttl)||CA,h=(i==null?void 0:i.prompt)||!1,p=(i==null?void 0:i.tag)||0,g=(i==null?void 0:i.id)||jn().toString(),f=vr(Mo().protocol),w={id:g,method:(i==null?void 0:i.publishMethod)||f.publish,params:gr({topic:n,message:r,ttl:u,prompt:h,tag:p,attestation:i==null?void 0:i.attestation},i==null?void 0:i.tvf)},E=`Failed to publish payload, please try again. id:${g} tag:${p}`;try{ze((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),ze((c=w.params)==null?void 0:c.tag)&&((l=w.params)==null||delete l.tag);const I=new Promise(async _=>{const v=({id:P})=>{var D;((D=w.id)==null?void 0:D.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(Fe.publish,v),_())};this.relayer.events.on(Fe.publish,v);const T=As(new Promise((P,D)=>{this.rpcPublish(w,i).then(P).catch(F=>{this.logger.warn(F,F==null?void 0:F.message),D(F)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${g} tag:${p}`);try{await T,this.events.removeListener(Fe.publish,v)}catch(P){this.queue.set(g,{request:w,opts:i,attempt:1}),this.logger.warn(P,P==null?void 0:P.message)}});this.logger.trace({type:"method",method:"publish",params:{id:g,topic:n,message:r,opts:i}}),await As(I,this.publishTimeout,E)}catch(I){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(I),(d=i==null?void 0:i.internal)!=null&&d.throwOnFailedPublish)throw I}finally{this.queue.delete(g)}}),Kt(this,"publishCustom",async n=>{var r,i,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:l,opts:d={}}=n,{attestation:u,tvf:h,publishMethod:p,prompt:g,tag:f,ttl:w=V.FIVE_MINUTES}=d,E=d.id||jn().toString(),I=vr(Mo().protocol),_=p||I.publish,v={id:E,method:_,params:gr(Mu(gr({},l),{ttl:w,prompt:g,tag:f,attestation:u}),h)},T=`Failed to publish custom payload, please try again. id:${E} tag:${f}`;try{ze((r=v.params)==null?void 0:r.prompt)&&((i=v.params)==null||delete i.prompt),ze((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const P=new Promise(async D=>{const F=({id:K})=>{var j;((j=v.id)==null?void 0:j.toString())===K.toString()&&(this.removeRequestFromQueue(K),this.relayer.events.removeListener(Fe.publish,F),D())};this.relayer.events.on(Fe.publish,F);const x=As(new Promise((K,j)=>{this.rpcPublish(v,d).then(K).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),j(R)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${_} id:${E} tag:${f}`);try{await x,this.events.removeListener(Fe.publish,F)}catch(K){this.queue.set(E,{request:v,opts:d,attempt:1}),this.logger.warn(K,K==null?void 0:K.message)}});this.logger.trace({type:"method",method:"publish",params:{id:E,payload:l,opts:d}}),await As(P,this.publishTimeout,T)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=d==null?void 0:d.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(E)}}),Kt(this,"on",(n,r)=>{this.events.on(n,r)}),Kt(this,"once",(n,r)=>{this.events.once(n,r)}),Kt(this,"off",(n,r)=>{this.events.off(n,r)}),Kt(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.relayer=e,this.logger=Ft(s,this.name),this.registerEventListeners()}get context(){return Pt(this.logger)}async rpcPublish(e,s){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(Fe.publish,gr(gr({},e),s)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{var n;const r=e.attempt+1;this.queue.set(s,Mu(gr({},e),{attempt:r})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${r}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(jr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Fe.connection_stalled);return}this.checkQueue()}),this.relayer.on(Fe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var LI=Object.defineProperty,BI=(t,e,s)=>e in t?LI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mr=(t,e,s)=>BI(t,typeof e!="symbol"?e+"":e,s);class MI{constructor(){mr(this,"map",new Map),mr(this,"set",(e,s)=>{const n=this.get(e);this.exists(e,s)||this.map.set(e,[...n,s])}),mr(this,"get",e=>this.map.get(e)||[]),mr(this,"exists",(e,s)=>this.get(e).includes(s)),mr(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,s))return;const r=n.filter(i=>i!==s);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),mr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var FI=Object.defineProperty,jI=Object.defineProperties,qI=Object.getOwnPropertyDescriptors,Fu=Object.getOwnPropertySymbols,WI=Object.prototype.hasOwnProperty,HI=Object.prototype.propertyIsEnumerable,Gc=(t,e,s)=>e in t?FI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Zr=(t,e)=>{for(var s in e||(e={}))WI.call(e,s)&&Gc(t,s,e[s]);if(Fu)for(var s of Fu(e))HI.call(e,s)&&Gc(t,s,e[s]);return t},Ga=(t,e)=>jI(t,qI(e)),Re=(t,e,s)=>Gc(t,typeof e!="symbol"?e+"":e,s);class KI extends My{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Re(this,"subscriptions",new Map),Re(this,"topicMap",new MI),Re(this,"events",new rr.EventEmitter),Re(this,"name",OA),Re(this,"version",RA),Re(this,"pending",new Map),Re(this,"cached",[]),Re(this,"initialized",!1),Re(this,"storagePrefix",Ts),Re(this,"subscribeTimeout",V.toMiliseconds(V.ONE_MINUTE)),Re(this,"initialSubscribeTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Re(this,"clientId"),Re(this,"batchSubscribeTopicsLimit",500),Re(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Re(this,"subscribe",async(n,r)=>{var i;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}});try{const o=Mo(r),a={topic:n,relay:o,transportType:r==null?void 0:r.transportType};(i=r==null?void 0:r.internal)!=null&&i.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,r);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),Re(this,"unsubscribe",async(n,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(n,r.id,r):await this.unsubscribeByTopic(n,r)}),Re(this,"isSubscribed",n=>new Promise(r=>{r(this.topicMap.topics.includes(n))})),Re(this,"isKnownTopic",n=>new Promise(r=>{r(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(i=>i.topic===n))})),Re(this,"on",(n,r)=>{this.events.on(n,r)}),Re(this,"once",(n,r)=>{this.events.once(n,r)}),Re(this,"off",(n,r)=>{this.events.off(n,r)}),Re(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),Re(this,"start",async()=>{await this.onConnect()}),Re(this,"stop",async()=>{await this.onDisconnect()}),Re(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Re(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(r=>{n.push(r)}),await this.batchSubscribe(n)}),Re(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(jr.pulse,async()=>{await this.checkPending()}),this.events.on(Ut.created,async n=>{const r=Ut.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()}),this.events.on(Ut.deleted,async n=>{const r=Ut.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()})}),this.relayer=e,this.logger=Ft(s,this.name),this.clientId=""}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,s){let n=!1;try{n=this.getSubscription(e).topic===s}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,s){const n=this.topicMap.get(e);await Promise.all(n.map(async r=>await this.unsubscribeById(e,r,s)))}async unsubscribeById(e,s,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}});try{const r=Mo(n);await this.restartToComplete({topic:e,id:s,relay:r}),await this.rpcUnsubscribe(e,s,r);const i=De("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,s,n){var r,i;const o=await this.getSubscriptionId(e);if((r=n==null?void 0:n.internal)!=null&&r.skipSubscribe)return o;(!n||(n==null?void 0:n.transportType)===xe.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const a={method:vr(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(i=n==null?void 0:n.internal)==null?void 0:i.throwOnFailedPublish;try{if((n==null?void 0:n.transportType)===xe.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(u=>this.logger.warn(u))},V.toMiliseconds(V.ONE_SECOND)),o;const l=new Promise(async u=>{const h=p=>{p.topic===e&&(this.events.removeListener(Ut.created,h),u(p.id))};this.events.on(Ut.created,h);try{const p=await As(new Promise((g,f)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),f(w)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ut.created,h),u(p)}catch{}}),d=await As(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!d&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return d?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Fe.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,n={method:vr(s.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await As(new Promise(r=>{this.relayer.request(n).catch(i=>this.logger.warn(i)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Fe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,n={method:vr(s.protocol).batchFetchMessages,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let r;try{r=await await As(new Promise((i,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Fe.connection_stalled)}return r}rpcUnsubscribe(e,s,n){const r={method:vr(n.protocol).unsubscribe,params:{topic:e,id:s}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,s){this.setSubscription(e,Ga(Zr({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,Zr({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,n){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,s){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:s}),this.addSubscription(e,s)}addSubscription(e,s){this.subscriptions.set(e,Zr({},s)),this.topicMap.set(s.topic,e),this.events.emit(Ut.created,s)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const s=this.subscriptions.get(e);if(!s){const{message:n}=H("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(Ut.deleted,Ga(Zr({},n),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ut.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<s;n++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(Ut.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(s=>{var n;return s.topic===((n=this.subscriptions.get(s.id))==null?void 0:n.topic)})){const{message:s}=H("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async s=>Ga(Zr({},s),{id:await this.getSubscriptionId(s.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const s=await this.rpcBatchFetchMessages(e);s&&s.messages&&(await wE(V.toMiliseconds(V.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(s.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=H("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 Xt(e+await this.getClientId())}}var zI=Object.defineProperty,ju=Object.getOwnPropertySymbols,VI=Object.prototype.hasOwnProperty,GI=Object.prototype.propertyIsEnumerable,Yc=(t,e,s)=>e in t?zI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qu=(t,e)=>{for(var s in e||(e={}))VI.call(e,s)&&Yc(t,s,e[s]);if(ju)for(var s of ju(e))GI.call(e,s)&&Yc(t,s,e[s]);return t},Ae=(t,e,s)=>Yc(t,typeof e!="symbol"?e+"":e,s);class YI extends Ly{constructor(e){var s;super(e),Ae(this,"protocol","wc"),Ae(this,"version",2),Ae(this,"core"),Ae(this,"logger"),Ae(this,"events",new rr.EventEmitter),Ae(this,"provider"),Ae(this,"messages"),Ae(this,"subscriber"),Ae(this,"publisher"),Ae(this,"name",_A),Ae(this,"transportExplicitlyClosed",!1),Ae(this,"initialized",!1),Ae(this,"connectionAttemptInProgress",!1),Ae(this,"relayUrl"),Ae(this,"projectId"),Ae(this,"packageName"),Ae(this,"bundleId"),Ae(this,"hasExperiencedNetworkDisruption",!1),Ae(this,"pingTimeout"),Ae(this,"heartBeatTimeout",V.toMiliseconds(V.THIRTY_SECONDS+V.FIVE_SECONDS)),Ae(this,"reconnectTimeout"),Ae(this,"connectPromise"),Ae(this,"reconnectInProgress",!1),Ae(this,"requestsInFlight",[]),Ae(this,"connectTimeout",V.toMiliseconds(V.ONE_SECOND*15)),Ae(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const o=n.id||jn().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const a=`${o}:${((i=n.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),Ae(this,"resetPingTimeout",()=>{ko()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,i,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||o.call(i)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),Ae(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),Ae(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Fe.connect)}),Ae(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ae(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(Fe.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ae(this,"registerProviderListeners",()=>{this.provider.on(Ht.payload,this.onPayloadHandler),this.provider.on(Ht.connect,this.onConnectHandler),this.provider.on(Ht.disconnect,this.onDisconnectHandler),this.provider.on(Ht.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Ul({logger:(s=e.logger)!=null?s:AA,name:this.name}),this.messages=new RI(this.logger,e.core),this.subscriber=new KI(this,this.logger),this.publisher=new DI(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Vf,tE()?this.packageName=Dd():sE()&&(this.bundleId=Dd()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e==null?void 0:e.message))}get context(){return Pt(this.logger)}get connected(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,n){this.isInitialized(),await this.publisher.publish(e,s,n),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:xe.relay},bo.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,s){var n,r,i;this.isInitialized(),(!(s!=null&&s.transportType)||(s==null?void 0:s.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((n=s==null?void 0:s.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(r=s==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",c;const l=d=>{d.topic===e&&(this.subscriber.off(Ut.created,l),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(Ut.created,l)}),new Promise(async(d,u)=>{a=await this.subscriber.subscribe(e,qu({internal:{throwOnFailedPublish:o}},s)).catch(h=>{o&&u(h)})||a,d()})]),a}async unsubscribe(e,s){this.isInitialized(),await this.subscriber.unsubscribe(e,s)}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}off(e,s){this.events.off(e,s)}removeListener(e,s){this.events.removeListener(e,s)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await As(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(s,n)=>{await this.connect(e).then(s).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Tu())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const s=e.sort((n,r)=>n.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const n of s)try{await this.onMessageEvent(n)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+(r==null?void 0:r.message))}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:n}=e;if(!s.sessionExists){const r=qe(V.FIVE_MINUTES),i={topic:n,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,i)}this.events.emit(Fe.message,e),await this.recordMessageEvent(e,bo.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let s=1;for(;s<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${s}...`),await this.createProvider(),await new Promise(async(n,r)=>{const i=()=>{r(new Error("Connection interrupted while trying to connect"))};this.provider.once(Ht.disconnect,i),await As(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off(Ht.disconnect,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ht.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Ht.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const r=n;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${s}`);break}await new Promise(n=>setTimeout(n,V.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,n,r,i;if(ko())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null||i.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new al(new Gg(aE({sdkVersion:Wc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,s){const{topic:n,message:r}=e;await this.messages.set(n,r,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const r=this.messages.has(s,n);return r&&this.logger.warn(`Ignoring duplicate message: ${n}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),cl(e)){if(!e.method.endsWith(IA))return;const s=e.params,{topic:n,message:r,publishedAt:i,attestation:o}=s.data,a={topic:n,message:r,publishedAt:i,transportType:xe.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(qu({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ll(e)&&this.events.emit(Fe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,bo.inbound),this.events.emit(Fe.message,e))}async acknowledgePayload(e){const s=gi(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Ht.payload,this.onPayloadHandler),this.provider.off(Ht.connect,this.onConnectHandler),this.provider.off(Ht.disconnect,this.onDisconnectHandler),this.provider.off(Ht.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Tu();tA(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(n=>this.logger.error(n,n==null?void 0:n.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(jr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&rA())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s==null?void 0:s.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Fe.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},V.toMiliseconds(SA)))))}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function JI(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Wu(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Hu(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const XI="[object RegExp]",ZI="[object String]",QI="[object Number]",eS="[object Boolean]",Ku="[object Arguments]",tS="[object Symbol]",sS="[object Date]",nS="[object Map]",rS="[object Set]",iS="[object Array]",oS="[object Function]",aS="[object ArrayBuffer]",Ya="[object Object]",cS="[object Error]",lS="[object DataView]",dS="[object Uint8Array]",uS="[object Uint8ClampedArray]",hS="[object Uint16Array]",pS="[object Uint32Array]",fS="[object BigUint64Array]",gS="[object Int8Array]",mS="[object Int16Array]",wS="[object Int32Array]",yS="[object BigInt64Array]",bS="[object Float32Array]",ES="[object Float64Array]";function CS(){}function zu(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function vS(t,e,s){return ii(t,e,void 0,void 0,void 0,void 0,s)}function ii(t,e,s,n,r,i,o){const a=o(t,e,s,n,r,i);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return hi(t,e,i,o)}return hi(t,e,i,o)}function hi(t,e,s,n){if(Object.is(t,e))return!0;let r=Hu(t),i=Hu(e);if(r===Ku&&(r=Ya),i===Ku&&(i=Ya),r!==i)return!1;switch(r){case ZI:return t.toString()===e.toString();case QI:{const c=t.valueOf(),l=e.valueOf();return JI(c,l)}case eS:case sS:case tS:return Object.is(t.valueOf(),e.valueOf());case XI:return t.source===e.source&&t.flags===e.flags;case oS:return t===e}s=s??new Map;const o=s.get(t),a=s.get(e);if(o!=null&&a!=null)return o===e;s.set(t,e),s.set(e,t);try{switch(r){case nS:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!ii(l,e.get(c),c,t,e,s,n))return!1;return!0}case rS:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let d=0;d<c.length;d++){const u=c[d],h=l.findIndex(p=>ii(u,p,void 0,t,e,s,n));if(h===-1)return!1;l.splice(h,1)}return!0}case iS:case dS:case uS:case hS:case pS:case fS:case gS:case mS:case wS:case yS:case bS:case ES:{if(typeof Ee<"u"&&Ee.isBuffer(t)!==Ee.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!ii(t[c],e[c],c,t,e,s,n))return!1;return!0}case aS:return t.byteLength!==e.byteLength?!1:hi(new Uint8Array(t),new Uint8Array(e),s,n);case lS:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:hi(new Uint8Array(t),new Uint8Array(e),s,n);case cS:return t.name===e.name&&t.message===e.message;case Ya:{if(!(hi(t.constructor,e.constructor,s,n)||zu(t)&&zu(e)))return!1;const c=[...Object.keys(t),...Wu(t)],l=[...Object.keys(e),...Wu(e)];if(c.length!==l.length)return!1;for(let d=0;d<c.length;d++){const u=c[d],h=t[u];if(!Object.hasOwn(e,u))return!1;const p=e[u];if(!ii(h,p,u,t,e,s,n))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function AS(t,e){return vS(t,e,CS)}var _S=Object.defineProperty,Vu=Object.getOwnPropertySymbols,IS=Object.prototype.hasOwnProperty,SS=Object.prototype.propertyIsEnumerable,Jc=(t,e,s)=>e in t?_S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Gu=(t,e)=>{for(var s in e||(e={}))IS.call(e,s)&&Jc(t,s,e[s]);if(Vu)for(var s of Vu(e))SS.call(e,s)&&Jc(t,s,e[s]);return t},vt=(t,e,s)=>Jc(t,typeof e!="symbol"?e+"":e,s);class lr extends By{constructor(e,s,n,r=Ts,i=void 0){super(e,s,n,r),this.core=e,this.logger=s,this.name=n,vt(this,"map",new Map),vt(this,"version",NA),vt(this,"cached",[]),vt(this,"initialized",!1),vt(this,"getKey"),vt(this,"storagePrefix",Ts),vt(this,"recentlyDeleted",[]),vt(this,"recentlyDeletedLimit",200),vt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ze(o)?this.map.set(this.getKey(o),o):xv(o)?this.map.set(o.id,o):kv(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),vt(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),vt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),vt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>AS(a[c],o[c]))):this.values)),vt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Gu(Gu({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),vt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ft(s,this.name),this.storagePrefix=r,this.getKey=i}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const s=this.map.get(e);if(!s){if(this.recentlyDeleted.includes(e)){const{message:r}=H("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:n}=H("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return s}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:s}=H("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var NS=Object.defineProperty,TS=(t,e,s)=>e in t?NS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fe=(t,e,s)=>TS(t,typeof e!="symbol"?e+"":e,s);class OS{constructor(e,s){this.core=e,this.logger=s,fe(this,"name",PA),fe(this,"version",xA),fe(this,"events",new ol),fe(this,"pairings"),fe(this,"initialized",!1),fe(this,"storagePrefix",Ts),fe(this,"ignoredPayloadTypes",[Vs]),fe(this,"registeredMethods",[]),fe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),fe(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),fe(this,"create",async n=>{this.isInitialized();const r=jc(),i=await this.core.crypto.setSymKey(r),o=qe(V.FIVE_MINUTES),a={protocol:zf},c={topic:i,expiry:o,relay:a,active:!1,methods:n==null?void 0:n.methods},l=bu({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:r,relay:a,expiryTimestamp:o,methods:n==null?void 0:n.methods});return this.events.emit(Bn.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:n==null?void 0:n.transportType,internal:n==null?void 0:n.internal}),{topic:i,uri:l}}),fe(this,"pair",async n=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:n==null?void 0:n.uri,trace:[ys.pairing_started]}});this.isValidPair(n,r);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=yu(n.uri);r.props.properties.topic=i,r.addTrace(ys.pairing_uri_validation_success),r.addTrace(ys.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(i)){if(d=this.pairings.get(i),r.addTrace(ys.existing_pairing),d.active)throw r.setError(Us.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);r.addTrace(ys.pairing_not_expired)}const u=c||qe(V.FIVE_MINUTES),h={topic:i,relay:a,expiry:u,active:!1,methods:l};this.core.expirer.set(i,u),await this.pairings.set(i,h),r.addTrace(ys.store_new_pairing),n.activatePairing&&await this.activate({topic:i}),this.events.emit(Bn.create,h),r.addTrace(ys.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),r.addTrace(ys.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(Us.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(p){throw r.setError(Us.subscribe_pairing_topic_failure),p}return r.addTrace(ys.subscribe_pairing_topic_success),h}),fe(this,"activate",async({topic:n})=>{this.isInitialized();const r=qe(V.FIVE_MINUTES);this.core.expirer.set(n,r),await this.pairings.update(n,{active:!0,expiry:r})}),fe(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=n;if(this.pairings.keys.includes(r)){const i=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ln();this.events.once(Ie("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}}),fe(this,"updateExpiry",async({topic:n,expiry:r})=>{this.isInitialized(),await this.pairings.update(n,{expiry:r})}),fe(this,"updateMetadata",async({topic:n,metadata:r})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:r})}),fe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),fe(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:r}=n;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",De("USER_DISCONNECTED")),await this.deletePairing(r))}),fe(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:r,relay:i,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(r);return bu({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:i,expiryTimestamp:o,methods:a})}),fe(this,"sendRequest",async(n,r,i)=>{const o=Es(r,i),a=await this.core.crypto.encode(n,o),c=Jr[r].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),fe(this,"sendResult",async(n,r,i)=>{const o=gi(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=Jr[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"sendError",async(n,r,i)=>{const o=Fh(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=Jr[c]?Jr[c].res:Jr.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"deletePairing",async(n,r)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,De("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),r?Promise.resolve():this.core.expirer.del(n)])}),fe(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(r=>Cs(r.expiry));await Promise.all(n.map(r=>this.deletePairing(r.topic)))}),fe(this,"onRelayEventRequest",async n=>{const{topic:r,payload:i}=n;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,i);default:return await this.onUnknownRpcMethodRequest(r,i)}}),fe(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i}=n,o=(await this.core.history.get(r,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,i);default:return this.onUnknownRpcMethodResponse(o)}}),fe(this,"onPairingPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult(i,n,!0),this.events.emit(Bn.ping,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),fe(this,"onPairingPingResponse",(n,r)=>{const{id:i}=r;setTimeout(()=>{ks(r)?this.events.emit(Ie("pairing_ping",i),{}):bs(r)&&this.events.emit(Ie("pairing_ping",i),{error:r.error})},500)}),fe(this,"onPairingDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Bn.delete,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),fe(this,"onUnknownRpcMethodRequest",async(n,r)=>{const{id:i,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=De("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,n,a),this.logger.error(a)}catch(a){await this.sendError(i,n,a),this.logger.error(a)}}),fe(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(De("WC_METHOD_UNSUPPORTED",n))}),fe(this,"isValidPair",(n,r)=>{var i;if(!_t(n)){const{message:a}=H("MISSING_OR_INVALID",`pair() params: ${n}`);throw r.setError(Us.malformed_pairing_uri),new Error(a)}if(!Pv(n.uri)){const{message:a}=H("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw r.setError(Us.malformed_pairing_uri),new Error(a)}const o=yu(n==null?void 0:n.uri);if(!((i=o==null?void 0:o.relay)!=null&&i.protocol)){const{message:a}=H("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(Us.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=H("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(Us.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&V.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(Us.pairing_expired);const{message:a}=H("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),fe(this,"isValidPing",async n=>{if(!_t(n)){const{message:i}=H("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),fe(this,"isValidDisconnect",async n=>{if(!_t(n)){const{message:i}=H("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),fe(this,"isValidPairingTopic",async n=>{if(!We(n,!1)){const{message:r}=H("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(r)}if(!this.pairings.keys.includes(n)){const{message:r}=H("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(r)}if(Cs(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:r}=H("EXPIRED",`pairing topic: ${n}`);throw new Error(r)}}),this.core=e,this.logger=Ft(s,this.name),this.pairings=new lr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Pt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Fe.message,async e=>{const{topic:s,message:n,transportType:r}=e;if(this.pairings.keys.includes(s)&&r!==xe.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const i=await this.core.crypto.decode(s,n);cl(i)?(this.core.history.set(s,i),await this.onRelayEventRequest({topic:s,payload:i})):ll(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:s,payload:i}),this.core.history.delete(s,i.id)),await this.core.relayer.messages.ack(s,n)}catch(i){this.logger.error(i)}})}registerExpirerEvents(){this.core.expirer.on(Yt.expired,async e=>{const{topic:s}=Wp(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(Bn.expire,{topic:s}))})}}var RS=Object.defineProperty,PS=(t,e,s)=>e in t?RS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qe=(t,e,s)=>PS(t,typeof e!="symbol"?e+"":e,s);class xS extends $y{constructor(e,s){super(e,s),this.core=e,this.logger=s,Qe(this,"records",new Map),Qe(this,"events",new rr.EventEmitter),Qe(this,"name",kA),Qe(this,"version",$A),Qe(this,"cached",[]),Qe(this,"initialized",!1),Qe(this,"storagePrefix",Ts),Qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Qe(this,"set",(n,r,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:r,chainId:i}),this.records.has(r.id))return;const o={id:r.id,topic:n,request:{method:r.method,params:r.params||null},chainId:i,expiry:qe(V.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(is.created,o)}),Qe(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const r=await this.getRecord(n.id);typeof r.response>"u"&&(r.response=bs(n)?{error:n.error}:{result:n.result},this.records.set(r.id,r),this.persist(),this.events.emit(is.updated,r))}),Qe(this,"get",async(n,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:r}),await this.getRecord(r))),Qe(this,"delete",(n,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(i=>{if(i.topic===n){if(typeof r<"u"&&i.id!==r)return;this.records.delete(i.id),this.events.emit(is.deleted,i)}}),this.persist()}),Qe(this,"exists",async(n,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===n:!1)),Qe(this,"on",(n,r)=>{this.events.on(n,r)}),Qe(this,"once",(n,r)=>{this.events.once(n,r)}),Qe(this,"off",(n,r)=>{this.events.off(n,r)}),Qe(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=Ft(s,this.name)}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(s=>{if(typeof s.response<"u")return;const n={topic:s.topic,request:Es(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const s=this.records.get(e);if(!s){const{message:n}=H("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(is.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=H("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(is.created,e=>{const s=is.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(is.updated,e=>{const s=is.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(is.deleted,e=>{const s=is.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(jr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{V.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(is.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var kS=Object.defineProperty,$S=(t,e,s)=>e in t?kS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ct=(t,e,s)=>$S(t,typeof e!="symbol"?e+"":e,s);class US extends Fy{constructor(e,s){super(e,s),this.core=e,this.logger=s,ct(this,"expirations",new Map),ct(this,"events",new rr.EventEmitter),ct(this,"name",UA),ct(this,"version",DA),ct(this,"cached",[]),ct(this,"initialized",!1),ct(this,"storagePrefix",Ts),ct(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ct(this,"has",n=>{try{const r=this.formatTarget(n);return typeof this.getExpiration(r)<"u"}catch{return!1}}),ct(this,"set",(n,r)=>{this.isInitialized();const i=this.formatTarget(n),o={target:i,expiry:r};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(Yt.created,{target:i,expiration:o})}),ct(this,"get",n=>{this.isInitialized();const r=this.formatTarget(n);return this.getExpiration(r)}),ct(this,"del",n=>{if(this.isInitialized(),this.has(n)){const r=this.formatTarget(n),i=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Yt.deleted,{target:r,expiration:i})}}),ct(this,"on",(n,r)=>{this.events.on(n,r)}),ct(this,"once",(n,r)=>{this.events.once(n,r)}),ct(this,"off",(n,r)=>{this.events.off(n,r)}),ct(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=Ft(s,this.name)}get context(){return Pt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return cE(e);if(typeof e=="number")return lE(e);const{message:s}=H("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(s)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Yt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=H("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const s=this.expirations.get(e);if(!s){const{message:n}=H("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return s}checkExpiry(e,s){const{expiry:n}=s;V.toMiliseconds(n)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(Yt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(jr.pulse,()=>this.checkExpirations()),this.events.on(Yt.created,e=>{const s=Yt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Yt.expired,e=>{const s=Yt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Yt.deleted,e=>{const s=Yt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}}var DS=Object.defineProperty,LS=(t,e,s)=>e in t?DS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,je=(t,e,s)=>LS(t,typeof e!="symbol"?e+"":e,s);class BS extends jy{constructor(e,s,n){super(e,s,n),this.core=e,this.logger=s,this.store=n,je(this,"name",LA),je(this,"abortController"),je(this,"isDevEnv"),je(this,"verifyUrlV3",MA),je(this,"storagePrefix",Ts),je(this,"version",Kf),je(this,"publicKey"),je(this,"fetchPromise"),je(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&V.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),je(this,"register",async r=>{if(!qr()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=xr(),d=this.startAbortTimer(V.ONE_SECOND*5),u=await new Promise((h,p)=>{const g=()=>{window.removeEventListener("message",w),l.body.removeChild(f),p("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const f=l.createElement("iframe");f.src=c,f.style.display="none",f.addEventListener("error",g,{signal:this.abortController.signal});const w=E=>{if(E.data&&typeof E.data=="string")try{const I=JSON.parse(E.data);if(I.type==="verify_attestation"){if(uc(I.attestation).payload.id!==o)return;clearInterval(d),l.body.removeChild(f),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",w),h(I.attestation===null?"":I.attestation)}}catch(I){this.logger.warn(I)}};l.body.appendChild(f),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(u,"jwt attestation"),u}catch(l){this.logger.warn(l)}return""}),je(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=r;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(uc(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),je(this,"fetchAttestation",async(r,i)=>{this.logger.debug(`resolving attestation: ${r} from url: ${i}`);const o=this.startAbortTimer(V.ONE_SECOND*5),a=await fetch(`${i}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),je(this,"getVerifyUrl",r=>{let i=r||ui;return FA.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${ui}`),i=ui),i}),je(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(V.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await i.json()}catch(r){this.logger.warn(r)}}),je(this,"persistPublicKey",async r=>{this.logger.debug(r,"persisting public key to local storage"),await this.store.setItem(this.storeKey,r),this.publicKey=r}),je(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),je(this,"isValidJwtAttestation",async r=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(r,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),je(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),je(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),je(this,"validateAttestation",(r,i)=>{const o=rv(r,i.publicKey),a={hasExpired:V.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ft(s,this.name),this.abortController=new AbortController,this.isDevEnv=Al(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Pt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),V.toMiliseconds(e))}}var MS=Object.defineProperty,FS=(t,e,s)=>e in t?MS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Yu=(t,e,s)=>FS(t,typeof e!="symbol"?e+"":e,s);class jS extends qy{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,Yu(this,"context",jA),Yu(this,"registerDeviceToken",async n=>{const{clientId:r,token:i,notificationType:o,enableEncrypted:a=!1}=n,c=`${qA}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:i,always_raw:a})})}),this.logger=Ft(s,this.context)}}var qS=Object.defineProperty,Ju=Object.getOwnPropertySymbols,WS=Object.prototype.hasOwnProperty,HS=Object.prototype.propertyIsEnumerable,Xc=(t,e,s)=>e in t?qS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qr=(t,e)=>{for(var s in e||(e={}))WS.call(e,s)&&Xc(t,s,e[s]);if(Ju)for(var s of Ju(e))HS.call(e,s)&&Xc(t,s,e[s]);return t},Ge=(t,e,s)=>Xc(t,typeof e!="symbol"?e+"":e,s);class KS extends Wy{constructor(e,s,n=!0){super(e,s,n),this.core=e,this.logger=s,Ge(this,"context",HA),Ge(this,"storagePrefix",Ts),Ge(this,"storageVersion",WA),Ge(this,"events",new Map),Ge(this,"shouldPersist",!1),Ge(this,"init",async()=>{if(!Al())try{const r={eventId:Bd(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:jp(this.core.relayer.protocol,this.core.relayer.version,Wc)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),Ge(this,"createEvent",r=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=Bd(),d=this.core.projectId||"",u=Date.now(),h=Qr({eventId:l,timestamp:u,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Ge(this,"getEvent",r=>{const{eventId:i,topic:o}=r;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Qr(Qr({},a),this.setMethods(a.eventId))}),Ge(this,"deleteEvent",r=>{const{eventId:i}=r;this.events.delete(i),this.shouldPersist=!0}),Ge(this,"setEventListeners",()=>{this.core.heartbeat.on(jr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{V.fromMiliseconds(Date.now())-V.fromMiliseconds(r.timestamp)>KA&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),Ge(this,"setMethods",r=>({addTrace:i=>this.addTrace(r,i),setError:i=>this.setError(r,i)})),Ge(this,"addTrace",(r,i)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(i),this.events.set(r,o),this.shouldPersist=!0)}),Ge(this,"setError",(r,i)=>{const o=this.events.get(r);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),Ge(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ge(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(i=>{this.events.set(i.eventId,Qr(Qr({},i),this.setMethods(i.eventId)))})}catch(r){this.logger.warn(r)}}),Ge(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[i,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const i of r)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}}),Ge(this,"sendEvent",async r=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${zA}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Wc}${i}`,{method:"POST",body:JSON.stringify(r)})}),Ge(this,"getAppDomain",()=>Fp().url),this.logger=Ft(s,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var zS=Object.defineProperty,Xu=Object.getOwnPropertySymbols,VS=Object.prototype.hasOwnProperty,GS=Object.prototype.propertyIsEnumerable,Zc=(t,e,s)=>e in t?zS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Zu=(t,e)=>{for(var s in e||(e={}))VS.call(e,s)&&Zc(t,s,e[s]);if(Xu)for(var s of Xu(e))GS.call(e,s)&&Zc(t,s,e[s]);return t},Pe=(t,e,s)=>Zc(t,typeof e!="symbol"?e+"":e,s);let YS=class og extends Ry{constructor(e){var s;super(e),Pe(this,"protocol",Hf),Pe(this,"version",Kf),Pe(this,"name",jo),Pe(this,"relayUrl"),Pe(this,"projectId"),Pe(this,"customStoragePrefix"),Pe(this,"events",new rr.EventEmitter),Pe(this,"logger"),Pe(this,"heartbeat"),Pe(this,"relayer"),Pe(this,"crypto"),Pe(this,"storage"),Pe(this,"history"),Pe(this,"expirer"),Pe(this,"pairing"),Pe(this,"verify"),Pe(this,"echoClient"),Pe(this,"linkModeSupportedApps"),Pe(this,"eventClient"),Pe(this,"initialized",!1),Pe(this,"logChunkController"),Pe(this,"on",(a,c)=>this.events.on(a,c)),Pe(this,"once",(a,c)=>this.events.once(a,c)),Pe(this,"off",(a,c)=>this.events.off(a,c)),Pe(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Pe(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const d={topic:a,message:c,publishedAt:Date.now(),transportType:xe.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:l})});const n=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Vf,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Ay({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:pA.logger,name:jo}),{logger:i,chunkLoggerController:o}=rp({opts:r,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(s=this.logChunkController)!=null&&s.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ft(i,this.name),this.heartbeat=new Vg,this.crypto=new vI(this,this.logger,e==null?void 0:e.keychain),this.history=new xS(this,this.logger),this.expirer=new US(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new ny(Zu(Zu({},fA),e==null?void 0:e.storageOptions)),this.relayer=new YI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new OS(this,this.logger),this.verify=new BS(this,this.logger,this.storage),this.echoClient=new jS(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new KS(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new og(e);await s.initialize();const n=await s.crypto.getClientId();return await s.storage.setItem(TA,n),s}get context(){return Pt(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Ru,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(Ru)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${e}`,n=`${s}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[s]}catch(s){console.warn("Failed to get global WalletConnect core",s);return}}setGlobalCore(e){var s;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof Ks<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const JS=YS,ag="wc",cg=2,lg="client",Dl=`${ag}@${cg}:${lg}:`,Ja={name:lg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Qu="WALLETCONNECT_DEEPLINK_CHOICE",XS="proposal",eh="Proposal expired",ZS="session",wr=V.SEVEN_DAYS,QS="engine",et={wc_sessionPropose:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1104},res:{ttl:V.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1106},res:{ttl:V.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:V.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1112},res:{ttl:V.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:V.ONE_DAY,prompt:!1,tag:1114},res:{ttl:V.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:V.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:V.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:V.FIVE_MINUTES,prompt:!1,tag:1119}}},Xa={min:V.FIVE_MINUTES,max:V.SEVEN_DAYS},ws={idle:"IDLE",active:"ACTIVE"},eN={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},tN="request",sN=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],nN="wc",rN="auth",iN="authKeys",oN="pairingTopics",aN="requests",ua=`${nN}@${1.5}:${rN}:`,Eo=`${ua}:PUB_KEY`;var cN=Object.defineProperty,lN=Object.defineProperties,dN=Object.getOwnPropertyDescriptors,th=Object.getOwnPropertySymbols,uN=Object.prototype.hasOwnProperty,hN=Object.prototype.propertyIsEnumerable,Qc=(t,e,s)=>e in t?cN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ne=(t,e)=>{for(var s in e||(e={}))uN.call(e,s)&&Qc(t,s,e[s]);if(th)for(var s of th(e))hN.call(e,s)&&Qc(t,s,e[s]);return t},lt=(t,e)=>lN(t,dN(e)),L=(t,e,s)=>Qc(t,typeof e!="symbol"?e+"":e,s);class pN extends Vy{constructor(e){super(e),L(this,"name",QS),L(this,"events",new ol),L(this,"initialized",!1),L(this,"requestQueue",{state:ws.idle,queue:[]}),L(this,"sessionRequestQueue",{state:ws.idle,queue:[]}),L(this,"emittedSessionRequests",new yE({limit:500})),L(this,"requestQueueDelay",V.ONE_SECOND),L(this,"expectedPairingMethodMap",new Map),L(this,"recentlyDeletedMap",new Map),L(this,"recentlyDeletedLimit",200),L(this,"relayMessageCache",[]),L(this,"pendingSessions",new Map),L(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(et)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay)))}),L(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=lt(Ne({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=Sv(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=n;let d=r,u,h=!1;try{if(d){const P=this.client.core.pairing.pairings.get(d);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=P.active}}catch(P){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),P}if(!d||!h){const{topic:P,uri:D}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});d=P,u=D}if(!d){const{message:P}=H("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(P)}const p=await this.client.core.crypto.generateKeyPair(),g=et.wc_sessionPropose.req.ttl||V.FIVE_MINUTES,f=qe(g),w=lt(Ne(Ne({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:zf}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:f,pairingTopic:d},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Xs()}),E=Ie("session_connect",w.id),{reject:I,resolve:_,done:v}=Ln(g,eh),T=({id:P})=>{P===w.id&&(this.client.events.off("proposal_expire",T),this.pendingSessions.delete(w.id),this.events.emit(E,{error:{message:eh,code:0}}))};return this.client.events.on("proposal_expire",T),this.events.once(E,({error:P,session:D})=>{this.client.events.off("proposal_expire",T),P?I(P):D&&_(D)}),await this.sendProposeSession({proposal:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:w.id}}}),await this.setProposal(w.id,w),{uri:u,approval:v}}),L(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(n){throw this.client.logger.error("pair() failed"),n}}),L(this,"approve",async s=>{var n,r,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=s==null?void 0:s.id)==null?void 0:n.toString(),trace:[os.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(x){throw o.setError(xn.no_internet_connection),x}try{await this.isValidProposalId(s==null?void 0:s.id)}catch(x){throw this.client.logger.error(`approve() -> proposal.get(${s==null?void 0:s.id}) failed`),o.setError(xn.proposal_not_found),x}try{await this.isValidApprove(s)}catch(x){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(xn.session_approve_namespace_validation_failure),x}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=s,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:f,requiredNamespaces:w,optionalNamespaces:E}=p;let I=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});I||(I=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:os.session_approve_started,properties:{topic:g,trace:[os.session_approve_started,os.session_namespaces_validation_success]}}));const _=await this.client.core.crypto.generateKeyPair(),v=f.publicKey,T=await this.client.core.crypto.generateSharedKey(_,v),P=Ne(Ne(Ne({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:_,metadata:this.client.metadata},expiry:qe(wr)},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),D=xe.relay;I.addTrace(os.subscribing_session_topic);try{await this.client.core.relayer.subscribe(T,{transportType:D,internal:{skipSubscribe:!0}})}catch(x){throw I.setError(xn.subscribe_session_topic_failure),x}I.addTrace(os.subscribe_session_topic_success);const F=lt(Ne({},P),{topic:T,requiredNamespaces:w,optionalNamespaces:E,pairingTopic:g,acknowledged:!1,self:P.controller,peer:{publicKey:f.publicKey,metadata:f.metadata},controller:_,transportType:xe.relay});await this.client.session.set(T,F),I.addTrace(os.store_session);try{await this.sendApproveSession({sessionTopic:T,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:_},sessionSettleRequest:P,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),I.addTrace(os.session_approve_publish_success)}catch(x){throw this.client.logger.error(x),this.client.session.delete(T,De("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(T),x}return this.client.core.eventClient.deleteEvent({eventId:I.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:f.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(T,qe(wr)),{topic:T,acknowledged:()=>Promise.resolve(this.client.session.get(T))}}),L(this,"reject",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(s)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:r}=s;let i;try{i=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}i&&await this.sendError({id:n,topic:i,error:r,rpcOpts:et.wc_sessionPropose.reject}),await this.deleteProposal(n)}),L(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:n,namespaces:r}=s,{done:i,resolve:o,reject:a}=Ln(),c=Xs(),l=jn().toString(),d=this.client.session.get(n).namespaces;return this.events.once(Ie("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(n,{namespaces:r}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(u=>{this.client.logger.error(u),this.client.session.update(n,{namespaces:d}),a(u)}),{acknowledged:i}}),L(this,"extend",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(s)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=s,r=Xs(),{done:i,resolve:o,reject:a}=Ln();return this.events.once(Ie("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,qe(wr)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),L(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:r,topic:i,expiry:o=et.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(i);(a==null?void 0:a.transportType)===xe.relay&&await this.confirmOnlineStateOrThrow();const c=Xs(),l=jn().toString(),{done:d,resolve:u,reject:h}=Ln(o,"Request expired. Please try again.");this.events.once(Ie("session_request",c),({error:w,result:E})=>{w?h(w):u(E)});const p="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:{request:lt(Ne({},r),{expiryTimestamp:qe(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>h(w)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),await d();const f={request:lt(Ne({},r),{expiryTimestamp:qe(o)}),chainId:n};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:f,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,f)}).catch(E=>h(E)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),w()}),new Promise(async w=>{var E;if(!((E=a.sessionConfig)!=null&&E.disableDeepLink)){const I=await pE(this.client.core.storage,Qu);await dE({id:c,topic:i,wcDeepLink:I})}w()}),d()]).then(w=>w[2])}),L(this,"respond",async s=>{var n,r;this.isInitialized();const i=this.client.core.eventClient.createEvent({properties:{topic:(s==null?void 0:s.topic)||((r=(n=s==null?void 0:s.response)==null?void 0:n.id)==null?void 0:r.toString()),trace:[os.session_request_response_started]}});try{await this.isValidRespond(s)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(xn.session_request_response_validation_failure),u}i.addTrace(os.session_request_response_validation_success);const{topic:o,response:a}=s,{id:c}=a,l=this.client.session.get(o);l.transportType===xe.relay&&await this.confirmOnlineStateOrThrow();const d=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{i.addTrace(os.session_request_response_publish_started),ks(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:d}):bs(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:d}),this.cleanupAfterResponse(s)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(xn.session_request_response_publish_failure),u}}),L(this,"ping",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(s)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:n}=s;if(this.client.session.keys.includes(n)){const r=Xs(),i=jn().toString(),{done:o,resolve:a,reject:c}=Ln();this.events.once(Ie("session_ping",r),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:i}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))}),L(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:n,event:r,chainId:i}=s,o=jn().toString(),a=Xs();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:r,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),L(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:n}=s;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:De("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:r}=H("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(r)}}),L(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(n=>Ov(n,s)))),L(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),L(this,"authenticate",async(s,n)=>{var r;this.isInitialized(),this.isValidAuthenticate(s);const i=n&&this.client.core.linkModeSupportedApps.includes(n)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=i?xe.link_mode:xe.relay;o===xe.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:d,nonce:u,type:h,exp:p,nbf:g,methods:f=[],expiry:w}=s,E=[...s.resources||[]],{topic:I,uri:_}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:I,uri:_}});const v=await this.client.core.crypto.generateKeyPair(),T=yo(v);if(await Promise.all([this.client.auth.authKeys.set(Eo,{responseTopic:T,publicKey:v}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:I})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${I}`),f.length>0){const{namespace:A}=zs(a[0]);let O=OC(A,"request",f);wo(E)&&(O=PC(O,E.pop())),E.push(O)}const P=w&&w>et.wc_sessionAuthenticate.req.ttl?w:et.wc_sessionAuthenticate.req.ttl,D={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:d,version:"1",nonce:u,iat:new Date().toISOString(),exp:p,nbf:g,resources:E},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:qe(P)},F={eip155:{chains:a,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},x={requiredNamespaces:{},optionalNamespaces:F,relays:[{protocol:"irn"}],pairingTopic:I,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:qe(et.wc_sessionPropose.req.ttl),id:Xs()},{done:K,resolve:j,reject:R}=Ln(P,"Request expired"),C=Xs(),S=Ie("session_connect",x.id),y=Ie("session_request",C),b=async({error:A,session:O})=>{this.events.off(y,N),A?R(A):O&&j({session:O})},N=async A=>{var O,M,W;if(await this.deletePendingAuthRequest(C,{message:"fulfilled",code:0}),A.error){const ce=De("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return A.error.code===ce.code?void 0:(this.events.off(S,b),R(A.error.message))}await this.deleteProposal(x.id),this.events.off(S,b);const{cacaos:ae,responder:se}=A.result,X=[],le=[];for(const ce of ae){await Yd({cacao:ce,projectId:this.client.core.projectId})||(this.client.logger.error(ce,"Signature verification failed"),R(De("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Oe}=ce,ht=wo(Oe.resources),yt=[Pc(Oe.iss)],pt=Uo(Oe.iss);if(ht){const jt=Jd(ht),Tn=Xd(ht);X.push(...jt),yt.push(...Tn)}for(const jt of yt)le.push(`${jt}:${pt}`)}const ie=await this.client.core.crypto.generateSharedKey(v,se.publicKey);let Se;X.length>0&&(Se={topic:ie,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:se,controller:se.publicKey,expiry:qe(wr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:I,namespaces:Au([...new Set(X)],[...new Set(le)]),transportType:o},await this.client.core.relayer.subscribe(ie,{transportType:o}),await this.client.session.set(ie,Se),I&&await this.client.core.pairing.updateMetadata({topic:I,metadata:se.metadata}),Se=this.client.session.get(ie)),(O=this.client.metadata.redirect)!=null&&O.linkMode&&(M=se.metadata.redirect)!=null&&M.linkMode&&(W=se.metadata.redirect)!=null&&W.universal&&n&&(this.client.core.addLinkModeSupportedApp(se.metadata.redirect.universal),this.client.session.update(ie,{transportType:xe.link_mode})),j({auths:ae,session:Se})};this.events.once(S,b),this.events.once(y,N);let $;try{if(i){const A=Es("wc_sessionAuthenticate",D,C);this.client.core.history.set(I,A);const O=await this.client.core.crypto.encode("",A,{type:Mi,encoding:fn});$=ro(n,I,O)}else await Promise.all([this.sendRequest({topic:I,method:"wc_sessionAuthenticate",params:D,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:C}),this.sendRequest({topic:I,method:"wc_sessionPropose",params:x,expiry:et.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:x.id})])}catch(A){throw this.events.off(S,b),this.events.off(y,N),A}return await this.setProposal(x.id,x),await this.setAuthRequest(C,{request:lt(Ne({},D),{verifyContext:{}}),pairingTopic:I,transportType:o}),{uri:$??_,response:K}}),L(this,"approveSessionAuthenticate",async s=>{const{id:n,auths:r}=s,i=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[kn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw i.setError(Xr.no_internet_connection),w}const o=this.getPendingAuthRequest(n);if(!o)throw i.setError(Xr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||xe.relay;a===xe.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=yo(c),u={type:Vs,receiverPublicKey:c,senderPublicKey:l},h=[],p=[];for(const w of r){if(!await Yd({cacao:w,projectId:this.client.core.projectId})){i.setError(Xr.invalid_cacao);const T=De("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:T,encodeOpts:u}),new Error(T.message)}i.addTrace(kn.cacaos_verified);const{p:E}=w,I=wo(E.resources),_=[Pc(E.iss)],v=Uo(E.iss);if(I){const T=Jd(I),P=Xd(I);h.push(...T),_.push(...P)}for(const T of _)p.push(`${T}:${v}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(kn.create_authenticated_session_topic);let f;if((h==null?void 0:h.length)>0){f={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:qe(wr),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Au([...new Set(h)],[...new Set(p)]),transportType:a},i.addTrace(kn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(w){throw i.setError(Xr.subscribe_authenticated_session_topic_failure),w}i.addTrace(kn.subscribe_authenticated_session_topic_success),await this.client.session.set(g,f),i.addTrace(kn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(kn.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw i.setError(Xr.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:f}}),L(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:n,reason:r}=s,i=this.getPendingAuthRequest(n);if(!i)throw new Error(`Could not find pending auth request with id ${n}`);i.transportType===xe.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=yo(o),l={type:Vs,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:r,encodeOpts:l,rpcOpts:et.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),L(this,"formatAuthMessage",s=>{this.isInitialized();const{request:n,iss:r}=s;return of(n,r)}),L(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const s=this.relayMessageCache.shift();s&&await this.onRelayMessage(s)}catch(s){this.client.logger.error(s)}},50)}),L(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const n=this.client.core.pairing.pairings.get(s.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter(i=>{var o,a;return((o=i.peerMetadata)==null?void 0:o.url)&&((a=i.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&i.topic&&i.topic!==n.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),L(this,"deleteSession",async s=>{var n;const{topic:r,expirerHasDeleted:i=!1,emitEvent:o=!0,id:a=0}=s,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,De("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),i||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Qu).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,De("USER_DISCONNECTED"))}),r===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=ws.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),L(this,"deleteProposal",async(s,n)=>{if(n)try{const r=this.client.proposal.get(s),i=this.client.core.eventClient.getEvent({topic:r.pairingTopic});i==null||i.setError(xn.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,De("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),L(this,"deletePendingSessionRequest",async(s,n,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==s),r&&(this.sessionRequestQueue.state=ws.idle,this.client.events.emit("session_request_expire",{id:s}))}),L(this,"deletePendingAuthRequest",async(s,n,r=!1)=>{await Promise.all([this.client.auth.requests.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)])}),L(this,"setExpiry",async(s,n)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,n),await this.client.session.update(s,{expiry:n}))}),L(this,"setProposal",async(s,n)=>{this.client.core.expirer.set(s,qe(et.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,n)}),L(this,"setAuthRequest",async(s,n)=>{const{request:r,pairingTopic:i,transportType:o=xe.relay}=n;this.client.core.expirer.set(s,r.expiryTimestamp),await this.client.auth.requests.set(s,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:s,pairingTopic:i,verifyContext:r.verifyContext,transportType:o})}),L(this,"setPendingSessionRequest",async s=>{const{id:n,topic:r,params:i,verifyContext:o}=s,a=i.request.expiryTimestamp||qe(et.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:r,params:i,verifyContext:o})}),L(this,"sendRequest",async s=>{const{topic:n,method:r,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:d,tvf:u,publishOpts:h={}}=s,p=Es(r,i,c);let g;const f=!!d;try{const I=f?fn:Nt;g=await this.client.core.crypto.encode(n,p,{encoding:I})}catch(I){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),I}let w;if(sN.includes(r)){const I=Xt(JSON.stringify(p)),_=Xt(g);w=await this.client.core.verify.register({id:_,decryptedId:I})}const E=Ne(Ne({},et[r].req),h);if(E.attestation=w,o&&(E.ttl=o),a&&(E.id=a),this.client.core.history.set(n,p),f){const I=ro(d,n,g);await de.Linking.openURL(I,this.client.name)}else E.tvf=lt(Ne({},u),{correlationId:p.id}),l?(E.internal=lt(Ne({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,g,E)):this.client.core.relayer.publish(n,g,E).catch(I=>this.client.logger.error(I));return p.id}),L(this,"sendProposeSession",async s=>{const{proposal:n,publishOpts:r}=s,i=Es("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,i);const o=await this.client.core.crypto.encode(n.pairingTopic,i,{encoding:Nt}),a=Xt(JSON.stringify(i)),c=Xt(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:o},opts:lt(Ne({},r),{publishMethod:"wc_proposeSession",attestation:l})})}),L(this,"sendApproveSession",async s=>{const{sessionTopic:n,pairingProposalResponse:r,proposal:i,sessionSettleRequest:o,publishOpts:a}=s,c=gi(i.id,r),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:Nt}),d=Es("wc_sessionSettle",o,a==null?void 0:a.id),u=await this.client.core.crypto.encode(n,d,{encoding:Nt});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:u},opts:lt(Ne({},a),{publishMethod:"wc_approveSession"})})}),L(this,"sendResult",async s=>{const{id:n,topic:r,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=gi(n,i);let d;const u=c&&typeof(de==null?void 0:de.Linking)<"u";try{const g=u?fn:Nt;d=await this.client.core.crypto.encode(r,l,lt(Ne({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let h,p;try{h=await this.client.core.history.get(r,n);const g=h.request;try{p=this.getTVFParams(n,g.params,i)}catch(f){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${f==null?void 0:f.message}`)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${n}) failed`),g}if(u){const g=ro(c,r,d);await de.Linking.openURL(g,this.client.name)}else{const g=h.request.method,f=et[g].res;f.tvf=lt(Ne({},p),{correlationId:n}),o?(f.internal=lt(Ne({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,d,f)):this.client.core.relayer.publish(r,d,f).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(l)}),L(this,"sendError",async s=>{const{id:n,topic:r,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=Fh(n,i);let d;const u=c&&typeof(de==null?void 0:de.Linking)<"u";try{const p=u?fn:Nt;d=await this.client.core.crypto.encode(r,l,lt(Ne({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),p}let h;try{h=await this.client.core.history.get(r,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${r}, ${n}) failed`),p}if(u){const p=ro(c,r,d);await de.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=a||et[p].res;this.client.core.relayer.publish(r,d,g)}await this.client.core.history.resolve(l)}),L(this,"cleanup",async()=>{const s=[],n=[];this.client.session.getAll().forEach(r=>{let i=!1;Cs(r.expiry)&&(i=!0),this.client.core.crypto.keychain.has(r.topic)||(i=!0),i&&s.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Cs(r.expiryTimestamp)&&n.push(r.id)}),await Promise.all([...s.map(r=>this.deleteSession({topic:r})),...n.map(r=>this.deleteProposal(r))])}),L(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),L(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),L(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===ws.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=ws.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=ws.idle}),L(this,"processRequest",async s=>{const{topic:n,payload:r,attestation:i,transportType:o,encryptedId:a}=s,c=r.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:r,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,r);case"wc_sessionPing":return await this.onSessionPingRequest(n,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),L(this,"onRelayEventResponse",async s=>{const{topic:n,payload:r,transportType:i}=s,o=(await this.client.core.history.get(n,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,r,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,r);case"wc_sessionExtend":return this.onSessionExtendResponse(n,r);case"wc_sessionPing":return this.onSessionPingResponse(n,r);case"wc_sessionRequest":return this.onSessionRequestResponse(n,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),L(this,"onRelayEventUnknownPayload",s=>{const{topic:n}=s,{message:r}=H("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),L(this,"shouldIgnorePairingRequest",s=>{const{topic:n,requestMethod:r}=s,i=this.expectedPairingMethodMap.get(n);return!i||i.includes(r)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),L(this,"onSessionProposeRequest",async s=>{const{topic:n,payload:r,attestation:i,encryptedId:o}=s,{params:a,id:c}=r;try{const l=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(Us.proposal_listener_not_found)),this.isValidConnect(Ne({},r.params));const d=a.expiryTimestamp||qe(et.wc_sessionPropose.req.ttl),u=Ne({id:c,pairingTopic:n,expiryTimestamp:d,attestation:i,encryptedId:o},a);await this.setProposal(c,u);const h=await this.getVerifyContext({attestationId:i,hash:Xt(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});l==null||l.addTrace(ys.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:h})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:et.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),L(this,"onSessionProposeResponse",async(s,n,r)=>{const{id:i}=n;if(ks(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const d=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(i,{sessionTopic:d,pairingTopic:s,proposalId:i,publicKey:c});const u=await this.client.core.relayer.subscribe(d,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:s})}else if(bs(n)){await this.deleteProposal(i);const o=Ie("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),L(this,"onSessionSettleRequest",async(s,n)=>{const{id:r,params:i}=n;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h}=n.params,p=[...this.pendingSessions.values()].find(w=>w.sessionTopic===s);if(!p)return this.client.logger.error(`Pending session not found for topic ${s}`);const g=this.client.proposal.get(p.proposalId),f=lt(Ne(Ne(Ne({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),{transportType:xe.relay});await this.client.session.set(f.topic,f),await this.setExpiry(f.topic,f.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:f.peer.metadata}),this.client.events.emit("session_connect",{session:f}),this.events.emit(Ie("session_connect",p.proposalId),{session:f}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(f),await this.sendResult({id:n.id,topic:s,result:!0})}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),L(this,"onSessionSettleResponse",async(s,n)=>{const{id:r}=n;ks(n)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(Ie("session_approve",r),{})):bs(n)&&(await this.client.session.delete(s,De("USER_DISCONNECTED")),this.events.emit(Ie("session_approve",r),{error:n.error}))}),L(this,"onSessionUpdateRequest",async(s,n)=>{const{params:r,id:i}=n;try{const o=`${s}_session_update`,a=Yr.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:s,error:De("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ne({topic:s},r));try{Yr.set(o,i),await this.client.session.update(s,{namespaces:r.namespaces}),await this.sendResult({id:i,topic:s,result:!0})}catch(c){throw Yr.delete(o),c}this.client.events.emit("session_update",{id:i,topic:s,params:r})}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),L(this,"isRequestOutOfSync",(s,n)=>n.toString().slice(0,-3)<s.toString().slice(0,-3)),L(this,"onSessionUpdateResponse",(s,n)=>{const{id:r}=n,i=Ie("session_update",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);ks(n)?this.events.emit(Ie("session_update",r),{}):bs(n)&&this.events.emit(Ie("session_update",r),{error:n.error})}),L(this,"onSessionExtendRequest",async(s,n)=>{const{id:r}=n;try{this.isValidExtend({topic:s}),await this.setExpiry(s,qe(wr)),await this.sendResult({id:r,topic:s,result:!0}),this.client.events.emit("session_extend",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),L(this,"onSessionExtendResponse",(s,n)=>{const{id:r}=n,i=Ie("session_extend",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);ks(n)?this.events.emit(Ie("session_extend",r),{}):bs(n)&&this.events.emit(Ie("session_extend",r),{error:n.error})}),L(this,"onSessionPingRequest",async(s,n)=>{const{id:r}=n;try{this.isValidPing({topic:s}),await this.sendResult({id:r,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),L(this,"onSessionPingResponse",(s,n)=>{const{id:r}=n,i=Ie("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);ks(n)?this.events.emit(Ie("session_ping",r),{}):bs(n)&&this.events.emit(Ie("session_ping",r),{error:n.error})},500)}),L(this,"onSessionDeleteRequest",async(s,n)=>{const{id:r}=n;try{this.isValidDisconnect({topic:s,reason:n.params}),await Promise.all([new Promise(i=>{this.client.core.relayer.once(Fe.publish,async()=>{i(await this.deleteSession({topic:s,id:r}))})}),this.sendResult({id:r,topic:s,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:De("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),L(this,"onSessionRequest",async s=>{var n,r,i;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:d}=s,{id:u,params:h}=a;try{await this.isValidRequest(Ne({topic:o},h));const p=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:Xt(JSON.stringify(Es("wc_sessionRequest",h,u))),encryptedId:l,metadata:p.peer.metadata,transportType:d}),f={id:u,topic:o,params:h,verifyContext:g};await this.setPendingSessionRequest(f),d===xe.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((r=p.peer.metadata.redirect)==null?void 0:r.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(p){await this.sendError({id:u,topic:o,error:p}),this.client.logger.error(p)}}),L(this,"onSessionRequestResponse",(s,n)=>{const{id:r}=n,i=Ie("session_request",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);ks(n)?this.events.emit(Ie("session_request",r),{result:n.result}):bs(n)&&this.events.emit(Ie("session_request",r),{error:n.error})}),L(this,"onSessionEventRequest",async(s,n)=>{const{id:r,params:i}=n;try{const o=`${s}_session_event_${i.event.name}`,a=Yr.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Ne({topic:s},i)),this.client.events.emit("session_event",{id:r,topic:s,params:i}),Yr.set(o,r)}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),L(this,"onSessionAuthenticateResponse",(s,n)=>{const{id:r}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:n}),ks(n)?this.events.emit(Ie("session_request",r),{result:n.result}):bs(n)&&this.events.emit(Ie("session_request",r),{error:n.error})}),L(this,"onSessionAuthenticateRequest",async s=>{var n;const{topic:r,payload:i,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:d,expiryTimestamp:u}=i.params,h=await this.getVerifyContext({attestationId:o,hash:Xt(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:r,id:i.id,authPayload:d,verifyContext:h,expiryTimestamp:u};await this.setAuthRequest(i.id,{request:p,pairingTopic:r,transportType:c}),c===xe.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:i.params,id:i.id,verifyContext:h})}catch(l){this.client.logger.error(l);const d=i.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(i.params.requester.metadata,c),p={type:Vs,receiverPublicKey:d,senderPublicKey:u};await this.sendError({id:i.id,topic:r,error:l,encodeOpts:p,rpcOpts:et.wc_sessionAuthenticate.autoReject,appLink:h})}}),L(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),L(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=ws.idle,this.processSessionRequestQueue()},V.toMiliseconds(this.requestQueueDelay))}),L(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:n})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(i=>i.topic===s&&i.request.method==="wc_sessionRequest").forEach(i=>{const o=i.request.id,a=Ie("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ie("session_request",i.request.id),{error:n})})}),L(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===ws.active){this.client.logger.info("session request queue is already active.");return}const s=this.sessionRequestQueue.queue[0];if(!s){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(s)}catch(n){this.client.logger.error(n)}}),L(this,"emitSessionRequest",s=>{if(this.emittedSessionRequests.has(s.id)){this.client.logger.warn({id:s.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${s.id}`);return}this.sessionRequestQueue.state=ws.active,this.emittedSessionRequests.add(s.id),this.client.events.emit("session_request",s)}),L(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const n=this.client.proposal.getAll().find(r=>r.pairingTopic===s.topic);n&&this.onSessionProposeRequest({topic:s.topic,payload:Es("wc_sessionPropose",lt(Ne({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),L(this,"isValidConnect",async s=>{if(!_t(s)){const{message:l}=H("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:n,requiredNamespaces:r,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=s;if(ze(n)||await this.isValidPairingTopic(n),!jv(c,!0)){const{message:l}=H("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(r&&!ze(r)&&Ns(r)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(r,"requiredNamespaces")}if(i&&!ze(i)&&Ns(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),o&&!ze(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!ze(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(r||{}).concat(Object.keys(i||{}));if(!Object.keys(a).every(d=>l.includes(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),L(this,"validateNamespaces",(s,n)=>{const r=Fv(s,"connect()",n);if(r)throw new Error(r.message)}),L(this,"isValidApprove",async s=>{if(!_t(s))throw new Error(H("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:n,namespaces:r,relayProtocol:i,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),l=Ka(r,"approve()");if(l)throw new Error(l.message);const d=Su(c.requiredNamespaces,r,"approve()");if(d)throw new Error(d.message);if(!We(i,!0)){const{message:u}=H("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(u)}if(o&&!ze(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!ze(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(h=>u.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),L(this,"isValidReject",async s=>{if(!_t(s)){const{message:i}=H("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(i)}const{id:n,reason:r}=s;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!Wv(r)){const{message:i}=H("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(i)}}),L(this,"isValidSessionSettleRequest",s=>{if(!_t(s)){const{message:l}=H("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:n,controller:r,namespaces:i,expiry:o}=s;if(!Wf(n)){const{message:l}=H("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=$v(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Ka(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Cs(o)){const{message:l}=H("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),L(this,"isValidUpdate",async s=>{if(!_t(s)){const{message:c}=H("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:n,namespaces:r}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const i=this.client.session.get(n),o=Ka(r,"update()");if(o)throw new Error(o.message);const a=Su(i.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),L(this,"isValidExtend",async s=>{if(!_t(s)){const{message:r}=H("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(r)}const{topic:n}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),L(this,"isValidRequest",async s=>{if(!_t(s)){const{message:c}=H("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:n,request:r,chainId:i,expiry:o}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!Iu(a,i)){const{message:c}=H("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!Hv(r)){const{message:c}=H("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!Vv(a,i,r.method)){const{message:c}=H("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Xv(o,Xa)){const{message:c}=H("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Xa.min} and ${Xa.max}`);throw new Error(c)}}),L(this,"isValidRespond",async s=>{var n;if(!_t(s)){const{message:a}=H("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(a)}const{topic:r,response:i}=s;try{await this.isValidSessionTopic(r)}catch(a){throw(n=s==null?void 0:s.response)!=null&&n.id&&this.cleanupAfterResponse(s),a}if(!Kv(i)){const{message:a}=H("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(a)}const o=this.client.pendingRequest.get(i.id);if(o.topic!==r){const{message:a}=H("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${i.id}, expected topic: ${o.topic}, received topic: ${r}`);throw new Error(a)}}),L(this,"isValidPing",async s=>{if(!_t(s)){const{message:r}=H("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),L(this,"isValidEmit",async s=>{if(!_t(s)){const{message:a}=H("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}const{topic:n,event:r,chainId:i}=s;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!Iu(o,i)){const{message:a}=H("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!zv(r)){const{message:a}=H("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Gv(o,i,r.name)){const{message:a}=H("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),L(this,"isValidDisconnect",async s=>{if(!_t(s)){const{message:r}=H("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),L(this,"isValidAuthenticate",s=>{const{chains:n,uri:r,domain:i,nonce:o}=s;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!We(r,!1))throw new Error("uri is required parameter");if(!We(i,!1))throw new Error("domain is required parameter");if(!We(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>zs(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=zs(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),L(this,"getVerifyContext",async s=>{const{attestationId:n,hash:r,encryptedId:i,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||ui,validation:"UNKNOWN",origin:o.url||""}};try{if(a===xe.link_mode){const d=this.getAppLinkIfEnabled(o,a);return c.verified.validation=d&&new URL(d).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:n,hash:r,encryptedId:i,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),L(this,"validateSessionProps",(s,n)=>{Object.values(s).forEach((r,i)=>{if(r==null){const{message:o}=H("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${r} for key ${Object.keys(s)[i]}`);throw new Error(o)}})}),L(this,"getPendingAuthRequest",s=>{const n=this.client.auth.requests.get(s);return typeof n=="object"?n:void 0}),L(this,"addToRecentlyDeleted",(s,n)=>{if(this.recentlyDeletedMap.set(s,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=i)break;this.recentlyDeletedMap.delete(o)}}}),L(this,"checkRecentlyDeleted",s=>{const n=this.recentlyDeletedMap.get(s);if(n){const{message:r}=H("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${s}`);throw new Error(r)}}),L(this,"isLinkModeEnabled",(s,n)=>{var r,i,o,a,c,l,d,u,h;return!s||n!==xe.link_mode?!1:((i=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:i.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((d=s==null?void 0:s.redirect)==null?void 0:d.universal)!==void 0&&((u=s==null?void 0:s.redirect)==null?void 0:u.universal)!==""&&((h=s==null?void 0:s.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(de==null?void 0:de.Linking)<"u"}),L(this,"getAppLinkIfEnabled",(s,n)=>{var r;return this.isLinkModeEnabled(s,n)?(r=s==null?void 0:s.redirect)==null?void 0:r.universal:void 0}),L(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const n=Ld(s,"topic")||"",r=decodeURIComponent(Ld(s,"wc_ev")||""),i=this.client.session.keys.includes(n);i&&this.client.session.update(n,{transportType:xe.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:r,sessionExists:i})}),L(this,"registerLinkModeListeners",async()=>{var s;if(Al()||Sn()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const n=de==null?void 0:de.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await n.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),L(this,"getTVFParams",(s,n,r)=>{var i,o,a;if(!((i=n.request)!=null&&i.method))return{};const c={correlationId:s,rpcMethods:[n.request.method],chainId:n.chainId};try{const l=this.extractTxHashesFromResult(n.request,r);c.txHashes=l,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(o=n.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),L(this,"isValidContractData",s=>{var n;if(!s)return!1;try{const r=(s==null?void 0:s.data)||((n=s==null?void 0:s[0])==null?void 0:n.data);if(!r.startsWith("0x"))return!1;const i=r.slice(2);return/^[0-9a-fA-F]*$/.test(i)?i.length%2===0:!1}catch{}return!1}),L(this,"extractTxHashesFromResult",(s,n)=>{var r;try{if(!n)return[];const i=s.method,o=eN[i];if(i==="sui_signTransaction")return[hC(n.transactionBytes)];if(i==="near_signTransaction")return[Kd(n)];if(i==="near_signTransactions")return n.map(c=>Kd(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(r=n.tx_json)==null?void 0:r.hash];if(i==="polkadot_signTransaction")return[hA({transaction:s.params.transactionPayload,signature:n.signature})];if(i==="algo_signTxn")return Gs(n)?n.map(c=>zd(c)):[zd(n)];if(i==="cosmos_signDirect")return[fC(n)];if(i==="wallet_sendCalls")return gC(n);if(typeof n=="string")return[n];const a=n[o.key];if(Gs(a))return i==="solana_signAllTransactions"?a.map(c=>uC(c)):a;if(typeof a=="string")return[a]}catch(i){this.client.logger.warn(i,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,s=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,r]of Object.entries(s))for(const i of r)try{await this.onProviderMessageEvent({topic:n,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${i}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=H("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Fe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:n,attestation:r,transportType:i}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Eo)?this.client.auth.authKeys.get(Eo):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,n,{receiverPublicKey:o,encoding:i===xe.link_mode?fn:Nt});cl(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:r,transportType:i,encryptedId:Xt(n)})):ll(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:i}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:i}),await this.client.core.relayer.messages.ack(s,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Yt.expired,async e=>{const{topic:s,id:n}=Wp(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,H("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,H("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(Bn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Bn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!We(e,!1)){const{message:s}=H("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(s)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:s}=H("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(Cs(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=H("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!We(e,!1)){const{message:s}=H("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(s)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:s}=H("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(Cs(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=H("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=H("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(s)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(We(e,!1)){const{message:s}=H("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=H("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!qv(e)){const{message:s}=H("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=H("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(Cs(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=H("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class fN extends lr{constructor(e,s){super(e,s,XS,Dl),this.core=e,this.logger=s}}let gN=class extends lr{constructor(e,s){super(e,s,ZS,Dl),this.core=e,this.logger=s}};class mN extends lr{constructor(e,s){super(e,s,tN,Dl,n=>n.id),this.core=e,this.logger=s}}class wN extends lr{constructor(e,s){super(e,s,iN,ua,()=>Eo),this.core=e,this.logger=s}}class yN extends lr{constructor(e,s){super(e,s,oN,ua),this.core=e,this.logger=s}}class bN extends lr{constructor(e,s){super(e,s,aN,ua,n=>n.id),this.core=e,this.logger=s}}var EN=Object.defineProperty,CN=(t,e,s)=>e in t?EN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Za=(t,e,s)=>CN(t,typeof e!="symbol"?e+"":e,s);class vN{constructor(e,s){this.core=e,this.logger=s,Za(this,"authKeys"),Za(this,"pairingTopics"),Za(this,"requests"),this.authKeys=new wN(this.core,this.logger),this.pairingTopics=new yN(this.core,this.logger),this.requests=new bN(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var AN=Object.defineProperty,_N=(t,e,s)=>e in t?AN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ge=(t,e,s)=>_N(t,typeof e!="symbol"?e+"":e,s);let IN=class dg extends zy{constructor(e){super(e),ge(this,"protocol",ag),ge(this,"version",cg),ge(this,"name",Ja.name),ge(this,"metadata"),ge(this,"core"),ge(this,"logger"),ge(this,"events",new rr.EventEmitter),ge(this,"engine"),ge(this,"session"),ge(this,"proposal"),ge(this,"pendingRequest"),ge(this,"auth"),ge(this,"signConfig"),ge(this,"on",(n,r)=>this.events.on(n,r)),ge(this,"once",(n,r)=>this.events.once(n,r)),ge(this,"off",(n,r)=>this.events.off(n,r)),ge(this,"removeListener",(n,r)=>this.events.removeListener(n,r)),ge(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),ge(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"update",async n=>{try{return await this.engine.update(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"request",async n=>{try{return await this.engine.request(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"find",n=>{try{return this.engine.find(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),ge(this,"authenticate",async(n,r)=>{try{return await this.engine.authenticate(n,r)}catch(i){throw this.logger.error(i.message),i}}),ge(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||Ja.name,this.metadata=rE(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const s=Ul({logger:(e==null?void 0:e.logger)||Ja.logger,name:this.name});this.logger=s,this.core=(e==null?void 0:e.core)||new JS(e),this.session=new gN(this.core,this.logger),this.proposal=new fN(this.core,this.logger),this.pendingRequest=new mN(this.core,this.logger),this.engine=new pN(this),this.auth=new vN(this.core,this.logger)}static async init(e){const s=new dg(e);return await s.initialize(),s}get context(){return Pt(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const SN=IN;function Ll(t){return t==null||typeof t!="object"&&typeof t!="function"}function ug(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function hg(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const NN="[object RegExp]",pg="[object String]",fg="[object Number]",gg="[object Boolean]",mg="[object Arguments]",TN="[object Symbol]",ON="[object Date]",RN="[object Map]",PN="[object Set]",xN="[object Array]",kN="[object ArrayBuffer]",$N="[object Object]",UN="[object DataView]",DN="[object Uint8Array]",LN="[object Uint8ClampedArray]",BN="[object Uint16Array]",MN="[object Uint32Array]",FN="[object Int8Array]",jN="[object Int16Array]",qN="[object Int32Array]",WN="[object Float32Array]",HN="[object Float64Array]";function Bl(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function KN(t,e){return _r(t,void 0,t,new Map,e)}function _r(t,e,s,n=new Map,r=void 0){const i=r==null?void 0:r(t,e,s,n);if(i!=null)return i;if(Ll(t))return t;if(n.has(t))return n.get(t);if(Array.isArray(t)){const o=new Array(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=_r(t[a],a,s,n,r);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;n.set(t,o);for(const[a,c]of t)o.set(a,_r(c,a,s,n,r));return o}if(t instanceof Set){const o=new Set;n.set(t,o);for(const a of t)o.add(_r(a,void 0,s,n,r));return o}if(typeof Ee<"u"&&Ee.isBuffer(t))return t.subarray();if(Bl(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=_r(t[a],a,s,n,r);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return n.set(t,o),Mn(o,t,s,n,r),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return n.set(t,o),Mn(o,t,s,n,r),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),Mn(o,t,s,n,r),o}if(t instanceof Error){const o=new t.constructor;return n.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Mn(o,t,s,n,r),o}if(typeof t=="object"&&zN(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),Mn(o,t,s,n,r),o}return t}function Mn(t,e,s=t,n,r){const i=[...Object.keys(e),...ug(e)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=_r(e[a],a,s,n,r))}}function zN(t){switch(hg(t)){case mg:case xN:case kN:case UN:case gg:case ON:case WN:case HN:case FN:case jN:case qN:case RN:case fg:case $N:case NN:case PN:case pg:case TN:case DN:case LN:case BN:case MN:return!0;default:return!1}}function VN(t,e){return KN(t,(s,n,r,i)=>{const o=e==null?void 0:e(s,n,r,i);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case fg:case pg:case gg:{const a=new t.constructor(t==null?void 0:t.valueOf());return Mn(a,t),a}case mg:{const a={};return Mn(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function sh(t){return VN(t)}function nh(t){return t!==null&&typeof t=="object"&&hg(t)==="[object Arguments]"}function rh(t){return typeof t=="object"&&t!==null}function GN(){}function YN(t){return Bl(t)}function JN(t){var s;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const n=t[Symbol.toStringTag];return n==null||!((s=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&s.writable)?!1:t.toString()===`[object ${n}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function XN(t){if(Ll(t))return t;if(Array.isArray(t)||Bl(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),s=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new s(t);if(t instanceof RegExp){const n=new s(t);return n.lastIndex=t.lastIndex,n}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const n=new s(t.message);return n.stack=t.stack,n.name=t.name,n.cause=t.cause,n}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const n=Object.create(e);return Object.assign(n,t)}return t}function ZN(t,...e){const s=e.slice(0,-1),n=e[e.length-1];let r=t;for(let i=0;i<s.length;i++){const o=s[i];r=el(r,o,n,new Map)}return r}function el(t,e,s,n){if(Ll(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return XN(n.get(e));if(n.set(e,t),Array.isArray(e)){e=e.slice();for(let i=0;i<e.length;i++)e[i]=e[i]??void 0}const r=[...Object.keys(e),...ug(e)];for(let i=0;i<r.length;i++){const o=r[i];let a=e[o],c=t[o];if(nh(a)&&(a={...a}),nh(c)&&(c={...c}),typeof Ee<"u"&&Ee.isBuffer(a)&&(a=sh(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const d=[],u=Reflect.ownKeys(c);for(let h=0;h<u.length;h++){const p=u[h];d[p]=c[p]}c=d}else c=[];const l=s(c,a,o,t,e,n);l!=null?t[o]=l:Array.isArray(a)||rh(c)&&rh(a)?t[o]=el(c,a,s,n):c==null&&JN(a)?t[o]=el({},a,s,n):c==null&&YN(a)?t[o]=sh(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function QN(t,...e){return ZN(t,...e,GN)}const ih="error",eT="wss://relay.walletconnect.org",tT="wc",wg="universal_provider",io=`${tT}@2:${wg}:`,yg="https://rpc.walletconnect.org/v1/",bg="generic",sT=`${yg}bundler`,Or="call_status",nT=86400,Ml={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var rT=Object.defineProperty,iT=Object.defineProperties,oT=Object.getOwnPropertyDescriptors,oh=Object.getOwnPropertySymbols,aT=Object.prototype.hasOwnProperty,cT=Object.prototype.propertyIsEnumerable,ah=(t,e,s)=>e in t?rT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oo=(t,e)=>{for(var s in e||(e={}))aT.call(e,s)&&ah(t,s,e[s]);if(oh)for(var s of oh(e))cT.call(e,s)&&ah(t,s,e[s]);return t},lT=(t,e)=>iT(t,oT(e));function Eg(t,e,s){var n;const r=zs(t);return((n=e.rpcMap)==null?void 0:n[r.reference])||`${yg}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function dT(t){return t.includes(":")?t.split(":")[1]:t}function Cg(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function uT(t,e){const s=Object.keys(e.namespaces).filter(r=>r.includes(t));if(!s.length)return[];const n=[];return s.forEach(r=>{const i=e.namespaces[r].accounts;n.push(...i)}),n}function ch(t){return Object.fromEntries(Object.entries(t).filter(([e,s])=>{var n,r;return((n=s==null?void 0:s.chains)==null?void 0:n.length)&&((r=s==null?void 0:s.chains)==null?void 0:r.length)>0}))}function ao(t={},e={}){const s=ch(lh(t)),n=ch(lh(e));return QN(s,n)}function lh(t){var e,s,n,r,i;const o={};if(!Ns(t))return o;for(const[a,c]of Object.entries(t)){const l=la(a)?[a]:c.chains,d=c.methods||[],u=c.events||[],h=c.rpcMap||{},p=Ar(a);o[p]=lT(oo(oo({},o[p]),c),{chains:Ss(l,(e=o[p])==null?void 0:e.chains),methods:Ss(d,(s=o[p])==null?void 0:s.methods),events:Ss(u,(n=o[p])==null?void 0:n.events)}),(Ns(h)||Ns(((r=o[p])==null?void 0:r.rpcMap)||{}))&&(o[p].rpcMap=oo(oo({},h),(i=o[p])==null?void 0:i.rpcMap))}return o}function dh(t){return t.includes(":")?t.split(":")[2]:t}function uh(t){const e={};for(const[s,n]of Object.entries(t)){const r=n.methods||[],i=n.events||[],o=n.accounts||[],a=la(s)?[s]:n.chains?n.chains:Cg(n.accounts);e[s]={chains:a,methods:r,events:i,accounts:o}}return e}function Qa(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function hT(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const vg={},Rr=t=>vg[t],ec=(t,e)=>{vg[t]=e};var pT=Object.defineProperty,hh=Object.getOwnPropertySymbols,fT=Object.prototype.hasOwnProperty,gT=Object.prototype.propertyIsEnumerable,ph=(t,e,s)=>e in t?pT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fh=(t,e)=>{for(var s in e||(e={}))fT.call(e,s)&&ph(t,s,e[s]);if(hh)for(var s of hh(e))gT.call(e,s)&&ph(t,s,e[s]);return t};const gh="eip155",mT=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],wT=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,tc=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,mh=t=>Object.keys(t).filter(e=>mT.includes(e)).reduce((e,s)=>(e[s]=yT(t[s]),e),{}),yT=t=>typeof t=="string"&&hT(t)?JSON.parse(t):t,bT=(t,e,s)=>{const{sessionProperties:n={},scopedProperties:r={}}=t,i={};if(!Ns(r)&&!Ns(n))return;const o=mh(n);for(const a of s){const c=wT(a);if(!c)continue;i[tc(c)]=o;const l=r==null?void 0:r[`${gh}:${c}`];if(l){const d=l==null?void 0:l[`${gh}:${c}:${e}`];i[tc(c)]=fh(fh({},i[tc(c)]),mh(d||l))}}for(const[a,c]of Object.entries(i))Object.keys(c).length===0&&delete i[a];return Object.keys(i).length>0?i:void 0};var ET=Object.defineProperty,CT=(t,e,s)=>e in t?ET(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vT=(t,e,s)=>CT(t,typeof e!="symbol"?e+"":e,s);let sc;class Fl{constructor(e){vT(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,s){return await this.storage.setItem(e,s)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return sc||(sc=new Fl(e)),sc}}var AT=Object.defineProperty,_T=Object.defineProperties,IT=Object.getOwnPropertyDescriptors,wh=Object.getOwnPropertySymbols,ST=Object.prototype.hasOwnProperty,NT=Object.prototype.propertyIsEnumerable,yh=(t,e,s)=>e in t?AT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,TT=(t,e)=>{for(var s in e||(e={}))ST.call(e,s)&&yh(t,s,e[s]);if(wh)for(var s of wh(e))NT.call(e,s)&&yh(t,s,e[s]);return t},OT=(t,e)=>_T(t,IT(e));async function RT(t,e){const s=zs(t.result.capabilities.caip345.caip2),n=t.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(n.map(u=>PT(s.reference,u,e))),i=r.filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u);r.filter(u=>u.status==="rejected").forEach(u=>console.warn("Failed to fetch transaction receipt:",u.reason));const o=!i.length||i.some(u=>!u),a=i.every(u=>(u==null?void 0:u.status)==="0x1"),c=i.every(u=>(u==null?void 0:u.status)==="0x0"),l=i.some(u=>(u==null?void 0:u.status)==="0x0");let d;return o?d=100:a?d=200:c?d=500:l&&(d=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:i,status:d}}async function PT(t,e,s){return await s(parseInt(t)).request(Es("eth_getTransactionReceipt",[e]))}async function xT({sendCalls:t,storage:e}){const s=await e.getItem(Or);await e.setItem(Or,OT(TT({},s),{[t.result.id]:{request:t.request,result:t.result,expiry:qe(nT)}}))}async function kT({resultId:t,storage:e}){const s=await e.getItem(Or);if(s){delete s[t],await e.setItem(Or,s);for(const n in s)Cs(s[n].expiry)&&delete s[n];await e.setItem(Or,s)}}async function $T({resultId:t,storage:e}){const s=await e.getItem(Or),n=s==null?void 0:s[t];if(n&&!Cs(n.expiry))return n;await kT({resultId:t,storage:e})}var UT=Object.defineProperty,DT=Object.defineProperties,LT=Object.getOwnPropertyDescriptors,bh=Object.getOwnPropertySymbols,BT=Object.prototype.hasOwnProperty,MT=Object.prototype.propertyIsEnumerable,tl=(t,e,s)=>e in t?UT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,nc=(t,e)=>{for(var s in e||(e={}))BT.call(e,s)&&tl(t,s,e[s]);if(bh)for(var s of bh(e))MT.call(e,s)&&tl(t,s,e[s]);return t},rc=(t,e)=>DT(t,LT(e)),$n=(t,e,s)=>tl(t,typeof e!="symbol"?e+"":e,s);class FT{constructor(e){$n(this,"name","eip155"),$n(this,"client"),$n(this,"chainId"),$n(this,"namespace"),$n(this,"httpProviders"),$n(this,"events"),$n(this,"storage"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=Fl.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s);const n=this.chainId;this.chainId=parseInt(e),this.events.emit(Ml.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,s){const n=s||Eg(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new al(new jh(n,Rr("disableProviderPing")))}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var n;const r=parseInt(dT(s));e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[s])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}getHttpProvider(e){const s=e||this.chainId;return this.httpProviders[s]||(this.httpProviders=rc(nc({},this.httpProviders),{[s]:this.createHttpProvider(s)}),this.httpProviders[s])}async handleSwitchChain(e){var s,n;let r=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const i=parseInt(r,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${i}`);else throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,n,r,i,o;const a=(n=(s=e.request)==null?void 0:s.params)==null?void 0:n[0],c=((i=(r=e.request)==null?void 0:r.params)==null?void 0:i[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),d=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{},u=`${a}${c.join(",")}`,h=d==null?void 0:d[u];if(h)return h;let p;try{p=bT(l,a,c)}catch(f){console.warn("Failed to extract capabilities from session",f)}if(p)return p;const g=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:rc(nc({},l.sessionProperties||{}),{capabilities:rc(nc({},d||{}),{[u]:g})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return g}async getCallStatus(e){var s,n,r;const i=this.client.session.get(e.topic),o=(s=i.sessionProperties)==null?void 0:s.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(d){console.warn("Failed to fetch call status from bundler",d,l)}}const a=(n=i.sessionProperties)==null?void 0:n.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await $T({resultId:(r=e.request.params)==null?void 0:r[0],storage:this.storage});if(c)try{return await RT(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,s){var n;const r=new URL(e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Es("eth_getUserOperationReceipt",[(n=s.request.params)==null?void 0:n[0]]))});if(!i.ok)throw new Error(`Failed to fetch user operation receipt - ${i.status}`);return await i.json()}getBundlerUrl(e,s){return`${sT}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}async sendCalls(e){var s,n,r;const i=await this.client.request(e),o=(s=e.request.params)==null?void 0:s[0],a=i==null?void 0:i.id,c=(i==null?void 0:i.capabilities)||{},l=(n=c==null?void 0:c.caip345)==null?void 0:n.caip2,d=(r=c==null?void 0:c.caip345)==null?void 0:r.transactionHashes;return!a||!l||!(d!=null&&d.length)||await xT({sendCalls:{request:o,result:i},storage:this.storage}),i}}var jT=Object.defineProperty,qT=(t,e,s)=>e in t?jT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yr=(t,e,s)=>qT(t,typeof e!="symbol"?e+"":e,s);class WT{constructor(e){yr(this,"name",bg),yr(this,"client"),yr(this,"httpProviders"),yr(this,"events"),yr(this,"namespace"),yr(this,"chainId"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s);const n=this.chainId;this.chainId=e,this.events.emit(Ml.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return zs(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){var e,s;const n={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(r=>{var i,o;const a=zs(r),c=(o=(i=this.namespace)==null?void 0:i.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];n[a.reference]=this.createHttpProvider(r,c)}),n}getHttpProvider(e){const s=zs(e).reference,n=this.httpProviders[s];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProvider(e,s){const n=s||Eg(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new al(new jh(n,Rr("disableProviderPing")))}}var HT=Object.defineProperty,KT=Object.defineProperties,zT=Object.getOwnPropertyDescriptors,Eh=Object.getOwnPropertySymbols,VT=Object.prototype.hasOwnProperty,GT=Object.prototype.propertyIsEnumerable,sl=(t,e,s)=>e in t?HT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ei=(t,e)=>{for(var s in e||(e={}))VT.call(e,s)&&sl(t,s,e[s]);if(Eh)for(var s of Eh(e))GT.call(e,s)&&sl(t,s,e[s]);return t},co=(t,e)=>KT(t,zT(e)),zt=(t,e,s)=>sl(t,typeof e!="symbol"?e+"":e,s);let YT=class Ag{constructor(e){zt(this,"client"),zt(this,"namespaces"),zt(this,"optionalNamespaces"),zt(this,"sessionProperties"),zt(this,"scopedProperties"),zt(this,"events",new ol),zt(this,"rpcProviders",{}),zt(this,"session"),zt(this,"providerOpts"),zt(this,"logger"),zt(this,"uri"),zt(this,"disableProviderPing",!1);var s,n;this.providerOpts=e,this.logger=Ul({logger:(s=e.logger)!=null?s:ih,name:(n=this.providerOpts.name)!=null?n:wg}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const s=new Ag(e);return await s.initialize(),s}async request(e,s,n){const[r,i]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:ei({},e),chainId:`${r}:${i}`,topic:this.session.topic,expiry:n})}sendAsync(e,s,n,r){const i=new Date().getTime();this.request(e,n,r).then(o=>s(null,gi(i,o))).catch(o=>s(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:De("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,s){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:r}=await this.client.authenticate(e,s);n&&(this.uri=n,this.events.emit("display_uri",n));const i=await r();if(this.session=i.session,this.session){const o=uh(this.session.namespaces);this.namespaces=ao(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return i}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}removeListener(e,s){this.events.removeListener(e,s)}off(e,s){this.events.off(e,s)}get isWalletConnect(){return!0}async pair(e){const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});s&&(this.uri=s,this.events.emit("display_uri",s));const r=await n();this.session=r;const i=uh(r.namespaces);return this.namespaces=ao(this.namespaces,i),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,s){try{if(!this.session)return;const[n,r]=this.validateChain(e);this.getProvider(n).setDefaultChain(r,s)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(!Gs(s))return;for(const n of s)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}catch(s){this.logger.warn(s,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,s;if(this.client=this.providerOpts.client||await SN.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ih,relayUrl:this.providerOpts.relayUrl||eT,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(n){throw this.logger.error(n,"Failed to get session"),new Error(`The provided session: ${(s=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:s.topic} doesn't exist in the Sign client`)}else{const n=this.client.session.getAll();this.session=n[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(s=>Ar(s)))];ec("client",this.client),ec("events",this.events),ec("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const n=uT(s,this.session);if((n==null?void 0:n.length)===0)return;const r=Cg(n),i=ao(this.namespaces,this.optionalNamespaces),o=co(ei({},i[s]),{accounts:n,chains:r});switch(s){case"eip155":this.rpcProviders[s]=new FT({namespace:o});break;default:this.rpcProviders[s]=new WT({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var s;const{topic:n}=e;n===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:n,topic:r}=e;if(r!==((s=this.session)==null?void 0:s.topic))return;const{event:i}=n;if(i.name==="accountsChanged"){const o=i.data;o&&Gs(o)&&this.events.emit("accountsChanged",o.map(dh))}else if(i.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Ar(o),l=Qa(o)!==Qa(a)?`${c}:${Qa(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var n,r;if(e!==((n=this.session)==null?void 0:n.topic))return;const{namespaces:i}=s,o=(r=this.client)==null?void 0:r.session.get(e);this.session=co(ei({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:s})}),this.client.on("session_delete",async e=>{var s;e.topic===((s=this.session)==null?void 0:s.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",co(ei({},De("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Ml.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(co(ei({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[bg]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var s;this.getProvider(e).updateNamespace((s=this.session)==null?void 0:s.namespaces[e])})}setNamespaces(e){const{namespaces:s={},optionalNamespaces:n={},sessionProperties:r,scopedProperties:i}=e;this.optionalNamespaces=ao(s,n),this.sessionProperties=r,this.scopedProperties=i}validateChain(e){const[s,n]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,n];if(s&&!Object.keys(this.namespaces||{}).map(o=>Ar(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&n)return[s,n];const r=Ar(Object.keys(this.namespaces)[0]),i=this.rpcProviders[r].getDefaultChain();return[r,i]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:s,internal:n=!1}){if(!this.namespaces)return;const[r,i]=this.validateChain(e);i&&(this.updateNamespaceChain(r,i),n?(this.events.emit("chainChanged",i),this.emitAccountsChangedOnChainChange({namespace:r,currentCaipChainId:e,previousCaipChainId:s})):this.getProvider(r).setDefaultChain(i),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:s,previousCaipChainId:n}){var r,i;try{if(n===s)return;const o=(i=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:i.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(dh);if(!Gs(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,s){if(!this.namespaces)return;const n=this.namespaces[e]?e:`${e}:${s}`,r={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=s):this.namespaces[n]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,s){var n;const r=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${io}/${e}${r}`,s)}async getFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${io}/${e}${n}`)}async deleteFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${io}/${e}${n}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const s=await this.client.core.storage.getKeys();for(const n of s)n.startsWith(io)&&await this.client.core.storage.removeItem(n)}catch(s){this.logger.warn(s,"Failed to cleanup storage")}}};const Me={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",EIP155:U.CHAIN.EVM,ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH",getSDKVersionWarningMessage(t,e){return`
|
|
16
16
|
@@@@@@@ @@@@@@@@@@@@@@@@@@
|
|
17
17
|
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
|
|
18
18
|
@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@
|
|
@@ -246,4 +246,4 @@ NPM Registry: https://www.npmjs.com/package/@reown/appkit`}},JT={ConnectorExplor
|
|
|
246
246
|
outline: none;
|
|
247
247
|
appearance: none;
|
|
248
248
|
}
|
|
249
|
-
`,uo={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};class ZO extends Tw{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new Ow({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit("disconnect")}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}return{connections:[]}}syncConnections(){return Promise.resolve()}async getAccounts({namespace:e}){var r,i,o,a;const s=this.provider,n=((a=(o=(i=(r=s==null?void 0:s.session)==null?void 0:r.namespaces)==null?void 0:i[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const[,,l]=c.split(":");return l}).filter((c,l,d)=>d.indexOf(c)===l))||[];return Promise.resolve({accounts:n.map(c=>J.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var o,a,c,l,d;if(!(e.caipNetwork&&ye.BALANCE_SUPPORTED_CHAINS.includes((o=e.caipNetwork)==null?void 0:o.chainNamespace))||(a=e.caipNetwork)!=null&&a.testnet)return{balance:"0.00",symbol:((c=e.caipNetwork)==null?void 0:c.nativeCurrency.symbol)||""};const n=m.getAccountData();if(n!=null&&n.balanceLoading&&e.chainId===((l=m.state.activeCaipNetwork)==null?void 0:l.id))return{balance:(n==null?void 0:n.balance)||"0.00",symbol:(n==null?void 0:n.balanceSymbol)||""};const i=(await m.fetchTokenBalance()).find(u=>{var h,p;return u.chainId===`${(h=e.caipNetwork)==null?void 0:h.chainNamespace}:${e.chainId}`&&u.symbol===((p=e.caipNetwork)==null?void 0:p.nativeCurrency.symbol)});return{balance:(i==null?void 0:i.quantity.numeric)||"0.00",symbol:(i==null?void 0:i.symbol)||((d=e.caipNetwork)==null?void 0:d.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:s,message:n,address:r}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let i="";return((o=m.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===U.CHAIN.SOLANA?i=(await s.request({method:"solana_signMessage",params:{message:Fr.encode(new TextEncoder().encode(n)),pubkey:r}},(a=m.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:i=await s.request({method:"personal_sign",params:[n,r]},(c=m.state.activeCaipNetwork)==null?void 0:c.caipNetworkId),{signature:i}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var r,i,o,a,c,l;const{caipNetwork:s}=e,n=this.getWalletConnectConnector();if(s.chainNamespace===U.CHAIN.EVM)try{await((r=n.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:ut.toHex(s.id)}]}))}catch(d){if(d.code===uo.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||d.code===uo.ERROR_INVALID_CHAIN_ID||d.code===uo.ERROR_CODE_DEFAULT||((o=(i=d==null?void 0:d.data)==null?void 0:i.originalError)==null?void 0:o.code)===uo.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=n.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:ut.toHex(s.id),rpcUrls:[(a=s==null?void 0:s.rpcUrls.chainDefault)==null?void 0:a.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[(c=s.blockExplorers)==null?void 0:c.default.url]}]}))}catch{throw new Error("Chain is not supported")}}n.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(n=>n.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}const QO=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication"],ho={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(s=>s!=="email"):!1},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?ye.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?ye.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?ye.DEFAULT_REMOTE_FEATURES.onramp:!1:t},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.activity:!!t},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.reownBranding:!!t},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>t.isEnabled&&(t.config??[]),processFallback:t=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>ye.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>ye.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>ye.DEFAULT_REMOTE_FEATURES.payments},reownAuthentication:{apiFeatureName:"reown_authentication",localFeatureName:"reownAuthentication",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>typeof t>"u"?ye.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!t}},e2={localSettingsOverridden:new Set,getApiConfig(t,e){return e==null?void 0:e.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=ho[e],n=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(n)}},processFeature(t,e,s,n,r){const i=ho[t],o=e[i.localFeatureName];if(r&&!i.isAvailableOnBasic)return!1;if(n){const a=this.getApiConfig(i.apiFeatureName,s);return(a==null?void 0:a.config)===null?this.processFallbackFeature(t,o):a!=null&&a.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return ho[t].processApi(e)},processFallbackFeature(t,e){return ho[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let n=null,r=!1;try{n=await Q.fetchProjectConfig(),r=n!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const i=r&&!e?ye.DEFAULT_REMOTE_FEATURES:ye.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of QO){const a=this.processFeature(o,s,n,r,e);Object.assign(i,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),ye.DEFAULT_REMOTE_FEATURES}if(r&&this.localSettingsOverridden.size>0){const o=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;$t.open({debugMessage:Vt.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(o)},"warning")}return i}};class t2{constructor(e){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,n)=>{var r,i,o;if(s){const a=(r=m.getCaipNetworks(s))==null?void 0:r.find(d=>d.id===n);if(a)return a;const c=(i=m.getNetworkData(s))==null?void 0:i.caipNetwork;return c||((o=m.getRequestedCaipNetworks(s).filter(d=>d.chainNamespace===s))==null?void 0:o[0])}return m.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>m.getCaipNetworks(s),this.getActiveChainNamespace=()=>m.state.activeChain,this.setRequestedCaipNetworks=(s,n)=>{m.setRequestedCaipNetworks(s,n)},this.getApprovedCaipNetworkIds=()=>m.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>{var n,r;return m.state.activeChain===s||!s?m.state.activeCaipAddress:(r=(n=m.state.chains.get(s))==null?void 0:n.accountState)==null?void 0:r.caipAddress},this.setClientId=s=>{re.setClientId(s)},this.getProvider=s=>Ue.getProvider(s),this.getProviderType=s=>Ue.getProviderId(s),this.getPreferredAccountType=s=>ts(s),this.setCaipAddress=(s,n,r=!1)=>{m.setAccountProp("caipAddress",s,n,r),m.setAccountProp("address",J.getPlainAddress(s),n,r)},this.setBalance=(s,n,r)=>{m.setAccountProp("balance",s,r),m.setAccountProp("balanceSymbol",n,r)},this.setProfileName=(s,n)=>{m.setAccountProp("profileName",s,n)},this.setProfileImage=(s,n)=>{m.setAccountProp("profileImage",s,n)},this.setUser=(s,n)=>{m.setAccountProp("user",s,n)},this.resetAccount=s=>{m.resetAccount(s)},this.setCaipNetwork=s=>{m.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,n)=>{m.setChainNetworkData(n,{caipNetwork:s})},this.setStatus=(s,n)=>{m.setAccountProp("status",s,n),q.isConnected()?B.setConnectionStatus("connected"):B.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>{var n;return(n=m.getAccountData(s))==null?void 0:n.address},this.setConnectors=s=>{const n=[...q.state.allConnectors,...s];q.setConnectors(n)},this.setConnections=(s,n)=>{B.setConnections(s,n),z.setConnections(s,n)},this.fetchIdentity=s=>re.fetchIdentity(s),this.getReownName=s=>li.getNamesForAddress(s),this.getConnectors=()=>q.getConnectors(),this.getConnectorImage=s=>Jh.getConnectorImage(s),this.getConnections=s=>this.remoteFeatures.multiWallet?So.getConnectionsData(s).connections:($t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=s=>this.remoteFeatures.multiWallet?So.getConnectionsData(s).recentConnections:($t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async s=>{if(!this.remoteFeatures.multiWallet){$t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await z.switchConnection(s)},this.deleteConnection=s=>{if(!this.remoteFeatures.multiWallet){$t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}B.deleteAddressFromConnection(s),z.syncStorageConnections()},this.setConnectedWalletInfo=(s,n)=>{const r=Ue.getProviderId(n),i=s?{...s,type:r}:void 0;m.setAccountProp("connectedWalletInfo",i,n)},this.getIsConnectedState=()=>!!m.state.activeCaipAddress,this.addAddressLabel=(s,n,r)=>{var o;const i=((o=m.getAccountData(r))==null?void 0:o.addressLabels)||{};m.setAccountProp("addressLabels",{...i,[s]:n},r)},this.removeAddressLabel=(s,n)=>{var i;const r=((i=m.getAccountData(n))==null?void 0:i.addressLabels)||{};m.setAccountProp("addressLabels",{...r,[s]:void 0},n)},this.getAddress=s=>{var r;const n=s||m.state.activeChain;return(r=m.getAccountData(n))==null?void 0:r.address},this.resetNetwork=s=>{m.resetNetwork(s)},this.addConnector=s=>{q.addConnector(s)},this.resetWcConnection=()=>{z.resetWcConnection()},this.setAddressExplorerUrl=(s,n)=>{m.setAccountProp("addressExplorerUrl",s,n)},this.setSmartAccountDeployed=(s,n)=>{m.setAccountProp("smartAccountDeployed",s,n)},this.setPreferredAccountType=(s,n)=>{m.setAccountProp("preferredAccountType",s,n)},this.setEIP6963Enabled=s=>{k.setEIP6963Enabled(s)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,s){const n=e==null?void 0:e.map(i=>i.namespace).filter(i=>!!i);if(n!=null&&n.length)return[...new Set(n)];const r=s==null?void 0:s.map(i=>i.chainNamespace);return[...new Set(r)]}async initialize(e){var s,n,r,i,o;if(this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),k.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),this.remoteFeatures=await e2.fetchRemoteFeatures(e),await Q.fetchUsage(),k.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&bc.setOnrampProviders(this.remoteFeatures.onramp),((s=k.state.remoteFeatures)!=null&&s.email||Array.isArray((n=k.state.remoteFeatures)==null?void 0:n.socials)&&((r=k.state.remoteFeatures)==null?void 0:r.socials.length)>0)&&await this.checkAllowedOrigins(),(i=k.state.features)!=null&&i.reownAuthentication||(o=k.state.remoteFeatures)!=null&&o.reownAuthentication){const{ReownAuthentication:a}=await Ao(()=>import("./features-e842dc9f.js"),["assets/features-e842dc9f.js","assets/index-726bc846.js","assets/index-a5cbd387.css","assets/index-37d53923.js","assets/index-c2e969f4.js"]),c=k.state.siwx;c instanceof a||(c&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),k.setSIWX(new a))}}async openSend(e){var i;const s=e.namespace||m.state.activeChain,n=this.getCaipAddress(s),r=(i=this.getCaipNetwork(s))==null?void 0:i.id;if(!n)throw new Error("openSend: caipAddress not found");if((r==null?void 0:r.toString())!==e.chainId.toString()){const o=m.getCaipNetworkById(e.chainId,s);if(!o)throw new Error(`openSend: caipNetwork with chainId ${e.chainId} not found`);await this.switchNetwork(o,{throwOnFailure:!0})}try{const o=_g.getTokenSymbolByAddress(e.assetAddress);o&&await Q.fetchTokenImages([o])}catch{}return await pe.open({view:"WalletSend",data:{send:e}}),new Promise((o,a)=>{const c=ue.subscribeKey("hash",u=>{u&&(d(),o({hash:u}))}),l=pe.subscribe(u=>{u.open||(d(),a(new Error("Modal closed")))}),d=this.createCleanupHandler([c,l])})}toModalOptions(){function e(n){return(n==null?void 0:n.view)==="Swap"}function s(n){return(n==null?void 0:n.view)==="WalletSend"}return{isSwap:e,isSend:s}}async checkAllowedOrigins(){try{const e=await Q.fetchAllowedOrigins();if(!J.isClient())return;const s=window.location.origin;En.isOriginAllowed(s,e,U.DEFAULT_ALLOWED_ANCESTORS)||$t.open(Vt.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error))return;switch(e.message){case"RATE_LIMITED":$t.open(Vt.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const s=e.cause instanceof Error?e.cause:e;$t.open({displayMessage:Vt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:Vt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(s.message)},"error");break}}}}createCleanupHandler(e){return()=>{e.forEach(s=>{try{s()}catch{}})}}sendInitializeEvent(e){var n;const{...s}=e;delete s.adapters,delete s.universalProvider,he.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(r=>r.id),siweConfig:{options:((n=e.siweConfig)==null?void 0:n.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initAdapterController(){Qh.initialize(this.chainAdapters)}initializeThemeController(e){e.themeMode&&Dt.setThemeMode(e.themeMode),e.themeVariables&&Dt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");m.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});const s=this.getDefaultNetwork();s&&m.setActiveCaipNetwork(s)}initializeConnectionController(e){z.initialize(e.adapters??[]),z.setWcBasic(e.basic??!1)}initializeConnectorController(){q.initialize(this.chainNamespaces)}initializeProjectSettings(e){k.setProjectId(e.projectId),k.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var r;k.setDebug(e.debug!==!1),k.setEnableWalletGuide(e.enableWalletGuide!==!1),k.setEnableWallets(e.enableWallets!==!1),k.setEIP6963Enabled(e.enableEIP6963!==!1),k.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),k.setEnableReconnect(e.enableReconnect!==!1),k.setEnableMobileFullScreen(e.enableMobileFullScreen===!0),k.setCoinbasePreference(e.coinbasePreference),k.setEnableAuthLogger(e.enableAuthLogger!==!1),k.setCustomRpcUrls(e.customRpcUrls),k.setEnableEmbedded(e.enableEmbedded),k.setAllWallets(e.allWallets),k.setIncludeWalletIds(e.includeWalletIds),k.setExcludeWalletIds(e.excludeWalletIds),k.setFeaturedWalletIds(e.featuredWalletIds),k.setTokens(e.tokens),k.setTermsConditionsUrl(e.termsConditionsUrl),k.setPrivacyPolicyUrl(e.privacyPolicyUrl),k.setCustomWallets(e.customWallets),k.setFeatures(e.features),k.setAllowUnsupportedChain(e.allowUnsupportedChain),k.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),k.setPreferUniversalLinks(e.experimental_preferUniversalLinks),k.setDefaultAccountTypes(e.defaultAccountTypes);const s=this.getDefaultMetaData();if(!e.metadata&&s&&(e.metadata=s),k.setMetadata(e.metadata),k.setDisableAppend(e.disableAppend),k.setEnableEmbedded(e.enableEmbedded),k.setSIWX(e.siwx),this.features=k.state.features??{},!e.projectId){$t.open(Vt.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(i=>i.namespace===U.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");k.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,s,n,r;return J.isClient()?{name:((s=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:s.textContent)||"",description:((n=document.querySelector('meta[property="og:description"]'))==null?void 0:n.content)||"",url:window.location.origin,icons:[((r=document.querySelector('link[rel~="icon"]'))==null?void 0:r.href)||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const n=br.getUnsupportedNetwork(`${s}:${e}`);m.setActiveCaipNetwork(n)}}getDefaultNetwork(){return br.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,s){return br.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return br.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(r=>{var i;return r.id===((i=e.defaultNetwork)==null?void 0:i.id)});return s?br.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectConnector(e,s){var n,r;try{this.setLoading(!0,e);let i={connections:[]};const o=this.getAdapter(e);return(((r=(n=m.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.caipAddress)||!k.state.enableReconnect)&&(o!=null&&o.disconnect)&&(i=await o.disconnect({id:s})),this.setLoading(!1,e),i}catch(i){throw this.setLoading(!1,e),new Error(`Failed to disconnect chains: ${i.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var l;const e=m.state.activeChain,s=this.getAdapter(e),n=(l=this.getCaipNetwork(e))==null?void 0:l.id,r=z.getConnections(e),i=this.remoteFeatures.multiWallet,o=r.length>0;if(!s)throw new Error("Adapter not found");const a=await s.connectWalletConnect(n);(!o||!i)&&this.close(),this.setClientId((a==null?void 0:a.clientId)||null),B.setConnectedNamespaces([...m.state.chains.keys()]),await this.syncWalletConnectAccount(),await ds.initializeIfEnabled()},connectExternal:async e=>{const s=await this.onConnectExternal(e);return await this.connectInactiveNamespaces(e,s),s?{address:s.address}:void 0},reconnectExternal:async({id:e,info:s,type:n,provider:r})=>{var a;const i=m.state.activeChain,o=this.getAdapter(i);if(!i)throw new Error("reconnectExternal: namespace not found");if(!o)throw new Error("reconnectExternal: adapter not found");o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:s,type:n,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),B.addConnectedNamespace(i),this.syncConnectedWalletInfo(i))},disconnectConnector:async e=>{await this.disconnectConnector(e.namespace,e.id)},disconnect:async e=>{var l;const{id:s,chainNamespace:n,initialDisconnect:r}=e||{},i=n||m.state.activeChain,o=q.getConnectorId(i),a=s===U.CONNECTOR_ID.AUTH||o===U.CONNECTOR_ID.AUTH,c=s===U.CONNECTOR_ID.WALLET_CONNECT||o===U.CONNECTOR_ID.WALLET_CONNECT;try{const d=Array.from(m.state.chains.keys());let u=n?[n]:d;(c||a)&&(u=d);const h=u.map(async f=>{const w=q.getConnectorId(f),E=s||w,I=await this.disconnectConnector(f,E);I&&(a&&B.deleteConnectedSocialProvider(),I.connections.forEach(_=>{B.addDisconnectedConnectorId(_.connectorId,f)})),r&&this.onDisconnectNamespace({chainNamespace:f,closeModal:!1})}),p=await Promise.allSettled(h);ue.resetSend(),z.resetWcConnection(),(l=ds.getSIWX())!=null&&l.signOutOnDisconnect&&await ds.clearSessions(),q.setFilterByNamespace(void 0),z.syncStorageConnections();const g=p.filter(f=>f.status==="rejected");if(g.length>0)throw new Error(g.map(f=>f.reason.message).join(", "));he.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:n||"all"}})}catch(d){throw new Error(`Failed to disconnect chains: ${d.message}`)}},checkInstalled:e=>e?e.some(s=>{var n;return!!((n=window.ethereum)!=null&&n[String(s)])}):!!window.ethereum,signMessage:async e=>{const s=m.state.activeChain,n=this.getAdapter(m.state.activeChain);if(!s)throw new Error("signMessage: namespace not found");if(!n)throw new Error("signMessage: adapter not found");const r=this.getAddress(s);if(!r)throw new Error("signMessage: address not found");const i=await(n==null?void 0:n.signMessage({message:e,address:r,provider:Ue.getProvider(s)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{const s=e.chainNamespace;if(!s)throw new Error("sendTransaction: namespace not found");if(ye.SEND_SUPPORTED_NAMESPACES.includes(s)){const n=this.getAdapter(s);if(!n)throw new Error("sendTransaction: adapter not found");const r=Ue.getProvider(s),i=await(n==null?void 0:n.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:r}));return(i==null?void 0:i.hash)||""}return""},estimateGas:async e=>{const s=e.chainNamespace;if(s===U.CHAIN.EVM){const n=this.getAdapter(s);if(!n)throw new Error("estimateGas: adapter is required but got undefined");const r=Ue.getProvider(s),i=this.getCaipNetwork();if(!i)throw new Error("estimateGas: caipNetwork is required but got undefined");const o=await(n==null?void 0:n.estimateGas({...e,provider:r,caipNetwork:i}));return(o==null?void 0:o.gas)||0n}return 0n},getEnsAvatar:async()=>{var r;const e=m.state.activeChain;if(!e)throw new Error("getEnsAvatar: namespace is required but got undefined");const s=this.getAddress(e);if(!s)throw new Error("getEnsAvatar: address not found");await this.syncIdentity({address:s,chainId:Number((r=this.getCaipNetwork())==null?void 0:r.id),chainNamespace:e});const n=m.getAccountData();return(n==null?void 0:n.profileImage)||!1},getEnsAddress:async e=>await En.resolveReownName(e),writeContract:async e=>{const s=m.state.activeChain,n=this.getAdapter(s);if(!s)throw new Error("writeContract: namespace is required but got undefined");if(!n)throw new Error("writeContract: adapter is required but got undefined");const r=this.getCaipNetwork(),i=this.getCaipAddress(),o=Ue.getProvider(s);if(!r||!i)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");const a=await(n==null?void 0:n.writeContract({...e,caipNetwork:r,provider:o,caipAddress:i}));return a==null?void 0:a.hash},parseUnits:(e,s)=>{const n=this.getAdapter(m.state.activeChain);if(!n)throw new Error("parseUnits: adapter is required but got undefined");return(n==null?void 0:n.parseUnits({value:e,decimals:s}))??0n},formatUnits:(e,s)=>{const n=this.getAdapter(m.state.activeChain);if(!n)throw new Error("formatUnits: adapter is required but got undefined");return(n==null?void 0:n.formatUnits({value:e,decimals:s}))??"0"},getCapabilities:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("getCapabilities: adapter is required but got undefined");return await(s==null?void 0:s.getCapabilities(e))},grantPermissions:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("grantPermissions: adapter is required but got undefined");return await(s==null?void 0:s.grantPermissions(e))},revokePermissions:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("revokePermissions: adapter is required but got undefined");return s!=null&&s.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("walletGetAssets: adapter is required but got undefined");return await(s==null?void 0:s.walletGetAssets(e))??{}},updateBalance:e=>{const s=this.getAddress(e),n=this.getCaipNetwork(e);!n||!s||this.updateNativeBalance(s,n==null?void 0:n.id,e)}},z.setClient(this.connectionControllerClient)}async onConnectExternal(e){var l,d,u,h,p,g,f,w;const s=m.state.activeChain,n=e.chain||s,r=this.getAdapter(n);let i=!0;if(e.type===Me.CONNECTOR_TYPE_AUTH&&U.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(_=>q.getConnectorId(_)===U.CONNECTOR_ID.AUTH)&&e.chain!==s&&(i=!1),e.chain&&e.chain!==s&&!e.caipNetwork){const E=this.getCaipNetworks().find(I=>I.chainNamespace===e.chain);E&&i&&this.setCaipNetwork(E)}if(!n)throw new Error("connectExternal: namespace not found");if(!r)throw new Error("connectExternal: adapter not found");const o=this.getCaipNetwork(n),a=e.caipNetwork||o,c=await r.connect({id:e.id,address:e.address,info:e.info,type:e.type,provider:e.provider,socialUri:e.socialUri,chainId:((l=e.caipNetwork)==null?void 0:l.id)||(o==null?void 0:o.id),rpcUrl:((p=(h=(u=(d=e.caipNetwork)==null?void 0:d.rpcUrls)==null?void 0:u.default)==null?void 0:h.http)==null?void 0:p[0])||((w=(f=(g=o==null?void 0:o.rpcUrls)==null?void 0:g.default)==null?void 0:f.http)==null?void 0:w[0])});if(c)return B.addConnectedNamespace(n),this.syncProvider({...c,chainNamespace:n}),this.setStatus("connected",n),this.syncConnectedWalletInfo(n),B.removeDisconnectedConnectorId(e.id,n),{address:c.address,connectedCaipNetwork:a}}async connectInactiveNamespaces(e,s){var a;const n=e.type===Me.CONNECTOR_TYPE_AUTH,r=Si.getOtherAuthNamespaces((a=s==null?void 0:s.connectedCaipNetwork)==null?void 0:a.chainNamespace),i=m.state.activeCaipNetwork,o=this.getAdapter(i==null?void 0:i.chainNamespace);n&&(await Promise.all(r.map(async c=>{var l,d,u;try{const h=Ue.getProvider(c),p=this.getCaipNetwork(c),g=this.getAdapter(c);await(g==null?void 0:g.connect({...e,provider:h,socialUri:void 0,chainId:p==null?void 0:p.id,rpcUrl:(u=(d=(l=p==null?void 0:p.rpcUrls)==null?void 0:l.default)==null?void 0:d.http)==null?void 0:u[0]}))&&(B.addConnectedNamespace(c),B.removeDisconnectedConnectorId(e.id,c),this.setStatus("connected",c),this.syncConnectedWalletInfo(c))}catch(h){$t.warn(Vt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,Vt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(c,h instanceof Error?h.message:void 0),Vt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),i&&await(o==null?void 0:o.switchNetwork({caipNetwork:i})))}getApprovedCaipNetworksData(){var s,n,r,i,o;if(Ue.getProviderId(m.state.activeChain)===Me.CONNECTOR_TYPE_WALLET_CONNECT){const a=(n=(s=this.universalProvider)==null?void 0:s.session)==null?void 0:n.namespaces;return{supportsAllNetworks:((o=(i=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:i.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=Ue.getProviderId(s);if(e.chainNamespace===m.state.activeChain){const i=this.getAdapter(s);await(i==null?void 0:i.switchNetwork({caipNetwork:e}))}else if(this.setCaipNetwork(e),r===Me.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const i=this.getAddressByChainNamespace(s);i&&this.syncAccount({address:i,chainId:e.id,chainNamespace:s})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(s=>{const n=s.chains||[],r=s.accounts.map(i=>{const{chainId:o,chainNamespace:a}=tt.parseCaipAddress(i);return`${a}:${o}`});return Array.from(new Set([...n,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,n)=>{var i,o;const r=e==null?void 0:e.find(a=>a.namespace===n);return r?(r.construct({namespace:n,projectId:(i=this.options)==null?void 0:i.projectId,networks:(o=this.caipNetworks)==null?void 0:o.filter(({chainNamespace:a})=>a===n)}),s[n]=r):s[n]=new ZO({namespace:n,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e);const s=this.getAdapter(e);if(!s)throw new Error("adapter not found");await s.syncConnectors(),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)})),this.initAdapterController()}onConnectors(e){const s=this.getAdapter(e);s==null||s.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const n=B.getConnectionStatus();k.state.enableReconnect===!1?this.setStatus("disconnected",e):n==="connected"?this.setStatus("connecting",e):n==="disconnected"?(B.clearAddressCache(),this.setStatus(n,e)):this.setStatus(n,e),s.on("switchNetwork",({address:r,chainId:i})=>{var l,d;const o=this.getCaipNetworks().find(u=>u.id.toString()===i.toString()||u.caipNetworkId.toString()===i.toString()),a=m.state.activeChain===e,c=(d=(l=m.state.chains.get(e))==null?void 0:l.accountState)==null?void 0:d.address;if(o){const u=a&&r?r:c;u&&this.syncAccount({address:u,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(i)}),s.on("disconnect",()=>{const r=this.remoteFeatures.multiWallet,i=Array.from(z.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:e,closeModal:!r||i.length===0})}),s.on("connections",r=>{this.setConnections(r,e)}),s.on("pendingTransactions",()=>{const r=this.getAddress(e),i=m.state.activeCaipNetwork;!r||!(i!=null&&i.id)||this.updateNativeBalance(r,i.id,i.chainNamespace)}),s.on("accountChanged",({address:r,chainId:i,connector:o})=>{var d,u;this.handlePreviousConnectorConnection(o);const a=m.state.activeChain===e;o!=null&&o.provider&&(this.syncProvider({id:o.id,type:o.type,provider:o==null?void 0:o.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e));const c=(u=(d=m.getNetworkData(e))==null?void 0:d.caipNetwork)==null?void 0:u.id,l=i||c;a&&l?this.syncAccount({address:r,chainId:l,chainNamespace:e}):!a&&l?(this.syncAccountInfo(r,l,e),this.syncBalance({address:r,chainId:l,chainNamespace:e})):this.syncAccountInfo(r,i,e),B.addConnectedNamespace(e)})}async handlePreviousConnectorConnection(e){var c;const s=e==null?void 0:e.chain,n=e==null?void 0:e.id,r=q.getConnectorId(s),i=(c=k.state.remoteFeatures)==null?void 0:c.multiWallet,a=s&&n&&r&&r!==n&&!i;try{a&&await z.disconnect({id:r,namespace:s})}catch(l){console.warn("Error disconnecting previous connector",l)}}async createUniversalProviderForAdapter(e){var s,n,r;await this.getUniversalProvider(),this.universalProvider&&await((r=(n=(s=this.chainAdapters)==null?void 0:s[e])==null?void 0:n.setUniversalProvider)==null?void 0:r.call(n,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(e=>z.disconnect({namespace:e,initialDisconnect:!0})))}catch(e){console.error("Error disconnecting existing connections:",e)}}async reconnectWalletConnect(){await this.syncWalletConnectAccount();const e=this.getAddress();this.getCaipAddress()||B.deleteRecentWallet();const s=B.getRecentWallet();he.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:J.isMobile()?"mobile":"qrcode",name:(s==null?void 0:s.name)||"Unknown",reconnect:!0,view:ne.state.view,walletRank:s==null?void 0:s.order}})}async syncNamespaceConnection(e){try{e===U.CHAIN.EVM&&J.isSafeApp()&&q.setConnectorId(U.CONNECTOR_ID.SAFE,e);const s=q.getConnectorId(e);switch(this.setStatus("connecting",e),s){case U.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case U.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}onDisconnectNamespace(e){const{chainNamespace:s,closeModal:n}=e||{};m.resetAccount(s),m.resetNetwork(s),B.removeConnectedNamespace(s);const r=Array.from(m.state.chains.keys());(s?[s]:r).forEach(o=>B.addDisconnectedConnectorId(q.getConnectorId(o)||"",o)),q.removeConnectorId(s),Ue.resetChain(s),this.setUser(null,s),this.setStatus("disconnected",s),this.setConnectedWalletInfo(null,s),n!==!1&&pe.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(e=>{const s=this.getAdapter(e),n=this.getCaipAddress(e),r=this.getCaipNetwork(e);return s==null?void 0:s.syncConnections({connectToFirstConnector:!n,caipNetwork:r})}))}async syncAdapterConnection(e){var a,c,l,d;const s=this.getAdapter(e),n=this.getCaipNetwork(e),r=q.getConnectorId(e),o=q.getConnectors(e).find(u=>u.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(n!=null&&n.id))throw new Error("CaipNetwork not found");const u=await(s==null?void 0:s.syncConnection({namespace:e,id:o.id,chainId:n.id,rpcUrl:(l=(c=(a=n==null?void 0:n.rpcUrls)==null?void 0:a.default)==null?void 0:c.http)==null?void 0:l[0]}));u?(this.syncProvider({...u,chainNamespace:e}),await this.syncAccount({...u,chainNamespace:e}),this.setStatus("connected",e),he.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:u.address,properties:{method:"browser",name:((d=o.info)==null?void 0:d.name)||o.name||"Unknown",reconnect:!0,view:ne.state.view,walletRank:void 0}})):this.setStatus("disconnected",e)}catch{this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})}}async syncWalletConnectAccount(){var n,r;const e=Object.keys(((r=(n=this.universalProvider)==null?void 0:n.session)==null?void 0:r.namespaces)||{}),s=this.chainNamespaces.map(async i=>{var u,h,p,g,f;const o=this.getAdapter(i);if(!o)return;const a=((g=(p=(h=(u=this.universalProvider)==null?void 0:u.session)==null?void 0:h.namespaces)==null?void 0:p[i])==null?void 0:g.accounts)||[],c=(f=m.state.activeCaipNetwork)==null?void 0:f.id,l=a.find(w=>{const{chainId:E}=tt.parseCaipAddress(w);return E===(c==null?void 0:c.toString())})||a[0];if(l){const w=tt.validateCaipAddress(l),{chainId:E,address:I}=tt.parseCaipAddress(w);if(Ue.setProviderId(i,Me.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&m.state.activeCaipNetwork&&o.namespace!==U.CHAIN.EVM){const _=o.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:m.state.activeCaipNetwork});Ue.setProvider(i,_)}else Ue.setProvider(i,this.universalProvider);q.setConnectorId(U.CONNECTOR_ID.WALLET_CONNECT,i),B.addConnectedNamespace(i),await this.syncAccount({address:I,chainId:E,chainNamespace:i})}else e.includes(i)&&this.setStatus("disconnected",i);const d=this.getApprovedCaipNetworksData();this.syncConnectedWalletInfo(i),m.setApprovedCaipNetworksData(i,{approvedCaipNetworkIds:d.approvedCaipNetworkIds,supportsAllNetworks:d.supportsAllNetworks})});await Promise.all(s)}syncProvider({type:e,provider:s,id:n,chainNamespace:r}){Ue.setProviderId(r,e),Ue.setProvider(r,s),q.setConnectorId(n,r)}async syncAccount(e){var u,h;const s=e.chainNamespace===m.state.activeChain,n=m.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:i,chainNamespace:o}=e,{chainId:a}=B.getActiveNetworkProps(),c=(n==null?void 0:n.id)||a,l=((u=m.state.activeCaipNetwork)==null?void 0:u.name)===U.UNSUPPORTED_NETWORK_NAME,d=m.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!d)&&c){let p=this.getCaipNetworks().find(E=>E.id.toString()===c.toString()),g=this.getCaipNetworks().find(E=>E.chainNamespace===o);if(!d&&!p&&!g){const E=this.getApprovedCaipNetworkIds()||[],I=E.find(v=>{var T;return((T=tt.parseCaipNetworkId(v))==null?void 0:T.chainId)===c.toString()}),_=E.find(v=>{var T;return((T=tt.parseCaipNetworkId(v))==null?void 0:T.chainNamespace)===o});p=this.getCaipNetworks().find(v=>v.caipNetworkId===I),g=this.getCaipNetworks().find(v=>v.caipNetworkId===_||"deprecatedCaipNetworkId"in v&&v.deprecatedCaipNetworkId===_)}const f=p||g;(f==null?void 0:f.chainNamespace)===m.state.activeChain?k.state.enableNetworkSwitch&&!k.state.allowUnsupportedChain&&((h=m.state.activeCaipNetwork)==null?void 0:h.name)===U.UNSUPPORTED_NETWORK_NAME?m.showUnsupportedChainUI():this.setCaipNetwork(f):s||n&&this.setCaipNetworkOfNamespace(n,o),this.syncConnectedWalletInfo(o);const w=this.getAddress(o);Si.isLowerCaseMatch(r,w)||this.syncAccountInfo(r,f==null?void 0:f.id,o),s?await this.syncBalance({address:r,chainId:f==null?void 0:f.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:n==null?void 0:n.id,chainNamespace:o}),this.syncIdentity({address:r,chainId:i,chainNamespace:o})}}async syncAccountInfo(e,s,n){const r=this.getCaipAddress(n),i=s||(r==null?void 0:r.split(":")[1]);if(!i)return;const o=`${n}:${i}:${e}`;this.setCaipAddress(o,n,!0),await this.syncIdentity({address:e,chainId:i,chainNamespace:n})}async syncReownName(e,s){try{const n=await this.getReownName(e);if(n[0]){const r=n[0];this.setProfileName(r.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){var r;const s=q.getConnectorId(e),n=Ue.getProviderId(e);if(n===Me.CONNECTOR_TYPE_ANNOUNCED||n===Me.CONNECTOR_TYPE_INJECTED){if(s){const o=this.getConnectors().find(a=>{var u,h;const c=a.id===s,l=((u=a.info)==null?void 0:u.rdns)===s,d=(h=a.connectors)==null?void 0:h.some(p=>{var g;return p.id===s||((g=p.info)==null?void 0:g.rdns)===s});return c||l||!!d});if(o){const{info:a,name:c,imageUrl:l}=o,d=l||this.getConnectorImage(o);this.setConnectedWalletInfo({name:c,icon:d,...a},e)}}}else if(n===Me.CONNECTOR_TYPE_WALLET_CONNECT){const i=Ue.getProvider(e);i!=null&&i.session&&this.setConnectedWalletInfo({...i.session.peer.metadata,name:i.session.peer.metadata.name,icon:(r=i.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(s&&(s===U.CONNECTOR_ID.COINBASE_SDK||s===U.CONNECTOR_ID.COINBASE)){const i=this.getConnectors().find(l=>l.id===s),o=(i==null?void 0:i.name)||"Coinbase Wallet",a=(i==null?void 0:i.imageUrl)||this.getConnectorImage(i),c=i==null?void 0:i.info;this.setConnectedWalletInfo({...c,name:o,icon:a},e)}}async syncBalance(e){!qh.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(n=>{var r;return n.id.toString()===((r=e.chainId)==null?void 0:r.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,n){const r=this.getAdapter(n),i=m.getCaipNetworkByNamespace(n,s);if(r){const o=await r.getBalance({address:e,chainId:s,caipNetwork:i,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,n),o}}async initializeUniversalAdapter(){var n,r,i,o,a,c,l,d,u,h;const e=CO.createLogger((p,...g)=>{p&&this.handleAlertError(p),console.error(...g)}),s={projectId:(n=this.options)==null?void 0:n.projectId,metadata:{name:(r=this.options)!=null&&r.metadata?(i=this.options)==null?void 0:i.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(c=this.options)!=null&&c.metadata?(l=this.options)==null?void 0:l.metadata.url:"",icons:(d=this.options)!=null&&d.metadata?(u=this.options)==null?void 0:u.metadata.icons:[""]},logger:e};k.setManualWCControl(!!((h=this.options)!=null&&h.manualWCControl)),this.universalProvider=this.options.universalProvider??await YT.init(s),k.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(e=>{En.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:s=>{z.setUri(s)},onConnect:s=>{const{address:n}=J.getAccount(s[0]);z.finalizeWcConnection(n)},onDisconnect:()=>{m.state.noAdapters&&this.resetAccount(e),z.resetWcConnection()},onChainChanged:s=>{const n=m.state.activeChain,r=n&&q.state.activeConnectorIds[n]===U.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(m.state.noAdapters||r)){const i=this.getCaipNetworks().find(a=>a.id.toString()===s.toString()||a.caipNetworkId.toString()===s.toString()),o=this.getCaipNetwork();if(!i){this.setUnsupportedNetwork(s);return}(o==null?void 0:o.id.toString())!==(i==null?void 0:i.id.toString())&&(o==null?void 0:o.chainNamespace)===(i==null?void 0:i.chainNamespace)&&this.setCaipNetwork(i)}},onAccountsChanged:s=>{const n=m.state.activeChain,r=n&&q.state.activeConnectorIds[n]===U.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(m.state.noAdapters||r)){const i=s==null?void 0:s[0];i&&this.syncAccount({address:i.address,chainId:i.chainId,chainNamespace:i.chainNamespace})}}})})}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&J.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){he.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}getDisabledCaipNetworks(){const e=m.getAllApprovedCaipNetworkIds(),s=m.getAllRequestedCaipNetworks();return J.sortRequestedNetworks(e,s).filter(r=>m.isCaipNetworkDisabled(r))}handleAlertError(e){const s=Object.entries(Vt.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[n,r]=s??[],{message:i,alertErrorKey:o}=r??{};if(n&&i&&!this.reportedAlertErrors[n]){const a=Vt.ALERT_ERRORS[o];a&&($t.open(a,"error"),this.reportedAlertErrors[n]=!0)}}getAdapter(e){var s;if(e)return(s=this.chainAdapters)==null?void 0:s[e]}createAdapter(e){var r,i;if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const n=e;n.namespace=s,n.construct({namespace:s,projectId:(r=this.options)==null?void 0:r.projectId,networks:(i=this.caipNetworks)==null?void 0:i.filter(({chainNamespace:o})=>o===s)}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=n)}async open(e){await this.injectModalUi(),e!=null&&e.uri&&z.setUri(e.uri);const{isSwap:s,isSend:n}=this.toModalOptions();return s(e)?pe.open({...e,data:{swap:e.arguments}}):n(e)&&e.arguments?this.openSend(e.arguments):pe.open(e)}async close(){await this.injectModalUi(),pe.close()}setLoading(e,s){pe.setLoading(e,s)}async disconnect(e){await z.disconnect({namespace:e})}getSIWX(){return k.state.siwx}getError(){return""}getChainId(){var e;return(e=m.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e,{throwOnFailure:s=!1}={}){const n=this.getCaipNetworks().find(r=>r.id===e.id);if(!n){$t.open(Vt.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await m.switchActiveNetwork(n,{throwOnFailure:s})}getWalletProvider(){return m.state.activeChain?Ue.state.providers[m.state.activeChain]:null}getWalletProviderType(){return Ue.getProviderId(m.state.activeChain)}subscribeProviders(e){return Ue.subscribeProviders(e)}getThemeMode(){return Dt.state.themeMode}getThemeVariables(){return Dt.state.themeVariables}setThemeMode(e){Dt.setThemeMode(e),il(Dt.state.themeMode)}setTermsConditionsUrl(e){k.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){k.setPrivacyPolicyUrl(e)}setThemeVariables(e){Dt.setThemeVariables(e),XO(Dt.state.themeVariables)}subscribeTheme(e){return Dt.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?z.subscribe(e):($t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){var n,r;if(e)return(r=(n=m.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.connectedWalletInfo;const s=m.getAccountData();return s==null?void 0:s.connectedWalletInfo}getAccount(e){const s=e||m.state.activeChain,n=q.getAuthConnector(s),r=m.getAccountData(s),i=B.getConnectedConnectorId(m.state.activeChain),o=z.getConnections(s);if(!s)throw new Error("AppKit:getAccount - namespace is required");const a=o.flatMap(c=>c.accounts.map(({address:l,type:d,publicKey:u})=>J.createAccount(s,l,d||"eoa",u)));if(r)return{allAccounts:a,caipAddress:r.caipAddress,address:J.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:n&&i===U.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:B.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:ts(s),isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const n=()=>{const r=this.getAccount(s);r&&e(r)};s?m.subscribeChainProp("accountState",n,s):m.subscribe(n),q.subscribe(n)}subscribeNetwork(e){return m.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s==null?void 0:s.id,caipNetworkId:s==null?void 0:s.caipNetworkId})})}subscribeWalletInfo(e,s){return s?m.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo),s):m.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo))}subscribeShouldUpdateToAddress(e){m.subscribeChainProp("accountState",s=>e(s==null?void 0:s.shouldUpdateToAddress))}subscribeCaipNetworkChange(e){m.subscribeKey("activeCaipNetwork",e)}getState(){return Ws.state}getRemoteFeatures(){return k.state.remoteFeatures}subscribeState(e){return Ws.subscribe(e)}subscribeRemoteFeatures(e){return k.subscribeKey("remoteFeatures",e)}showErrorMessage(e){vs.showError(e)}showSuccessMessage(e){vs.showSuccess(e)}getEvent(){return{...he.state}}subscribeEvents(e){return he.subscribe(e)}replace(e){ne.replace(e)}redirect(e){ne.push(e)}popTransactionStack(e){ne.popTransactionStack(e)}isOpen(){return pe.state.open}isTransactionStackEmpty(){return ne.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){k.setFeatures(e)}updateRemoteFeatures(e){k.setRemoteFeatures(e)}updateOptions(e){const n={...k.state||{},...e};k.setOptions(n)}setConnectMethodsOrder(e){k.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){k.setWalletFeaturesOrder(e)}setCollapseWallets(e){k.setCollapseWallets(e)}setSocialsOrder(e){k.setSocialsOrder(e)}getConnectMethodsOrder(){return oi.getConnectOrderMethod(k.state.features,q.getConnectors())}addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const n=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(r=>r.id===n.id)||m.addNetwork(n)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(r=>r.id===s)&&m.removeNetwork(e,s)}}let Dh=!1;class kg extends t2{async open(e){q.isConnected()||await super.open(e)}async close(){var e;if(await super.close(),this.options.manualWCControl){const s=(e=m.getAccountData(this.activeChainNamespace))==null?void 0:e.address;z.finalizeWcConnection(s)}}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!Dh&&J.isClient()){if(await Ao(()=>import("./basic-de12c849.js"),["assets/basic-de12c849.js","assets/index-bc60e460.js","assets/index-726bc846.js","assets/index-a5cbd387.css","assets/index-37d53923.js","assets/index-c2e969f4.js"]),await Ao(()=>import("./w3m-modal-d813356f.js"),["assets/w3m-modal-d813356f.js","assets/index-bc60e460.js","assets/index-726bc846.js","assets/index-a5cbd387.css","assets/index-37d53923.js","assets/index-c2e969f4.js"]),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!k.state.disableAppend&&!k.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}Dh=!0}}}const s2="1.8.11";function n2(t){return new kg({...t,basic:!0,sdkVersion:`html-core-${s2}`})}const Y2=Object.freeze(Object.defineProperty({__proto__:null,AppKit:kg,createAppKit:n2},Symbol.toStringTag,{value:"Module"}));export{Y2 as $,Q as A,re as B,q as C,ul as D,he as E,$t as F,ts as G,Si as H,Qt as I,ds as J,JO as K,AO as L,pe as M,cm as N,k as O,z2 as P,nl as Q,ne as R,vs as S,Dt as T,Ng as U,Lr as V,oi as W,qh as X,te as Y,Ki as Z,Z as _,J as a,z as b,U as c,K2 as d,Zt as e,oc as f,Jh as g,G2 as h,vo as i,Qn as j,js as k,ye as l,H2 as m,m as n,br as o,B as p,Xe as q,V2 as r,mn as s,ke as t,st as u,nt as v,ns as w,W2 as x,Zh as y,ew as z};
|
|
249
|
+
`,uo={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};class ZO extends Tw{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new Ow({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit("disconnect")}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}return{connections:[]}}syncConnections(){return Promise.resolve()}async getAccounts({namespace:e}){var r,i,o,a;const s=this.provider,n=((a=(o=(i=(r=s==null?void 0:s.session)==null?void 0:r.namespaces)==null?void 0:i[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const[,,l]=c.split(":");return l}).filter((c,l,d)=>d.indexOf(c)===l))||[];return Promise.resolve({accounts:n.map(c=>J.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var o,a,c,l,d;if(!(e.caipNetwork&&ye.BALANCE_SUPPORTED_CHAINS.includes((o=e.caipNetwork)==null?void 0:o.chainNamespace))||(a=e.caipNetwork)!=null&&a.testnet)return{balance:"0.00",symbol:((c=e.caipNetwork)==null?void 0:c.nativeCurrency.symbol)||""};const n=m.getAccountData();if(n!=null&&n.balanceLoading&&e.chainId===((l=m.state.activeCaipNetwork)==null?void 0:l.id))return{balance:(n==null?void 0:n.balance)||"0.00",symbol:(n==null?void 0:n.balanceSymbol)||""};const i=(await m.fetchTokenBalance()).find(u=>{var h,p;return u.chainId===`${(h=e.caipNetwork)==null?void 0:h.chainNamespace}:${e.chainId}`&&u.symbol===((p=e.caipNetwork)==null?void 0:p.nativeCurrency.symbol)});return{balance:(i==null?void 0:i.quantity.numeric)||"0.00",symbol:(i==null?void 0:i.symbol)||((d=e.caipNetwork)==null?void 0:d.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:s,message:n,address:r}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let i="";return((o=m.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===U.CHAIN.SOLANA?i=(await s.request({method:"solana_signMessage",params:{message:Fr.encode(new TextEncoder().encode(n)),pubkey:r}},(a=m.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:i=await s.request({method:"personal_sign",params:[n,r]},(c=m.state.activeCaipNetwork)==null?void 0:c.caipNetworkId),{signature:i}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){var r,i,o,a,c,l;const{caipNetwork:s}=e,n=this.getWalletConnectConnector();if(s.chainNamespace===U.CHAIN.EVM)try{await((r=n.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:ut.toHex(s.id)}]}))}catch(d){if(d.code===uo.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||d.code===uo.ERROR_INVALID_CHAIN_ID||d.code===uo.ERROR_CODE_DEFAULT||((o=(i=d==null?void 0:d.data)==null?void 0:i.originalError)==null?void 0:o.code)===uo.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=n.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:ut.toHex(s.id),rpcUrls:[(a=s==null?void 0:s.rpcUrls.chainDefault)==null?void 0:a.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[(c=s.blockExplorers)==null?void 0:c.default.url]}]}))}catch{throw new Error("Chain is not supported")}}n.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(n=>n.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}const QO=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication"],ho={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(s=>s!=="email"):!1},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?ye.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?ye.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?ye.DEFAULT_REMOTE_FEATURES.onramp:!1:t},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.activity:!!t},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?ye.DEFAULT_REMOTE_FEATURES.reownBranding:!!t},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>t.isEnabled&&(t.config??[]),processFallback:t=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>ye.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>ye.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>ye.DEFAULT_REMOTE_FEATURES.payments},reownAuthentication:{apiFeatureName:"reown_authentication",localFeatureName:"reownAuthentication",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>typeof t>"u"?ye.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!t}},e2={localSettingsOverridden:new Set,getApiConfig(t,e){return e==null?void 0:e.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=ho[e],n=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(n)}},processFeature(t,e,s,n,r){const i=ho[t],o=e[i.localFeatureName];if(r&&!i.isAvailableOnBasic)return!1;if(n){const a=this.getApiConfig(i.apiFeatureName,s);return(a==null?void 0:a.config)===null?this.processFallbackFeature(t,o):a!=null&&a.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return ho[t].processApi(e)},processFallbackFeature(t,e){return ho[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let n=null,r=!1;try{n=await Q.fetchProjectConfig(),r=n!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const i=r&&!e?ye.DEFAULT_REMOTE_FEATURES:ye.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of QO){const a=this.processFeature(o,s,n,r,e);Object.assign(i,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),ye.DEFAULT_REMOTE_FEATURES}if(r&&this.localSettingsOverridden.size>0){const o=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;$t.open({debugMessage:Vt.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(o)},"warning")}return i}};class t2{constructor(e){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,n)=>{var r,i,o;if(s){const a=(r=m.getCaipNetworks(s))==null?void 0:r.find(d=>d.id===n);if(a)return a;const c=(i=m.getNetworkData(s))==null?void 0:i.caipNetwork;return c||((o=m.getRequestedCaipNetworks(s).filter(d=>d.chainNamespace===s))==null?void 0:o[0])}return m.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>m.getCaipNetworks(s),this.getActiveChainNamespace=()=>m.state.activeChain,this.setRequestedCaipNetworks=(s,n)=>{m.setRequestedCaipNetworks(s,n)},this.getApprovedCaipNetworkIds=()=>m.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>{var n,r;return m.state.activeChain===s||!s?m.state.activeCaipAddress:(r=(n=m.state.chains.get(s))==null?void 0:n.accountState)==null?void 0:r.caipAddress},this.setClientId=s=>{re.setClientId(s)},this.getProvider=s=>Ue.getProvider(s),this.getProviderType=s=>Ue.getProviderId(s),this.getPreferredAccountType=s=>ts(s),this.setCaipAddress=(s,n,r=!1)=>{m.setAccountProp("caipAddress",s,n,r),m.setAccountProp("address",J.getPlainAddress(s),n,r)},this.setBalance=(s,n,r)=>{m.setAccountProp("balance",s,r),m.setAccountProp("balanceSymbol",n,r)},this.setProfileName=(s,n)=>{m.setAccountProp("profileName",s,n)},this.setProfileImage=(s,n)=>{m.setAccountProp("profileImage",s,n)},this.setUser=(s,n)=>{m.setAccountProp("user",s,n)},this.resetAccount=s=>{m.resetAccount(s)},this.setCaipNetwork=s=>{m.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,n)=>{m.setChainNetworkData(n,{caipNetwork:s})},this.setStatus=(s,n)=>{m.setAccountProp("status",s,n),q.isConnected()?B.setConnectionStatus("connected"):B.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>{var n;return(n=m.getAccountData(s))==null?void 0:n.address},this.setConnectors=s=>{const n=[...q.state.allConnectors,...s];q.setConnectors(n)},this.setConnections=(s,n)=>{B.setConnections(s,n),z.setConnections(s,n)},this.fetchIdentity=s=>re.fetchIdentity(s),this.getReownName=s=>li.getNamesForAddress(s),this.getConnectors=()=>q.getConnectors(),this.getConnectorImage=s=>Jh.getConnectorImage(s),this.getConnections=s=>this.remoteFeatures.multiWallet?So.getConnectionsData(s).connections:($t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=s=>this.remoteFeatures.multiWallet?So.getConnectionsData(s).recentConnections:($t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async s=>{if(!this.remoteFeatures.multiWallet){$t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await z.switchConnection(s)},this.deleteConnection=s=>{if(!this.remoteFeatures.multiWallet){$t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}B.deleteAddressFromConnection(s),z.syncStorageConnections()},this.setConnectedWalletInfo=(s,n)=>{const r=Ue.getProviderId(n),i=s?{...s,type:r}:void 0;m.setAccountProp("connectedWalletInfo",i,n)},this.getIsConnectedState=()=>!!m.state.activeCaipAddress,this.addAddressLabel=(s,n,r)=>{var o;const i=((o=m.getAccountData(r))==null?void 0:o.addressLabels)||{};m.setAccountProp("addressLabels",{...i,[s]:n},r)},this.removeAddressLabel=(s,n)=>{var i;const r=((i=m.getAccountData(n))==null?void 0:i.addressLabels)||{};m.setAccountProp("addressLabels",{...r,[s]:void 0},n)},this.getAddress=s=>{var r;const n=s||m.state.activeChain;return(r=m.getAccountData(n))==null?void 0:r.address},this.resetNetwork=s=>{m.resetNetwork(s)},this.addConnector=s=>{q.addConnector(s)},this.resetWcConnection=()=>{z.resetWcConnection()},this.setAddressExplorerUrl=(s,n)=>{m.setAccountProp("addressExplorerUrl",s,n)},this.setSmartAccountDeployed=(s,n)=>{m.setAccountProp("smartAccountDeployed",s,n)},this.setPreferredAccountType=(s,n)=>{m.setAccountProp("preferredAccountType",s,n)},this.setEIP6963Enabled=s=>{k.setEIP6963Enabled(s)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,s){const n=e==null?void 0:e.map(i=>i.namespace).filter(i=>!!i);if(n!=null&&n.length)return[...new Set(n)];const r=s==null?void 0:s.map(i=>i.chainNamespace);return[...new Set(r)]}async initialize(e){var s,n,r,i,o;if(this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),k.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),this.remoteFeatures=await e2.fetchRemoteFeatures(e),await Q.fetchUsage(),k.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&bc.setOnrampProviders(this.remoteFeatures.onramp),((s=k.state.remoteFeatures)!=null&&s.email||Array.isArray((n=k.state.remoteFeatures)==null?void 0:n.socials)&&((r=k.state.remoteFeatures)==null?void 0:r.socials.length)>0)&&await this.checkAllowedOrigins(),(i=k.state.features)!=null&&i.reownAuthentication||(o=k.state.remoteFeatures)!=null&&o.reownAuthentication){const{ReownAuthentication:a}=await Ao(()=>import("./features-b72c9430.js"),["assets/features-b72c9430.js","assets/index-2ef9f1d1.js","assets/index-a8255d1c.css","assets/index-74e34dfb.js","assets/index-c1c8440f.js"]),c=k.state.siwx;c instanceof a||(c&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),k.setSIWX(new a))}}async openSend(e){var i;const s=e.namespace||m.state.activeChain,n=this.getCaipAddress(s),r=(i=this.getCaipNetwork(s))==null?void 0:i.id;if(!n)throw new Error("openSend: caipAddress not found");if((r==null?void 0:r.toString())!==e.chainId.toString()){const o=m.getCaipNetworkById(e.chainId,s);if(!o)throw new Error(`openSend: caipNetwork with chainId ${e.chainId} not found`);await this.switchNetwork(o,{throwOnFailure:!0})}try{const o=_g.getTokenSymbolByAddress(e.assetAddress);o&&await Q.fetchTokenImages([o])}catch{}return await pe.open({view:"WalletSend",data:{send:e}}),new Promise((o,a)=>{const c=ue.subscribeKey("hash",u=>{u&&(d(),o({hash:u}))}),l=pe.subscribe(u=>{u.open||(d(),a(new Error("Modal closed")))}),d=this.createCleanupHandler([c,l])})}toModalOptions(){function e(n){return(n==null?void 0:n.view)==="Swap"}function s(n){return(n==null?void 0:n.view)==="WalletSend"}return{isSwap:e,isSend:s}}async checkAllowedOrigins(){try{const e=await Q.fetchAllowedOrigins();if(!J.isClient())return;const s=window.location.origin;En.isOriginAllowed(s,e,U.DEFAULT_ALLOWED_ANCESTORS)||$t.open(Vt.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error))return;switch(e.message){case"RATE_LIMITED":$t.open(Vt.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const s=e.cause instanceof Error?e.cause:e;$t.open({displayMessage:Vt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:Vt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(s.message)},"error");break}}}}createCleanupHandler(e){return()=>{e.forEach(s=>{try{s()}catch{}})}}sendInitializeEvent(e){var n;const{...s}=e;delete s.adapters,delete s.universalProvider,he.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(r=>r.id),siweConfig:{options:((n=e.siweConfig)==null?void 0:n.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initAdapterController(){Qh.initialize(this.chainAdapters)}initializeThemeController(e){e.themeMode&&Dt.setThemeMode(e.themeMode),e.themeVariables&&Dt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");m.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});const s=this.getDefaultNetwork();s&&m.setActiveCaipNetwork(s)}initializeConnectionController(e){z.initialize(e.adapters??[]),z.setWcBasic(e.basic??!1)}initializeConnectorController(){q.initialize(this.chainNamespaces)}initializeProjectSettings(e){k.setProjectId(e.projectId),k.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var r;k.setDebug(e.debug!==!1),k.setEnableWalletGuide(e.enableWalletGuide!==!1),k.setEnableWallets(e.enableWallets!==!1),k.setEIP6963Enabled(e.enableEIP6963!==!1),k.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),k.setEnableReconnect(e.enableReconnect!==!1),k.setEnableMobileFullScreen(e.enableMobileFullScreen===!0),k.setCoinbasePreference(e.coinbasePreference),k.setEnableAuthLogger(e.enableAuthLogger!==!1),k.setCustomRpcUrls(e.customRpcUrls),k.setEnableEmbedded(e.enableEmbedded),k.setAllWallets(e.allWallets),k.setIncludeWalletIds(e.includeWalletIds),k.setExcludeWalletIds(e.excludeWalletIds),k.setFeaturedWalletIds(e.featuredWalletIds),k.setTokens(e.tokens),k.setTermsConditionsUrl(e.termsConditionsUrl),k.setPrivacyPolicyUrl(e.privacyPolicyUrl),k.setCustomWallets(e.customWallets),k.setFeatures(e.features),k.setAllowUnsupportedChain(e.allowUnsupportedChain),k.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),k.setPreferUniversalLinks(e.experimental_preferUniversalLinks),k.setDefaultAccountTypes(e.defaultAccountTypes);const s=this.getDefaultMetaData();if(!e.metadata&&s&&(e.metadata=s),k.setMetadata(e.metadata),k.setDisableAppend(e.disableAppend),k.setEnableEmbedded(e.enableEmbedded),k.setSIWX(e.siwx),this.features=k.state.features??{},!e.projectId){$t.open(Vt.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(i=>i.namespace===U.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");k.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,s,n,r;return J.isClient()?{name:((s=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:s.textContent)||"",description:((n=document.querySelector('meta[property="og:description"]'))==null?void 0:n.content)||"",url:window.location.origin,icons:[((r=document.querySelector('link[rel~="icon"]'))==null?void 0:r.href)||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const n=br.getUnsupportedNetwork(`${s}:${e}`);m.setActiveCaipNetwork(n)}}getDefaultNetwork(){return br.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,s){return br.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return br.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(r=>{var i;return r.id===((i=e.defaultNetwork)==null?void 0:i.id)});return s?br.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectConnector(e,s){var n,r;try{this.setLoading(!0,e);let i={connections:[]};const o=this.getAdapter(e);return(((r=(n=m.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.caipAddress)||!k.state.enableReconnect)&&(o!=null&&o.disconnect)&&(i=await o.disconnect({id:s})),this.setLoading(!1,e),i}catch(i){throw this.setLoading(!1,e),new Error(`Failed to disconnect chains: ${i.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var l;const e=m.state.activeChain,s=this.getAdapter(e),n=(l=this.getCaipNetwork(e))==null?void 0:l.id,r=z.getConnections(e),i=this.remoteFeatures.multiWallet,o=r.length>0;if(!s)throw new Error("Adapter not found");const a=await s.connectWalletConnect(n);(!o||!i)&&this.close(),this.setClientId((a==null?void 0:a.clientId)||null),B.setConnectedNamespaces([...m.state.chains.keys()]),await this.syncWalletConnectAccount(),await ds.initializeIfEnabled()},connectExternal:async e=>{const s=await this.onConnectExternal(e);return await this.connectInactiveNamespaces(e,s),s?{address:s.address}:void 0},reconnectExternal:async({id:e,info:s,type:n,provider:r})=>{var a;const i=m.state.activeChain,o=this.getAdapter(i);if(!i)throw new Error("reconnectExternal: namespace not found");if(!o)throw new Error("reconnectExternal: adapter not found");o!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:s,type:n,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),B.addConnectedNamespace(i),this.syncConnectedWalletInfo(i))},disconnectConnector:async e=>{await this.disconnectConnector(e.namespace,e.id)},disconnect:async e=>{var l;const{id:s,chainNamespace:n,initialDisconnect:r}=e||{},i=n||m.state.activeChain,o=q.getConnectorId(i),a=s===U.CONNECTOR_ID.AUTH||o===U.CONNECTOR_ID.AUTH,c=s===U.CONNECTOR_ID.WALLET_CONNECT||o===U.CONNECTOR_ID.WALLET_CONNECT;try{const d=Array.from(m.state.chains.keys());let u=n?[n]:d;(c||a)&&(u=d);const h=u.map(async f=>{const w=q.getConnectorId(f),E=s||w,I=await this.disconnectConnector(f,E);I&&(a&&B.deleteConnectedSocialProvider(),I.connections.forEach(_=>{B.addDisconnectedConnectorId(_.connectorId,f)})),r&&this.onDisconnectNamespace({chainNamespace:f,closeModal:!1})}),p=await Promise.allSettled(h);ue.resetSend(),z.resetWcConnection(),(l=ds.getSIWX())!=null&&l.signOutOnDisconnect&&await ds.clearSessions(),q.setFilterByNamespace(void 0),z.syncStorageConnections();const g=p.filter(f=>f.status==="rejected");if(g.length>0)throw new Error(g.map(f=>f.reason.message).join(", "));he.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:n||"all"}})}catch(d){throw new Error(`Failed to disconnect chains: ${d.message}`)}},checkInstalled:e=>e?e.some(s=>{var n;return!!((n=window.ethereum)!=null&&n[String(s)])}):!!window.ethereum,signMessage:async e=>{const s=m.state.activeChain,n=this.getAdapter(m.state.activeChain);if(!s)throw new Error("signMessage: namespace not found");if(!n)throw new Error("signMessage: adapter not found");const r=this.getAddress(s);if(!r)throw new Error("signMessage: address not found");const i=await(n==null?void 0:n.signMessage({message:e,address:r,provider:Ue.getProvider(s)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{const s=e.chainNamespace;if(!s)throw new Error("sendTransaction: namespace not found");if(ye.SEND_SUPPORTED_NAMESPACES.includes(s)){const n=this.getAdapter(s);if(!n)throw new Error("sendTransaction: adapter not found");const r=Ue.getProvider(s),i=await(n==null?void 0:n.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:r}));return(i==null?void 0:i.hash)||""}return""},estimateGas:async e=>{const s=e.chainNamespace;if(s===U.CHAIN.EVM){const n=this.getAdapter(s);if(!n)throw new Error("estimateGas: adapter is required but got undefined");const r=Ue.getProvider(s),i=this.getCaipNetwork();if(!i)throw new Error("estimateGas: caipNetwork is required but got undefined");const o=await(n==null?void 0:n.estimateGas({...e,provider:r,caipNetwork:i}));return(o==null?void 0:o.gas)||0n}return 0n},getEnsAvatar:async()=>{var r;const e=m.state.activeChain;if(!e)throw new Error("getEnsAvatar: namespace is required but got undefined");const s=this.getAddress(e);if(!s)throw new Error("getEnsAvatar: address not found");await this.syncIdentity({address:s,chainId:Number((r=this.getCaipNetwork())==null?void 0:r.id),chainNamespace:e});const n=m.getAccountData();return(n==null?void 0:n.profileImage)||!1},getEnsAddress:async e=>await En.resolveReownName(e),writeContract:async e=>{const s=m.state.activeChain,n=this.getAdapter(s);if(!s)throw new Error("writeContract: namespace is required but got undefined");if(!n)throw new Error("writeContract: adapter is required but got undefined");const r=this.getCaipNetwork(),i=this.getCaipAddress(),o=Ue.getProvider(s);if(!r||!i)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");const a=await(n==null?void 0:n.writeContract({...e,caipNetwork:r,provider:o,caipAddress:i}));return a==null?void 0:a.hash},parseUnits:(e,s)=>{const n=this.getAdapter(m.state.activeChain);if(!n)throw new Error("parseUnits: adapter is required but got undefined");return(n==null?void 0:n.parseUnits({value:e,decimals:s}))??0n},formatUnits:(e,s)=>{const n=this.getAdapter(m.state.activeChain);if(!n)throw new Error("formatUnits: adapter is required but got undefined");return(n==null?void 0:n.formatUnits({value:e,decimals:s}))??"0"},getCapabilities:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("getCapabilities: adapter is required but got undefined");return await(s==null?void 0:s.getCapabilities(e))},grantPermissions:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("grantPermissions: adapter is required but got undefined");return await(s==null?void 0:s.grantPermissions(e))},revokePermissions:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("revokePermissions: adapter is required but got undefined");return s!=null&&s.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("walletGetAssets: adapter is required but got undefined");return await(s==null?void 0:s.walletGetAssets(e))??{}},updateBalance:e=>{const s=this.getAddress(e),n=this.getCaipNetwork(e);!n||!s||this.updateNativeBalance(s,n==null?void 0:n.id,e)}},z.setClient(this.connectionControllerClient)}async onConnectExternal(e){var l,d,u,h,p,g,f,w;const s=m.state.activeChain,n=e.chain||s,r=this.getAdapter(n);let i=!0;if(e.type===Me.CONNECTOR_TYPE_AUTH&&U.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(_=>q.getConnectorId(_)===U.CONNECTOR_ID.AUTH)&&e.chain!==s&&(i=!1),e.chain&&e.chain!==s&&!e.caipNetwork){const E=this.getCaipNetworks().find(I=>I.chainNamespace===e.chain);E&&i&&this.setCaipNetwork(E)}if(!n)throw new Error("connectExternal: namespace not found");if(!r)throw new Error("connectExternal: adapter not found");const o=this.getCaipNetwork(n),a=e.caipNetwork||o,c=await r.connect({id:e.id,address:e.address,info:e.info,type:e.type,provider:e.provider,socialUri:e.socialUri,chainId:((l=e.caipNetwork)==null?void 0:l.id)||(o==null?void 0:o.id),rpcUrl:((p=(h=(u=(d=e.caipNetwork)==null?void 0:d.rpcUrls)==null?void 0:u.default)==null?void 0:h.http)==null?void 0:p[0])||((w=(f=(g=o==null?void 0:o.rpcUrls)==null?void 0:g.default)==null?void 0:f.http)==null?void 0:w[0])});if(c)return B.addConnectedNamespace(n),this.syncProvider({...c,chainNamespace:n}),this.setStatus("connected",n),this.syncConnectedWalletInfo(n),B.removeDisconnectedConnectorId(e.id,n),{address:c.address,connectedCaipNetwork:a}}async connectInactiveNamespaces(e,s){var a;const n=e.type===Me.CONNECTOR_TYPE_AUTH,r=Si.getOtherAuthNamespaces((a=s==null?void 0:s.connectedCaipNetwork)==null?void 0:a.chainNamespace),i=m.state.activeCaipNetwork,o=this.getAdapter(i==null?void 0:i.chainNamespace);n&&(await Promise.all(r.map(async c=>{var l,d,u;try{const h=Ue.getProvider(c),p=this.getCaipNetwork(c),g=this.getAdapter(c);await(g==null?void 0:g.connect({...e,provider:h,socialUri:void 0,chainId:p==null?void 0:p.id,rpcUrl:(u=(d=(l=p==null?void 0:p.rpcUrls)==null?void 0:l.default)==null?void 0:d.http)==null?void 0:u[0]}))&&(B.addConnectedNamespace(c),B.removeDisconnectedConnectorId(e.id,c),this.setStatus("connected",c),this.syncConnectedWalletInfo(c))}catch(h){$t.warn(Vt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,Vt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(c,h instanceof Error?h.message:void 0),Vt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),i&&await(o==null?void 0:o.switchNetwork({caipNetwork:i})))}getApprovedCaipNetworksData(){var s,n,r,i,o;if(Ue.getProviderId(m.state.activeChain)===Me.CONNECTOR_TYPE_WALLET_CONNECT){const a=(n=(s=this.universalProvider)==null?void 0:s.session)==null?void 0:n.namespaces;return{supportsAllNetworks:((o=(i=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:i.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=Ue.getProviderId(s);if(e.chainNamespace===m.state.activeChain){const i=this.getAdapter(s);await(i==null?void 0:i.switchNetwork({caipNetwork:e}))}else if(this.setCaipNetwork(e),r===Me.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const i=this.getAddressByChainNamespace(s);i&&this.syncAccount({address:i,chainId:e.id,chainNamespace:s})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(s=>{const n=s.chains||[],r=s.accounts.map(i=>{const{chainId:o,chainNamespace:a}=tt.parseCaipAddress(i);return`${a}:${o}`});return Array.from(new Set([...n,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,n)=>{var i,o;const r=e==null?void 0:e.find(a=>a.namespace===n);return r?(r.construct({namespace:n,projectId:(i=this.options)==null?void 0:i.projectId,networks:(o=this.caipNetworks)==null?void 0:o.filter(({chainNamespace:a})=>a===n)}),s[n]=r):s[n]=new ZO({namespace:n,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e);const s=this.getAdapter(e);if(!s)throw new Error("adapter not found");await s.syncConnectors(),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)})),this.initAdapterController()}onConnectors(e){const s=this.getAdapter(e);s==null||s.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const n=B.getConnectionStatus();k.state.enableReconnect===!1?this.setStatus("disconnected",e):n==="connected"?this.setStatus("connecting",e):n==="disconnected"?(B.clearAddressCache(),this.setStatus(n,e)):this.setStatus(n,e),s.on("switchNetwork",({address:r,chainId:i})=>{var l,d;const o=this.getCaipNetworks().find(u=>u.id.toString()===i.toString()||u.caipNetworkId.toString()===i.toString()),a=m.state.activeChain===e,c=(d=(l=m.state.chains.get(e))==null?void 0:l.accountState)==null?void 0:d.address;if(o){const u=a&&r?r:c;u&&this.syncAccount({address:u,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(i)}),s.on("disconnect",()=>{const r=this.remoteFeatures.multiWallet,i=Array.from(z.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:e,closeModal:!r||i.length===0})}),s.on("connections",r=>{this.setConnections(r,e)}),s.on("pendingTransactions",()=>{const r=this.getAddress(e),i=m.state.activeCaipNetwork;!r||!(i!=null&&i.id)||this.updateNativeBalance(r,i.id,i.chainNamespace)}),s.on("accountChanged",({address:r,chainId:i,connector:o})=>{var d,u;this.handlePreviousConnectorConnection(o);const a=m.state.activeChain===e;o!=null&&o.provider&&(this.syncProvider({id:o.id,type:o.type,provider:o==null?void 0:o.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e));const c=(u=(d=m.getNetworkData(e))==null?void 0:d.caipNetwork)==null?void 0:u.id,l=i||c;a&&l?this.syncAccount({address:r,chainId:l,chainNamespace:e}):!a&&l?(this.syncAccountInfo(r,l,e),this.syncBalance({address:r,chainId:l,chainNamespace:e})):this.syncAccountInfo(r,i,e),B.addConnectedNamespace(e)})}async handlePreviousConnectorConnection(e){var c;const s=e==null?void 0:e.chain,n=e==null?void 0:e.id,r=q.getConnectorId(s),i=(c=k.state.remoteFeatures)==null?void 0:c.multiWallet,a=s&&n&&r&&r!==n&&!i;try{a&&await z.disconnect({id:r,namespace:s})}catch(l){console.warn("Error disconnecting previous connector",l)}}async createUniversalProviderForAdapter(e){var s,n,r;await this.getUniversalProvider(),this.universalProvider&&await((r=(n=(s=this.chainAdapters)==null?void 0:s[e])==null?void 0:n.setUniversalProvider)==null?void 0:r.call(n,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(e=>z.disconnect({namespace:e,initialDisconnect:!0})))}catch(e){console.error("Error disconnecting existing connections:",e)}}async reconnectWalletConnect(){await this.syncWalletConnectAccount();const e=this.getAddress();this.getCaipAddress()||B.deleteRecentWallet();const s=B.getRecentWallet();he.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:J.isMobile()?"mobile":"qrcode",name:(s==null?void 0:s.name)||"Unknown",reconnect:!0,view:ne.state.view,walletRank:s==null?void 0:s.order}})}async syncNamespaceConnection(e){try{e===U.CHAIN.EVM&&J.isSafeApp()&&q.setConnectorId(U.CONNECTOR_ID.SAFE,e);const s=q.getConnectorId(e);switch(this.setStatus("connecting",e),s){case U.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case U.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}onDisconnectNamespace(e){const{chainNamespace:s,closeModal:n}=e||{};m.resetAccount(s),m.resetNetwork(s),B.removeConnectedNamespace(s);const r=Array.from(m.state.chains.keys());(s?[s]:r).forEach(o=>B.addDisconnectedConnectorId(q.getConnectorId(o)||"",o)),q.removeConnectorId(s),Ue.resetChain(s),this.setUser(null,s),this.setStatus("disconnected",s),this.setConnectedWalletInfo(null,s),n!==!1&&pe.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(e=>{const s=this.getAdapter(e),n=this.getCaipAddress(e),r=this.getCaipNetwork(e);return s==null?void 0:s.syncConnections({connectToFirstConnector:!n,caipNetwork:r})}))}async syncAdapterConnection(e){var a,c,l,d;const s=this.getAdapter(e),n=this.getCaipNetwork(e),r=q.getConnectorId(e),o=q.getConnectors(e).find(u=>u.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(n!=null&&n.id))throw new Error("CaipNetwork not found");const u=await(s==null?void 0:s.syncConnection({namespace:e,id:o.id,chainId:n.id,rpcUrl:(l=(c=(a=n==null?void 0:n.rpcUrls)==null?void 0:a.default)==null?void 0:c.http)==null?void 0:l[0]}));u?(this.syncProvider({...u,chainNamespace:e}),await this.syncAccount({...u,chainNamespace:e}),this.setStatus("connected",e),he.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:u.address,properties:{method:"browser",name:((d=o.info)==null?void 0:d.name)||o.name||"Unknown",reconnect:!0,view:ne.state.view,walletRank:void 0}})):this.setStatus("disconnected",e)}catch{this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})}}async syncWalletConnectAccount(){var n,r;const e=Object.keys(((r=(n=this.universalProvider)==null?void 0:n.session)==null?void 0:r.namespaces)||{}),s=this.chainNamespaces.map(async i=>{var u,h,p,g,f;const o=this.getAdapter(i);if(!o)return;const a=((g=(p=(h=(u=this.universalProvider)==null?void 0:u.session)==null?void 0:h.namespaces)==null?void 0:p[i])==null?void 0:g.accounts)||[],c=(f=m.state.activeCaipNetwork)==null?void 0:f.id,l=a.find(w=>{const{chainId:E}=tt.parseCaipAddress(w);return E===(c==null?void 0:c.toString())})||a[0];if(l){const w=tt.validateCaipAddress(l),{chainId:E,address:I}=tt.parseCaipAddress(w);if(Ue.setProviderId(i,Me.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&m.state.activeCaipNetwork&&o.namespace!==U.CHAIN.EVM){const _=o.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:m.state.activeCaipNetwork});Ue.setProvider(i,_)}else Ue.setProvider(i,this.universalProvider);q.setConnectorId(U.CONNECTOR_ID.WALLET_CONNECT,i),B.addConnectedNamespace(i),await this.syncAccount({address:I,chainId:E,chainNamespace:i})}else e.includes(i)&&this.setStatus("disconnected",i);const d=this.getApprovedCaipNetworksData();this.syncConnectedWalletInfo(i),m.setApprovedCaipNetworksData(i,{approvedCaipNetworkIds:d.approvedCaipNetworkIds,supportsAllNetworks:d.supportsAllNetworks})});await Promise.all(s)}syncProvider({type:e,provider:s,id:n,chainNamespace:r}){Ue.setProviderId(r,e),Ue.setProvider(r,s),q.setConnectorId(n,r)}async syncAccount(e){var u,h;const s=e.chainNamespace===m.state.activeChain,n=m.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:i,chainNamespace:o}=e,{chainId:a}=B.getActiveNetworkProps(),c=(n==null?void 0:n.id)||a,l=((u=m.state.activeCaipNetwork)==null?void 0:u.name)===U.UNSUPPORTED_NETWORK_NAME,d=m.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!d)&&c){let p=this.getCaipNetworks().find(E=>E.id.toString()===c.toString()),g=this.getCaipNetworks().find(E=>E.chainNamespace===o);if(!d&&!p&&!g){const E=this.getApprovedCaipNetworkIds()||[],I=E.find(v=>{var T;return((T=tt.parseCaipNetworkId(v))==null?void 0:T.chainId)===c.toString()}),_=E.find(v=>{var T;return((T=tt.parseCaipNetworkId(v))==null?void 0:T.chainNamespace)===o});p=this.getCaipNetworks().find(v=>v.caipNetworkId===I),g=this.getCaipNetworks().find(v=>v.caipNetworkId===_||"deprecatedCaipNetworkId"in v&&v.deprecatedCaipNetworkId===_)}const f=p||g;(f==null?void 0:f.chainNamespace)===m.state.activeChain?k.state.enableNetworkSwitch&&!k.state.allowUnsupportedChain&&((h=m.state.activeCaipNetwork)==null?void 0:h.name)===U.UNSUPPORTED_NETWORK_NAME?m.showUnsupportedChainUI():this.setCaipNetwork(f):s||n&&this.setCaipNetworkOfNamespace(n,o),this.syncConnectedWalletInfo(o);const w=this.getAddress(o);Si.isLowerCaseMatch(r,w)||this.syncAccountInfo(r,f==null?void 0:f.id,o),s?await this.syncBalance({address:r,chainId:f==null?void 0:f.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:n==null?void 0:n.id,chainNamespace:o}),this.syncIdentity({address:r,chainId:i,chainNamespace:o})}}async syncAccountInfo(e,s,n){const r=this.getCaipAddress(n),i=s||(r==null?void 0:r.split(":")[1]);if(!i)return;const o=`${n}:${i}:${e}`;this.setCaipAddress(o,n,!0),await this.syncIdentity({address:e,chainId:i,chainNamespace:n})}async syncReownName(e,s){try{const n=await this.getReownName(e);if(n[0]){const r=n[0];this.setProfileName(r.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){var r;const s=q.getConnectorId(e),n=Ue.getProviderId(e);if(n===Me.CONNECTOR_TYPE_ANNOUNCED||n===Me.CONNECTOR_TYPE_INJECTED){if(s){const o=this.getConnectors().find(a=>{var u,h;const c=a.id===s,l=((u=a.info)==null?void 0:u.rdns)===s,d=(h=a.connectors)==null?void 0:h.some(p=>{var g;return p.id===s||((g=p.info)==null?void 0:g.rdns)===s});return c||l||!!d});if(o){const{info:a,name:c,imageUrl:l}=o,d=l||this.getConnectorImage(o);this.setConnectedWalletInfo({name:c,icon:d,...a},e)}}}else if(n===Me.CONNECTOR_TYPE_WALLET_CONNECT){const i=Ue.getProvider(e);i!=null&&i.session&&this.setConnectedWalletInfo({...i.session.peer.metadata,name:i.session.peer.metadata.name,icon:(r=i.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(s&&(s===U.CONNECTOR_ID.COINBASE_SDK||s===U.CONNECTOR_ID.COINBASE)){const i=this.getConnectors().find(l=>l.id===s),o=(i==null?void 0:i.name)||"Coinbase Wallet",a=(i==null?void 0:i.imageUrl)||this.getConnectorImage(i),c=i==null?void 0:i.info;this.setConnectedWalletInfo({...c,name:o,icon:a},e)}}async syncBalance(e){!qh.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(n=>{var r;return n.id.toString()===((r=e.chainId)==null?void 0:r.toString())})||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,n){const r=this.getAdapter(n),i=m.getCaipNetworkByNamespace(n,s);if(r){const o=await r.getBalance({address:e,chainId:s,caipNetwork:i,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,n),o}}async initializeUniversalAdapter(){var n,r,i,o,a,c,l,d,u,h;const e=CO.createLogger((p,...g)=>{p&&this.handleAlertError(p),console.error(...g)}),s={projectId:(n=this.options)==null?void 0:n.projectId,metadata:{name:(r=this.options)!=null&&r.metadata?(i=this.options)==null?void 0:i.metadata.name:"",description:(o=this.options)!=null&&o.metadata?(a=this.options)==null?void 0:a.metadata.description:"",url:(c=this.options)!=null&&c.metadata?(l=this.options)==null?void 0:l.metadata.url:"",icons:(d=this.options)!=null&&d.metadata?(u=this.options)==null?void 0:u.metadata.icons:[""]},logger:e};k.setManualWCControl(!!((h=this.options)!=null&&h.manualWCControl)),this.universalProvider=this.options.universalProvider??await YT.init(s),k.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(e=>{En.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:s=>{z.setUri(s)},onConnect:s=>{const{address:n}=J.getAccount(s[0]);z.finalizeWcConnection(n)},onDisconnect:()=>{m.state.noAdapters&&this.resetAccount(e),z.resetWcConnection()},onChainChanged:s=>{const n=m.state.activeChain,r=n&&q.state.activeConnectorIds[n]===U.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(m.state.noAdapters||r)){const i=this.getCaipNetworks().find(a=>a.id.toString()===s.toString()||a.caipNetworkId.toString()===s.toString()),o=this.getCaipNetwork();if(!i){this.setUnsupportedNetwork(s);return}(o==null?void 0:o.id.toString())!==(i==null?void 0:i.id.toString())&&(o==null?void 0:o.chainNamespace)===(i==null?void 0:i.chainNamespace)&&this.setCaipNetwork(i)}},onAccountsChanged:s=>{const n=m.state.activeChain,r=n&&q.state.activeConnectorIds[n]===U.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(m.state.noAdapters||r)){const i=s==null?void 0:s[0];i&&this.syncAccount({address:i.address,chainId:i.chainId,chainNamespace:i.chainNamespace})}}})})}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&J.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){he.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}getDisabledCaipNetworks(){const e=m.getAllApprovedCaipNetworkIds(),s=m.getAllRequestedCaipNetworks();return J.sortRequestedNetworks(e,s).filter(r=>m.isCaipNetworkDisabled(r))}handleAlertError(e){const s=Object.entries(Vt.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[n,r]=s??[],{message:i,alertErrorKey:o}=r??{};if(n&&i&&!this.reportedAlertErrors[n]){const a=Vt.ALERT_ERRORS[o];a&&($t.open(a,"error"),this.reportedAlertErrors[n]=!0)}}getAdapter(e){var s;if(e)return(s=this.chainAdapters)==null?void 0:s[e]}createAdapter(e){var r,i;if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const n=e;n.namespace=s,n.construct({namespace:s,projectId:(r=this.options)==null?void 0:r.projectId,networks:(i=this.caipNetworks)==null?void 0:i.filter(({chainNamespace:o})=>o===s)}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=n)}async open(e){await this.injectModalUi(),e!=null&&e.uri&&z.setUri(e.uri);const{isSwap:s,isSend:n}=this.toModalOptions();return s(e)?pe.open({...e,data:{swap:e.arguments}}):n(e)&&e.arguments?this.openSend(e.arguments):pe.open(e)}async close(){await this.injectModalUi(),pe.close()}setLoading(e,s){pe.setLoading(e,s)}async disconnect(e){await z.disconnect({namespace:e})}getSIWX(){return k.state.siwx}getError(){return""}getChainId(){var e;return(e=m.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e,{throwOnFailure:s=!1}={}){const n=this.getCaipNetworks().find(r=>r.id===e.id);if(!n){$t.open(Vt.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await m.switchActiveNetwork(n,{throwOnFailure:s})}getWalletProvider(){return m.state.activeChain?Ue.state.providers[m.state.activeChain]:null}getWalletProviderType(){return Ue.getProviderId(m.state.activeChain)}subscribeProviders(e){return Ue.subscribeProviders(e)}getThemeMode(){return Dt.state.themeMode}getThemeVariables(){return Dt.state.themeVariables}setThemeMode(e){Dt.setThemeMode(e),il(Dt.state.themeMode)}setTermsConditionsUrl(e){k.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){k.setPrivacyPolicyUrl(e)}setThemeVariables(e){Dt.setThemeVariables(e),XO(Dt.state.themeVariables)}subscribeTheme(e){return Dt.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?z.subscribe(e):($t.open(U.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){var n,r;if(e)return(r=(n=m.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.connectedWalletInfo;const s=m.getAccountData();return s==null?void 0:s.connectedWalletInfo}getAccount(e){const s=e||m.state.activeChain,n=q.getAuthConnector(s),r=m.getAccountData(s),i=B.getConnectedConnectorId(m.state.activeChain),o=z.getConnections(s);if(!s)throw new Error("AppKit:getAccount - namespace is required");const a=o.flatMap(c=>c.accounts.map(({address:l,type:d,publicKey:u})=>J.createAccount(s,l,d||"eoa",u)));if(r)return{allAccounts:a,caipAddress:r.caipAddress,address:J.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:n&&i===U.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:B.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:ts(s),isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const n=()=>{const r=this.getAccount(s);r&&e(r)};s?m.subscribeChainProp("accountState",n,s):m.subscribe(n),q.subscribe(n)}subscribeNetwork(e){return m.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s==null?void 0:s.id,caipNetworkId:s==null?void 0:s.caipNetworkId})})}subscribeWalletInfo(e,s){return s?m.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo),s):m.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo))}subscribeShouldUpdateToAddress(e){m.subscribeChainProp("accountState",s=>e(s==null?void 0:s.shouldUpdateToAddress))}subscribeCaipNetworkChange(e){m.subscribeKey("activeCaipNetwork",e)}getState(){return Ws.state}getRemoteFeatures(){return k.state.remoteFeatures}subscribeState(e){return Ws.subscribe(e)}subscribeRemoteFeatures(e){return k.subscribeKey("remoteFeatures",e)}showErrorMessage(e){vs.showError(e)}showSuccessMessage(e){vs.showSuccess(e)}getEvent(){return{...he.state}}subscribeEvents(e){return he.subscribe(e)}replace(e){ne.replace(e)}redirect(e){ne.push(e)}popTransactionStack(e){ne.popTransactionStack(e)}isOpen(){return pe.state.open}isTransactionStackEmpty(){return ne.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){k.setFeatures(e)}updateRemoteFeatures(e){k.setRemoteFeatures(e)}updateOptions(e){const n={...k.state||{},...e};k.setOptions(n)}setConnectMethodsOrder(e){k.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){k.setWalletFeaturesOrder(e)}setCollapseWallets(e){k.setCollapseWallets(e)}setSocialsOrder(e){k.setSocialsOrder(e)}getConnectMethodsOrder(){return oi.getConnectOrderMethod(k.state.features,q.getConnectors())}addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const n=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(r=>r.id===n.id)||m.addNetwork(n)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(r=>r.id===s)&&m.removeNetwork(e,s)}}let Dh=!1;class kg extends t2{async open(e){q.isConnected()||await super.open(e)}async close(){var e;if(await super.close(),this.options.manualWCControl){const s=(e=m.getAccountData(this.activeChainNamespace))==null?void 0:e.address;z.finalizeWcConnection(s)}}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!Dh&&J.isClient()){if(await Ao(()=>import("./basic-ca749c4c.js"),["assets/basic-ca749c4c.js","assets/index-372705ba.js","assets/index-2ef9f1d1.js","assets/index-a8255d1c.css","assets/index-74e34dfb.js","assets/index-c1c8440f.js"]),await Ao(()=>import("./w3m-modal-26eff9d9.js"),["assets/w3m-modal-26eff9d9.js","assets/index-372705ba.js","assets/index-2ef9f1d1.js","assets/index-a8255d1c.css","assets/index-74e34dfb.js","assets/index-c1c8440f.js"]),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!k.state.disableAppend&&!k.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}Dh=!0}}}const s2="1.8.11";function n2(t){return new kg({...t,basic:!0,sdkVersion:`html-core-${s2}`})}const Y2=Object.freeze(Object.defineProperty({__proto__:null,AppKit:kg,createAppKit:n2},Symbol.toStringTag,{value:"Module"}));export{Y2 as $,Q as A,re as B,q as C,ul as D,he as E,$t as F,ts as G,Si as H,Qt as I,ds as J,JO as K,AO as L,pe as M,cm as N,k as O,z2 as P,nl as Q,ne as R,vs as S,Dt as T,Ng as U,Lr as V,oi as W,qh as X,te as Y,Ki as Z,Z as _,J as a,z as b,U as c,K2 as d,Zt as e,oc as f,Jh as g,G2 as h,vo as i,Qn as j,js as k,ye as l,H2 as m,m as n,br as o,B as p,Xe as q,V2 as r,mn as s,ke as t,st as u,nt as v,ns as w,W2 as x,Zh as y,ew as z};
|