@wormhole-foundation/wormhole-connect 4.0.0-beta.1-development → 4.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.
Files changed (59) hide show
  1. package/dist/main.js +1 -1
  2. package/lib/{aptos-5b4F4UXd.mjs → aptos-Dol0ReEK.mjs} +2 -2
  3. package/lib/{aptos-B_Yz-0gh.js → aptos-eGdJuKke.js} +1 -1
  4. package/lib/{basic-BdiYk8Hf.js → basic-B3aoOwRb.js} +1 -1
  5. package/lib/{basic-BclwqsOq.mjs → basic-BI1HDLIO.mjs} +3 -3
  6. package/lib/{basic-HasHL_DG.mjs → basic-C6oQe5cg.mjs} +3 -3
  7. package/lib/{basic-CuO6iz8a.js → basic-pJmrDH53.js} +1 -1
  8. package/lib/{constants-DnbaS3cF.mjs → constants-BPs5UFxq.mjs} +3 -3
  9. package/lib/constants-BqHCu7gS.js +1 -0
  10. package/lib/{core-COM78LTW.js → core-BN_eDiBJ.js} +3 -3
  11. package/lib/{core-DT_3gIqi.mjs → core-BZzw8R4f.mjs} +4 -4
  12. package/lib/{evm-Dv-WYu07.js → evm-BdbjSrMR.js} +1 -1
  13. package/lib/{evm-DoVrPE_X.mjs → evm-CUhPokEi.mjs} +3 -3
  14. package/lib/{evm-CUR4-a7F.mjs → evm-IC5cigOX.mjs} +3 -3
  15. package/lib/{evm-CoLwXequ.js → evm-bdCQPjof.js} +2 -2
  16. package/lib/hosted.js +1 -1
  17. package/lib/hosted.mjs +1 -1
  18. package/lib/{index-cggXdVJu.mjs → index-1boJ8yzF.mjs} +1 -1
  19. package/lib/{index-C8HxYDNY.js → index-943_uCEO.js} +1 -1
  20. package/lib/{index-CkGYgQTz.js → index-BeBO_sCU.js} +1 -1
  21. package/lib/{index-DaY7_eQ6.js → index-Blvg4PFN.js} +2 -2
  22. package/lib/{index-P9DbJOzh.js → index-BnMkdrhM.js} +1 -1
  23. package/lib/{index-B1KwS33G.mjs → index-CQ0RB2r3.mjs} +1 -1
  24. package/lib/{index-DZaOh3F9.mjs → index-CR3DmYPt.mjs} +3 -3
  25. package/lib/{index-BaYN-RHF.js → index-CbFvm_Mr.js} +1 -1
  26. package/lib/{index-B7Afz_5P.js → index-Cv9hvmqc.js} +1 -1
  27. package/lib/{index-cCBQV2Yv.js → index-D61fXWwH.js} +2 -2
  28. package/lib/{index-DlmQ0_RF.mjs → index-DJs1h8_N.mjs} +10 -10
  29. package/lib/{index-DGzoIr_I.mjs → index-N8cPdMnf.mjs} +1 -1
  30. package/lib/{index-B3idKQJG.mjs → index-UOvy4usi.mjs} +1 -1
  31. package/lib/{index-B2sVzSwb.mjs → index-dU3yVyBt.mjs} +1 -1
  32. package/lib/{index.es-5ecqX8B9.mjs → index.es-B5hLka3L.mjs} +3 -3
  33. package/lib/{index.es-owVcNlof.js → index.es-CSmeunOk.js} +3 -3
  34. package/lib/{index.es-LBG64XJ6.js → index.es-E2DQPkYK.js} +1 -1
  35. package/lib/{index.es-zNH_KzcH.mjs → index.es-Vlpe_OYB.mjs} +1 -1
  36. package/lib/index.js +1 -1
  37. package/lib/index.mjs +2 -2
  38. package/lib/mayan.js +1 -1
  39. package/lib/mayan.mjs +1 -1
  40. package/lib/{secp256k1-BF6Vm50D.mjs → secp256k1-B-wUOgWh.mjs} +1 -1
  41. package/lib/{secp256k1-DRTQ6WrU.js → secp256k1-BAjH_sHz.js} +1 -1
  42. package/lib/{secp256k1-BfK5OWRP.mjs → secp256k1-CpJIg24C.mjs} +1 -1
  43. package/lib/{secp256k1-Bb6lbAjK.js → secp256k1-Ds1M1Mtb.js} +1 -1
  44. package/lib/{secp256k1-D_GNj8sK.js → secp256k1-PbbUc2aU.js} +1 -1
  45. package/lib/{secp256k1-CqT-a-I8.mjs → secp256k1-YWWAmpaN.mjs} +1 -1
  46. package/lib/{solana-C1puc64V.mjs → solana-Bh5bkUXQ.mjs} +7 -7
  47. package/lib/{solana-CtBdJ6Wt.js → solana-sjjxa4_B.js} +4 -4
  48. package/lib/{solanaEmbed.esm-BpIKVhXq.js → solanaEmbed.esm-CDt8Bk0U.js} +1 -1
  49. package/lib/{solanaEmbed.esm-NdE_DQuw.mjs → solanaEmbed.esm-DGgxfQDB.mjs} +2 -2
  50. package/lib/{sui-DdujB9Bc.js → sui-Do5RtJvP.js} +1 -1
  51. package/lib/{sui-BW7tMLZs.mjs → sui-tKXg9e-c.mjs} +2 -2
  52. package/lib/{tokens-DI-tPIbd.mjs → tokens-CNITO7DN.mjs} +1 -1
  53. package/lib/{tokens-DJos2DwM.js → tokens-DhBcLH6x.js} +1 -1
  54. package/lib/{w3m-modal-DSY2qJYP.js → w3m-modal-BUP-c20y.js} +1 -1
  55. package/lib/{w3m-modal-C32eQxEe.mjs → w3m-modal-Bj2tG9wb.mjs} +2 -2
  56. package/lib/{w3m-modal-DgqSQLqZ.js → w3m-modal-CGeDlu49.js} +1 -1
  57. package/lib/{w3m-modal-B2VF8j7W.mjs → w3m-modal-D78VqEEI.mjs} +2 -2
  58. package/package.json +1 -1
  59. package/lib/constants-abC7FLXq.js +0 -1
@@ -1,5 +1,5 @@
1
- "use strict";const N=require("./web3-BKaP497Y.js"),se=require("./index-DaY7_eQ6.js"),jb=require("./util-G2vxTeU2.js"),Rb=require("./wallets-DLkIKXkb.js"),Xt=require("./index-cCBQV2Yv.js"),$a=require("./unsignedTransaction-DL3WyIkF.js"),Nu=require("./signer-MBixef_P.js"),h=require("./index.es-LBG64XJ6.js"),k=require("./lit-element-CwBgQkCS.js");require("./browser-ponyfill-VhIu9z_I.js");const gn=require("./http-Dz7hx6tx.js");class Mt extends Error{constructor(e,t){super(e),this.error=t}}class Ri extends Mt{constructor(){super(...arguments),this.name="WalletNotReadyError"}}class Ub extends Mt{constructor(){super(...arguments),this.name="WalletLoadError"}}class ln extends Mt{constructor(){super(...arguments),this.name="WalletConfigError"}}class ic extends Mt{constructor(){super(...arguments),this.name="WalletConnectionError"}}class uf extends Mt{constructor(){super(...arguments),this.name="WalletDisconnectedError"}}class xo extends Mt{constructor(){super(...arguments),this.name="WalletDisconnectionError"}}class Es extends Mt{constructor(){super(...arguments),this.name="WalletAccountError"}}class gr extends Mt{constructor(){super(...arguments),this.name="WalletPublicKeyError"}}class Ke extends Mt{constructor(){super(...arguments),this.name="WalletNotConnectedError"}}class sr extends Mt{constructor(){super(...arguments),this.name="WalletSendTransactionError"}}class rt extends Mt{constructor(){super(...arguments),this.name="WalletSignTransactionError"}}class Mo extends Mt{constructor(){super(...arguments),this.name="WalletSignMessageError"}}class Cu extends Mt{constructor(){super(...arguments),this.name="WalletSignInError"}}class Lb extends Mt{constructor(){super(...arguments),this.name="WalletWindowClosedError"}}var ge;(function(s){s.Installed="Installed",s.NotDetected="NotDetected",s.Loadable="Loadable",s.Unsupported="Unsupported"})(ge||(ge={}));class df extends N.EventEmitter{get connected(){return!!this.publicKey}async autoConnect(){await this.connect()}async prepareTransaction(e,t,i={}){const r=this.publicKey;if(!r)throw new Ke;return e.feePayer=e.feePayer||r,e.recentBlockhash=e.recentBlockhash||(await t.getLatestBlockhash({commitment:i.preflightCommitment,minContextSlot:i.minContextSlot})).blockhash,e}}function Oo(s){if(typeof window>"u"||typeof document>"u")return;const e=[];function t(){if(s())for(const n of e)n()}const i=setInterval(t,1e3);e.push(()=>clearInterval(i)),document.readyState==="loading"&&(document.addEventListener("DOMContentLoaded",t,{once:!0}),e.push(()=>document.removeEventListener("DOMContentLoaded",t))),document.readyState!=="complete"&&(window.addEventListener("load",t,{once:!0}),e.push(()=>window.removeEventListener("load",t))),t()}function ui(s){return"version"in s}class _h extends df{async sendTransaction(e,t,i={}){let r=!0;try{if(ui(e)){if(!this.supportedTransactionVersions)throw new sr("Sending versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(e.version))throw new sr(`Sending transaction version ${e.version} isn't supported by this wallet`);try{e=await this.signTransaction(e);const n=e.serialize();return await t.sendRawTransaction(n,i)}catch(n){throw n instanceof rt?(r=!1,n):new sr(n?.message,n)}}else try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n?.length&&e.partialSign(...n),e=await this.signTransaction(e);const a=e.serialize();return await t.sendRawTransaction(a,o)}catch(n){throw n instanceof rt?(r=!1,n):new sr(n?.message,n)}}catch(n){throw r&&this.emit("error",n),n}}async signAllTransactions(e){for(const i of e)if(ui(i)){if(!this.supportedTransactionVersions)throw new rt("Signing versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(i.version))throw new rt(`Signing transaction version ${i.version} isn't supported by this wallet`)}const t=[];for(const i of e)t.push(await this.signTransaction(i));return t}}class Do extends _h{}function zb(s){return se.StandardConnect in s.features&&se.StandardEvents in s.features&&(se.SolanaSignAndSendTransaction in s.features||se.SolanaSignTransaction in s.features)}var vo;(function(s){s.Mainnet="mainnet-beta",s.Testnet="testnet",s.Devnet="devnet"})(vo||(vo={}));const Fb="Bitget";class qb extends Do{constructor(e={}){super(),this.name=Fb,this.url="https://web3.bitget.com",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgdmlld0JveD0iMCAwIDUxMiA1MTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiBmaWxsPSIjMDAxRjI5Ii8+CjxwYXRoIGQ9Ik0yMTkuOTQ4IDk1LjcwMjJDMjAxLjYyMyA5NS42OTI5IDE4My4zMyA5NS42ODM1IDE2NC45NDEgOTUuNzExNkMxNTMuODIyIDk1LjcxMTYgMTQ5LjY1MSAxMDkuNjcxIDE1Ny45MjEgMTE3LjkzOUwyODMuMDk4IDI0My4xMTdDMjg3LjAwNCAyNDYuNjkgMjg5LjQ0MSAyNTAuNTc0IDI4OS41MyAyNTUuNjkzQzI4OS40NDEgMjYwLjgxMiAyODcuMDA0IDI2NC42OTYgMjgzLjA5OCAyNjguMjY5TDE1Ny45MjEgMzkzLjQ0NkMxNDkuNjUxIDQwMS43MTUgMTUzLjgyMiA0MTUuNjc0IDE2NC45NDEgNDE1LjY3NEMxODMuMzMgNDE1LjcwMiAyMDEuNjIzIDQxNS42OTMgMjE5Ljk0OCA0MTUuNjgzQzIyOS4xMjIgNDE1LjY3OSAyMzguMzA1IDQxNS42NzQgMjQ3LjUxMSA0MTUuNjc0QzI1OS41NTUgNDE1LjY3NCAyNjYuNzIgNDA5LjI0IDI3My4xNTQgNDAyLjgwNUwzODYuMDQ3IDI4OS45MTJDMzk1LjA1NyAyODAuOTAyIDQwMy4xMTkgMjY4LjkzOSA0MDMuMDA5IDI1NS42OTNDNDAzLjExOSAyNDIuNDQ3IDM5NS4wNTcgMjMwLjQ4NCAzODYuMDQ3IDIyMS40NzRMMjczLjE1NCAxMDguNThDMjY2LjcyIDEwMi4xNDYgMjU5LjU1NSA5NS43MTE2IDI0Ny41MTEgOTUuNzExNkMyMzguMzA1IDk1LjcxMTYgMjI5LjEyMiA5NS43MDY5IDIxOS45NDggOTUuNzAyMloiIGZpbGw9IiMwMEYwRkYiLz4KPC9zdmc+Cg==",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ge.Unsupported&&Oo(()=>window.bitkeep?.solana?.isBitKeep?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.bitkeep.solana;let t;try{t=await e.getAccount()}catch(r){throw new Es(r?.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new gr(r?.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new xo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{const{signature:i}=await t.signMessage(e);return i}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Bb="Clover";class Hb extends Do{constructor(e={}){super(),this.name=Bb,this.url="https://clv.org",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDgiIGhlaWdodD0iNDgiIHZpZXdCb3g9IjAgMCA0OCA0OCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTM2LjQ4IDBIMTEuNTJDNS4xNTc2OCAwIDAgNS4xNTc2OCAwIDExLjUyVjM2LjQ4QzAgNDIuODQyMyA1LjE1NzY4IDQ4IDExLjUyIDQ4SDM2LjQ4QzQyLjg0MjMgNDggNDggNDIuODQyMyA0OCAzNi40OFYxMS41MkM0OCA1LjE1NzY4IDQyLjg0MjMgMCAzNi40OCAwWiIgZmlsbD0idXJsKCNwYWludDBfbGluZWFyXzc5MTBfMTYzMzUxKSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTI0LjAwMDYgMzkuMzYwNkMzMi40ODM3IDM5LjM2MDYgMzkuMzYwNiAzMi40ODM3IDM5LjM2MDYgMjQuMDAwNkMzOS4zNjA2IDE1LjUxNzUgMzIuNDgzNyA4LjY0MDYyIDI0LjAwMDYgOC42NDA2MkMxNS41MTc1IDguNjQwNjIgOC42NDA2MiAxNS41MTc1IDguNjQwNjIgMjQuMDAwNkM4LjY0MDYyIDMyLjQ4MzcgMTUuNTE3NSAzOS4zNjA2IDI0LjAwMDYgMzkuMzYwNlpNMjEuMjg5OSAxNS44Njg4SDI2LjcxMVYyMS4zNDdIMjEuMjkwNFYyNi42NTRIMjYuNzExVjMyLjEzMjJIMjEuMjg5OVYyNi44MjUySDE1Ljg2OTNWMjEuMzQ3SDIxLjI4OTlWMTUuODY4OFpNMjYuNzEyIDIxLjM0N0gzMi4xMzMxVjI2LjgyNTJIMjYuNzEyVjIxLjM0N1oiIGZpbGw9ImJsYWNrIi8+CjxkZWZzPgo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfNzkxMF8xNjMzNTEiIHgxPSI0OCIgeTE9Ii0xLjQzMDUxZS0wNiIgeDI9IjEuNDMwNTFlLTA2IiB5Mj0iNDgiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0E5RkZFMCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM4NkQ1RkYiLz4KPC9saW5lYXJHcmFkaWVudD4KPC9kZWZzPgo8L3N2Zz4=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ge.Unsupported&&Oo(()=>window.clover_solana?.isCloverWallet?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.clover_solana;let t;try{t=await e.getAccount()}catch(r){throw new Es(r?.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new gr(r?.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{const{signature:i}=await t.signMessage(e);return Uint8Array.from(i)}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}function Wb(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const u=s.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,u++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let m=l[p],A=0;for(let C=g-1;(m!==0||A<d)&&C!==-1;C--,A++)m+=256*w[C]>>>0,w[C]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let b=g-d;for(;b!==g&&w[b]===0;)b++;let v=i.repeat(u);for(;b<g;++b)v+=s.charAt(w[b]);return v}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,p=0;for(;l[u]===i;)d++,u++;const f=(l.length-u)*r+1>>>0,g=new Uint8Array(f);for(;u<l.length;){const m=l.charCodeAt(u);if(m>255)return;let A=e[m];if(A===255)return;let C=0;for(let S=f-1;(A!==0||C<p)&&S!==-1;S--,C++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=C,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const b=new Uint8Array(d+(f-w));let v=d;for(;w!==f;)b[v++]=g[w++];return b}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Vb="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Sc=Wb(Vb),Kb="Coin98";class Gb extends Do{constructor(e={}){super(),this.name=Kb,this.url="https://coin98.com",this.icon="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA3NiA3NSI+CiAgPGRlZnM+CiAgICA8bGluZWFyR3JhZGllbnQgaWQ9ImEiIHgxPSIxMDEuNjgxJSIgeDI9Ii0xLjU1NyUiIHkxPSIxNS4yNjglIiB5Mj0iODQuOTE3JSI+CiAgICAgIDxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9IiNGMUQ5NjEiLz4KICAgICAgPHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjQ0RBMTQ2Ii8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogIDwvZGVmcz4KICA8ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgPHJlY3Qgd2lkdGg9Ijc1IiBoZWlnaHQ9Ijc1IiBmaWxsPSIjMDAwIiByeD0iMTYiLz4KICAgIDxwYXRoIGZpbGw9InVybCgjYSkiIGZpbGwtcnVsZT0ibm9uemVybyIgZD0iTTYxLjQ0IDBhMTMuNzE0IDEzLjcxNCAwIDAgMSA5LjY4IDQuMDEgMTMuNjYxIDEzLjY2MSAwIDAgMSA0LjAwOCA5LjY2OHY0Ny42NDZhMTMuNjYgMTMuNjYgMCAwIDEtNC4wMDcgOS42NjZBMTMuNzEzIDEzLjcxMyAwIDAgMSA2MS40NCA3NUgxMy42ODZhMTMuNzEzIDEzLjcxMyAwIDAgMS05LjY4LTQuMDFBMTMuNjYgMTMuNjYgMCAwIDEgMCA2MS4zMjRWMTMuNjc4YzAtMy42MjUgMS40NC03LjEwMiA0LjAwNy05LjY2N0ExMy43MTQgMTMuNzE0IDAgMCAxIDEzLjY4NyAwWk0yMC4wNjMgNDYuMjMxaC00LjgyNWExMC4wMzIgMTAuMDMyIDAgMCAwIDIuOTQ2IDcuMDg2IDEwLjA3IDEwLjA3IDAgMCAwIDcuMSAyLjk0MiAxMC4wNjUgMTAuMDY1IDAgMCAwIDcuMTA4LTIuOTM1IDEwLjAzIDEwLjAzIDAgMCAwIDIuOTQ2LTcuMDkzaC00LjgyNGE1LjIwNyA1LjIwNyAwIDAgMS0xLjUzIDMuNjg4IDUuMjI1IDUuMjI1IDAgMCAxLTMuNjk2IDEuNTI4IDUuMjM0IDUuMjM0IDAgMCAxLTMuNjk1LTEuNTI4IDUuMjEzIDUuMjEzIDAgMCAxLTEuNTMtMy42ODhaTTU0LjMzIDMzLjcxNmExMS43NjMgMTEuNzYzIDAgMCAwLTEyLjc5OSAyLjUzOEExMS42OTcgMTEuNjk3IDAgMCAwIDM4Ljk5IDQ5LjAzYTExLjcyMyAxMS43MjMgMCAwIDAgNC4zMjggNS4yNTkgMTEuNzU3IDExLjc1NyAwIDAgMCA2LjUyNiAxLjk3IDExLjc2NiAxMS43NjYgMCAwIDAgOC4yOS0zLjQzNSAxMS43MiAxMS43MiAwIDAgMCAzLjQ0Mi04LjI3NCAxMS43MDIgMTEuNzAyIDAgMCAwLTEuOTc1LTYuNTE0IDExLjczNiAxMS43MzYgMCAwIDAtNS4yNjktNC4zMlptLTQuNDg4IDMuOTJhNi45MzcgNi45MzcgMCAwIDEgNC45IDIuMDI1IDYuOTEgNi45MSAwIDAgMSAyLjAyOCA0Ljg5MiA2Ljg5NyA2Ljg5NyAwIDAgMS0xLjE3IDMuODM0IDYuOTMyIDYuOTMyIDAgMCAxLTEwLjY0MyAxLjA0MiA2LjkwMiA2LjkwMiAwIDAgMS0xLjUtNy41MjIgNi45MDkgNi45MDkgMCAwIDEgMi41NDQtMy4xIDYuOTI4IDYuOTI4IDAgMCAxIDMuODQxLTEuMTY3Wm0uMTcgNC41NTJhMi40MzEgMi40MzEgMCAwIDAtMi4yNDEgMS4xNTQgMi40MTggMi40MTggMCAwIDAtLjM1NiAxLjI1NyAyLjM5NSAyLjM5NSAwIDAgMCAxLjYxOSAyLjI5djEuNzUzaDEuNjE4di0xLjc1NGEyLjQyNyAyLjQyNyAwIDAgMCAxLjU5NC0xLjk1IDIuNDE4IDIuNDE4IDAgMCAwLTEtMi4zMSAyLjQzMSAyLjQzMSAwIDAgMC0xLjIzNC0uNDRabS0yMC4yMi0yMi41NTJhMTEuNzYyIDExLjc2MiAwIDAgMC0xMi43OTYgMi41MzEgMTEuNjk3IDExLjY5NyAwIDAgMC0yLjU1NCAxMi43NjkgMTEuNzIzIDExLjcyMyAwIDAgMCA0LjMyIDUuMjYyIDExLjc1NyAxMS43NTcgMCAwIDAgMTQuODI1LTEuNDQ2IDExLjcxNyAxMS43MTcgMCAwIDAgMy40NDUtOC4yODQgMTEuNzAzIDExLjcwMyAwIDAgMC0xLjk3NC02LjUxMiAxMS43MzYgMTEuNzM2IDAgMCAwLTUuMjY2LTQuMzJabS00LjUxIDMuOTE3YTYuOTQ1IDYuOTQ1IDAgMCAxIDQuODk3IDIuMDI5IDYuOTE4IDYuOTE4IDAgMCAxIDIuMDMyIDQuODg2IDYuOTA2IDYuOTA2IDAgMCAxLTEuMTY4IDMuODQyIDYuOTQgNi45NCAwIDAgMS0xMC42NiAxLjA0OCA2LjkxMSA2LjkxMSAwIDAgMS0xLjUtNy41MzYgNi45MTggNi45MTggMCAwIDEgMi41NS0zLjEwMyA2LjkzNyA2LjkzNyAwIDAgMSAzLjg1LTEuMTY2Wm0yNC41Ni00LjgxYTEwLjA1OSAxMC4wNTkgMCAwIDAtNy4xMDMgMi45NCAxMC4wMiAxMC4wMiAwIDAgMC0yLjk0IDcuMDkgOS45IDkuOSAwIDAgMCAxLjIzIDQuNzk1IDEzLjU3NSAxMy41NzUgMCAwIDEgNC4yMTQtMi4zMjIgNS4wODIgNS4wODIgMCAwIDEtLjYyNS0yLjQ3NyA1LjIwNiA1LjIwNiAwIDAgMSAxLjUwMy0zLjczNiA1LjIyMyA1LjIyMyAwIDAgMSAzLjcyMi0xLjU1NCA1LjIzNCA1LjIzNCAwIDAgMSAzLjcyIDEuNTU0IDUuMjEzIDUuMjEzIDAgMCAxIDEuNTA1IDMuNzM2IDUuMjc5IDUuMjc5IDAgMCAxLS42MjMgMi40NzMgMTMuNTc0IDEzLjU3NCAwIDAgMSA0LjIxMyAyLjMyMiA5LjkwMyA5LjkwMyAwIDAgMCAxLjIzLTQuNzk1IDEwLjAzMiAxMC4wMzIgMCAwIDAtMi45NDYtNy4wODYgMTAuMDcgMTAuMDcgMCAwIDAtNy4xLTIuOTRabS0yMy43NSA3Ljk5aC0xLjYxN3YxLjc1YTIuNDE5IDIuNDE5IDAgMCAwLTEuNTgyIDIuNjg3IDIuNDE0IDIuNDE0IDAgMCAwIDIuMzkgMi4wMDYgMi40NSAyLjQ1IDAgMCAwIDEuNTU1LS41NzQgMi40MTQgMi40MTQgMCAwIDAtLjc0Ni00LjExOXYtMS43NVoiLz4KICA8L2c+Cjwvc3ZnPgo=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ge.Unsupported&&Oo(()=>window.coin98?.sol?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){return!!this._wallet?.isConnected()}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.coin98.sol;let t;try{t=(await e.connect())[0]}catch(r){throw new Es(r?.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new gr(r?.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new xo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{const i=await t.request({method:"sol_sign",params:[e]}),r=new N.PublicKey(i.publicKey),n=Sc.decode(i.signature);return e.addSignature(r,N.Buffer.from(n)),e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{const i=await t.request({method:"sol_signAllTransactions",params:[e]}),r=new N.PublicKey(i.publicKey),n=i.signatures;return e.map((o,a)=>{const c=Sc.decode(n[a]);return o.addSignature(r,N.Buffer.from(c)),o})}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{const i=await t.request({method:"sol_signMessage",params:[e]});return Sc.decode(i.signature)}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Yb="Nightly";class _u extends Do{constructor(){super(),this.name=Yb,this.url="https://nightly.app",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iOTYiIGhlaWdodD0iOTYiIHZpZXdCb3g9IjAgMCA5NiA5NiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQ4IDk2Qzc0LjUwOTcgOTYgOTYgNzQuNTA5NyA5NiA0OEM5NiAyMS40OTAzIDc0LjUwOTcgMCA0OCAwQzIxLjQ5MDMgMCAwIDIxLjQ5MDMgMCA0OEMwIDc0LjUwOTcgMjEuNDkwMyA5NiA0OCA5NloiIGZpbGw9IiM2RDczRjgiLz4KPHBhdGggZD0iTTQ4IDg1LjYzNTZDNDggODUuNjM1NiA1Mi40NTMzIDg1LjYzNTYgNTUuNDQgODIuNTg2N0M1OC45MTU1IDc5LjI4MDEgNTcuMzUxMSA3NS40MzEyIDYyLjI3NTUgNzEuNDMxMkM2Ni45ODY2IDY3LjY0NDUgNzIuOTI0NCA3MC4zMzc5IDcyLjkyNDQgNzAuMzM3OUM3Ny4wMjIyIDYyLjEyNDUgNzQuNzkxMSA1Mi41NjkgNzQuNzkxMSA1Mi41NjlDODEuNzY4OCAzNC4yNTc5IDc1Ljk2NDQgMjEuMTU1NyA3NC40NDQ0IDE3LjM2MDFDNjkuNDQ4OCAyNC4zMzc5IDYzLjE5MTEgMjkuMTczNCA1NS43OTU1IDMyLjQwOUM1My4yMjY2IDMxLjcwNjggNTAuNTk1NSAzMS4zMzM0IDQ4IDMxLjM2MDFDNDUuNDEzMyAzMS4zMzM0IDQyLjc3MzMgMzEuNzA2OCA0MC4yMDQ0IDMyLjQwOUMzMi44MTc3IDI5LjE2NDUgMjYuNTUxMSAyNC4zMzc5IDIxLjU1NTUgMTcuMzYwMUMyMC4wMzU1IDIxLjE1NTcgMTQuMjMxMSAzNC4yNTc5IDIxLjIwODkgNTIuNTY5QzIxLjIwODkgNTIuNTY5IDE4Ljk3NzggNjIuMTI0NSAyMy4wNzU1IDcwLjMzNzlDMjMuMDc1NSA3MC4zMzc5IDI5LjAxMzMgNjcuNjQ0NSAzMy43MjQ0IDcxLjQzMTJDMzguNjU3NyA3NS40MzEyIDM3LjA4NDQgNzkuMjgwMSA0MC41NiA4Mi41ODY3QzQzLjU0NjYgODUuNjM1NiA0OCA4NS42MzU2IDQ4IDg1LjYzNTZaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNNDIuNDc5OSA2NS4yOThDNDIuMjkzMyA1OS4yMTggMzYuMzAyMSA1Ny4yNjI0IDMyLjIxMzMgNTkuODIyNEMzMi4yMTMzIDU5LjgyMjQgMzIuODUzMyA2Mi40MzU4IDM1LjgzOTkgNjMuNzUxM0MzOC4yNzU1IDY0LjgyNjkgMzkuMzI0NCA2My4zODY5IDQyLjQ3OTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNMjIuNDk3NyAyMy4wOTM1QzIwLjA4ODggMzEuNTQ2OCAyMS4xMjg4IDQyLjI0MDIgMjQuOTMzMyA1MC4wMjY5QzI4LjgyNjYgNDcuMjcxMyAzMi45MTU1IDQzLjAxMzUgMzUuMDkzMyAzOC41MDY5QzI5Ljk2NDQgMzQuNzExMyAyNS42NjIyIDMxLjEwMjQgMjIuNDk3NyAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNTMuNTE5OSA2NS4yOThDNTMuNzA2NiA1OS4yMTggNTkuNjk3NyA1Ny4yNjI0IDYzLjc4NjYgNTkuODIyNEM2My43ODY2IDU5LjgyMjQgNjMuMTQ2NiA2Mi40MzU4IDYwLjE1OTkgNjMuNzUxM0M1Ny43MjQzIDY0LjgyNjkgNTYuNjc1NSA2My4zODY5IDUzLjUxOTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNzMuNTAyMiAyMy4wOTM1Qzc1LjkxMTEgMzEuNTQ2OCA3NC44NzExIDQyLjI0MDIgNzEuMDY2NiA1MC4wMjY5QzY3LjE3MzMgNDcuMjcxMyA2My4wODQ0IDQzLjAxMzUgNjAuOTA2NiAzOC41MDY5QzY2LjAzNTUgMzQuNzExMyA3MC4zMzc3IDMxLjEwMjQgNzMuNTAyMiAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNDcuOTk5OSA4NS4zMDY5QzUwLjE0MDQgODUuMzA2OSA1MS44NzU1IDgzLjc3ODcgNTEuODc1NSA4MS44OTM2QzUxLjg3NTUgODAuMDA4NCA1MC4xNDA0IDc4LjQ4MDIgNDcuOTk5OSA3OC40ODAyQzQ1Ljg1OTUgNzguNDgwMiA0NC4xMjQ0IDgwLjAwODQgNDQuMTI0NCA4MS44OTM2QzQ0LjEyNDQgODMuNzc4NyA0NS44NTk1IDg1LjMwNjkgNDcuOTk5OSA4NS4zMDY5WiIgZmlsbD0iIzdCODFGOSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=new Set(["legacy",0]),this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._publicKey=null,this._wallet=null,this._readyState!==ge.Unsupported&&Oo(()=>window?.nightly?.solana?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get connecting(){return this._connecting}get readyState(){return this._readyState}get publicKey(){return this._publicKey}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.nightly.solana;try{await e.connect()}catch(i){throw new ic(i?.message,i)}if(e.publicKey.toString()==="11111111111111111111111111111111")throw new Es;let t;try{t=new N.PublicKey(e.publicKey.toBytes())}catch(i){throw new gr(i?.message,i)}this._wallet=e,this._publicKey=t,this.emit("connect",t)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch{this.emit("error",new uf)}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{return t.signMessage(new TextDecoder().decode(e))}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Qb="Solong";class Jb extends _h{constructor(e={}){super(),this.name=Qb,this.url="https://solongwallet.io",this.icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAGlklEQVR4Ae3bA5DsyhfH8TNr49r2/du2bdu2bdu2zcdNrm3b9toz533rvctUn3Umk9p01WfdvVW/6nROBxJVS1rSkpa0pCUtaUlLWtKSpl4VXos3GJ4sujQFuUKfWl+qT730arzB8Ex9YksKcgXjFOCVeIPhBYydB8mawQ+yiGC8n0EN6zAVcgXhpQjoq1DDdsyDAAB9Pwo1HMC9INk0FIM8Bt1Qh9WohQQCvD+BtEMdtmC8I7y5aIE67MV0SBwDvB3qsE/UHwMJIpC/QB1OYiLEEeCPoQ7nMRcSwwDrao3Zl8aTIEGEUYlL0IAMXuQOr66UvsegDm+ExDJAPNiafSg0AlyIbmjAWX1aQzEkiH6T0QkNaEdpnAN8NNRhPcSF9e9el2ebBhyAuNBvGtLQgIuQOAd4D6jDMRQbM3AmOqEBDfq0xjJIEP3GohkakEFVjAP0y401sAsLnAE+pb6EsC5AA9J4sHsG+kX0PQR1eFJ8AwTWQh0+DjFm4a1Qh2/AOoz/BHX4ZdwD/CDU4aioX2GUMW+AOnB2bqiBBDHe86EOTYw5GRKJwQ/ijUM91OGTxgysxSmowzeNw7j08m5DHX4l7Igg2TY0g9hbLBZ+f7oxC98CdWjDvYzD+MVQh07GfEQsZyDgVWA71OGvorfnQQCAcqaYUFZDHW6j/itAoB70GcergzqsEa0rhGTTEA7mP0koK4xdyeOMmvBBhJU2zsjPMw7lu9O3zShpXheHk4hhcZ4w26AOG4RSxDiUfwZ12KdPqy+FBDHeV6EOZxizIg6HsMGbiQ5jdjzBXRfeefGg3tgbv9BYC0fhZE7sjUMY9Pf9rdcI5XtQh39BjBA/C3VYnM0zcgiDek+GOhzh93mQoMs7kIxze/eMhnxIEOPNM9bcFtTEeAb6I419axu/m2CsgxU4Aw1A/UxIUM/bO/9+cVkDDd5x42x8N1iH8Taow0NhHcZLoQ5Pi/MMzDMW+DTu7g6vIY9AdkAdHmaUMyn6roA6PD22AeLB6DbWplHG7LubfY+kfiIkiH5T0AJ1uFtMA1xUzOc1UIclzvCeXF+o7DygDlvds29RgVVzYj+K4xhgEX4NdcjgecE++rSL+ZdLmIxRB77Ose7l4XPIQB3eF8M60C/n8++ghltE/QLIFfqUiyUE8kOoYSW7jmLIFXeN4X0NaajDDlG/NG6XswrxKdxu+G/weh27j3wCej9uN9zEOjc3sObl4S243XBLhDfWE0mAMQjwZfhxDng7pG/8Sj4/ER/Gd/BdfBhPRGW2A/wxNAfcBOnFCHwZZ6GGs/gqapMAb/QEnIT20Uk8IQkQeB7aof3UihcM9wDvhyboANHXv1+IdWBOB2hsIftto+iSPEif8aGPcjrA50GHyPMiOIT9B/N5apaMgQT8D2poxMdwt8s+hkao4X9ZDxBTIdHwy/h8AeqQxhMhAU9BB9ThPMqHTYCYjU6owy3uPstSfL4Z6uZPC+Mk8gOomz8DEg3vXshAHb4MMXwZarhXGDPwa739w2j48623BPAniOFPUMPsMAL8INTw9AgDrLZOCmjFPEjA3WD1aUJVGAG+CGr4ECRCy6GGg3iyaF0+n/PwFByEGpaJ+qkw1sB7QA3/hUTozdBetFymvXhTWGVMOc7bp36/FhKRamNW9dcxZmpZiI+32ad+vAQSoWejGzpAXXh22Fek3wY1rDD2kVnijR3ExYQMPgkJOUB/nFW0Is3vnw6JhlHX9a4N70Iq/ACBv0MNu7J9WxHw7jaA2deFOtw32zeVHtHLWvMN0dtSkOzwS3spYy7iH1hx2d/wYdyTvnkR3BdeQjjerVBDN14JyZIfQWH5RC7e1rw32npZV54LCc+SPD5/HgqYD3WW5+gTqt6X+rA4v0701hRkKF0+bL+HTM9Hgv/MHH60wyvHWigsafwA1ZAhMguLoL34kbDcQEI1uAH8mcbuxPHImf8i5EMGxqvER9EI7cUqVMTl0Y6HoxHaBzvxNkyC9EEe7oEv4Sy0D/YQ+IS4ver1JNT38z7sWnwbb8TT8Cg8Gs/Gu/Ar7EEXtI/2ud7Ni0GAYCbiJDQiazA57k9nTcdqaJb9UtSvitXbmjavCJ9AMzRkJ/B80boUJBLhDe7Nw1/QCR1i9fgKRg6HByzvjZ/hInQQMjiCT2PSMHxC1a/l8wvwGxyG9kEaW/EtPI4xiiE5JcLrd6PxcLwM78SH8EG8Fc/H/UUXVUByGh8SSYBJgEmASYCJJMAkwBi6A3xCqZhiBz8+AAAAAElFTkSuQmCC",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ge.Unsupported&&Oo(()=>window.solong?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){return!!this._wallet?.currentAccount}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.solong;let t;try{t=await e.selectAccount()}catch(r){throw new Es(r?.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new gr(r?.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Zb="Torus";class Xb extends Do{constructor({params:e={showTorusButton:!1}}={params:{showTorusButton:!1}}){super(),this.name=Zb,this.url="https://tor.us",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzMiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMyAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYuNSIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzAzNjRGRiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTExLjIxODYgOS40OTIxOUMxMC40NTM5IDkuNDkyMTkgOS44MzM5OCAxMC4xMTIxIDkuODMzOTggMTAuODc2OFYxMi40ODk4QzkuODMzOTggMTMuMjU0NSAxMC40NTM5IDEzLjg3NDQgMTEuMjE4NiAxMy44NzQ0SDEzLjY2ODRWMjIuODk3NkMxMy42Njg0IDIzLjY2MjMgMTQuMjg4MyAyNC4yODIyIDE1LjA1MyAyNC4yODIySDE2LjY2NkMxNy40MzA3IDI0LjI4MjIgMTguMDUwNiAyMy42NjIzIDE4LjA1MDYgMjIuODk3NlYxMi41MDE1QzE4LjA1MDYgMTIuNDk3NiAxOC4wNTA2IDEyLjQ5MzcgMTguMDUwNiAxMi40ODk4VjEwLjg3NjhDMTguMDUwNiAxMC4xMTIxIDE3LjQzMDcgOS40OTIxOSAxNi42NjYgOS40OTIxOUgxNS4wNTNIMTEuMjE4NloiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0yMS4zMzc2IDEzLjg3NDRDMjIuNTQ3NyAxMy44NzQ0IDIzLjUyODcgMTIuODkzNCAyMy41Mjg3IDExLjY4MzNDMjMuNTI4NyAxMC40NzMyIDIyLjU0NzcgOS40OTIxOSAyMS4zMzc2IDkuNDkyMTlDMjAuMTI3NSA5LjQ5MjE5IDE5LjE0NjUgMTAuNDczMiAxOS4xNDY1IDExLjY4MzNDMTkuMTQ2NSAxMi44OTM0IDIwLjEyNzUgMTMuODc0NCAyMS4zMzc2IDEzLjg3NDRaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.Loadable,this._connecting=!1,this._wallet=null,this._publicKey=null,this._params=e}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){return!!this._wallet?.isLoggedIn}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Loadable)throw new Ri;this._connecting=!0;let e;try{e=(await Promise.resolve().then(()=>require("./solanaEmbed.esm-BpIKVhXq.js"))).default}catch(n){throw new Ub(n?.message,n)}let t;try{t=window.torus||new e}catch(n){throw new ln(n?.message,n)}if(!t.isInitialized)try{await t.init(this._params)}catch(n){throw new ic(n?.message,n)}let i;try{i=await t.login()}catch(n){throw new Es(n?.message,n)}let r;try{r=new N.PublicKey(i[0])}catch(n){throw new gr(n?.message,n)}this._wallet=t,this._publicKey=r,this.emit("connect",r)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{e.isLoggedIn&&await e.cleanUp()}catch(t){this.emit("error",new xo(t?.message,t))}}this.emit("disconnect")}async sendTransaction(e,t,i={}){try{const r=this._wallet;if(!r)throw new Ke;try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n?.length&&e.partialSign(...n),o.preflightCommitment=o.preflightCommitment||t.commitment;const{signature:a}=await r.signAndSendTransaction(e,o);return a}catch(n){throw n instanceof Mt?n:new sr(n?.message,n)}}catch(r){throw this.emit("error",r),r}}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signMessage(e)}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}function $c(s){switch(s){case"processed":case"confirmed":case"finalized":case void 0:return s;case"recent":return"processed";case"single":case"singleGossip":return"confirmed";case"max":case"root":return"finalized";default:return}}const ev="https://api.mainnet-beta.solana.com";function tv(s){return s.includes(ev)?se.SOLANA_MAINNET_CHAIN:/\bdevnet\b/i.test(s)?se.SOLANA_DEVNET_CHAIN:/\btestnet\b/i.test(s)?se.SOLANA_TESTNET_CHAIN:/\blocalhost\b/i.test(s)||/\b127\.0\.0\.1\b/.test(s)?se.SOLANA_LOCALNET_CHAIN:se.SOLANA_MAINNET_CHAIN}var La;(function(s){s.Mainnet="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",s.Devnet="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",s.Deprecated_Mainnet="solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",s.Deprecated_Devnet="solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})(La||(La={}));var vs;(function(s){s.signTransaction="solana_signTransaction",s.signMessage="solana_signMessage",s.signAndSendTransaction="solana_signAndSendTransaction",s.signAndSendAllTransactions="solana_signAndSendAllTransactions",s.signAllTransactions="solana_signAllTransactions"})(vs||(vs={}));const gt={Mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Deprecated_Mainnet:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",Deprecated_Devnet:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"};var sv=Object.defineProperty,iv=(s,e,t)=>e in s?sv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Su=(s,e,t)=>iv(s,typeof e!="symbol"?e+"":e,t);let rv=class extends h.IEvents{constructor(e){super(),this.opts=e,Su(this,"protocol","wc"),Su(this,"version",2)}};var nv=Object.defineProperty,ov=(s,e,t)=>e in s?nv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,av=(s,e,t)=>ov(s,e+"",t);let cv=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,av(this,"records",new Map)}},lv=class{constructor(e,t){this.logger=e,this.core=t}},hv=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},uv=class extends h.IEvents{constructor(e){super()}},dv=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},pv=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},gv=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},fv=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},wv=class{constructor(e,t){this.projectId=e,this.logger=t}},yv=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};function Io(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function $u(s){return Io(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const pf="2.23.2";let Tc={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${pf}`},rc=class El extends Error{constructor(e,t={}){const i=t.cause instanceof El?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof El&&t.cause.docsPath||t.docsPath,n=Tc.getDocsUrl?.({...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...Tc.version?[`Version: ${Tc.version}`]:[]].join(`
2
- `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=pf}walk(e){return gf(this,e)}};function gf(s,e){return e?.(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?gf(s.cause,e):e?null:s}let ff=class extends rc{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};function Cn(s,{dir:e,size:t=32}={}){return typeof s=="string"?mv(s,{dir:e,size:t}):bv(s,{dir:e,size:t})}function mv(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new ff({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function bv(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new ff({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}let vv=class extends rc{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}},Iv=class extends rc{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function _n(s,{size:e}){if($u(s)>e)throw new Iv({givenSize:$u(s),maxSize:e})}function Al(s,e={}){const{signed:t}=e;e.size&&_n(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function Ev(s,e={}){return Number(Al(s,e))}const Av=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Nl(s,e={}){return typeof s=="number"||typeof s=="bigint"?yf(s,e):typeof s=="string"?_v(s,e):typeof s=="boolean"?Nv(s,e):wf(s,e)}function Nv(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(_n(t,{size:e.size}),Cn(t,{size:e.size})):t}function wf(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=Av[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(_n(i,{size:e.size}),Cn(i,{dir:"right",size:e.size})):i}function yf(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof s=="bigint"?"n":"";throw new vv({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${s}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?Cn(a,{size:i}):a}const Cv=new TextEncoder;function _v(s,e={}){const t=Cv.encode(s);return wf(t,e)}const Sv=new TextEncoder;function $v(s,e={}){return typeof s=="number"||typeof s=="bigint"?Pv(s,e):typeof s=="boolean"?Tv(s,e):Io(s)?mf(s,e):bf(s,e)}function Tv(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(_n(t,{size:e.size}),Cn(t,{size:e.size})):t}const ti={zero:48,nine:57,A:65,F:70,a:97,f:102};function Tu(s){if(s>=ti.zero&&s<=ti.nine)return s-ti.zero;if(s>=ti.A&&s<=ti.F)return s-(ti.A-10);if(s>=ti.a&&s<=ti.f)return s-(ti.a-10)}function mf(s,e={}){let t=s;e.size&&(_n(t,{size:e.size}),t=Cn(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Tu(i.charCodeAt(a++)),l=Tu(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new rc(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function Pv(s,e){const t=yf(s,e);return mf(t)}function bf(s,e={}){const t=Sv.encode(s);return typeof e.size=="number"?(_n(t,{size:e.size}),Cn(t,{dir:"right",size:e.size})):t}function za(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function xv(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ko(s,...e){if(!xv(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Mv(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");za(s.outputLen),za(s.blockLen)}function Cl(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function vf(s,e){ko(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const na=BigInt(2**32-1),Pu=BigInt(32);function Ov(s,e=!1){return e?{h:Number(s&na),l:Number(s>>Pu&na)}:{h:Number(s>>Pu&na)|0,l:Number(s&na)|0}}function Dv(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=Ov(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const kv=(s,e,t)=>s<<t|e>>>32-t,jv=(s,e,t)=>e<<t|s>>>32-t,Rv=(s,e,t)=>e<<t-32|s>>>64-t,Uv=(s,e,t)=>s<<t-32|e>>>64-t,Er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Lv(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function zv(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Fv(s,e){return s<<32-e|s>>>e}const xu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function qv(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Mu(s){for(let e=0;e<s.length;e++)s[e]=qv(s[e])}function Bv(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Sh(s){return typeof s=="string"&&(s=Bv(s)),ko(s),s}function Hv(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];ko(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}let If=class{clone(){return this._cloneInto()}};function Ef(s){const e=i=>s().update(Sh(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Wv(s=32){if(Er&&typeof Er.getRandomValues=="function")return Er.getRandomValues(new Uint8Array(s));if(Er&&typeof Er.randomBytes=="function")return Er.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Af=[],Nf=[],Cf=[],Vv=BigInt(0),Rn=BigInt(1),Kv=BigInt(2),Gv=BigInt(7),Yv=BigInt(256),Qv=BigInt(113);for(let s=0,e=Rn,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Af.push(2*(5*i+t)),Nf.push((s+1)*(s+2)/2%64);let r=Vv;for(let n=0;n<7;n++)e=(e<<Rn^(e>>Gv)*Qv)%Yv,e&Kv&&(r^=Rn<<(Rn<<BigInt(n))-Rn);Cf.push(r)}const[Jv,Zv]=Dv(Cf,!0),Ou=(s,e,t)=>t>32?Rv(s,e,t):kv(s,e,t),Du=(s,e,t)=>t>32?Uv(s,e,t):jv(s,e,t);function Xv(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],u=t[c+1],d=Ou(l,u,1)^t[a],p=Du(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Nf[o],c=Ou(r,n,a),l=Du(r,n,a),u=Af[o];r=s[u],n=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=Jv[i],s[1]^=Zv[i]}t.fill(0)}let e0=class _f extends If{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,za(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Lv(this.state)}keccak(){xu||Mu(this.state32),Xv(this.state32,this.rounds),xu||Mu(this.state32),this.posOut=0,this.pos=0}update(e){Cl(this);const{blockLen:t,state:i}=this;e=Sh(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(t&128)!==0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Cl(this,!1),ko(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.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 za(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(vf(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new _f(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const t0=(s,e,t)=>Ef(()=>new e0(e,s,t)),s0=t0(1,136,256/8);function Sf(s,e){const t=e||"hex",i=s0(Io(s,{strict:!1})?$v(s):s);return t==="bytes"?i:Nl(i)}let i0=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}};const Pc=new i0(8192);function r0(s,e){if(Pc.has(`${s}.${e}`))return Pc.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Sf(bf(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Pc.set(`${s}.${e}`,n),n}function n0(s){const e=Sf(`0x${s.substring(4)}`).substring(26);return r0(`0x${e}`)}async function o0({hash:s,signature:e}){const t=Io(s)?s:Nl(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-D_GNj8sK.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:d,yParity:p}=e,f=Number(p??d),g=ku(f);return new i.Signature(Al(l),Al(u)).addRecoveryBit(g)}const o=Io(e)?e:Nl(e),a=Ev(`0x${o.slice(130)}`),c=ku(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function ku(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function a0({hash:s,signature:e}){return n0(await o0({hash:s,signature:e}))}var $f=Xt.requireElliptic();const Tf=":";function fn(s){const[e,t]=s.split(Tf);return{namespace:e,reference:t}}function c0(s){const[e,t,i]=s.split(Tf);return{namespace:e,reference:t,address:i}}function Pf(s,e){return s.includes(":")?[s]:e.chains||[]}const l0="ReactNative",cs={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},h0="js";function Fa(){return typeof N.process$1<"u"&&typeof N.process$1.versions<"u"&&typeof N.process$1.versions.node<"u"}function Ui(){return!h.cjsExports$2.getDocument()&&!!h.cjsExports$2.getNavigator()&&navigator.product===l0}function u0(){return Ui()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"&&(N.global==null?void 0:N.global.Platform.OS)==="android"}function d0(){return Ui()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"&&(N.global==null?void 0:N.global.Platform.OS)==="ios"}function jo(){return!Fa()&&!!h.cjsExports$2.getNavigator()&&!!h.cjsExports$2.getDocument()}function Ro(){return Ui()?cs.reactNative:Fa()?cs.node:jo()?cs.browser:cs.unknown}function ju(){var s;try{return Ui()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Application)<"u"?(s=N.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function p0(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function xf(){return h.cjsExports.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function g0(){if(Ro()===cs.reactNative&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"){const{OS:t,Version:i}=N.global.Platform;return[t,i].join("-")}const s=h.detect();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function f0(){var s;const e=Ro();return e===cs.browser?[e,((s=h.cjsExports$2.getLocation())==null?void 0:s.host)||"unknown"].join(":"):e}function Mf(s,e,t){const i=g0(),r=f0();return[[s,e].join("-"),[h0,t].join("-"),i,r].join("/")}function w0({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),u=Mf(s,e,i),d={auth:r,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=p0(l[1]||"",d);return l[0]+"?"+p}function ir(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Of(s){return Object.fromEntries(s.entries())}function Df(s){return new Map(Object.entries(s))}function Yi(s=h.cjsExports$1.FIVE_MINUTES,e){const t=h.cjsExports$1.toMiliseconds(s||h.cjsExports$1.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},t),i=a,r=c})}}function $i(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function kf(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.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: ${s}`)}function y0(s){return kf("topic",s)}function m0(s){return kf("id",s)}function jf(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function dt(s,e){return h.cjsExports$1.fromMiliseconds(Date.now()+h.cjsExports$1.toMiliseconds(s))}function Ci(s){return Date.now()>=h.cjsExports$1.toMiliseconds(s)}function Pe(s,e){return`${s}${e?`:${e}`:""}`}function Ta(s=[],e=[]){return[...new Set([...s,...e])]}async function b0({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r?.href;if(typeof n!="string")return;const o=v0(n,s,e),a=Ro();if(a===cs.browser){if(!((i=h.cjsExports$2.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}I0(o)}else a===cs.reactNative&&typeof(N.global==null?void 0:N.global.Linking)<"u"&&await N.global.Linking.openURL(o)}catch(r){console.error(r)}}function v0(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${C0(i,!0)}`}else r=`${r}/wc?${i}`;return r}function I0(s){let e="_self";N0()?e="_top":(A0()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function E0(s,e){let t="";try{if(jo()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Ru(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Uu(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function $h(){return typeof N.process$1<"u"&&N.process$1.env.IS_VITEST==="true"}function A0(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function N0(){try{return window.self!==window.top}catch{return!1}}function C0(s,e=!1){const t=N.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Rf(s){return N.Buffer.from(s,"base64").toString("utf-8")}function _0(s){return new Promise(e=>setTimeout(e,s))}function Eo(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function S0(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function nc(s,...e){if(!S0(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Th(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Eo(s.outputLen),Eo(s.blockLen)}function bn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Uf(s,e){nc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const oa=BigInt(2**32-1),Lu=BigInt(32);function $0(s,e=!1){return e?{h:Number(s&oa),l:Number(s>>Lu&oa)}:{h:Number(s>>Lu&oa)|0,l:Number(s&oa)|0}}function T0(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=$0(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const P0=(s,e,t)=>s<<t|e>>>32-t,x0=(s,e,t)=>e<<t|s>>>32-t,M0=(s,e,t)=>e<<t-32|s>>>64-t,O0=(s,e,t)=>s<<t-32|e>>>64-t,Ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function D0(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function xc(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Ls(s,e){return s<<32-e|s>>>e}const zu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function k0(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Fu(s){for(let e=0;e<s.length;e++)s[e]=k0(s[e])}function j0(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function vn(s){return typeof s=="string"&&(s=j0(s)),nc(s),s}let Ph=class{clone(){return this._cloneInto()}};function Lf(s){const e=i=>s().update(vn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Uo(s=32){if(Ar&&typeof Ar.getRandomValues=="function")return Ar.getRandomValues(new Uint8Array(s));if(Ar&&typeof Ar.randomBytes=="function")return Ar.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const zf=[],Ff=[],qf=[],R0=BigInt(0),Un=BigInt(1),U0=BigInt(2),L0=BigInt(7),z0=BigInt(256),F0=BigInt(113);for(let s=0,e=Un,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],zf.push(2*(5*i+t)),Ff.push((s+1)*(s+2)/2%64);let r=R0;for(let n=0;n<7;n++)e=(e<<Un^(e>>L0)*F0)%z0,e&U0&&(r^=Un<<(Un<<BigInt(n))-Un);qf.push(r)}const[q0,B0]=T0(qf,!0),qu=(s,e,t)=>t>32?M0(s,e,t):P0(s,e,t),Bu=(s,e,t)=>t>32?O0(s,e,t):x0(s,e,t);function H0(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],u=t[c+1],d=qu(l,u,1)^t[a],p=Bu(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Ff[o],c=qu(r,n,a),l=Bu(r,n,a),u=zf[o];r=s[u],n=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=q0[i],s[1]^=B0[i]}t.fill(0)}let W0=class Bf extends Ph{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Eo(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=D0(this.state)}keccak(){zu||Fu(this.state32),H0(this.state32,this.rounds),zu||Fu(this.state32),this.posOut=0,this.pos=0}update(e){bn(this);const{blockLen:t,state:i}=this;e=vn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(t&128)!==0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){bn(this,!1),nc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.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 Eo(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Uf(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Bf(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const V0=(s,e,t)=>Lf(()=>new W0(e,s,t)),K0=V0(1,136,256/8),G0="https://rpc.walletconnect.org/v1";function Hf(s){const e=`Ethereum Signed Message:
1
+ "use strict";const N=require("./web3-BKaP497Y.js"),se=require("./index-Blvg4PFN.js"),jb=require("./util-G2vxTeU2.js"),Rb=require("./wallets-DLkIKXkb.js"),Xt=require("./index-D61fXWwH.js"),$a=require("./unsignedTransaction-DL3WyIkF.js"),Nu=require("./signer-MBixef_P.js"),h=require("./index.es-E2DQPkYK.js"),k=require("./lit-element-CwBgQkCS.js");require("./browser-ponyfill-VhIu9z_I.js");const gn=require("./http-Dz7hx6tx.js");class Mt extends Error{constructor(e,t){super(e),this.error=t}}class Ri extends Mt{constructor(){super(...arguments),this.name="WalletNotReadyError"}}class Ub extends Mt{constructor(){super(...arguments),this.name="WalletLoadError"}}class ln extends Mt{constructor(){super(...arguments),this.name="WalletConfigError"}}class ic extends Mt{constructor(){super(...arguments),this.name="WalletConnectionError"}}class uf extends Mt{constructor(){super(...arguments),this.name="WalletDisconnectedError"}}class xo extends Mt{constructor(){super(...arguments),this.name="WalletDisconnectionError"}}class Es extends Mt{constructor(){super(...arguments),this.name="WalletAccountError"}}class gr extends Mt{constructor(){super(...arguments),this.name="WalletPublicKeyError"}}class Ke extends Mt{constructor(){super(...arguments),this.name="WalletNotConnectedError"}}class sr extends Mt{constructor(){super(...arguments),this.name="WalletSendTransactionError"}}class rt extends Mt{constructor(){super(...arguments),this.name="WalletSignTransactionError"}}class Mo extends Mt{constructor(){super(...arguments),this.name="WalletSignMessageError"}}class Cu extends Mt{constructor(){super(...arguments),this.name="WalletSignInError"}}class Lb extends Mt{constructor(){super(...arguments),this.name="WalletWindowClosedError"}}var ge;(function(s){s.Installed="Installed",s.NotDetected="NotDetected",s.Loadable="Loadable",s.Unsupported="Unsupported"})(ge||(ge={}));class df extends N.EventEmitter{get connected(){return!!this.publicKey}async autoConnect(){await this.connect()}async prepareTransaction(e,t,i={}){const r=this.publicKey;if(!r)throw new Ke;return e.feePayer=e.feePayer||r,e.recentBlockhash=e.recentBlockhash||(await t.getLatestBlockhash({commitment:i.preflightCommitment,minContextSlot:i.minContextSlot})).blockhash,e}}function Oo(s){if(typeof window>"u"||typeof document>"u")return;const e=[];function t(){if(s())for(const n of e)n()}const i=setInterval(t,1e3);e.push(()=>clearInterval(i)),document.readyState==="loading"&&(document.addEventListener("DOMContentLoaded",t,{once:!0}),e.push(()=>document.removeEventListener("DOMContentLoaded",t))),document.readyState!=="complete"&&(window.addEventListener("load",t,{once:!0}),e.push(()=>window.removeEventListener("load",t))),t()}function ui(s){return"version"in s}class _h extends df{async sendTransaction(e,t,i={}){let r=!0;try{if(ui(e)){if(!this.supportedTransactionVersions)throw new sr("Sending versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(e.version))throw new sr(`Sending transaction version ${e.version} isn't supported by this wallet`);try{e=await this.signTransaction(e);const n=e.serialize();return await t.sendRawTransaction(n,i)}catch(n){throw n instanceof rt?(r=!1,n):new sr(n?.message,n)}}else try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n?.length&&e.partialSign(...n),e=await this.signTransaction(e);const a=e.serialize();return await t.sendRawTransaction(a,o)}catch(n){throw n instanceof rt?(r=!1,n):new sr(n?.message,n)}}catch(n){throw r&&this.emit("error",n),n}}async signAllTransactions(e){for(const i of e)if(ui(i)){if(!this.supportedTransactionVersions)throw new rt("Signing versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(i.version))throw new rt(`Signing transaction version ${i.version} isn't supported by this wallet`)}const t=[];for(const i of e)t.push(await this.signTransaction(i));return t}}class Do extends _h{}function zb(s){return se.StandardConnect in s.features&&se.StandardEvents in s.features&&(se.SolanaSignAndSendTransaction in s.features||se.SolanaSignTransaction in s.features)}var vo;(function(s){s.Mainnet="mainnet-beta",s.Testnet="testnet",s.Devnet="devnet"})(vo||(vo={}));const Fb="Bitget";class qb extends Do{constructor(e={}){super(),this.name=Fb,this.url="https://web3.bitget.com",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgdmlld0JveD0iMCAwIDUxMiA1MTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiBmaWxsPSIjMDAxRjI5Ii8+CjxwYXRoIGQ9Ik0yMTkuOTQ4IDk1LjcwMjJDMjAxLjYyMyA5NS42OTI5IDE4My4zMyA5NS42ODM1IDE2NC45NDEgOTUuNzExNkMxNTMuODIyIDk1LjcxMTYgMTQ5LjY1MSAxMDkuNjcxIDE1Ny45MjEgMTE3LjkzOUwyODMuMDk4IDI0My4xMTdDMjg3LjAwNCAyNDYuNjkgMjg5LjQ0MSAyNTAuNTc0IDI4OS41MyAyNTUuNjkzQzI4OS40NDEgMjYwLjgxMiAyODcuMDA0IDI2NC42OTYgMjgzLjA5OCAyNjguMjY5TDE1Ny45MjEgMzkzLjQ0NkMxNDkuNjUxIDQwMS43MTUgMTUzLjgyMiA0MTUuNjc0IDE2NC45NDEgNDE1LjY3NEMxODMuMzMgNDE1LjcwMiAyMDEuNjIzIDQxNS42OTMgMjE5Ljk0OCA0MTUuNjgzQzIyOS4xMjIgNDE1LjY3OSAyMzguMzA1IDQxNS42NzQgMjQ3LjUxMSA0MTUuNjc0QzI1OS41NTUgNDE1LjY3NCAyNjYuNzIgNDA5LjI0IDI3My4xNTQgNDAyLjgwNUwzODYuMDQ3IDI4OS45MTJDMzk1LjA1NyAyODAuOTAyIDQwMy4xMTkgMjY4LjkzOSA0MDMuMDA5IDI1NS42OTNDNDAzLjExOSAyNDIuNDQ3IDM5NS4wNTcgMjMwLjQ4NCAzODYuMDQ3IDIyMS40NzRMMjczLjE1NCAxMDguNThDMjY2LjcyIDEwMi4xNDYgMjU5LjU1NSA5NS43MTE2IDI0Ny41MTEgOTUuNzExNkMyMzguMzA1IDk1LjcxMTYgMjI5LjEyMiA5NS43MDY5IDIxOS45NDggOTUuNzAyMloiIGZpbGw9IiMwMEYwRkYiLz4KPC9zdmc+Cg==",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ge.Unsupported&&Oo(()=>window.bitkeep?.solana?.isBitKeep?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.bitkeep.solana;let t;try{t=await e.getAccount()}catch(r){throw new Es(r?.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new gr(r?.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new xo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{const{signature:i}=await t.signMessage(e);return i}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Bb="Clover";class Hb extends Do{constructor(e={}){super(),this.name=Bb,this.url="https://clv.org",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDgiIGhlaWdodD0iNDgiIHZpZXdCb3g9IjAgMCA0OCA0OCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTM2LjQ4IDBIMTEuNTJDNS4xNTc2OCAwIDAgNS4xNTc2OCAwIDExLjUyVjM2LjQ4QzAgNDIuODQyMyA1LjE1NzY4IDQ4IDExLjUyIDQ4SDM2LjQ4QzQyLjg0MjMgNDggNDggNDIuODQyMyA0OCAzNi40OFYxMS41MkM0OCA1LjE1NzY4IDQyLjg0MjMgMCAzNi40OCAwWiIgZmlsbD0idXJsKCNwYWludDBfbGluZWFyXzc5MTBfMTYzMzUxKSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTI0LjAwMDYgMzkuMzYwNkMzMi40ODM3IDM5LjM2MDYgMzkuMzYwNiAzMi40ODM3IDM5LjM2MDYgMjQuMDAwNkMzOS4zNjA2IDE1LjUxNzUgMzIuNDgzNyA4LjY0MDYyIDI0LjAwMDYgOC42NDA2MkMxNS41MTc1IDguNjQwNjIgOC42NDA2MiAxNS41MTc1IDguNjQwNjIgMjQuMDAwNkM4LjY0MDYyIDMyLjQ4MzcgMTUuNTE3NSAzOS4zNjA2IDI0LjAwMDYgMzkuMzYwNlpNMjEuMjg5OSAxNS44Njg4SDI2LjcxMVYyMS4zNDdIMjEuMjkwNFYyNi42NTRIMjYuNzExVjMyLjEzMjJIMjEuMjg5OVYyNi44MjUySDE1Ljg2OTNWMjEuMzQ3SDIxLjI4OTlWMTUuODY4OFpNMjYuNzEyIDIxLjM0N0gzMi4xMzMxVjI2LjgyNTJIMjYuNzEyVjIxLjM0N1oiIGZpbGw9ImJsYWNrIi8+CjxkZWZzPgo8bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MF9saW5lYXJfNzkxMF8xNjMzNTEiIHgxPSI0OCIgeTE9Ii0xLjQzMDUxZS0wNiIgeDI9IjEuNDMwNTFlLTA2IiB5Mj0iNDgiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0E5RkZFMCIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiM4NkQ1RkYiLz4KPC9saW5lYXJHcmFkaWVudD4KPC9kZWZzPgo8L3N2Zz4=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ge.Unsupported&&Oo(()=>window.clover_solana?.isCloverWallet?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.clover_solana;let t;try{t=await e.getAccount()}catch(r){throw new Es(r?.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new gr(r?.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{const{signature:i}=await t.signMessage(e);return Uint8Array.from(i)}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}function Wb(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const u=s.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,u++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let m=l[p],A=0;for(let C=g-1;(m!==0||A<d)&&C!==-1;C--,A++)m+=256*w[C]>>>0,w[C]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let b=g-d;for(;b!==g&&w[b]===0;)b++;let v=i.repeat(u);for(;b<g;++b)v+=s.charAt(w[b]);return v}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,p=0;for(;l[u]===i;)d++,u++;const f=(l.length-u)*r+1>>>0,g=new Uint8Array(f);for(;u<l.length;){const m=l.charCodeAt(u);if(m>255)return;let A=e[m];if(A===255)return;let C=0;for(let S=f-1;(A!==0||C<p)&&S!==-1;S--,C++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=C,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const b=new Uint8Array(d+(f-w));let v=d;for(;w!==f;)b[v++]=g[w++];return b}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Vb="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Sc=Wb(Vb),Kb="Coin98";class Gb extends Do{constructor(e={}){super(),this.name=Kb,this.url="https://coin98.com",this.icon="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA3NiA3NSI+CiAgPGRlZnM+CiAgICA8bGluZWFyR3JhZGllbnQgaWQ9ImEiIHgxPSIxMDEuNjgxJSIgeDI9Ii0xLjU1NyUiIHkxPSIxNS4yNjglIiB5Mj0iODQuOTE3JSI+CiAgICAgIDxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9IiNGMUQ5NjEiLz4KICAgICAgPHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjQ0RBMTQ2Ii8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogIDwvZGVmcz4KICA8ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPgogICAgPHJlY3Qgd2lkdGg9Ijc1IiBoZWlnaHQ9Ijc1IiBmaWxsPSIjMDAwIiByeD0iMTYiLz4KICAgIDxwYXRoIGZpbGw9InVybCgjYSkiIGZpbGwtcnVsZT0ibm9uemVybyIgZD0iTTYxLjQ0IDBhMTMuNzE0IDEzLjcxNCAwIDAgMSA5LjY4IDQuMDEgMTMuNjYxIDEzLjY2MSAwIDAgMSA0LjAwOCA5LjY2OHY0Ny42NDZhMTMuNjYgMTMuNjYgMCAwIDEtNC4wMDcgOS42NjZBMTMuNzEzIDEzLjcxMyAwIDAgMSA2MS40NCA3NUgxMy42ODZhMTMuNzEzIDEzLjcxMyAwIDAgMS05LjY4LTQuMDFBMTMuNjYgMTMuNjYgMCAwIDEgMCA2MS4zMjRWMTMuNjc4YzAtMy42MjUgMS40NC03LjEwMiA0LjAwNy05LjY2N0ExMy43MTQgMTMuNzE0IDAgMCAxIDEzLjY4NyAwWk0yMC4wNjMgNDYuMjMxaC00LjgyNWExMC4wMzIgMTAuMDMyIDAgMCAwIDIuOTQ2IDcuMDg2IDEwLjA3IDEwLjA3IDAgMCAwIDcuMSAyLjk0MiAxMC4wNjUgMTAuMDY1IDAgMCAwIDcuMTA4LTIuOTM1IDEwLjAzIDEwLjAzIDAgMCAwIDIuOTQ2LTcuMDkzaC00LjgyNGE1LjIwNyA1LjIwNyAwIDAgMS0xLjUzIDMuNjg4IDUuMjI1IDUuMjI1IDAgMCAxLTMuNjk2IDEuNTI4IDUuMjM0IDUuMjM0IDAgMCAxLTMuNjk1LTEuNTI4IDUuMjEzIDUuMjEzIDAgMCAxLTEuNTMtMy42ODhaTTU0LjMzIDMzLjcxNmExMS43NjMgMTEuNzYzIDAgMCAwLTEyLjc5OSAyLjUzOEExMS42OTcgMTEuNjk3IDAgMCAwIDM4Ljk5IDQ5LjAzYTExLjcyMyAxMS43MjMgMCAwIDAgNC4zMjggNS4yNTkgMTEuNzU3IDExLjc1NyAwIDAgMCA2LjUyNiAxLjk3IDExLjc2NiAxMS43NjYgMCAwIDAgOC4yOS0zLjQzNSAxMS43MiAxMS43MiAwIDAgMCAzLjQ0Mi04LjI3NCAxMS43MDIgMTEuNzAyIDAgMCAwLTEuOTc1LTYuNTE0IDExLjczNiAxMS43MzYgMCAwIDAtNS4yNjktNC4zMlptLTQuNDg4IDMuOTJhNi45MzcgNi45MzcgMCAwIDEgNC45IDIuMDI1IDYuOTEgNi45MSAwIDAgMSAyLjAyOCA0Ljg5MiA2Ljg5NyA2Ljg5NyAwIDAgMS0xLjE3IDMuODM0IDYuOTMyIDYuOTMyIDAgMCAxLTEwLjY0MyAxLjA0MiA2LjkwMiA2LjkwMiAwIDAgMS0xLjUtNy41MjIgNi45MDkgNi45MDkgMCAwIDEgMi41NDQtMy4xIDYuOTI4IDYuOTI4IDAgMCAxIDMuODQxLTEuMTY3Wm0uMTcgNC41NTJhMi40MzEgMi40MzEgMCAwIDAtMi4yNDEgMS4xNTQgMi40MTggMi40MTggMCAwIDAtLjM1NiAxLjI1NyAyLjM5NSAyLjM5NSAwIDAgMCAxLjYxOSAyLjI5djEuNzUzaDEuNjE4di0xLjc1NGEyLjQyNyAyLjQyNyAwIDAgMCAxLjU5NC0xLjk1IDIuNDE4IDIuNDE4IDAgMCAwLTEtMi4zMSAyLjQzMSAyLjQzMSAwIDAgMC0xLjIzNC0uNDRabS0yMC4yMi0yMi41NTJhMTEuNzYyIDExLjc2MiAwIDAgMC0xMi43OTYgMi41MzEgMTEuNjk3IDExLjY5NyAwIDAgMC0yLjU1NCAxMi43NjkgMTEuNzIzIDExLjcyMyAwIDAgMCA0LjMyIDUuMjYyIDExLjc1NyAxMS43NTcgMCAwIDAgMTQuODI1LTEuNDQ2IDExLjcxNyAxMS43MTcgMCAwIDAgMy40NDUtOC4yODQgMTEuNzAzIDExLjcwMyAwIDAgMC0xLjk3NC02LjUxMiAxMS43MzYgMTEuNzM2IDAgMCAwLTUuMjY2LTQuMzJabS00LjUxIDMuOTE3YTYuOTQ1IDYuOTQ1IDAgMCAxIDQuODk3IDIuMDI5IDYuOTE4IDYuOTE4IDAgMCAxIDIuMDMyIDQuODg2IDYuOTA2IDYuOTA2IDAgMCAxLTEuMTY4IDMuODQyIDYuOTQgNi45NCAwIDAgMS0xMC42NiAxLjA0OCA2LjkxMSA2LjkxMSAwIDAgMS0xLjUtNy41MzYgNi45MTggNi45MTggMCAwIDEgMi41NS0zLjEwMyA2LjkzNyA2LjkzNyAwIDAgMSAzLjg1LTEuMTY2Wm0yNC41Ni00LjgxYTEwLjA1OSAxMC4wNTkgMCAwIDAtNy4xMDMgMi45NCAxMC4wMiAxMC4wMiAwIDAgMC0yLjk0IDcuMDkgOS45IDkuOSAwIDAgMCAxLjIzIDQuNzk1IDEzLjU3NSAxMy41NzUgMCAwIDEgNC4yMTQtMi4zMjIgNS4wODIgNS4wODIgMCAwIDEtLjYyNS0yLjQ3NyA1LjIwNiA1LjIwNiAwIDAgMSAxLjUwMy0zLjczNiA1LjIyMyA1LjIyMyAwIDAgMSAzLjcyMi0xLjU1NCA1LjIzNCA1LjIzNCAwIDAgMSAzLjcyIDEuNTU0IDUuMjEzIDUuMjEzIDAgMCAxIDEuNTA1IDMuNzM2IDUuMjc5IDUuMjc5IDAgMCAxLS42MjMgMi40NzMgMTMuNTc0IDEzLjU3NCAwIDAgMSA0LjIxMyAyLjMyMiA5LjkwMyA5LjkwMyAwIDAgMCAxLjIzLTQuNzk1IDEwLjAzMiAxMC4wMzIgMCAwIDAtMi45NDYtNy4wODYgMTAuMDcgMTAuMDcgMCAwIDAtNy4xLTIuOTRabS0yMy43NSA3Ljk5aC0xLjYxN3YxLjc1YTIuNDE5IDIuNDE5IDAgMCAwLTEuNTgyIDIuNjg3IDIuNDE0IDIuNDE0IDAgMCAwIDIuMzkgMi4wMDYgMi40NSAyLjQ1IDAgMCAwIDEuNTU1LS41NzQgMi40MTQgMi40MTQgMCAwIDAtLjc0Ni00LjExOXYtMS43NVoiLz4KICA8L2c+Cjwvc3ZnPgo=",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ge.Unsupported&&Oo(()=>window.coin98?.sol?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){return!!this._wallet?.isConnected()}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.coin98.sol;let t;try{t=(await e.connect())[0]}catch(r){throw new Es(r?.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new gr(r?.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch(t){this.emit("error",new xo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{const i=await t.request({method:"sol_sign",params:[e]}),r=new N.PublicKey(i.publicKey),n=Sc.decode(i.signature);return e.addSignature(r,N.Buffer.from(n)),e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{const i=await t.request({method:"sol_signAllTransactions",params:[e]}),r=new N.PublicKey(i.publicKey),n=i.signatures;return e.map((o,a)=>{const c=Sc.decode(n[a]);return o.addSignature(r,N.Buffer.from(c)),o})}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{const i=await t.request({method:"sol_signMessage",params:[e]});return Sc.decode(i.signature)}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Yb="Nightly";class _u extends Do{constructor(){super(),this.name=Yb,this.url="https://nightly.app",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iOTYiIGhlaWdodD0iOTYiIHZpZXdCb3g9IjAgMCA5NiA5NiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQ4IDk2Qzc0LjUwOTcgOTYgOTYgNzQuNTA5NyA5NiA0OEM5NiAyMS40OTAzIDc0LjUwOTcgMCA0OCAwQzIxLjQ5MDMgMCAwIDIxLjQ5MDMgMCA0OEMwIDc0LjUwOTcgMjEuNDkwMyA5NiA0OCA5NloiIGZpbGw9IiM2RDczRjgiLz4KPHBhdGggZD0iTTQ4IDg1LjYzNTZDNDggODUuNjM1NiA1Mi40NTMzIDg1LjYzNTYgNTUuNDQgODIuNTg2N0M1OC45MTU1IDc5LjI4MDEgNTcuMzUxMSA3NS40MzEyIDYyLjI3NTUgNzEuNDMxMkM2Ni45ODY2IDY3LjY0NDUgNzIuOTI0NCA3MC4zMzc5IDcyLjkyNDQgNzAuMzM3OUM3Ny4wMjIyIDYyLjEyNDUgNzQuNzkxMSA1Mi41NjkgNzQuNzkxMSA1Mi41NjlDODEuNzY4OCAzNC4yNTc5IDc1Ljk2NDQgMjEuMTU1NyA3NC40NDQ0IDE3LjM2MDFDNjkuNDQ4OCAyNC4zMzc5IDYzLjE5MTEgMjkuMTczNCA1NS43OTU1IDMyLjQwOUM1My4yMjY2IDMxLjcwNjggNTAuNTk1NSAzMS4zMzM0IDQ4IDMxLjM2MDFDNDUuNDEzMyAzMS4zMzM0IDQyLjc3MzMgMzEuNzA2OCA0MC4yMDQ0IDMyLjQwOUMzMi44MTc3IDI5LjE2NDUgMjYuNTUxMSAyNC4zMzc5IDIxLjU1NTUgMTcuMzYwMUMyMC4wMzU1IDIxLjE1NTcgMTQuMjMxMSAzNC4yNTc5IDIxLjIwODkgNTIuNTY5QzIxLjIwODkgNTIuNTY5IDE4Ljk3NzggNjIuMTI0NSAyMy4wNzU1IDcwLjMzNzlDMjMuMDc1NSA3MC4zMzc5IDI5LjAxMzMgNjcuNjQ0NSAzMy43MjQ0IDcxLjQzMTJDMzguNjU3NyA3NS40MzEyIDM3LjA4NDQgNzkuMjgwMSA0MC41NiA4Mi41ODY3QzQzLjU0NjYgODUuNjM1NiA0OCA4NS42MzU2IDQ4IDg1LjYzNTZaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNNDIuNDc5OSA2NS4yOThDNDIuMjkzMyA1OS4yMTggMzYuMzAyMSA1Ny4yNjI0IDMyLjIxMzMgNTkuODIyNEMzMi4yMTMzIDU5LjgyMjQgMzIuODUzMyA2Mi40MzU4IDM1LjgzOTkgNjMuNzUxM0MzOC4yNzU1IDY0LjgyNjkgMzkuMzI0NCA2My4zODY5IDQyLjQ3OTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNMjIuNDk3NyAyMy4wOTM1QzIwLjA4ODggMzEuNTQ2OCAyMS4xMjg4IDQyLjI0MDIgMjQuOTMzMyA1MC4wMjY5QzI4LjgyNjYgNDcuMjcxMyAzMi45MTU1IDQzLjAxMzUgMzUuMDkzMyAzOC41MDY5QzI5Ljk2NDQgMzQuNzExMyAyNS42NjIyIDMxLjEwMjQgMjIuNDk3NyAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNTMuNTE5OSA2NS4yOThDNTMuNzA2NiA1OS4yMTggNTkuNjk3NyA1Ny4yNjI0IDYzLjc4NjYgNTkuODIyNEM2My43ODY2IDU5LjgyMjQgNjMuMTQ2NiA2Mi40MzU4IDYwLjE1OTkgNjMuNzUxM0M1Ny43MjQzIDY0LjgyNjkgNTYuNjc1NSA2My4zODY5IDUzLjUxOTkgNjUuMjk4WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNzMuNTAyMiAyMy4wOTM1Qzc1LjkxMTEgMzEuNTQ2OCA3NC44NzExIDQyLjI0MDIgNzEuMDY2NiA1MC4wMjY5QzY3LjE3MzMgNDcuMjcxMyA2My4wODQ0IDQzLjAxMzUgNjAuOTA2NiAzOC41MDY5QzY2LjAzNTUgMzQuNzExMyA3MC4zMzc3IDMxLjEwMjQgNzMuNTAyMiAyMy4wOTM1WiIgZmlsbD0iIzdCODFGOSIvPgo8cGF0aCBkPSJNNDcuOTk5OSA4NS4zMDY5QzUwLjE0MDQgODUuMzA2OSA1MS44NzU1IDgzLjc3ODcgNTEuODc1NSA4MS44OTM2QzUxLjg3NTUgODAuMDA4NCA1MC4xNDA0IDc4LjQ4MDIgNDcuOTk5OSA3OC40ODAyQzQ1Ljg1OTUgNzguNDgwMiA0NC4xMjQ0IDgwLjAwODQgNDQuMTI0NCA4MS44OTM2QzQ0LjEyNDQgODMuNzc4NyA0NS44NTk1IDg1LjMwNjkgNDcuOTk5OSA4NS4zMDY5WiIgZmlsbD0iIzdCODFGOSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=new Set(["legacy",0]),this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._publicKey=null,this._wallet=null,this._readyState!==ge.Unsupported&&Oo(()=>window?.nightly?.solana?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get connecting(){return this._connecting}get readyState(){return this._readyState}get publicKey(){return this._publicKey}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.nightly.solana;try{await e.connect()}catch(i){throw new ic(i?.message,i)}if(e.publicKey.toString()==="11111111111111111111111111111111")throw new Es;let t;try{t=new N.PublicKey(e.publicKey.toBytes())}catch(i){throw new gr(i?.message,i)}this._wallet=e,this._publicKey=t,this.emit("connect",t)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{await e.disconnect()}catch{this.emit("error",new uf)}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{return t.signMessage(new TextDecoder().decode(e))}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Qb="Solong";class Jb extends _h{constructor(e={}){super(),this.name=Qb,this.url="https://solongwallet.io",this.icon="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAGlklEQVR4Ae3bA5DsyhfH8TNr49r2/du2bdu2bdu2zcdNrm3b9toz533rvctUn3Umk9p01WfdvVW/6nROBxJVS1rSkpa0pCUtaUlLWtKSpl4VXos3GJ4sujQFuUKfWl+qT730arzB8Ex9YksKcgXjFOCVeIPhBYydB8mawQ+yiGC8n0EN6zAVcgXhpQjoq1DDdsyDAAB9Pwo1HMC9INk0FIM8Bt1Qh9WohQQCvD+BtEMdtmC8I7y5aIE67MV0SBwDvB3qsE/UHwMJIpC/QB1OYiLEEeCPoQ7nMRcSwwDrao3Zl8aTIEGEUYlL0IAMXuQOr66UvsegDm+ExDJAPNiafSg0AlyIbmjAWX1aQzEkiH6T0QkNaEdpnAN8NNRhPcSF9e9el2ebBhyAuNBvGtLQgIuQOAd4D6jDMRQbM3AmOqEBDfq0xjJIEP3GohkakEFVjAP0y401sAsLnAE+pb6EsC5AA9J4sHsG+kX0PQR1eFJ8AwTWQh0+DjFm4a1Qh2/AOoz/BHX4ZdwD/CDU4aioX2GUMW+AOnB2bqiBBDHe86EOTYw5GRKJwQ/ijUM91OGTxgysxSmowzeNw7j08m5DHX4l7Igg2TY0g9hbLBZ+f7oxC98CdWjDvYzD+MVQh07GfEQsZyDgVWA71OGvorfnQQCAcqaYUFZDHW6j/itAoB70GcergzqsEa0rhGTTEA7mP0koK4xdyeOMmvBBhJU2zsjPMw7lu9O3zShpXheHk4hhcZ4w26AOG4RSxDiUfwZ12KdPqy+FBDHeV6EOZxizIg6HsMGbiQ5jdjzBXRfeefGg3tgbv9BYC0fhZE7sjUMY9Pf9rdcI5XtQh39BjBA/C3VYnM0zcgiDek+GOhzh93mQoMs7kIxze/eMhnxIEOPNM9bcFtTEeAb6I419axu/m2CsgxU4Aw1A/UxIUM/bO/9+cVkDDd5x42x8N1iH8Taow0NhHcZLoQ5Pi/MMzDMW+DTu7g6vIY9AdkAdHmaUMyn6roA6PD22AeLB6DbWplHG7LubfY+kfiIkiH5T0AJ1uFtMA1xUzOc1UIclzvCeXF+o7DygDlvds29RgVVzYj+K4xhgEX4NdcjgecE++rSL+ZdLmIxRB77Ose7l4XPIQB3eF8M60C/n8++ghltE/QLIFfqUiyUE8kOoYSW7jmLIFXeN4X0NaajDDlG/NG6XswrxKdxu+G/weh27j3wCej9uN9zEOjc3sObl4S243XBLhDfWE0mAMQjwZfhxDng7pG/8Sj4/ER/Gd/BdfBhPRGW2A/wxNAfcBOnFCHwZZ6GGs/gqapMAb/QEnIT20Uk8IQkQeB7aof3UihcM9wDvhyboANHXv1+IdWBOB2hsIftto+iSPEif8aGPcjrA50GHyPMiOIT9B/N5apaMgQT8D2poxMdwt8s+hkao4X9ZDxBTIdHwy/h8AeqQxhMhAU9BB9ThPMqHTYCYjU6owy3uPstSfL4Z6uZPC+Mk8gOomz8DEg3vXshAHb4MMXwZarhXGDPwa739w2j48623BPAniOFPUMPsMAL8INTw9AgDrLZOCmjFPEjA3WD1aUJVGAG+CGr4ECRCy6GGg3iyaF0+n/PwFByEGpaJ+qkw1sB7QA3/hUTozdBetFymvXhTWGVMOc7bp36/FhKRamNW9dcxZmpZiI+32ad+vAQSoWejGzpAXXh22Fek3wY1rDD2kVnijR3ExYQMPgkJOUB/nFW0Is3vnw6JhlHX9a4N70Iq/ACBv0MNu7J9WxHw7jaA2deFOtw32zeVHtHLWvMN0dtSkOzwS3spYy7iH1hx2d/wYdyTvnkR3BdeQjjerVBDN14JyZIfQWH5RC7e1rw32npZV54LCc+SPD5/HgqYD3WW5+gTqt6X+rA4v0701hRkKF0+bL+HTM9Hgv/MHH60wyvHWigsafwA1ZAhMguLoL34kbDcQEI1uAH8mcbuxPHImf8i5EMGxqvER9EI7cUqVMTl0Y6HoxHaBzvxNkyC9EEe7oEv4Sy0D/YQ+IS4ver1JNT38z7sWnwbb8TT8Cg8Gs/Gu/Ar7EEXtI/2ud7Ni0GAYCbiJDQiazA57k9nTcdqaJb9UtSvitXbmjavCJ9AMzRkJ/B80boUJBLhDe7Nw1/QCR1i9fgKRg6HByzvjZ/hInQQMjiCT2PSMHxC1a/l8wvwGxyG9kEaW/EtPI4xiiE5JcLrd6PxcLwM78SH8EG8Fc/H/UUXVUByGh8SSYBJgEmASYCJJMAkwBi6A3xCqZhiBz8+AAAAAElFTkSuQmCC",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.NotDetected,this._connecting=!1,this._wallet=null,this._publicKey=null,this._readyState!==ge.Unsupported&&Oo(()=>window.solong?(this._readyState=ge.Installed,this.emit("readyStateChange",this._readyState),!0):!1)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){return!!this._wallet?.currentAccount}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Installed)throw new Ri;this._connecting=!0;const e=window.solong;let t;try{t=await e.selectAccount()}catch(r){throw new Es(r?.message,r)}let i;try{i=new N.PublicKey(t)}catch(r){throw new gr(r?.message,r)}this._wallet=e,this._publicKey=i,this.emit("connect",i)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){this._wallet&&(this._wallet=null,this._publicKey=null),this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Zb="Torus";class Xb extends Do{constructor({params:e={showTorusButton:!1}}={params:{showTorusButton:!1}}){super(),this.name=Zb,this.url="https://tor.us",this.icon="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzMiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMyAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYuNSIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzAzNjRGRiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTExLjIxODYgOS40OTIxOUMxMC40NTM5IDkuNDkyMTkgOS44MzM5OCAxMC4xMTIxIDkuODMzOTggMTAuODc2OFYxMi40ODk4QzkuODMzOTggMTMuMjU0NSAxMC40NTM5IDEzLjg3NDQgMTEuMjE4NiAxMy44NzQ0SDEzLjY2ODRWMjIuODk3NkMxMy42Njg0IDIzLjY2MjMgMTQuMjg4MyAyNC4yODIyIDE1LjA1MyAyNC4yODIySDE2LjY2NkMxNy40MzA3IDI0LjI4MjIgMTguMDUwNiAyMy42NjIzIDE4LjA1MDYgMjIuODk3NlYxMi41MDE1QzE4LjA1MDYgMTIuNDk3NiAxOC4wNTA2IDEyLjQ5MzcgMTguMDUwNiAxMi40ODk4VjEwLjg3NjhDMTguMDUwNiAxMC4xMTIxIDE3LjQzMDcgOS40OTIxOSAxNi42NjYgOS40OTIxOUgxNS4wNTNIMTEuMjE4NloiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0yMS4zMzc2IDEzLjg3NDRDMjIuNTQ3NyAxMy44NzQ0IDIzLjUyODcgMTIuODkzNCAyMy41Mjg3IDExLjY4MzNDMjMuNTI4NyAxMC40NzMyIDIyLjU0NzcgOS40OTIxOSAyMS4zMzc2IDkuNDkyMTlDMjAuMTI3NSA5LjQ5MjE5IDE5LjE0NjUgMTAuNDczMiAxOS4xNDY1IDExLjY4MzNDMTkuMTQ2NSAxMi44OTM0IDIwLjEyNzUgMTMuODc0NCAyMS4zMzc2IDEzLjg3NDRaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K",this.supportedTransactionVersions=null,this._readyState=typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.Loadable,this._connecting=!1,this._wallet=null,this._publicKey=null,this._params=e}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get connected(){return!!this._wallet?.isLoggedIn}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Loadable)throw new Ri;this._connecting=!0;let e;try{e=(await Promise.resolve().then(()=>require("./solanaEmbed.esm-CDt8Bk0U.js"))).default}catch(n){throw new Ub(n?.message,n)}let t;try{t=window.torus||new e}catch(n){throw new ln(n?.message,n)}if(!t.isInitialized)try{await t.init(this._params)}catch(n){throw new ic(n?.message,n)}let i;try{i=await t.login()}catch(n){throw new Es(n?.message,n)}let r;try{r=new N.PublicKey(i[0])}catch(n){throw new gr(n?.message,n)}this._wallet=t,this._publicKey=r,this.emit("connect",r)}catch(e){throw this.emit("error",e),e}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){this._wallet=null,this._publicKey=null;try{e.isLoggedIn&&await e.cleanUp()}catch(t){this.emit("error",new xo(t?.message,t))}}this.emit("disconnect")}async sendTransaction(e,t,i={}){try{const r=this._wallet;if(!r)throw new Ke;try{const{signers:n,...o}=i;e=await this.prepareTransaction(e,t,o),n?.length&&e.partialSign(...n),o.preflightCommitment=o.preflightCommitment||t.commitment;const{signature:a}=await r.signAndSendTransaction(e,o);return a}catch(n){throw n instanceof Mt?n:new sr(n?.message,n)}}catch(r){throw this.emit("error",r),r}}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)||e}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signMessage(e)}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}function $c(s){switch(s){case"processed":case"confirmed":case"finalized":case void 0:return s;case"recent":return"processed";case"single":case"singleGossip":return"confirmed";case"max":case"root":return"finalized";default:return}}const ev="https://api.mainnet-beta.solana.com";function tv(s){return s.includes(ev)?se.SOLANA_MAINNET_CHAIN:/\bdevnet\b/i.test(s)?se.SOLANA_DEVNET_CHAIN:/\btestnet\b/i.test(s)?se.SOLANA_TESTNET_CHAIN:/\blocalhost\b/i.test(s)||/\b127\.0\.0\.1\b/.test(s)?se.SOLANA_LOCALNET_CHAIN:se.SOLANA_MAINNET_CHAIN}var La;(function(s){s.Mainnet="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",s.Devnet="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",s.Deprecated_Mainnet="solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",s.Deprecated_Devnet="solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})(La||(La={}));var vs;(function(s){s.signTransaction="solana_signTransaction",s.signMessage="solana_signMessage",s.signAndSendTransaction="solana_signAndSendTransaction",s.signAndSendAllTransactions="solana_signAndSendAllTransactions",s.signAllTransactions="solana_signAllTransactions"})(vs||(vs={}));const gt={Mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Deprecated_Mainnet:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",Deprecated_Devnet:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"};var sv=Object.defineProperty,iv=(s,e,t)=>e in s?sv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Su=(s,e,t)=>iv(s,typeof e!="symbol"?e+"":e,t);let rv=class extends h.IEvents{constructor(e){super(),this.opts=e,Su(this,"protocol","wc"),Su(this,"version",2)}};var nv=Object.defineProperty,ov=(s,e,t)=>e in s?nv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,av=(s,e,t)=>ov(s,e+"",t);let cv=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,av(this,"records",new Map)}},lv=class{constructor(e,t){this.logger=e,this.core=t}},hv=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},uv=class extends h.IEvents{constructor(e){super()}},dv=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},pv=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},gv=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},fv=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},wv=class{constructor(e,t){this.projectId=e,this.logger=t}},yv=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};function Io(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function $u(s){return Io(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const pf="2.23.2";let Tc={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${pf}`},rc=class El extends Error{constructor(e,t={}){const i=t.cause instanceof El?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof El&&t.cause.docsPath||t.docsPath,n=Tc.getDocsUrl?.({...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...Tc.version?[`Version: ${Tc.version}`]:[]].join(`
2
+ `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=pf}walk(e){return gf(this,e)}};function gf(s,e){return e?.(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?gf(s.cause,e):e?null:s}let ff=class extends rc{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}};function Cn(s,{dir:e,size:t=32}={}){return typeof s=="string"?mv(s,{dir:e,size:t}):bv(s,{dir:e,size:t})}function mv(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new ff({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function bv(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new ff({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}let vv=class extends rc{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}},Iv=class extends rc{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}};function _n(s,{size:e}){if($u(s)>e)throw new Iv({givenSize:$u(s),maxSize:e})}function Al(s,e={}){const{signed:t}=e;e.size&&_n(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function Ev(s,e={}){return Number(Al(s,e))}const Av=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Nl(s,e={}){return typeof s=="number"||typeof s=="bigint"?yf(s,e):typeof s=="string"?_v(s,e):typeof s=="boolean"?Nv(s,e):wf(s,e)}function Nv(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(_n(t,{size:e.size}),Cn(t,{size:e.size})):t}function wf(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=Av[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(_n(i,{size:e.size}),Cn(i,{dir:"right",size:e.size})):i}function yf(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof s=="bigint"?"n":"";throw new vv({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${s}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?Cn(a,{size:i}):a}const Cv=new TextEncoder;function _v(s,e={}){const t=Cv.encode(s);return wf(t,e)}const Sv=new TextEncoder;function $v(s,e={}){return typeof s=="number"||typeof s=="bigint"?Pv(s,e):typeof s=="boolean"?Tv(s,e):Io(s)?mf(s,e):bf(s,e)}function Tv(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(_n(t,{size:e.size}),Cn(t,{size:e.size})):t}const ti={zero:48,nine:57,A:65,F:70,a:97,f:102};function Tu(s){if(s>=ti.zero&&s<=ti.nine)return s-ti.zero;if(s>=ti.A&&s<=ti.F)return s-(ti.A-10);if(s>=ti.a&&s<=ti.f)return s-(ti.a-10)}function mf(s,e={}){let t=s;e.size&&(_n(t,{size:e.size}),t=Cn(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Tu(i.charCodeAt(a++)),l=Tu(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new rc(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function Pv(s,e){const t=yf(s,e);return mf(t)}function bf(s,e={}){const t=Sv.encode(s);return typeof e.size=="number"?(_n(t,{size:e.size}),Cn(t,{dir:"right",size:e.size})):t}function za(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function xv(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ko(s,...e){if(!xv(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Mv(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");za(s.outputLen),za(s.blockLen)}function Cl(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function vf(s,e){ko(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const na=BigInt(2**32-1),Pu=BigInt(32);function Ov(s,e=!1){return e?{h:Number(s&na),l:Number(s>>Pu&na)}:{h:Number(s>>Pu&na)|0,l:Number(s&na)|0}}function Dv(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=Ov(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const kv=(s,e,t)=>s<<t|e>>>32-t,jv=(s,e,t)=>e<<t|s>>>32-t,Rv=(s,e,t)=>e<<t-32|s>>>64-t,Uv=(s,e,t)=>s<<t-32|e>>>64-t,Er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Lv(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function zv(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Fv(s,e){return s<<32-e|s>>>e}const xu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function qv(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Mu(s){for(let e=0;e<s.length;e++)s[e]=qv(s[e])}function Bv(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Sh(s){return typeof s=="string"&&(s=Bv(s)),ko(s),s}function Hv(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];ko(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}let If=class{clone(){return this._cloneInto()}};function Ef(s){const e=i=>s().update(Sh(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Wv(s=32){if(Er&&typeof Er.getRandomValues=="function")return Er.getRandomValues(new Uint8Array(s));if(Er&&typeof Er.randomBytes=="function")return Er.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Af=[],Nf=[],Cf=[],Vv=BigInt(0),Rn=BigInt(1),Kv=BigInt(2),Gv=BigInt(7),Yv=BigInt(256),Qv=BigInt(113);for(let s=0,e=Rn,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Af.push(2*(5*i+t)),Nf.push((s+1)*(s+2)/2%64);let r=Vv;for(let n=0;n<7;n++)e=(e<<Rn^(e>>Gv)*Qv)%Yv,e&Kv&&(r^=Rn<<(Rn<<BigInt(n))-Rn);Cf.push(r)}const[Jv,Zv]=Dv(Cf,!0),Ou=(s,e,t)=>t>32?Rv(s,e,t):kv(s,e,t),Du=(s,e,t)=>t>32?Uv(s,e,t):jv(s,e,t);function Xv(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],u=t[c+1],d=Ou(l,u,1)^t[a],p=Du(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Nf[o],c=Ou(r,n,a),l=Du(r,n,a),u=Af[o];r=s[u],n=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=Jv[i],s[1]^=Zv[i]}t.fill(0)}let e0=class _f extends If{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,za(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Lv(this.state)}keccak(){xu||Mu(this.state32),Xv(this.state32,this.rounds),xu||Mu(this.state32),this.posOut=0,this.pos=0}update(e){Cl(this);const{blockLen:t,state:i}=this;e=Sh(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(t&128)!==0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Cl(this,!1),ko(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.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 za(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(vf(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new _f(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const t0=(s,e,t)=>Ef(()=>new e0(e,s,t)),s0=t0(1,136,256/8);function Sf(s,e){const t=e||"hex",i=s0(Io(s,{strict:!1})?$v(s):s);return t==="bytes"?i:Nl(i)}let i0=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}};const Pc=new i0(8192);function r0(s,e){if(Pc.has(`${s}.${e}`))return Pc.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=Sf(bf(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Pc.set(`${s}.${e}`,n),n}function n0(s){const e=Sf(`0x${s.substring(4)}`).substring(26);return r0(`0x${e}`)}async function o0({hash:s,signature:e}){const t=Io(s)?s:Nl(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-PbbUc2aU.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:d,yParity:p}=e,f=Number(p??d),g=ku(f);return new i.Signature(Al(l),Al(u)).addRecoveryBit(g)}const o=Io(e)?e:Nl(e),a=Ev(`0x${o.slice(130)}`),c=ku(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function ku(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function a0({hash:s,signature:e}){return n0(await o0({hash:s,signature:e}))}var $f=Xt.requireElliptic();const Tf=":";function fn(s){const[e,t]=s.split(Tf);return{namespace:e,reference:t}}function c0(s){const[e,t,i]=s.split(Tf);return{namespace:e,reference:t,address:i}}function Pf(s,e){return s.includes(":")?[s]:e.chains||[]}const l0="ReactNative",cs={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},h0="js";function Fa(){return typeof N.process$1<"u"&&typeof N.process$1.versions<"u"&&typeof N.process$1.versions.node<"u"}function Ui(){return!h.cjsExports$2.getDocument()&&!!h.cjsExports$2.getNavigator()&&navigator.product===l0}function u0(){return Ui()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"&&(N.global==null?void 0:N.global.Platform.OS)==="android"}function d0(){return Ui()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"&&(N.global==null?void 0:N.global.Platform.OS)==="ios"}function jo(){return!Fa()&&!!h.cjsExports$2.getNavigator()&&!!h.cjsExports$2.getDocument()}function Ro(){return Ui()?cs.reactNative:Fa()?cs.node:jo()?cs.browser:cs.unknown}function ju(){var s;try{return Ui()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Application)<"u"?(s=N.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function p0(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function xf(){return h.cjsExports.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function g0(){if(Ro()===cs.reactNative&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"){const{OS:t,Version:i}=N.global.Platform;return[t,i].join("-")}const s=h.detect();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function f0(){var s;const e=Ro();return e===cs.browser?[e,((s=h.cjsExports$2.getLocation())==null?void 0:s.host)||"unknown"].join(":"):e}function Mf(s,e,t){const i=g0(),r=f0();return[[s,e].join("-"),[h0,t].join("-"),i,r].join("/")}function w0({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),u=Mf(s,e,i),d={auth:r,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=p0(l[1]||"",d);return l[0]+"?"+p}function ir(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Of(s){return Object.fromEntries(s.entries())}function Df(s){return new Map(Object.entries(s))}function Yi(s=h.cjsExports$1.FIVE_MINUTES,e){const t=h.cjsExports$1.toMiliseconds(s||h.cjsExports$1.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},t),i=a,r=c})}}function $i(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function kf(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.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: ${s}`)}function y0(s){return kf("topic",s)}function m0(s){return kf("id",s)}function jf(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function dt(s,e){return h.cjsExports$1.fromMiliseconds(Date.now()+h.cjsExports$1.toMiliseconds(s))}function Ci(s){return Date.now()>=h.cjsExports$1.toMiliseconds(s)}function Pe(s,e){return`${s}${e?`:${e}`:""}`}function Ta(s=[],e=[]){return[...new Set([...s,...e])]}async function b0({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r?.href;if(typeof n!="string")return;const o=v0(n,s,e),a=Ro();if(a===cs.browser){if(!((i=h.cjsExports$2.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}I0(o)}else a===cs.reactNative&&typeof(N.global==null?void 0:N.global.Linking)<"u"&&await N.global.Linking.openURL(o)}catch(r){console.error(r)}}function v0(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${C0(i,!0)}`}else r=`${r}/wc?${i}`;return r}function I0(s){let e="_self";N0()?e="_top":(A0()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function E0(s,e){let t="";try{if(jo()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Ru(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Uu(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function $h(){return typeof N.process$1<"u"&&N.process$1.env.IS_VITEST==="true"}function A0(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function N0(){try{return window.self!==window.top}catch{return!1}}function C0(s,e=!1){const t=N.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Rf(s){return N.Buffer.from(s,"base64").toString("utf-8")}function _0(s){return new Promise(e=>setTimeout(e,s))}function Eo(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function S0(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function nc(s,...e){if(!S0(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Th(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Eo(s.outputLen),Eo(s.blockLen)}function bn(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Uf(s,e){nc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const oa=BigInt(2**32-1),Lu=BigInt(32);function $0(s,e=!1){return e?{h:Number(s&oa),l:Number(s>>Lu&oa)}:{h:Number(s>>Lu&oa)|0,l:Number(s&oa)|0}}function T0(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=$0(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const P0=(s,e,t)=>s<<t|e>>>32-t,x0=(s,e,t)=>e<<t|s>>>32-t,M0=(s,e,t)=>e<<t-32|s>>>64-t,O0=(s,e,t)=>s<<t-32|e>>>64-t,Ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function D0(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function xc(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Ls(s,e){return s<<32-e|s>>>e}const zu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function k0(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Fu(s){for(let e=0;e<s.length;e++)s[e]=k0(s[e])}function j0(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function vn(s){return typeof s=="string"&&(s=j0(s)),nc(s),s}let Ph=class{clone(){return this._cloneInto()}};function Lf(s){const e=i=>s().update(vn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Uo(s=32){if(Ar&&typeof Ar.getRandomValues=="function")return Ar.getRandomValues(new Uint8Array(s));if(Ar&&typeof Ar.randomBytes=="function")return Ar.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const zf=[],Ff=[],qf=[],R0=BigInt(0),Un=BigInt(1),U0=BigInt(2),L0=BigInt(7),z0=BigInt(256),F0=BigInt(113);for(let s=0,e=Un,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],zf.push(2*(5*i+t)),Ff.push((s+1)*(s+2)/2%64);let r=R0;for(let n=0;n<7;n++)e=(e<<Un^(e>>L0)*F0)%z0,e&U0&&(r^=Un<<(Un<<BigInt(n))-Un);qf.push(r)}const[q0,B0]=T0(qf,!0),qu=(s,e,t)=>t>32?M0(s,e,t):P0(s,e,t),Bu=(s,e,t)=>t>32?O0(s,e,t):x0(s,e,t);function H0(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],u=t[c+1],d=qu(l,u,1)^t[a],p=Bu(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Ff[o],c=qu(r,n,a),l=Bu(r,n,a),u=zf[o];r=s[u],n=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=q0[i],s[1]^=B0[i]}t.fill(0)}let W0=class Bf extends Ph{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Eo(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=D0(this.state)}keccak(){zu||Fu(this.state32),H0(this.state32,this.rounds),zu||Fu(this.state32),this.posOut=0,this.pos=0}update(e){bn(this);const{blockLen:t,state:i}=this;e=vn(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(t&128)!==0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){bn(this,!1),nc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.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 Eo(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Uf(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Bf(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const V0=(s,e,t)=>Lf(()=>new W0(e,s,t)),K0=V0(1,136,256/8),G0="https://rpc.walletconnect.org/v1";function Hf(s){const e=`Ethereum Signed Message:
3
3
  ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+N.Buffer.from(K0(t)).toString("hex")}async function Y0(s,e,t,i,r,n){switch(t.t){case"eip191":return await Q0(s,e,t.s);case"eip1271":return await J0(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function Q0(s,e,t){return(await a0({hash:Hf(e),signature:t})).toLowerCase()===s.toLowerCase()}async function J0(s,e,t,i,r,n){const o=fn(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l="0000000000000000000000000000000000000000000000000000000000000041",u=t.substring(2),d=Hf(e).substring(2),p=a+d+c+l+u,f=await fetch(`${n||G0}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:Z0(),jsonrpc:"2.0",method:"eth_call",params:[{to:s,data:p},"latest"]})}),{result:g}=await f.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Z0(){return Date.now()+Math.floor(Math.random()*1e3)}var X0=Object.defineProperty,eI=Object.defineProperties,tI=Object.getOwnPropertyDescriptors,Hu=Object.getOwnPropertySymbols,sI=Object.prototype.hasOwnProperty,iI=Object.prototype.propertyIsEnumerable,Wu=(s,e,t)=>e in s?X0(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,rI=(s,e)=>{for(var t in e||(e={}))sI.call(e,t)&&Wu(s,t,e[t]);if(Hu)for(var t of Hu(e))iI.call(e,t)&&Wu(s,t,e[t]);return s},nI=(s,e)=>eI(s,tI(e));const oI="did:pkh:",xh=s=>s?.split(":"),aI=s=>{const e=s&&xh(s);if(e)return s.includes(oI)?e[3]:e[1]},_l=s=>{const e=s&&xh(s);if(e)return e[2]+":"+e[3]},qa=s=>{const e=s&&xh(s);if(e)return e.pop()};async function Vu(s){const{cacao:e,projectId:t}=s,{s:i,p:r}=e,n=Wf(r,r.iss),o=qa(r.iss);return await Y0(o,n,i,_l(r.iss),t)}const Wf=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=qa(e);if(!s.aud&&!s.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=s.statement||void 0;const n=`URI: ${s.aud||s.uri}`,o=`Version: ${s.version}`,a=`Chain ID: ${aI(e)}`,c=`Nonce: ${s.nonce}`,l=`Issued At: ${s.iat}`,u=s.exp?`Expiration Time: ${s.exp}`:void 0,d=s.nbf?`Not Before: ${s.nbf}`:void 0,p=s.requestId?`Request ID: ${s.requestId}`:void 0,f=s.resources?`Resources:${s.resources.map(w=>`
4
4
  - ${w}`).join("")}`:void 0,g=Pa(s.resources);if(g){const w=Ao(g);r=wI(r,w)}return[t,i,"",r,"",n,o,a,c,l,u,d,p,f].filter(w=>w!=null).join(`
5
5
  `)};function cI(s){return N.Buffer.from(JSON.stringify(s)).toString("base64")}function lI(s){return JSON.parse(N.Buffer.from(s,"base64").toString("utf-8"))}function ar(s){if(!s)throw new Error("No recap provided, value is undefined");if(!s.att)throw new Error("No `att` property found");const e=Object.keys(s.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=s.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(r=>{const n=i[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function hI(s,e,t,i={}){return t?.sort((r,n)=>r.localeCompare(n)),{att:{[s]:uI(e,t,i)}}}function uI(s,e,t={}){e=e?.sort((r,n)=>r.localeCompare(n));const i=e.map(r=>({[`${s}/${r}`]:[t]}));return Object.assign({},...i)}function Vf(s){return ar(s),`urn:recap:${cI(s).replace(/=/g,"")}`}function Ao(s){const e=lI(s.replace("urn:recap:",""));return ar(e),e}function dI(s,e,t){const i=hI(s,e,t);return Vf(i)}function pI(s){return s&&s.includes("urn:recap:")}function gI(s,e){const t=Ao(s),i=Ao(e),r=fI(t,i);return Vf(r)}function fI(s,e){ar(s),ar(e);const t=Object.keys(s.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),i={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=s.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;i.att[r]=nI(rI({},i.att[r]),{[a]:((c=s.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),i}function wI(s="",e){ar(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(s.includes(t))return s;const i=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,p)=>d.action.localeCompare(p.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const u=Object.keys(l).map(d=>(r++,`(${r}) '${d}': '${l[d].join("', '")}' for '${a}'.`));i.push(u.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function Ku(s){var e;const t=Ao(s);ar(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function Gu(s){const e=Ao(s);ar(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(r=>{var n;(n=r?.[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function Pa(s){if(!s)return;const e=s?.[s.length-1];return pI(e)?e:void 0}function Mc(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Kf(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function os(s,...e){if(!Kf(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Yu(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function yI(s,e){os(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Qu(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const Oi=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),mI=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),bI=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!bI)throw new Error("Non little-endian hardware is not supported");function vI(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function Sl(s){if(typeof s=="string")s=vI(s);else if(Kf(s))s=$l(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function II(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function EI(s,e){if(s.length!==e.length)return!1;let t=0;for(let i=0;i<s.length;i++)t|=s[i]^e[i];return t===0}const AI=(s,e)=>{function t(i,...r){if(os(i),s.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");s.varSizeNonce?os(l):os(l,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&os(r[1]);const o=e(i,...r),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");os(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,os(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(os(l),n&&l.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(t,s),t};function Ju(s,e,t=!0){if(e===void 0)return new Uint8Array(s);if(e.length!==s)throw new Error("invalid output length, expected "+s+", got: "+e.length);if(t&&!NI(e))throw new Error("invalid output, must be aligned");return e}function Zu(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);s.setUint32(e+4,o,i),s.setUint32(e+0,a,i)}function NI(s){return s.byteOffset%4===0}function $l(s){return Uint8Array.from(s)}function In(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const Gf=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),CI=Gf("expand 16-byte k"),_I=Gf("expand 32-byte k"),SI=Oi(CI),$I=Oi(_I);function Ee(s,e){return s<<e|s>>>32-e}function Tl(s){return s.byteOffset%4===0}const aa=64,TI=16,Yf=2**32-1,Xu=new Uint32Array;function PI(s,e,t,i,r,n,o,a){const c=r.length,l=new Uint8Array(aa),u=Oi(l),d=Tl(r)&&Tl(n),p=d?Oi(r):Xu,f=d?Oi(n):Xu;for(let g=0;g<c;o++){if(s(e,t,i,u,o,a),o>=Yf)throw new Error("arx: counter overflow");const w=Math.min(aa,c-g);if(d&&w===aa){const b=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let v=0,m;v<TI;v++)m=b+v,f[m]=p[m]^u[v];g+=aa;continue}for(let b=0,v;b<w;b++)v=g+b,n[v]=r[v]^l[b];g+=w}}function xI(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=II({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return Mc(r),Mc(o),Qu(n),Qu(t),(a,c,l,u,d=0)=>{os(a),os(c),os(l);const p=l.length;if(u===void 0&&(u=new Uint8Array(p)),os(u),Mc(d),d<0||d>=Yf)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);const f=[];let g=a.length,w,b;if(g===32)f.push(w=$l(a)),b=$I;else if(g===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),b=SI,f.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Tl(c)||f.push(c=$l(c));const v=Oi(w);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(b,v,Oi(c.subarray(0,16)),v),c=c.subarray(16)}const m=16-r;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const C=new Uint8Array(12);C.set(c,n?0:12-c.length),c=C,f.push(c)}const A=Oi(c);return PI(s,b,v,A,l,u,d,o),In(...f),u}}const Nt=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let MI=class{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=Sl(e),os(e,32);const t=Nt(e,0),i=Nt(e,2),r=Nt(e,4),n=Nt(e,6),o=Nt(e,8),a=Nt(e,10),c=Nt(e,12),l=Nt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Nt(e,16+2*u)}process(e,t,i=!1){const r=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],p=o[5],f=o[6],g=o[7],w=o[8],b=o[9],v=Nt(e,t+0),m=Nt(e,t+2),A=Nt(e,t+4),C=Nt(e,t+6),S=Nt(e,t+8),$=Nt(e,t+10),O=Nt(e,t+12),D=Nt(e,t+14);let T=n[0]+(v&8191),q=n[1]+((v>>>13|m<<3)&8191),j=n[2]+((m>>>10|A<<6)&8191),G=n[3]+((A>>>7|C<<9)&8191),B=n[4]+((C>>>4|S<<12)&8191),W=n[5]+(S>>>1&8191),V=n[6]+((S>>>14|$<<2)&8191),H=n[7]+(($>>>11|O<<5)&8191),K=n[8]+((O>>>8|D<<8)&8191),Q=n[9]+(D>>>5|r),_=0,z=_+T*a+q*(5*b)+j*(5*w)+G*(5*g)+B*(5*f);_=z>>>13,z&=8191,z+=W*(5*p)+V*(5*d)+H*(5*u)+K*(5*l)+Q*(5*c),_+=z>>>13,z&=8191;let ee=_+T*c+q*a+j*(5*b)+G*(5*w)+B*(5*g);_=ee>>>13,ee&=8191,ee+=W*(5*f)+V*(5*p)+H*(5*d)+K*(5*u)+Q*(5*l),_+=ee>>>13,ee&=8191;let J=_+T*l+q*c+j*a+G*(5*b)+B*(5*w);_=J>>>13,J&=8191,J+=W*(5*g)+V*(5*f)+H*(5*p)+K*(5*d)+Q*(5*u),_+=J>>>13,J&=8191;let ve=_+T*u+q*l+j*c+G*a+B*(5*b);_=ve>>>13,ve&=8191,ve+=W*(5*w)+V*(5*g)+H*(5*f)+K*(5*p)+Q*(5*d),_+=ve>>>13,ve&=8191;let pe=_+T*d+q*u+j*l+G*c+B*a;_=pe>>>13,pe&=8191,pe+=W*(5*b)+V*(5*w)+H*(5*g)+K*(5*f)+Q*(5*p),_+=pe>>>13,pe&=8191;let te=_+T*p+q*d+j*u+G*l+B*c;_=te>>>13,te&=8191,te+=W*a+V*(5*b)+H*(5*w)+K*(5*g)+Q*(5*f),_+=te>>>13,te&=8191;let st=_+T*f+q*p+j*d+G*u+B*l;_=st>>>13,st&=8191,st+=W*c+V*a+H*(5*b)+K*(5*w)+Q*(5*g),_+=st>>>13,st&=8191;let Le=_+T*g+q*f+j*p+G*d+B*u;_=Le>>>13,Le&=8191,Le+=W*l+V*c+H*a+K*(5*b)+Q*(5*w),_+=Le>>>13,Le&=8191;let Ie=_+T*w+q*g+j*f+G*p+B*d;_=Ie>>>13,Ie&=8191,Ie+=W*u+V*l+H*c+K*a+Q*(5*b),_+=Ie>>>13,Ie&=8191;let ke=_+T*b+q*w+j*g+G*f+B*p;_=ke>>>13,ke&=8191,ke+=W*d+V*u+H*l+K*c+Q*a,_+=ke>>>13,ke&=8191,_=(_<<2)+_|0,_=_+z|0,z=_&8191,_=_>>>13,ee+=_,n[0]=z,n[1]=ee,n[2]=J,n[3]=ve,n[4]=pe,n[5]=te,n[6]=st,n[7]=Le,n[8]=Ie,n[9]=ke}finalize(){const{h:e,pad:t}=this,i=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,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+r,r=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[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]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;In(i)}update(e){Yu(this);const{buffer:t,blockLen:i}=this;e=Sl(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){for(;i<=r-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){In(this.h,this.r,this.buffer,this.pad)}digestInto(e){Yu(this),yI(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}};function OI(s){const e=(i,r)=>s(r).update(Sl(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const DI=OI(s=>new MI(s));function kI(s,e,t,i,r,n=20){let o=s[0],a=s[1],c=s[2],l=s[3],u=e[0],d=e[1],p=e[2],f=e[3],g=e[4],w=e[5],b=e[6],v=e[7],m=r,A=t[0],C=t[1],S=t[2],$=o,O=a,D=c,T=l,q=u,j=d,G=p,B=f,W=g,V=w,H=b,K=v,Q=m,_=A,z=C,ee=S;for(let ve=0;ve<n;ve+=2)$=$+q|0,Q=Ee(Q^$,16),W=W+Q|0,q=Ee(q^W,12),$=$+q|0,Q=Ee(Q^$,8),W=W+Q|0,q=Ee(q^W,7),O=O+j|0,_=Ee(_^O,16),V=V+_|0,j=Ee(j^V,12),O=O+j|0,_=Ee(_^O,8),V=V+_|0,j=Ee(j^V,7),D=D+G|0,z=Ee(z^D,16),H=H+z|0,G=Ee(G^H,12),D=D+G|0,z=Ee(z^D,8),H=H+z|0,G=Ee(G^H,7),T=T+B|0,ee=Ee(ee^T,16),K=K+ee|0,B=Ee(B^K,12),T=T+B|0,ee=Ee(ee^T,8),K=K+ee|0,B=Ee(B^K,7),$=$+j|0,ee=Ee(ee^$,16),H=H+ee|0,j=Ee(j^H,12),$=$+j|0,ee=Ee(ee^$,8),H=H+ee|0,j=Ee(j^H,7),O=O+G|0,Q=Ee(Q^O,16),K=K+Q|0,G=Ee(G^K,12),O=O+G|0,Q=Ee(Q^O,8),K=K+Q|0,G=Ee(G^K,7),D=D+B|0,_=Ee(_^D,16),W=W+_|0,B=Ee(B^W,12),D=D+B|0,_=Ee(_^D,8),W=W+_|0,B=Ee(B^W,7),T=T+q|0,z=Ee(z^T,16),V=V+z|0,q=Ee(q^V,12),T=T+q|0,z=Ee(z^T,8),V=V+z|0,q=Ee(q^V,7);let J=0;i[J++]=o+$|0,i[J++]=a+O|0,i[J++]=c+D|0,i[J++]=l+T|0,i[J++]=u+q|0,i[J++]=d+j|0,i[J++]=p+G|0,i[J++]=f+B|0,i[J++]=g+W|0,i[J++]=w+V|0,i[J++]=b+H|0,i[J++]=v+K|0,i[J++]=m+Q|0,i[J++]=A+_|0,i[J++]=C+z|0,i[J++]=S+ee|0}const jI=xI(kI,{counterRight:!1,counterLength:4,allowShortKeys:!1}),RI=new Uint8Array(16),ed=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(RI.subarray(t))},UI=new Uint8Array(32);function td(s,e,t,i,r){const n=s(e,t,UI),o=DI.create(n);r&&ed(o,r),ed(o,i);const a=new Uint8Array(16),c=mI(a);Zu(c,0,BigInt(r?r.length:0),!0),Zu(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return In(n,a),l}const LI=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=Ju(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const c=td(s,e,t,a,i);return n.set(c,o),In(c),n},decrypt(r,n){n=Ju(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=td(s,e,t,o,i);if(!EI(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),In(c),n}}),Qf=AI({blockSize:64,nonceLength:12,tagLength:16},LI(jI));let Jf=class extends Ph{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Th(e);const i=vn(t);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,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return bn(this),this.iHash.update(e),this}digestInto(e){bn(this),nc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Mh=(s,e,t)=>new Jf(s,e).update(t).digest();Mh.create=(s,e)=>new Jf(s,e);function zI(s,e,t){return Th(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Mh(s,vn(t),vn(e))}const Oc=new Uint8Array([0]),sd=new Uint8Array;function FI(s,e,t,i=32){if(Th(s),Eo(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=sd);const n=new Uint8Array(r*s.outputLen),o=Mh.create(s,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)Oc[0]=l+1,a.update(l===0?sd:c).update(t).update(Oc).digestInto(c),n.set(c,s.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Oc.fill(0),n.slice(0,i)}const qI=(s,e,t,i,r)=>FI(s,zI(s,e,t),i,r);function BI(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=i?4:0,l=i?0:4;s.setUint32(e+c,o,i),s.setUint32(e+l,a,i)}function HI(s,e,t){return s&e^~s&t}function WI(s,e,t){return s&e^s&t^e&t}let VI=class extends Ph{constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=xc(this.buffer)}update(e){bn(this);const{view:t,buffer:i,blockLen:r}=this;e=vn(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=xc(e);for(;r<=n-o;o+=r)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){bn(this),Uf(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(i,0),o=0);for(let d=o;d<r;d++)t[d]=0;BI(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=xc(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%t&&e.buffer.set(i),e}};const KI=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),mi=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),bi=new Uint32Array(64);let GI=class extends VI{constructor(){super(64,32,8,!1),this.A=mi[0]|0,this.B=mi[1]|0,this.C=mi[2]|0,this.D=mi[3]|0,this.E=mi[4]|0,this.F=mi[5]|0,this.G=mi[6]|0,this.H=mi[7]|0}get(){const{A:e,B:t,C:i,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,i,r,n,o,a,c]}set(e,t,i,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=i|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)bi[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const p=bi[d-15],f=bi[d-2],g=Ls(p,7)^Ls(p,18)^p>>>3,w=Ls(f,17)^Ls(f,19)^f>>>10;bi[d]=w+bi[d-7]+g+bi[d-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const p=Ls(a,6)^Ls(a,11)^Ls(a,25),f=u+p+HI(a,c,l)+KI[d]+bi[d]|0,g=(Ls(i,2)^Ls(i,13)^Ls(i,22))+WI(i,r,n)|0;u=l,l=c,c=a,a=o+f|0,o=n,n=r,r=i,i=f+g|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(i,r,n,o,a,c,l,u)}roundClean(){bi.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const oc=Lf(()=>new GI);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Zf=BigInt(0);function Oh(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Xf(s){if(!Oh(s))throw new Error("Uint8Array expected")}const YI=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function QI(s){Xf(s);let e="";for(let t=0;t<s.length;t++)e+=YI[s[t]];return e}function JI(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Zf:BigInt("0x"+s)}const si={_0:48,_9:57,A:65,F:70,a:97,f:102};function id(s){if(s>=si._0&&s<=si._9)return s-si._0;if(s>=si.A&&s<=si.F)return s-(si.A-10);if(s>=si.a&&s<=si.f)return s-(si.a-10)}function ew(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=id(s.charCodeAt(n)),a=id(s.charCodeAt(n+1));if(o===void 0||a===void 0){const c=s[n]+s[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[r]=o*16+a}return i}function rd(s){return Xf(s),JI(QI(Uint8Array.from(s).reverse()))}function ZI(s,e){return ew(s.toString(16).padStart(e*2,"0"))}function XI(s,e){return ZI(s,e).reverse()}function nd(s,e,t){let i;if(typeof e=="string")try{i=ew(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(Oh(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const r=i.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return i}const Dc=s=>typeof s=="bigint"&&Zf<=s;function e1(s,e,t){return Dc(s)&&Dc(e)&&Dc(t)&&e<=s&&s<t}function od(s,e,t,i){if(!e1(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const t1={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||Oh(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function s1(s,e,t={}){const i=(r,n,o)=>{const a=t1[n];if(typeof a!="function")throw new Error("invalid validator function");const c=s[r];if(!(o&&c===void 0)&&!a(c,s))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))i(r,n,!1);for(const[r,n]of Object.entries(t))i(r,n,!0);return s}const hn=BigInt(0),ca=BigInt(1);function tw(s,e){const t=s%e;return t>=hn?t:e+t}function i1(s,e,t){if(e<hn)throw new Error("invalid exponent, negatives unsupported");if(t<=hn)throw new Error("invalid modulus");if(t===ca)return hn;let i=ca;for(;e>hn;)e&ca&&(i=i*s%t),s=s*s%t,e>>=ca;return i}function Os(s,e,t){let i=s;for(;e-- >hn;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Nr=BigInt(0),kc=BigInt(1);function r1(s){return s1(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function n1(s){const e=r1(s),{P:t}=e,i=m=>tw(m,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),c=e.powPminus2||(m=>i1(m,t-BigInt(2),t));function l(m,A,C){const S=i(m*(A-C));return A=i(A-S),C=i(C+S),[A,C]}const u=(e.a-BigInt(2))/BigInt(4);function d(m,A){od("u",m,Nr,t),od("scalar",A,Nr,t);const C=A,S=m;let $=kc,O=Nr,D=m,T=kc,q=Nr,j;for(let B=BigInt(r-1);B>=Nr;B--){const W=C>>B&kc;q^=W,j=l(q,$,D),$=j[0],D=j[1],j=l(q,O,T),O=j[0],T=j[1],q=W;const V=$+O,H=i(V*V),K=$-O,Q=i(K*K),_=H-Q,z=D+T,ee=D-T,J=i(ee*V),ve=i(z*K),pe=J+ve,te=J-ve;D=i(pe*pe),T=i(S*i(te*te)),$=i(H*Q),O=i(_*(H+i(u*_)))}j=l(q,$,D),$=j[0],D=j[1],j=l(q,O,T),O=j[0],T=j[1];const G=c(O);return i($*G)}function p(m){return XI(i(m),n)}function f(m){const A=nd("u coordinate",m,n);return o===32&&(A[31]&=127),rd(A)}function g(m){const A=nd("scalar",m),C=A.length;if(C!==n&&C!==o){let S=""+n+" or "+o;throw new Error("invalid scalar, expected "+S+" bytes, got "+C)}return rd(a(A))}function w(m,A){const C=f(A),S=g(m),$=d(C,S);if($===Nr)throw new Error("invalid private or public key received");return p($)}const b=p(e.Gu);function v(m){return w(m,b)}return{scalarMult:w,scalarMultBase:v,getSharedSecret:(m,A)=>w(m,A),getPublicKey:m=>v(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:b}}const Pl=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const o1=BigInt(1),ad=BigInt(2),a1=BigInt(3),c1=BigInt(5);BigInt(8);function l1(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=Pl,o=s*s%n*s%n,a=Os(o,ad,n)*o%n,c=Os(a,o1,n)*s%n,l=Os(c,c1,n)*c%n,u=Os(l,e,n)*l%n,d=Os(u,t,n)*u%n,p=Os(d,i,n)*d%n,f=Os(p,r,n)*p%n,g=Os(f,r,n)*p%n,w=Os(g,e,n)*l%n;return{pow_p_5_8:Os(w,ad,n)*s%n,b2:o}}function h1(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const xl=n1({P:Pl,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=Pl,{pow_p_5_8:t,b2:i}=l1(s);return tw(Os(t,a1,e)*i,e)},adjustScalarBytes:h1,randomBytes:Uo}),sw="base10",zt="base16",Ti="base64pad",Ln="base64url",Lo="utf8",iw=0,di=1,zo=2,u1=0,cd=1,ho=12,Dh=32;function d1(){const s=xl.utils.randomPrivateKey(),e=xl.getPublicKey(s);return{privateKey:h.toString(s,zt),publicKey:h.toString(e,zt)}}function Ml(){const s=Uo(Dh);return h.toString(s,zt)}function p1(s,e){const t=xl.getSharedSecret(h.fromString(s,zt),h.fromString(e,zt)),i=qI(oc,t,void 0,void 0,Dh);return h.toString(i,zt)}function xa(s){const e=oc(h.fromString(s,zt));return h.toString(e,zt)}function hi(s){const e=oc(h.fromString(s,Lo));return h.toString(e,zt)}function rw(s){return h.fromString(`${s}`,sw)}function cr(s){return Number(h.toString(s,sw))}function g1(s){const e=rw(typeof s.type<"u"?s.type:iw);if(cr(e)===di&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?h.fromString(s.senderPublicKey,zt):void 0,i=typeof s.iv<"u"?h.fromString(s.iv,zt):Uo(ho),r=h.fromString(s.symKey,zt),n=Qf(r,i).encrypt(h.fromString(s.message,Lo));return nw({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function f1(s){const e=h.fromString(s.symKey,zt),{sealed:t,iv:i}=No(s),r=Qf(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return h.toString(r,Lo)}function w1(s,e){const t=rw(zo),i=Uo(ho),r=h.fromString(s,Lo);return nw({type:t,sealed:r,iv:i,encoding:e})}function y1(s,e){const{sealed:t}=No({encoded:s,encoding:e});return h.toString(t,Lo)}function nw(s){const{encoding:e=Ti}=s;if(cr(s.type)===zo)return h.toString(h.concat([s.type,s.sealed]),e);if(cr(s.type)===di){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return h.toString(h.concat([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return h.toString(h.concat([s.type,s.iv,s.sealed]),e)}function No(s){const{encoded:e,encoding:t=Ti}=s,i=h.fromString(e,t),r=i.slice(u1,cd),n=cd;if(cr(r)===di){const l=n+Dh,u=l+ho,d=i.slice(n,l),p=i.slice(l,u),f=i.slice(u);return{type:r,sealed:f,iv:p,senderPublicKey:d}}if(cr(r)===zo){const l=i.slice(n),u=Uo(ho);return{type:r,sealed:l,iv:u}}const o=n+ho,a=i.slice(n,o),c=i.slice(o);return{type:r,sealed:c,iv:a}}function m1(s,e){const t=No({encoded:s,encoding:e?.encoding});return ow({type:cr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?h.toString(t.senderPublicKey,zt):void 0,receiverPublicKey:e?.receiverPublicKey})}function ow(s){const e=s?.type||iw;if(e===di){if(typeof s?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof s?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:s?.senderPublicKey,receiverPublicKey:s?.receiverPublicKey}}function ld(s){return s.type===di&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function hd(s){return s.type===zo}function b1(s){return new $f.ec("p256").keyFromPublic({x:N.Buffer.from(s.x,"base64").toString("hex"),y:N.Buffer.from(s.y,"base64").toString("hex")},"hex")}function v1(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function I1(s){return N.Buffer.from(v1(s),"base64")}function E1(s,e){const[t,i,r]=s.split("."),n=I1(r);if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32).toString("hex"),a=n.slice(32,64).toString("hex"),c=`${t}.${i}`,l=oc(c),u=b1(e),d=h.toString(l,zt);if(!u.verify(d,{r:o,s:a}))throw new Error("Invalid signature");return h.sn(s).payload}const A1="irn";function Ba(s){return s?.relay||{protocol:A1}}function so(s){const e=h.C[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function N1(s,e="-"){const t={},i="relay"+e;return Object.keys(s).forEach(r=>{if(r.startsWith(i)){const n=r.replace(i,""),o=s[r];t[n]=o}}),t}function ud(s){if(!s.includes("wc:")){const l=Rf(s);l!=null&&l.includes("wc:")&&(s=l)}s=s.includes("wc://")?s.replace("wc://",""):s,s=s.includes("wc:")?s.replace("wc:",""):s;const e=s.indexOf(":"),t=s.indexOf("?")!==-1?s.indexOf("?"):void 0,i=s.substring(0,e),r=s.substring(e+1,t).split("@"),n=typeof t<"u"?s.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((l,u)=>{a[u]=l});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:C1(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:N1(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function C1(s){return s.startsWith("//")?s.substring(2):s}function _1(s,e="-"){const t="relay",i={};return Object.keys(s).forEach(r=>{const n=r,o=t+e+n;s[n]&&(i[o]=s[n])}),i}function dd(s){const e=new URLSearchParams,t=_1(s.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",s.symKey),s.expiryTimestamp&&e.set("expiryTimestamp",s.expiryTimestamp.toString()),s.methods&&e.set("methods",s.methods.join(","));const i=e.toString();return`${s.protocol}:${s.topic}@${s.version}?${i}`}function la(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function Sn(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function S1(s){const e=[];return Object.values(s).forEach(t=>{e.push(...Sn(t.accounts))}),e}function $1(s,e){const t=[];return Object.values(s).forEach(i=>{Sn(i.accounts).includes(e)&&t.push(...i.methods)}),t}function T1(s,e){const t=[];return Object.values(s).forEach(i=>{Sn(i.accounts).includes(e)&&t.push(...i.events)}),t}function kh(s){return s.includes(":")}function io(s){return kh(s)?s.split(":")[0]:s}function P1(s){const e={};return s?.forEach(t=>{var i;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(i=e[r].chains)==null||i.push(`${r}:${n}`)}),e}function pd(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=P1(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=Ta(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const x1={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}},M1={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function U(s,e){const{message:t,code:i}=M1[s];return{message:e?`${t} ${e}`:t,code:i}}function Re(s,e){const{message:t,code:i}=x1[s];return{message:e?`${t} ${e}`:t,code:i}}function lr(s,e){return!!Array.isArray(s)}function Co(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function Bt(s){return typeof s>"u"}function nt(s,e){return e&&Bt(s)?!0:typeof s=="string"&&!!s.trim().length}function jh(s,e){return e&&Bt(s)?!0:typeof s=="number"&&!isNaN(s)}function O1(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return ir(r,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=s.namespaces[o],u=Sn(a),d=t[o];(!ir(Pf(o,d),u)||!ir(d.methods,c)||!ir(d.events,l))&&(n=!1)}),n):!1}function Ha(s){return nt(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function D1(s){if(nt(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Ha(t)}}return!1}function k1(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(nt(s,!1)){if(e(s))return!0;const t=Rf(s);return e(t)}}catch{}return!1}function j1(s){var e;return(e=s?.proposer)==null?void 0:e.publicKey}function R1(s){return s?.topic}function U1(s,e){let t=null;return nt(s?.publicKey,!1)||(t=U("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function gd(s){let e=!0;return lr(s)?s.length&&(e=s.every(t=>nt(t,!1))):e=!1,e}function L1(s,e,t){let i=null;return lr(e)&&e.length?e.forEach(r=>{i||Ha(r)||(i=Re("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Ha(s)||(i=Re("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function z1(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=L1(r,Pf(r,n),`${e} ${t}`);o&&(i=o)}),i}function F1(s,e){let t=null;return lr(s)?s.forEach(i=>{t||D1(i)||(t=Re("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Re("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function q1(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=F1(i?.accounts,`${e} namespace`);r&&(t=r)}),t}function B1(s,e){let t=null;return gd(s?.methods)?gd(s?.events)||(t=Re("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Re("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function aw(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=B1(i,`${e}, namespace`);r&&(t=r)}),t}function H1(s,e,t){let i=null;if(s&&Co(s)){const r=aw(s,e);r&&(i=r);const n=z1(s,e,t);n&&(i=n)}else i=U("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function jc(s,e){let t=null;if(s&&Co(s)){const i=aw(s,e);i&&(t=i);const r=q1(s,e);r&&(t=r)}else t=U("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function cw(s){return nt(s.protocol,!0)}function W1(s,e){let t=!1;return s?s&&lr(s)&&s.length&&s.forEach(i=>{t=cw(i)}):t=!0,t}function V1(s){return typeof s=="number"}function Qt(s){return typeof s<"u"&&typeof s!==null}function K1(s){return!(!s||typeof s!="object"||!s.code||!jh(s.code,!1)||!s.message||!nt(s.message,!1))}function G1(s){return!(Bt(s)||!nt(s.method,!1))}function Y1(s){return!(Bt(s)||Bt(s.result)&&Bt(s.error)||!jh(s.id,!1)||!nt(s.jsonrpc,!1))}function Q1(s){return!(Bt(s)||!nt(s.name,!1))}function fd(s,e){return!(!Ha(e)||!S1(s).includes(e))}function J1(s,e,t){return nt(t,!1)?$1(s,e).includes(t):!1}function Z1(s,e,t){return nt(t,!1)?T1(s,e).includes(t):!1}function wd(s,e,t){let i=null;const r=X1(s),n=eE(e),o=Object.keys(r),a=Object.keys(n),c=yd(Object.keys(s)),l=yd(Object.keys(e)),u=c.filter(d=>!l.includes(d));return u.length&&(i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
@@ -9,7 +9,7 @@ ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+N.Buffer.from(K0(t)).toS
9
9
  Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||i)return;const p=Sn(e[d].accounts);p.includes(d)||(i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${d}
10
10
  Required: ${d}
11
11
  Approved: ${p.toString()}`))}),o.forEach(d=>{i||(ir(r[d].methods,n[d].methods)?ir(r[d].events,n[d].events)||(i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${d}`)):i=U("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${d}`))}),i}function X1(s){const e={};return Object.keys(s).forEach(t=>{var i;t.includes(":")?e[t]=s[t]:(i=s[t].chains)==null||i.forEach(r=>{e[r]={methods:s[t].methods,events:s[t].events}})}),e}function yd(s){return[...new Set(s.map(e=>e.includes(":")?e.split(":")[0]:e))]}function eE(s){const e={};return Object.keys(s).forEach(t=>{t.includes(":")?e[t]=s[t]:Sn(s[t].accounts)?.forEach(r=>{e[r]={accounts:s[t].accounts.filter(n=>n.includes(`${r}:`)),methods:s[t].methods,events:s[t].events}})}),e}function tE(s,e){return jh(s,!1)&&s<=e.max&&s>=e.min}function md(){const s=Ro();return new Promise(e=>{switch(s){case cs.browser:e(sE());break;case cs.reactNative:e(iE());break;case cs.node:e(rE());break;default:e(!0)}})}function sE(){return jo()&&navigator?.onLine}async function iE(){return Ui()&&typeof N.global<"u"&&N.global!=null&&N.global.NetInfo?(await(N.global==null?void 0:N.global.NetInfo.fetch()))?.isConnected:!0}function rE(){return!0}function nE(s){switch(Ro()){case cs.browser:oE(s);break;case cs.reactNative:aE(s);break}}function oE(s){!Ui()&&jo()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function aE(s){Ui()&&typeof N.global<"u"&&N.global!=null&&N.global.NetInfo&&N.global?.NetInfo.addEventListener(e=>s(e?.isConnected))}const Rc={};let zn=class{static get(e){return Rc[e]}static set(e,t){Rc[e]=t}static delete(e){delete Rc[e]}};var ro={exports:{}};ro.exports;var bd;function cE(){return bd||(bd=1,(function(s,e){var t=200,i="__lodash_hash_undefined__",r=1,n=2,o=9007199254740991,a="[object Arguments]",c="[object Array]",l="[object AsyncFunction]",u="[object Boolean]",d="[object Date]",p="[object Error]",f="[object Function]",g="[object GeneratorFunction]",w="[object Map]",b="[object Number]",v="[object Null]",m="[object Object]",A="[object Promise]",C="[object Proxy]",S="[object RegExp]",$="[object Set]",O="[object String]",D="[object Symbol]",T="[object Undefined]",q="[object WeakMap]",j="[object ArrayBuffer]",G="[object DataView]",B="[object Float32Array]",W="[object Float64Array]",V="[object Int8Array]",H="[object Int16Array]",K="[object Int32Array]",Q="[object Uint8Array]",_="[object Uint8ClampedArray]",z="[object Uint16Array]",ee="[object Uint32Array]",J=/[\\^$.*+?()[\]{}|]/g,ve=/^\[object .+?Constructor\]$/,pe=/^(?:0|[1-9]\d*)$/,te={};te[B]=te[W]=te[V]=te[H]=te[K]=te[Q]=te[_]=te[z]=te[ee]=!0,te[a]=te[c]=te[j]=te[u]=te[G]=te[d]=te[p]=te[f]=te[w]=te[b]=te[m]=te[S]=te[$]=te[O]=te[q]=!1;var st=typeof N.commonjsGlobal=="object"&&N.commonjsGlobal&&N.commonjsGlobal.Object===Object&&N.commonjsGlobal,Le=typeof self=="object"&&self&&self.Object===Object&&self,Ie=st||Le||Function("return this")(),ke=e&&!e.nodeType&&e,ks=ke&&!0&&s&&!s.nodeType&&s,js=ks&&ks.exports===ke,Zs=js&&st.process,vr=(function(){try{return Zs&&Zs.binding&&Zs.binding("util")}catch{}})(),Rs=vr&&vr.isTypedArray;function Mn(y,E){for(var P=-1,Y=y==null?0:y.length,Ge=0,ae=[];++P<Y;){var it=y[P];E(it,P,y)&&(ae[Ge++]=it)}return ae}function Sm(y,E){for(var P=-1,Y=E.length,Ge=y.length;++P<Y;)y[Ge+P]=E[P];return y}function $m(y,E){for(var P=-1,Y=y==null?0:y.length;++P<Y;)if(E(y[P],P,y))return!0;return!1}function Tm(y,E){for(var P=-1,Y=Array(y);++P<y;)Y[P]=E(P);return Y}function Pm(y){return function(E){return y(E)}}function xm(y,E){return y.has(E)}function Mm(y,E){return y?.[E]}function Om(y){var E=-1,P=Array(y.size);return y.forEach(function(Y,Ge){P[++E]=[Ge,Y]}),P}function Dm(y,E){return function(P){return y(E(P))}}function km(y){var E=-1,P=Array(y.size);return y.forEach(function(Y){P[++E]=Y}),P}var jm=Array.prototype,Rm=Function.prototype,Jo=Object.prototype,vc=Ie["__core-js_shared__"],ou=Rm.toString,Us=Jo.hasOwnProperty,au=(function(){var y=/[^.]+$/.exec(vc&&vc.keys&&vc.keys.IE_PROTO||"");return y?"Symbol(src)_1."+y:""})(),cu=Jo.toString,Um=RegExp("^"+ou.call(Us).replace(J,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),lu=js?Ie.Buffer:void 0,Zo=Ie.Symbol,hu=Ie.Uint8Array,uu=Jo.propertyIsEnumerable,Lm=jm.splice,zi=Zo?Zo.toStringTag:void 0,du=Object.getOwnPropertySymbols,zm=lu?lu.isBuffer:void 0,Fm=Dm(Object.keys,Object),Ic=Ir(Ie,"DataView"),On=Ir(Ie,"Map"),Ec=Ir(Ie,"Promise"),Ac=Ir(Ie,"Set"),Nc=Ir(Ie,"WeakMap"),Dn=Ir(Object,"create"),qm=Bi(Ic),Bm=Bi(On),Hm=Bi(Ec),Wm=Bi(Ac),Vm=Bi(Nc),pu=Zo?Zo.prototype:void 0,Cc=pu?pu.valueOf:void 0;function Fi(y){var E=-1,P=y==null?0:y.length;for(this.clear();++E<P;){var Y=y[E];this.set(Y[0],Y[1])}}function Km(){this.__data__=Dn?Dn(null):{},this.size=0}function Gm(y){var E=this.has(y)&&delete this.__data__[y];return this.size-=E?1:0,E}function Ym(y){var E=this.__data__;if(Dn){var P=E[y];return P===i?void 0:P}return Us.call(E,y)?E[y]:void 0}function Qm(y){var E=this.__data__;return Dn?E[y]!==void 0:Us.call(E,y)}function Jm(y,E){var P=this.__data__;return this.size+=this.has(y)?0:1,P[y]=Dn&&E===void 0?i:E,this}Fi.prototype.clear=Km,Fi.prototype.delete=Gm,Fi.prototype.get=Ym,Fi.prototype.has=Qm,Fi.prototype.set=Jm;function Xs(y){var E=-1,P=y==null?0:y.length;for(this.clear();++E<P;){var Y=y[E];this.set(Y[0],Y[1])}}function Zm(){this.__data__=[],this.size=0}function Xm(y){var E=this.__data__,P=ea(E,y);if(P<0)return!1;var Y=E.length-1;return P==Y?E.pop():Lm.call(E,P,1),--this.size,!0}function eb(y){var E=this.__data__,P=ea(E,y);return P<0?void 0:E[P][1]}function tb(y){return ea(this.__data__,y)>-1}function sb(y,E){var P=this.__data__,Y=ea(P,y);return Y<0?(++this.size,P.push([y,E])):P[Y][1]=E,this}Xs.prototype.clear=Zm,Xs.prototype.delete=Xm,Xs.prototype.get=eb,Xs.prototype.has=tb,Xs.prototype.set=sb;function qi(y){var E=-1,P=y==null?0:y.length;for(this.clear();++E<P;){var Y=y[E];this.set(Y[0],Y[1])}}function ib(){this.size=0,this.__data__={hash:new Fi,map:new(On||Xs),string:new Fi}}function rb(y){var E=ta(this,y).delete(y);return this.size-=E?1:0,E}function nb(y){return ta(this,y).get(y)}function ob(y){return ta(this,y).has(y)}function ab(y,E){var P=ta(this,y),Y=P.size;return P.set(y,E),this.size+=P.size==Y?0:1,this}qi.prototype.clear=ib,qi.prototype.delete=rb,qi.prototype.get=nb,qi.prototype.has=ob,qi.prototype.set=ab;function Xo(y){var E=-1,P=y==null?0:y.length;for(this.__data__=new qi;++E<P;)this.add(y[E])}function cb(y){return this.__data__.set(y,i),this}function lb(y){return this.__data__.has(y)}Xo.prototype.add=Xo.prototype.push=cb,Xo.prototype.has=lb;function fi(y){var E=this.__data__=new Xs(y);this.size=E.size}function hb(){this.__data__=new Xs,this.size=0}function ub(y){var E=this.__data__,P=E.delete(y);return this.size=E.size,P}function db(y){return this.__data__.get(y)}function pb(y){return this.__data__.has(y)}function gb(y,E){var P=this.__data__;if(P instanceof Xs){var Y=P.__data__;if(!On||Y.length<t-1)return Y.push([y,E]),this.size=++P.size,this;P=this.__data__=new qi(Y)}return P.set(y,E),this.size=P.size,this}fi.prototype.clear=hb,fi.prototype.delete=ub,fi.prototype.get=db,fi.prototype.has=pb,fi.prototype.set=gb;function fb(y,E){var P=sa(y),Y=!P&&Pb(y),Ge=!P&&!Y&&_c(y),ae=!P&&!Y&&!Ge&&Eu(y),it=P||Y||Ge||ae,ft=it?Tm(y.length,String):[],At=ft.length;for(var Xe in y)Us.call(y,Xe)&&!(it&&(Xe=="length"||Ge&&(Xe=="offset"||Xe=="parent")||ae&&(Xe=="buffer"||Xe=="byteLength"||Xe=="byteOffset")||Cb(Xe,At)))&&ft.push(Xe);return ft}function ea(y,E){for(var P=y.length;P--;)if(mu(y[P][0],E))return P;return-1}function wb(y,E,P){var Y=E(y);return sa(y)?Y:Sm(Y,P(y))}function kn(y){return y==null?y===void 0?T:v:zi&&zi in Object(y)?Ab(y):Tb(y)}function gu(y){return jn(y)&&kn(y)==a}function fu(y,E,P,Y,Ge){return y===E?!0:y==null||E==null||!jn(y)&&!jn(E)?y!==y&&E!==E:yb(y,E,P,Y,fu,Ge)}function yb(y,E,P,Y,Ge,ae){var it=sa(y),ft=sa(E),At=it?c:wi(y),Xe=ft?c:wi(E);At=At==a?m:At,Xe=Xe==a?m:Xe;var es=At==m,Cs=Xe==m,kt=At==Xe;if(kt&&_c(y)){if(!_c(E))return!1;it=!0,es=!1}if(kt&&!es)return ae||(ae=new fi),it||Eu(y)?wu(y,E,P,Y,Ge,ae):Ib(y,E,At,P,Y,Ge,ae);if(!(P&r)){var ds=es&&Us.call(y,"__wrapped__"),ps=Cs&&Us.call(E,"__wrapped__");if(ds||ps){var yi=ds?y.value():y,ei=ps?E.value():E;return ae||(ae=new fi),Ge(yi,ei,P,Y,ae)}}return kt?(ae||(ae=new fi),Eb(y,E,P,Y,Ge,ae)):!1}function mb(y){if(!Iu(y)||Sb(y))return!1;var E=bu(y)?Um:ve;return E.test(Bi(y))}function bb(y){return jn(y)&&vu(y.length)&&!!te[kn(y)]}function vb(y){if(!$b(y))return Fm(y);var E=[];for(var P in Object(y))Us.call(y,P)&&P!="constructor"&&E.push(P);return E}function wu(y,E,P,Y,Ge,ae){var it=P&r,ft=y.length,At=E.length;if(ft!=At&&!(it&&At>ft))return!1;var Xe=ae.get(y);if(Xe&&ae.get(E))return Xe==E;var es=-1,Cs=!0,kt=P&n?new Xo:void 0;for(ae.set(y,E),ae.set(E,y);++es<ft;){var ds=y[es],ps=E[es];if(Y)var yi=it?Y(ps,ds,es,E,y,ae):Y(ds,ps,es,y,E,ae);if(yi!==void 0){if(yi)continue;Cs=!1;break}if(kt){if(!$m(E,function(ei,Hi){if(!xm(kt,Hi)&&(ds===ei||Ge(ds,ei,P,Y,ae)))return kt.push(Hi)})){Cs=!1;break}}else if(!(ds===ps||Ge(ds,ps,P,Y,ae))){Cs=!1;break}}return ae.delete(y),ae.delete(E),Cs}function Ib(y,E,P,Y,Ge,ae,it){switch(P){case G:if(y.byteLength!=E.byteLength||y.byteOffset!=E.byteOffset)return!1;y=y.buffer,E=E.buffer;case j:return!(y.byteLength!=E.byteLength||!ae(new hu(y),new hu(E)));case u:case d:case b:return mu(+y,+E);case p:return y.name==E.name&&y.message==E.message;case S:case O:return y==E+"";case w:var ft=Om;case $:var At=Y&r;if(ft||(ft=km),y.size!=E.size&&!At)return!1;var Xe=it.get(y);if(Xe)return Xe==E;Y|=n,it.set(y,E);var es=wu(ft(y),ft(E),Y,Ge,ae,it);return it.delete(y),es;case D:if(Cc)return Cc.call(y)==Cc.call(E)}return!1}function Eb(y,E,P,Y,Ge,ae){var it=P&r,ft=yu(y),At=ft.length,Xe=yu(E),es=Xe.length;if(At!=es&&!it)return!1;for(var Cs=At;Cs--;){var kt=ft[Cs];if(!(it?kt in E:Us.call(E,kt)))return!1}var ds=ae.get(y);if(ds&&ae.get(E))return ds==E;var ps=!0;ae.set(y,E),ae.set(E,y);for(var yi=it;++Cs<At;){kt=ft[Cs];var ei=y[kt],Hi=E[kt];if(Y)var Au=it?Y(Hi,ei,kt,E,y,ae):Y(ei,Hi,kt,y,E,ae);if(!(Au===void 0?ei===Hi||Ge(ei,Hi,P,Y,ae):Au)){ps=!1;break}yi||(yi=kt=="constructor")}if(ps&&!yi){var ia=y.constructor,ra=E.constructor;ia!=ra&&"constructor"in y&&"constructor"in E&&!(typeof ia=="function"&&ia instanceof ia&&typeof ra=="function"&&ra instanceof ra)&&(ps=!1)}return ae.delete(y),ae.delete(E),ps}function yu(y){return wb(y,Ob,Nb)}function ta(y,E){var P=y.__data__;return _b(E)?P[typeof E=="string"?"string":"hash"]:P.map}function Ir(y,E){var P=Mm(y,E);return mb(P)?P:void 0}function Ab(y){var E=Us.call(y,zi),P=y[zi];try{y[zi]=void 0;var Y=!0}catch{}var Ge=cu.call(y);return Y&&(E?y[zi]=P:delete y[zi]),Ge}var Nb=du?function(y){return y==null?[]:(y=Object(y),Mn(du(y),function(E){return uu.call(y,E)}))}:Db,wi=kn;(Ic&&wi(new Ic(new ArrayBuffer(1)))!=G||On&&wi(new On)!=w||Ec&&wi(Ec.resolve())!=A||Ac&&wi(new Ac)!=$||Nc&&wi(new Nc)!=q)&&(wi=function(y){var E=kn(y),P=E==m?y.constructor:void 0,Y=P?Bi(P):"";if(Y)switch(Y){case qm:return G;case Bm:return w;case Hm:return A;case Wm:return $;case Vm:return q}return E});function Cb(y,E){return E=E??o,!!E&&(typeof y=="number"||pe.test(y))&&y>-1&&y%1==0&&y<E}function _b(y){var E=typeof y;return E=="string"||E=="number"||E=="symbol"||E=="boolean"?y!=="__proto__":y===null}function Sb(y){return!!au&&au in y}function $b(y){var E=y&&y.constructor,P=typeof E=="function"&&E.prototype||Jo;return y===P}function Tb(y){return cu.call(y)}function Bi(y){if(y!=null){try{return ou.call(y)}catch{}try{return y+""}catch{}}return""}function mu(y,E){return y===E||y!==y&&E!==E}var Pb=gu((function(){return arguments})())?gu:function(y){return jn(y)&&Us.call(y,"callee")&&!uu.call(y,"callee")},sa=Array.isArray;function xb(y){return y!=null&&vu(y.length)&&!bu(y)}var _c=zm||kb;function Mb(y,E){return fu(y,E)}function bu(y){if(!Iu(y))return!1;var E=kn(y);return E==f||E==g||E==l||E==C}function vu(y){return typeof y=="number"&&y>-1&&y%1==0&&y<=o}function Iu(y){var E=typeof y;return y!=null&&(E=="object"||E=="function")}function jn(y){return y!=null&&typeof y=="object"}var Eu=Rs?Pm(Rs):bb;function Ob(y){return xb(y)?fb(y):vb(y)}function Db(){return[]}function kb(){return!1}s.exports=Mb})(ro,ro.exports)),ro.exports}var lE=cE();const hE=N.getDefaultExportFromCjs(lE),lw="wc",hw=2,Ol="core",Qs=`${lw}@2:${Ol}:`,uE={logger:"error"},dE={database:":memory:"},pE="crypto",vd="client_ed25519_seed",gE=h.cjsExports$1.ONE_DAY,fE="keychain",wE="0.3",yE="messages",mE="0.3",Id=h.cjsExports$1.SIX_HOURS,bE="publisher",uw="irn",vE="error",dw="wss://relay.walletconnect.org",IE="relayer",It={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"},EE="_subscription",gs={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},AE=.1,Dl="2.19.0",Qe={link_mode:"link_mode",relay:"relay"},NE="0.3",CE="WALLETCONNECT_CLIENT_ID",Ed="WALLETCONNECT_LINK_MODE_APPS",rs={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},_E="subscription",SE="0.3",$E=h.cjsExports$1.FIVE_SECONDS*1e3,TE="pairing",PE="0.3",Fn={wc_pairingDelete:{req:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:h.cjsExports$1.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:h.cjsExports$1.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:0},res:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:0}}},Xi={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},_s={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},xE="history",ME="0.3",OE="expirer",ms={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},DE="0.3",kE="verify-api",jE="https://verify.walletconnect.com",pw="https://verify.walletconnect.org",uo=pw,RE=`${uo}/v3`,UE=[jE,pw],LE="echo",zE="https://echo.walletconnect.com",Ks={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"},ai={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"},Ss={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"},Wi={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"},Vi={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},qn={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},FE=.1,qE="event-client",BE=86400,HE="https://pulse.walletconnect.org/batch";function WE(s,e){if(s.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var r=0;r<s.length;r++){var n=s.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=s.length,c=s.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(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 w=0,b=0,v=0,m=g.length;v!==m&&g[v]===0;)v++,w++;for(var A=(m-v)*u+1>>>0,C=new Uint8Array(A);v!==m;){for(var S=g[v],$=0,O=A-1;(S!==0||$<b)&&O!==-1;O--,$++)S+=256*C[O]>>>0,C[O]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");b=$,v++}for(var D=A-b;D!==A&&C[D]===0;)D++;for(var T=c.repeat(w);D<A;++D)T+=s.charAt(C[D]);return T}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var b=0,v=0;g[w]===c;)b++,w++;for(var m=(g.length-w)*l+1>>>0,A=new Uint8Array(m);g[w];){var C=t[g.charCodeAt(w)];if(C===255)return;for(var S=0,$=m-1;(C!==0||S<v)&&$!==-1;$--,S++)C+=a*A[$]>>>0,A[$]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");v=S,w++}if(g[w]!==" "){for(var O=m-v;O!==m&&A[O]===0;)O++;for(var D=new Uint8Array(b+(m-O)),T=b;O!==m;)D[T++]=A[O++];return D}}}function f(g){var w=p(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var VE=WE,KE=VE;const gw=s=>{if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")},GE=s=>new TextEncoder().encode(s),YE=s=>new TextDecoder().decode(s);let QE=class{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},JE=class{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}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 fw(this,e)}},ZE=class{constructor(e){this.decoders=e}or(e){return fw(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const fw=(s,e)=>new ZE({...s.decoders||{[s.prefix]:s},...e.decoders||{[e.prefix]:e}});let XE=class{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new QE(e,t,i),this.decoder=new JE(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const ac=({name:s,prefix:e,encode:t,decode:i})=>new XE(s,e,t,i),Fo=({prefix:s,name:e,alphabet:t})=>{const{encode:i,decode:r}=KE(t,e);return ac({prefix:s,name:e,encode:i,decode:n=>gw(r(n))})},eA=(s,e,t,i)=>{const r={};for(let u=0;u<e.length;++u)r[e[u]]=u;let n=s.length;for(;s[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const d=r[s[u]];if(d===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|d,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},tA=(s,e,t)=>{const i=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<s.length;++c)for(a=a<<8|s[c],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Ot=({name:s,prefix:e,bitsPerChar:t,alphabet:i})=>ac({prefix:e,name:s,encode(r){return tA(r,i,t)},decode(r){return eA(r,i,t,s)}}),sA=ac({prefix:"\0",name:"identity",encode:s=>YE(s),decode:s=>GE(s)});var iA=Object.freeze({__proto__:null,identity:sA});const rA=Ot({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var nA=Object.freeze({__proto__:null,base2:rA});const oA=Ot({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var aA=Object.freeze({__proto__:null,base8:oA});const cA=Fo({prefix:"9",name:"base10",alphabet:"0123456789"});var lA=Object.freeze({__proto__:null,base10:cA});const hA=Ot({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),uA=Ot({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var dA=Object.freeze({__proto__:null,base16:hA,base16upper:uA});const pA=Ot({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),gA=Ot({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),fA=Ot({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),wA=Ot({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),yA=Ot({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),mA=Ot({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),bA=Ot({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),vA=Ot({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),IA=Ot({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var EA=Object.freeze({__proto__:null,base32:pA,base32upper:gA,base32pad:fA,base32padupper:wA,base32hex:yA,base32hexupper:mA,base32hexpad:bA,base32hexpadupper:vA,base32z:IA});const AA=Fo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),NA=Fo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var CA=Object.freeze({__proto__:null,base36:AA,base36upper:NA});const _A=Fo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),SA=Fo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var $A=Object.freeze({__proto__:null,base58btc:_A,base58flickr:SA});const TA=Ot({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),PA=Ot({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xA=Ot({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),MA=Ot({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var OA=Object.freeze({__proto__:null,base64:TA,base64pad:PA,base64url:xA,base64urlpad:MA});const ww=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),DA=ww.reduce((s,e,t)=>(s[t]=e,s),[]),kA=ww.reduce((s,e,t)=>(s[e.codePointAt(0)]=t,s),[]);function jA(s){return s.reduce((e,t)=>(e+=DA[t],e),"")}function RA(s){const e=[];for(const t of s){const i=kA[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const UA=ac({prefix:"🚀",name:"base256emoji",encode:jA,decode:RA});var LA=Object.freeze({__proto__:null,base256emoji:UA}),zA=yw,Ad=128,FA=-128,qA=Math.pow(2,31);function yw(s,e,t){e=e||[],t=t||0;for(var i=t;s>=qA;)e[t++]=s&255|Ad,s/=128;for(;s&FA;)e[t++]=s&255|Ad,s>>>=7;return e[t]=s|0,yw.bytes=t-i+1,e}var BA=kl,HA=128,Nd=127;function kl(s,i){var t=0,i=i||0,r=0,n=i,o,a=s.length;do{if(n>=a)throw kl.bytes=0,new RangeError("Could not decode varint");o=s[n++],t+=r<28?(o&Nd)<<r:(o&Nd)*Math.pow(2,r),r+=7}while(o>=HA);return kl.bytes=n-i,t}var WA=Math.pow(2,7),VA=Math.pow(2,14),KA=Math.pow(2,21),GA=Math.pow(2,28),YA=Math.pow(2,35),QA=Math.pow(2,42),JA=Math.pow(2,49),ZA=Math.pow(2,56),XA=Math.pow(2,63),eN=function(s){return s<WA?1:s<VA?2:s<KA?3:s<GA?4:s<YA?5:s<QA?6:s<JA?7:s<ZA?8:s<XA?9:10},tN={encode:zA,decode:BA,encodingLength:eN},mw=tN;const Cd=(s,e,t=0)=>(mw.encode(s,e,t),e),_d=s=>mw.encodingLength(s),jl=(s,e)=>{const t=e.byteLength,i=_d(s),r=i+_d(t),n=new Uint8Array(r+t);return Cd(s,n,0),Cd(t,n,i),n.set(e,r),new sN(s,t,e,n)};let sN=class{constructor(e,t,i,r){this.code=e,this.size=t,this.digest=i,this.bytes=r}};const bw=({name:s,code:e,encode:t})=>new iN(s,e,t);let iN=class{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?jl(this.code,t):t.then(i=>jl(this.code,i))}else throw Error("Unknown type, must be binary type")}};const vw=s=>async e=>new Uint8Array(await crypto.subtle.digest(s,e)),rN=bw({name:"sha2-256",code:18,encode:vw("SHA-256")}),nN=bw({name:"sha2-512",code:19,encode:vw("SHA-512")});var oN=Object.freeze({__proto__:null,sha256:rN,sha512:nN});const Iw=0,aN="identity",Ew=gw,cN=s=>jl(Iw,Ew(s)),lN={code:Iw,name:aN,encode:Ew,digest:cN};var hN=Object.freeze({__proto__:null,identity:lN});new TextEncoder,new TextDecoder;const Sd={...iA,...nA,...aA,...lA,...dA,...EA,...CA,...$A,...OA,...LA};({...oN,...hN});function uN(s=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(s):new Uint8Array(s)}function Aw(s,e,t,i){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:i}}}const $d=Aw("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),Uc=Aw("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);const e=uN(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),dN={utf8:$d,"utf-8":$d,hex:Sd.base16,latin1:Uc,ascii:Uc,binary:Uc,...Sd};function pN(s,e="utf8"){const t=dN[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(s,"utf8"):t.decoder.decode(`${t.prefix}${s}`)}var gN=Object.defineProperty,fN=(s,e,t)=>e in s?gN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,zs=(s,e,t)=>fN(s,typeof e!="symbol"?e+"":e,t);let wN=class{constructor(e,t){this.core=e,this.logger=t,zs(this,"keychain",new Map),zs(this,"name",fE),zs(this,"version",wE),zs(this,"initialized",!1),zs(this,"storagePrefix",Qs),zs(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),zs(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),zs(this,"set",async(i,r)=>{this.isInitialized(),this.keychain.set(i,r),await this.persist()}),zs(this,"get",i=>{this.isInitialized();const r=this.keychain.get(i);if(typeof r>"u"){const{message:n}=U("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return r}),zs(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=h.E(t,this.name)}get context(){return h.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Of(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Df(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var yN=Object.defineProperty,mN=(s,e,t)=>e in s?yN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ct=(s,e,t)=>mN(s,typeof e!="symbol"?e+"":e,t);let bN=class{constructor(e,t,i){this.core=e,this.logger=t,Ct(this,"name",pE),Ct(this,"keychain"),Ct(this,"randomSessionIdentifier",Ml()),Ct(this,"initialized",!1),Ct(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ct(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ct(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=h.Po(r);return h.Qe(n.publicKey)}),Ct(this,"generateKeyPair",()=>{this.isInitialized();const r=d1();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ct(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=h.Po(n),a=this.randomSessionIdentifier,c=gE;return await h.Qo(a,r,c,o)}),Ct(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=p1(a,n);return this.setSymKey(c,o)}),Ct(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||xa(r);return await this.keychain.set(o,r),o}),Ct(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ct(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ct(this,"encode",async(r,n,o)=>{this.isInitialized();const a=ow(o),c=h.safeJsonStringify(n);if(hd(a))return w1(c,o?.encoding);if(ld(a)){const p=a.senderPublicKey,f=a.receiverPublicKey;r=await this.generateSharedKey(p,f)}const l=this.getSymKey(r),{type:u,senderPublicKey:d}=a;return g1({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Ct(this,"decode",async(r,n,o)=>{this.isInitialized();const a=m1(n,o);if(hd(a)){const c=y1(n,o?.encoding);return h.safeJsonParse(c)}if(ld(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=f1({symKey:c,encoded:n,encoding:o?.encoding});return h.safeJsonParse(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ct(this,"getPayloadType",(r,n=Ti)=>{const o=No({encoded:r,encoding:n});return cr(o.type)}),Ct(this,"getPayloadSenderPublicKey",(r,n=Ti)=>{const o=No({encoded:r,encoding:n});return o.senderPublicKey?h.toString(o.senderPublicKey,zt):void 0}),this.core=e,this.logger=h.E(t,this.name),this.keychain=i||new wN(this.core,this.logger)}get context(){return h.y(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(vd)}catch{e=Ml(),await this.keychain.set(vd,e)}return pN(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var vN=Object.defineProperty,IN=(s,e,t)=>e in s?vN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Fs=(s,e,t)=>IN(s,typeof e!="symbol"?e+"":e,t);let EN=class extends lv{constructor(e,t){super(e,t),this.logger=e,this.core=t,Fs(this,"messages",new Map),Fs(this,"name",yE),Fs(this,"version",mE),Fs(this,"initialized",!1),Fs(this,"storagePrefix",Qs),Fs(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),Fs(this,"set",async(i,r)=>{this.isInitialized();const n=hi(r);let o=this.messages.get(i);return typeof o>"u"&&(o={}),typeof o[n]<"u"||(o[n]=r,this.messages.set(i,o),await this.persist()),n}),Fs(this,"get",i=>{this.isInitialized();let r=this.messages.get(i);return typeof r>"u"&&(r={}),r}),Fs(this,"has",(i,r)=>{this.isInitialized();const n=this.get(i),o=hi(r);return typeof n[o]<"u"}),Fs(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),await this.persist()}),this.logger=h.E(e,this.name),this.core=t}get context(){return h.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Of(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Df(e):void 0}async persist(){await this.setRelayerMessages(this.messages)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var AN=Object.defineProperty,NN=Object.defineProperties,CN=Object.getOwnPropertyDescriptors,Td=Object.getOwnPropertySymbols,_N=Object.prototype.hasOwnProperty,SN=Object.prototype.propertyIsEnumerable,Rl=(s,e,t)=>e in s?AN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ha=(s,e)=>{for(var t in e||(e={}))_N.call(e,t)&&Rl(s,t,e[t]);if(Td)for(var t of Td(e))SN.call(e,t)&&Rl(s,t,e[t]);return s},Lc=(s,e)=>NN(s,CN(e)),$s=(s,e,t)=>Rl(s,typeof e!="symbol"?e+"":e,t);let $N=class extends hv{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,$s(this,"events",new h.eventsExports.EventEmitter),$s(this,"name",bE),$s(this,"queue",new Map),$s(this,"publishTimeout",h.cjsExports$1.toMiliseconds(h.cjsExports$1.ONE_MINUTE)),$s(this,"initialPublishTimeout",h.cjsExports$1.toMiliseconds(h.cjsExports$1.ONE_SECOND*15)),$s(this,"needsTransportRestart",!1),$s(this,"publish",async(i,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:r,opts:n}});const a=n?.ttl||Id,c=Ba(n),l=n?.prompt||!1,u=n?.tag||0,d=n?.id||h.getBigIntRpcId().toString(),p={topic:i,message:r,opts:{ttl:a,relay:c,prompt:l,tag:u,id:d,attestation:n?.attestation,tvf:n?.tvf}},f=`Failed to publish payload, please try again. id:${d} tag:${u}`;try{const g=new Promise(async w=>{const b=({id:m})=>{p.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(It.publish,b),w(p))};this.relayer.events.on(It.publish,b);const v=$i(new Promise((m,A)=>{this.rpcPublish({topic:i,message:r,ttl:a,prompt:l,tag:u,id:d,attestation:n?.attestation,tvf:n?.tvf}).then(m).catch(C=>{this.logger.warn(C,C?.message),A(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await v,this.events.removeListener(It.publish,b)}catch(m){this.queue.set(d,Lc(ha({},p),{attempt:1})),this.logger.warn(m,m?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:i,message:r,opts:n}}),await $i(g,this.publishTimeout,f)}catch(g){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(g),(o=n?.internal)!=null&&o.throwOnFailedPublish)throw g}finally{this.queue.delete(d)}}),$s(this,"on",(i,r)=>{this.events.on(i,r)}),$s(this,"once",(i,r)=>{this.events.once(i,r)}),$s(this,"off",(i,r)=>{this.events.off(i,r)}),$s(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.relayer=e,this.logger=h.E(t,this.name),this.registerEventListeners()}get context(){return h.y(this.logger)}async rpcPublish(e){var t,i,r,n;const{topic:o,message:a,ttl:c=Id,prompt:l,tag:u,id:d,attestation:p,tvf:f}=e,g={method:so(Ba().protocol).publish,params:ha({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:p},f),id:d};Bt((t=g.params)==null?void 0:t.prompt)&&((i=g.params)==null||delete i.prompt),Bt((r=g.params)==null?void 0:r.tag)&&((n=g.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:g});const w=await this.relayer.request(g);return this.relayer.events.emit(It.publish,e),this.logger.debug("Successfully Published Payload"),w}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,Lc(ha({},e),{attempt:i}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Lc(ha({},e),{topic:r,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(h.r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(It.connection_stalled);return}this.checkQueue()}),this.relayer.on(It.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}};var TN=Object.defineProperty,PN=(s,e,t)=>e in s?TN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Cr=(s,e,t)=>PN(s,typeof e!="symbol"?e+"":e,t);let xN=class{constructor(){Cr(this,"map",new Map),Cr(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),Cr(this,"get",e=>this.map.get(e)||[]),Cr(this,"exists",(e,t)=>this.get(e).includes(t)),Cr(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const r=i.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),Cr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}};var MN=Object.defineProperty,ON=Object.defineProperties,DN=Object.getOwnPropertyDescriptors,Pd=Object.getOwnPropertySymbols,kN=Object.prototype.hasOwnProperty,jN=Object.prototype.propertyIsEnumerable,Ul=(s,e,t)=>e in s?MN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Bn=(s,e)=>{for(var t in e||(e={}))kN.call(e,t)&&Ul(s,t,e[t]);if(Pd)for(var t of Pd(e))jN.call(e,t)&&Ul(s,t,e[t]);return s},zc=(s,e)=>ON(s,DN(e)),je=(s,e,t)=>Ul(s,typeof e!="symbol"?e+"":e,t);let RN=class extends pv{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,je(this,"subscriptions",new Map),je(this,"topicMap",new xN),je(this,"events",new h.eventsExports.EventEmitter),je(this,"name",_E),je(this,"version",SE),je(this,"pending",new Map),je(this,"cached",[]),je(this,"initialized",!1),je(this,"pendingSubscriptionWatchLabel","pending_sub_watch_label"),je(this,"pollingInterval",20),je(this,"storagePrefix",Qs),je(this,"subscribeTimeout",h.cjsExports$1.toMiliseconds(h.cjsExports$1.ONE_MINUTE)),je(this,"initialSubscribeTimeout",h.cjsExports$1.toMiliseconds(h.cjsExports$1.ONE_SECOND*15)),je(this,"clientId"),je(this,"batchSubscribeTopicsLimit",500),je(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),je(this,"subscribe",async(i,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}});try{const n=Ba(r),o={topic:i,relay:n,transportType:r?.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,r);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),je(this,"unsubscribe",async(i,r)=>{this.isInitialized(),typeof r?.id<"u"?await this.unsubscribeById(i,r.id,r):await this.unsubscribeByTopic(i,r)}),je(this,"isSubscribed",async i=>{if(this.topics.includes(i))return!0;const r=`${this.pendingSubscriptionWatchLabel}_${i}`;return await new Promise((n,o)=>{const a=new h.cjsExports$1.Watch;a.start(r);const c=setInterval(()=>{(!this.pending.has(i)&&this.topics.includes(i)||this.cached.some(l=>l.topic===i))&&(clearInterval(c),a.stop(r),n(!0)),a.elapsed(r)>=$E&&(clearInterval(c),a.stop(r),o(new Error("Subscription resolution timeout")))},this.pollingInterval)}).catch(()=>!1)}),je(this,"on",(i,r)=>{this.events.on(i,r)}),je(this,"once",(i,r)=>{this.events.once(i,r)}),je(this,"off",(i,r)=>{this.events.off(i,r)}),je(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),je(this,"start",async()=>{await this.onConnect()}),je(this,"stop",async()=>{await this.onDisconnect()}),je(this,"restart",async()=>{await this.restore(),await this.onRestart()}),je(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(r=>{i.push(r)}),await this.batchSubscribe(i)}),je(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(h.r.pulse,async()=>{await this.checkPending()}),this.events.on(rs.created,async i=>{const r=rs.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()}),this.events.on(rs.deleted,async i=>{const r=rs.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:i}),await this.persist()})}),this.relayer=e,this.logger=h.E(t,this.name),this.clientId=""}get context(){return h.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const r=Ba(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Re("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,i){var r;(!i||i?.transportType===Qe.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:so(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=i?.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(i?.transportType===Qe.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(u=>this.logger.warn(u))},h.cjsExports$1.toMiliseconds(h.cjsExports$1.ONE_SECOND)),a;const c=new Promise(async u=>{const d=p=>{p.topic===e&&(this.events.removeListener(rs.created,d),u(p.id))};this.events.on(rs.created,d);try{const p=await $i(new Promise((f,g)=>{this.relayer.request(n).catch(w=>{this.logger.warn(w,w?.message),g(w)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(rs.created,d),u(p)}catch{}}),l=await $i(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(It.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:so(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await $i(new Promise(r=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(It.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:so(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let r;try{r=await await $i(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(It.connection_stalled)}return r}rpcUnsubscribe(e,t,i){const r={method:so(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,zc(Bn({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Bn({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,Bn({},t)),this.topicMap.set(t.topic,e),this.events.emit(rs.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(rs.deleted,zc(Bn({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(rs.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(rs.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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 t=>zc(Bn({},t),{id:await this.getSubscriptionId(t.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await _0(h.cjsExports$1.toMiliseconds(h.cjsExports$1.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return hi(e+await this.getClientId())}};var UN=Object.defineProperty,xd=Object.getOwnPropertySymbols,LN=Object.prototype.hasOwnProperty,zN=Object.prototype.propertyIsEnumerable,Ll=(s,e,t)=>e in s?UN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Md=(s,e)=>{for(var t in e||(e={}))LN.call(e,t)&&Ll(s,t,e[t]);if(xd)for(var t of xd(e))zN.call(e,t)&&Ll(s,t,e[t]);return s},Ae=(s,e,t)=>Ll(s,typeof e!="symbol"?e+"":e,t);let FN=class extends uv{constructor(e){super(e),Ae(this,"protocol","wc"),Ae(this,"version",2),Ae(this,"core"),Ae(this,"logger"),Ae(this,"events",new h.eventsExports.EventEmitter),Ae(this,"provider"),Ae(this,"messages"),Ae(this,"subscriber"),Ae(this,"publisher"),Ae(this,"name",IE),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",h.cjsExports$1.toMiliseconds(h.cjsExports$1.THIRTY_SECONDS+h.cjsExports$1.FIVE_SECONDS)),Ae(this,"reconnectTimeout"),Ae(this,"connectPromise"),Ae(this,"reconnectInProgress",!1),Ae(this,"requestsInFlight",[]),Ae(this,"connectTimeout",h.cjsExports$1.toMiliseconds(h.cjsExports$1.ONE_SECOND*15)),Ae(this,"request",async t=>{var i,r;this.logger.debug("Publishing Request Payload");const n=t.id||h.getBigIntRpcId().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((r=t.params)==null?void 0:r.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),Ae(this,"resetPingTimeout",()=>{if(Fa())try{clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,r;this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(r=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null||r.terminate()},this.heartBeatTimeout)}catch(t){this.logger.warn(t,t?.message)}}),Ae(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),Ae(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(It.connect)}),Ae(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ae(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(It.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ae(this,"registerProviderListeners",()=>{this.provider.on(gs.payload,this.onPayloadHandler),this.provider.on(gs.connect,this.onConnectHandler),this.provider.on(gs.disconnect,this.onDisconnectHandler),this.provider.on(gs.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?h.E(e.logger,this.name):h.Ot(h.k({level:e.logger||vE})),this.messages=new EN(this.logger,e.core),this.subscriber=new RN(this,this.logger),this.publisher=new $N(this,this.logger),this.relayUrl=e?.relayUrl||dw,this.projectId=e.projectId,u0()?this.packageName=ju():d0()&&(this.bundleId=ju()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return h.y(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Qe.relay})}async subscribe(e,t){var i,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((i=t?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(r=t?.internal)==null?void 0:r.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(rs.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(rs.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,Md({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&d(p)})||a,u()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await $i(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,i)=>{await this.connect(e).then(t).catch(i).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 md())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,r)=>i.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+r?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const r=dt(h.cjsExports$1.FIVE_MINUTES),n={topic:i,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(It.message,e),await this.recordMessageEvent(e)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(gs.disconnect,n),await $i(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(gs.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(gs.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(gs.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const r=i;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: ${t}`);break}await new Promise(i=>setTimeout(i,h.cjsExports$1.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,r,n;if(Fa())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(i=this.provider)==null?void 0:i.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new h.o(new h.f(w0({sdkVersion:Dl,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){const{topic:t,message:i}=e;await this.messages.set(t,i)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isSubscribed(t))return this.logger.warn(`Ignoring message for non-subscribed topic ${t}`),!0;const r=this.messages.has(t,i);return r&&this.logger.warn(`Ignoring duplicate message: ${i}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),h.isJsonRpcRequest(e)){if(!e.method.endsWith(EE))return;const t=e.params,{topic:i,message:r,publishedAt:n,attestation:o}=t.data,a={topic:i,message:r,publishedAt:n,transportType:Qe.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Md({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else h.isJsonRpcResponse(e)&&this.events.emit(It.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(It.message,e),await this.recordMessageEvent(e))}async acknowledgePayload(e){const t=h.formatJsonRpcResult(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(gs.payload,this.onPayloadHandler),this.provider.off(gs.connect,this.onConnectHandler),this.provider.off(gs.disconnect,this.onDisconnectHandler),this.provider.off(gs.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await md();nE(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(It.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},h.cjsExports$1.toMiliseconds(AE)))))}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}};var qN=Object.defineProperty,Od=Object.getOwnPropertySymbols,BN=Object.prototype.hasOwnProperty,HN=Object.prototype.propertyIsEnumerable,zl=(s,e,t)=>e in s?qN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Dd=(s,e)=>{for(var t in e||(e={}))BN.call(e,t)&&zl(s,t,e[t]);if(Od)for(var t of Od(e))HN.call(e,t)&&zl(s,t,e[t]);return s},Wt=(s,e,t)=>zl(s,typeof e!="symbol"?e+"":e,t);let fr=class extends dv{constructor(e,t,i,r=Qs,n=void 0){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,Wt(this,"map",new Map),Wt(this,"version",NE),Wt(this,"cached",[]),Wt(this,"initialized",!1),Wt(this,"getKey"),Wt(this,"storagePrefix",Qs),Wt(this,"recentlyDeleted",[]),Wt(this,"recentlyDeletedLimit",200),Wt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Bt(o)?this.map.set(this.getKey(o),o):j1(o)?this.map.set(o.id,o):R1(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Wt(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())}),Wt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Wt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>hE(a[c],o[c]))):this.values)),Wt(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=Dd(Dd({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Wt(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=h.E(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return h.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=U("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:i}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var WN=Object.defineProperty,VN=(s,e,t)=>e in s?WN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fe=(s,e,t)=>VN(s,typeof e!="symbol"?e+"":e,t);let KN=class{constructor(e,t){this.core=e,this.logger=t,fe(this,"name",TE),fe(this,"version",PE),fe(this,"events",new h.Nt),fe(this,"pairings"),fe(this,"initialized",!1),fe(this,"storagePrefix",Qs),fe(this,"ignoredPayloadTypes",[di]),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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),fe(this,"create",async i=>{this.isInitialized();const r=Ml(),n=await this.core.crypto.setSymKey(r),o=dt(h.cjsExports$1.FIVE_MINUTES),a={protocol:uw},c={topic:n,expiry:o,relay:a,active:!1,methods:i?.methods},l=dd({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:i?.methods});return this.events.emit(Xi.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i?.transportType}),{topic:n,uri:l}}),fe(this,"pair",async i=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[Ks.pairing_started]}});this.isValidPair(i,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=ud(i.uri);r.props.properties.topic=n,r.addTrace(Ks.pairing_uri_validation_success),r.addTrace(Ks.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),r.addTrace(Ks.existing_pairing),u.active)throw r.setError(ai.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(Ks.pairing_not_expired)}const d=c||dt(h.cjsExports$1.FIVE_MINUTES),p={topic:n,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(n,d),await this.pairings.set(n,p),r.addTrace(Ks.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(Xi.create,p),r.addTrace(Ks.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(Ks.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(ai.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(f){throw r.setError(ai.subscribe_pairing_topic_failure),f}return r.addTrace(Ks.subscribe_pairing_topic_success),p}),fe(this,"activate",async({topic:i})=>{this.isInitialized();const r=dt(h.cjsExports$1.FIVE_MINUTES);this.core.expirer.set(i,r),await this.pairings.update(i,{active:!0,expiry:r})}),fe(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=i;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Yi();this.events.once(Pe("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),fe(this,"updateExpiry",async({topic:i,expiry:r})=>{this.isInitialized(),await this.pairings.update(i,{expiry:r})}),fe(this,"updateMetadata",async({topic:i,metadata:r})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:r})}),fe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),fe(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:r}=i;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Re("USER_DISCONNECTED")),await this.deletePairing(r))}),fe(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(r);return dd({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),fe(this,"sendRequest",async(i,r,n)=>{const o=h.formatJsonRpcRequest(r,n),a=await this.core.crypto.encode(i,o),c=Fn[r].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),fe(this,"sendResult",async(i,r,n)=>{const o=h.formatJsonRpcResult(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=Fn[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"sendError",async(i,r,n)=>{const o=h.formatJsonRpcError(i,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,i)).request.method,l=Fn[c]?Fn[c].res:Fn.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"deletePairing",async(i,r)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,Re("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),r?Promise.resolve():this.core.expirer.del(i)])}),fe(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(r=>Ci(r.expiry));await Promise.all(i.map(r=>this.deletePairing(r.topic)))}),fe(this,"onRelayEventRequest",i=>{const{topic:r,payload:n}=i;switch(n.method){case"wc_pairingPing":return this.onPairingPingRequest(r,n);case"wc_pairingDelete":return this.onPairingDeleteRequest(r,n);default:return this.onUnknownRpcMethodRequest(r,n)}}),fe(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n}=i,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),fe(this,"onPairingPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(Xi.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),fe(this,"onPairingPingResponse",(i,r)=>{const{id:n}=r;setTimeout(()=>{h.isJsonRpcResult(r)?this.events.emit(Pe("pairing_ping",n),{}):h.isJsonRpcError(r)&&this.events.emit(Pe("pairing_ping",n),{error:r.error})},500)}),fe(this,"onPairingDeleteRequest",async(i,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Xi.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),fe(this,"onUnknownRpcMethodRequest",async(i,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Re("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),fe(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(Re("WC_METHOD_UNSUPPORTED",i))}),fe(this,"isValidPair",(i,r)=>{var n;if(!Qt(i)){const{message:a}=U("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(ai.malformed_pairing_uri),new Error(a)}if(!k1(i.uri)){const{message:a}=U("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(ai.malformed_pairing_uri),new Error(a)}const o=ud(i?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(ai.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(ai.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&h.cjsExports$1.toMiliseconds(o?.expiryTimestamp)<Date.now()){r.setError(ai.pairing_expired);const{message:a}=U("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),fe(this,"isValidPing",async i=>{if(!Qt(i)){const{message:n}=U("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),fe(this,"isValidDisconnect",async i=>{if(!Qt(i)){const{message:n}=U("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidPairingTopic(r)}),fe(this,"isValidPairingTopic",async i=>{if(!nt(i,!1)){const{message:r}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(r)}if(!this.pairings.keys.includes(i)){const{message:r}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(r)}if(Ci(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:r}=U("EXPIRED",`pairing topic: ${i}`);throw new Error(r)}}),this.core=e,this.logger=h.E(t,this.name),this.pairings=new fr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return h.y(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(It.message,async e=>{const{topic:t,message:i,transportType:r}=e;if(!this.pairings.keys.includes(t)||r===Qe.link_mode||this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))return;const n=await this.core.crypto.decode(t,i);try{h.isJsonRpcRequest(n)?(this.core.history.set(t,n),this.onRelayEventRequest({topic:t,payload:n})):h.isJsonRpcResponse(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id))}catch(o){this.logger.error(o)}})}registerExpirerEvents(){this.core.expirer.on(ms.expired,async e=>{const{topic:t}=jf(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Xi.expire,{topic:t}))})}};var GN=Object.defineProperty,YN=(s,e,t)=>e in s?GN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,_t=(s,e,t)=>YN(s,typeof e!="symbol"?e+"":e,t);let QN=class extends cv{constructor(e,t){super(e,t),this.core=e,this.logger=t,_t(this,"records",new Map),_t(this,"events",new h.eventsExports.EventEmitter),_t(this,"name",xE),_t(this,"version",ME),_t(this,"cached",[]),_t(this,"initialized",!1),_t(this,"storagePrefix",Qs),_t(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),_t(this,"set",(i,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:i,request:{method:r.method,params:r.params||null},chainId:n,expiry:dt(h.cjsExports$1.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(_s.created,o)}),_t(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const r=await this.getRecord(i.id);typeof r.response>"u"&&(r.response=h.isJsonRpcError(i)?{error:i.error}:{result:i.result},this.records.set(r.id,r),this.persist(),this.events.emit(_s.updated,r))}),_t(this,"get",async(i,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:r}),await this.getRecord(r))),_t(this,"delete",(i,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===i){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(_s.deleted,n)}}),this.persist()}),_t(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),_t(this,"on",(i,r)=>{this.events.on(i,r)}),_t(this,"once",(i,r)=>{this.events.once(i,r)}),_t(this,"off",(i,r)=>{this.events.off(i,r)}),_t(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=h.E(t,this.name)}get context(){return h.y(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:h.formatJsonRpcRequest(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(_s.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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(_s.created,e=>{const t=_s.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(_s.updated,e=>{const t=_s.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(_s.deleted,e=>{const t=_s.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(h.r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{h.cjsExports$1.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(_s.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var JN=Object.defineProperty,ZN=(s,e,t)=>e in s?JN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,jt=(s,e,t)=>ZN(s,typeof e!="symbol"?e+"":e,t);let XN=class extends gv{constructor(e,t){super(e,t),this.core=e,this.logger=t,jt(this,"expirations",new Map),jt(this,"events",new h.eventsExports.EventEmitter),jt(this,"name",OE),jt(this,"version",DE),jt(this,"cached",[]),jt(this,"initialized",!1),jt(this,"storagePrefix",Qs),jt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),jt(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),jt(this,"set",(i,r)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(ms.created,{target:n,expiration:o})}),jt(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),jt(this,"del",i=>{if(this.isInitialized(),this.has(i)){const r=this.formatTarget(i),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(ms.deleted,{target:r,expiration:n})}}),jt(this,"on",(i,r)=>{this.events.on(i,r)}),jt(this,"once",(i,r)=>{this.events.once(i,r)}),jt(this,"off",(i,r)=>{this.events.off(i,r)}),jt(this,"removeListener",(i,r)=>{this.events.removeListener(i,r)}),this.logger=h.E(t,this.name)}get context(){return h.y(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 y0(e);if(typeof e=="number")return m0(e);const{message:t}=U("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(ms.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=U("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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 t=this.expirations.get(e);if(!t){const{message:i}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;h.cjsExports$1.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(ms.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(h.r.pulse,()=>this.checkExpirations()),this.events.on(ms.created,e=>{const t=ms.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ms.expired,e=>{const t=ms.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ms.deleted,e=>{const t=ms.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}};var eC=Object.defineProperty,tC=(s,e,t)=>e in s?eC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,at=(s,e,t)=>tC(s,typeof e!="symbol"?e+"":e,t);let sC=class extends fv{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,at(this,"name",kE),at(this,"abortController"),at(this,"isDevEnv"),at(this,"verifyUrlV3",RE),at(this,"storagePrefix",Qs),at(this,"version",hw),at(this,"publicKey"),at(this,"fetchPromise"),at(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&h.cjsExports$1.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),at(this,"register",async r=>{if(!jo()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=h.cjsExports$2.getDocument(),u=this.startAbortTimer(h.cjsExports$1.ONE_SECOND*5),d=await new Promise((p,f)=>{const g=()=>{window.removeEventListener("message",b),l.body.removeChild(w),f("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const w=l.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",g,{signal:this.abortController.signal});const b=v=>{if(v.data&&typeof v.data=="string")try{const m=JSON.parse(v.data);if(m.type==="verify_attestation"){if(h.sn(m.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(w),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",b),p(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};l.body.appendChild(w),window.addEventListener("message",b,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),at(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(h.sn(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(r?.verifyUrl);return this.fetchAttestation(o,c)}),at(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(h.cjsExports$1.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),at(this,"getVerifyUrl",r=>{let n=r||uo;return UE.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${uo}`),n=uo),n}),at(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(h.cjsExports$1.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),at(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),at(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),at(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}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")}}),at(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),at(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),at(this,"validateAttestation",(r,n)=>{const o=E1(r,n.publicKey),a={hasExpired:h.cjsExports$1.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=h.E(t,this.name),this.abortController=new AbortController,this.isDevEnv=$h(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return h.y(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),h.cjsExports$1.toMiliseconds(e))}};var iC=Object.defineProperty,rC=(s,e,t)=>e in s?iC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,kd=(s,e,t)=>rC(s,typeof e!="symbol"?e+"":e,t);let nC=class extends wv{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,kd(this,"context",LE),kd(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${zE}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=h.E(t,this.context)}};var oC=Object.defineProperty,jd=Object.getOwnPropertySymbols,aC=Object.prototype.hasOwnProperty,cC=Object.prototype.propertyIsEnumerable,Fl=(s,e,t)=>e in s?oC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Hn=(s,e)=>{for(var t in e||(e={}))aC.call(e,t)&&Fl(s,t,e[t]);if(jd)for(var t of jd(e))cC.call(e,t)&&Fl(s,t,e[t]);return s},wt=(s,e,t)=>Fl(s,typeof e!="symbol"?e+"":e,t);let lC=class extends yv{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,wt(this,"context",qE),wt(this,"storagePrefix",Qs),wt(this,"storageVersion",FE),wt(this,"events",new Map),wt(this,"shouldPersist",!1),wt(this,"init",async()=>{if(!$h())try{const r={eventId:Uu(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Mf(this.core.relayer.protocol,this.core.relayer.version,Dl)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),wt(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=Uu(),u=this.core.projectId||"",d=Date.now(),p=Hn({eventId:l,timestamp:d,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,p),this.shouldPersist=!0),p}),wt(this,"getEvent",r=>{const{eventId:n,topic:o}=r;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Hn(Hn({},a),this.setMethods(a.eventId))}),wt(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),wt(this,"setEventListeners",()=>{this.core.heartbeat.on(h.r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{h.cjsExports$1.fromMiliseconds(Date.now())-h.cjsExports$1.fromMiliseconds(r.timestamp)>BE&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),wt(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),wt(this,"addTrace",(r,n)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(n),this.events.set(r,o),this.shouldPersist=!0)}),wt(this,"setError",(r,n)=>{const o=this.events.get(r);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),wt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),wt(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(n=>{this.events.set(n.eventId,Hn(Hn({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),wt(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[n,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const n of r)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),wt(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${HE}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Dl}${n}`,{method:"POST",body:JSON.stringify(r)})}),wt(this,"getAppDomain",()=>xf().url),this.logger=h.E(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}};var hC=Object.defineProperty,Rd=Object.getOwnPropertySymbols,uC=Object.prototype.hasOwnProperty,dC=Object.prototype.propertyIsEnumerable,ql=(s,e,t)=>e in s?hC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ud=(s,e)=>{for(var t in e||(e={}))uC.call(e,t)&&ql(s,t,e[t]);if(Rd)for(var t of Rd(e))dC.call(e,t)&&ql(s,t,e[t]);return s},He=(s,e,t)=>ql(s,typeof e!="symbol"?e+"":e,t);let pC=class Nw extends rv{constructor(e){var t;super(e),He(this,"protocol",lw),He(this,"version",hw),He(this,"name",Ol),He(this,"relayUrl"),He(this,"projectId"),He(this,"customStoragePrefix"),He(this,"events",new h.eventsExports.EventEmitter),He(this,"logger"),He(this,"heartbeat"),He(this,"relayer"),He(this,"crypto"),He(this,"storage"),He(this,"history"),He(this,"expirer"),He(this,"pairing"),He(this,"verify"),He(this,"echoClient"),He(this,"linkModeSupportedApps"),He(this,"eventClient"),He(this,"initialized",!1),He(this,"logChunkController"),He(this,"on",(o,a)=>this.events.on(o,a)),He(this,"once",(o,a)=>this.events.once(o,a)),He(this,"off",(o,a)=>this.events.off(o,a)),He(this,"removeListener",(o,a)=>this.events.removeListener(o,a)),He(this,"dispatchEnvelope",({topic:o,message:a,sessionExists:c})=>{if(!o||!a)return;const l={topic:o,message:a,publishedAt:Date.now(),transportType:Qe.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:c})}),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||dw,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=h.k({level:typeof e?.logger=="string"&&e.logger?e.logger:uE.logger,name:Ol}),{logger:r,chunkLoggerController:n}=h.A({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=n,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var o,a;(o=this.logChunkController)!=null&&o.downloadLogsBlobInBrowser&&((a=this.logChunkController)==null||a.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=h.E(r,this.name),this.heartbeat=new h.i,this.crypto=new bN(this,this.logger,e?.keychain),this.history=new QN(this,this.logger),this.expirer=new XN(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new h.h(Ud(Ud({},dE),e?.storageOptions)),this.relayer=new FN({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new KN(this,this.logger),this.verify=new sC(this,this.logger,this.storage),this.echoClient=new nC(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new lC(this,this.logger,e?.telemetryEnabled)}static async init(e){const t=new Nw(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(CE,i),t}get context(){return h.y(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(Ed,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(Ed)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}};const gC=pC;var fC=Object.defineProperty,wC=(s,e,t)=>e in s?fC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ld=(s,e,t)=>wC(s,typeof e!="symbol"?e+"":e,t);let yC=class{constructor(e){this.opts=e,Ld(this,"protocol","wc"),Ld(this,"version",2)}},mC=class{constructor(e){this.client=e}};const Cw="wc",_w=2,Sw="client",Rh=`${Cw}@${_w}:${Sw}:`,Fc={name:Sw,logger:"error"},zd="WALLETCONNECT_DEEPLINK_CHOICE",bC="proposal",Fd="Proposal expired",vC="session",_r=h.cjsExports$1.SEVEN_DAYS,IC="engine",yt={wc_sessionPropose:{req:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1104},res:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1106},res:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1112},res:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1114},res:{ttl:h.cjsExports$1.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:h.cjsExports$1.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:h.cjsExports$1.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:h.cjsExports$1.FIVE_MINUTES,prompt:!1,tag:1119}}},qc={min:h.cjsExports$1.FIVE_MINUTES,max:h.cjsExports$1.SEVEN_DAYS},qs={idle:"IDLE",active:"ACTIVE"},qd={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},EC="request",AC=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],NC="wc",CC="auth",_C="authKeys",SC="pairingTopics",$C="requests",cc=`${NC}@${1.5}:${CC}:`,Ma=`${cc}:PUB_KEY`;var TC=Object.defineProperty,PC=Object.defineProperties,xC=Object.getOwnPropertyDescriptors,Bd=Object.getOwnPropertySymbols,MC=Object.prototype.hasOwnProperty,OC=Object.prototype.propertyIsEnumerable,Bl=(s,e,t)=>e in s?TC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,et=(s,e)=>{for(var t in e||(e={}))MC.call(e,t)&&Bl(s,t,e[t]);if(Bd)for(var t of Bd(e))OC.call(e,t)&&Bl(s,t,e[t]);return s},Vt=(s,e)=>PC(s,xC(e)),M=(s,e,t)=>Bl(s,typeof e!="symbol"?e+"":e,t);let DC=class extends mC{constructor(e){super(e),M(this,"name",IC),M(this,"events",new h.Nt),M(this,"initialized",!1),M(this,"requestQueue",{state:qs.idle,queue:[]}),M(this,"sessionRequestQueue",{state:qs.idle,queue:[]}),M(this,"requestQueueDelay",h.cjsExports$1.ONE_SECOND),M(this,"expectedPairingMethodMap",new Map),M(this,"recentlyDeletedMap",new Map),M(this,"recentlyDeletedLimit",200),M(this,"relayMessageCache",[]),M(this,"pendingSessions",new Map),M(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(yt)}),this.initialized=!0,setTimeout(()=>{this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},h.cjsExports$1.toMiliseconds(this.requestQueueDelay)))}),M(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Vt(et({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,relays:c}=i;let l=r,u,d=!1;try{if(l){const S=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=S.active}}catch(S){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),S}if(!l||!d){const{topic:S,uri:$}=await this.client.core.pairing.create();l=S,u=$}if(!l){const{message:S}=U("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(S)}const p=await this.client.core.crypto.generateKeyPair(),f=yt.wc_sessionPropose.req.ttl||h.cjsExports$1.FIVE_MINUTES,g=dt(f),w=Vt(et({requiredNamespaces:n,optionalNamespaces:o,relays:c??[{protocol:uw}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},a&&{sessionProperties:a}),{id:h.payloadId()}),b=Pe("session_connect",w.id),{reject:v,resolve:m,done:A}=Yi(f,Fd),C=({id:S})=>{S===w.id&&(this.client.events.off("proposal_expire",C),this.pendingSessions.delete(w.id),this.events.emit(b,{error:{message:Fd,code:0}}))};return this.client.events.on("proposal_expire",C),this.events.once(b,({error:S,session:$})=>{this.client.events.off("proposal_expire",C),S?v(S):$&&m($)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:w,throwOnFailedPublish:!0,clientRpcId:w.id}),await this.setProposal(w.id,w),{uri:u,approval:A}}),M(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}}),M(this,"approve",async t=>{var i,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=t?.id)==null?void 0:i.toString(),trace:[Ss.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(D){throw o.setError(Wi.no_internet_connection),D}try{await this.isValidProposalId(t?.id)}catch(D){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),o.setError(Wi.proposal_not_found),D}try{await this.isValidApprove(t)}catch(D){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Wi.session_approve_namespace_validation_failure),D}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,sessionConfig:d}=t,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:g,requiredNamespaces:w,optionalNamespaces:b}=p;let v=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});v||(v=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Ss.session_approve_started,properties:{topic:f,trace:[Ss.session_approve_started,Ss.session_namespaces_validation_success]}}));const m=await this.client.core.crypto.generateKeyPair(),A=g.publicKey,C=await this.client.core.crypto.generateSharedKey(m,A),S=et(et({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:m,metadata:this.client.metadata},expiry:dt(_r)},u&&{sessionProperties:u}),d&&{sessionConfig:d}),$=Qe.relay;v.addTrace(Ss.subscribing_session_topic);try{await this.client.core.relayer.subscribe(C,{transportType:$})}catch(D){throw v.setError(Wi.subscribe_session_topic_failure),D}v.addTrace(Ss.subscribe_session_topic_success);const O=Vt(et({},S),{topic:C,requiredNamespaces:w,optionalNamespaces:b,pairingTopic:f,acknowledged:!1,self:S.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:m,transportType:Qe.relay});await this.client.session.set(C,O),v.addTrace(Ss.store_session);try{v.addTrace(Ss.publishing_session_settle),await this.sendRequest({topic:C,method:"wc_sessionSettle",params:S,throwOnFailedPublish:!0}).catch(D=>{throw v?.setError(Wi.session_settle_publish_failure),D}),v.addTrace(Ss.session_settle_publish_success),v.addTrace(Ss.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:m},throwOnFailedPublish:!0}).catch(D=>{throw v?.setError(Wi.session_approve_publish_failure),D}),v.addTrace(Ss.session_approve_publish_success)}catch(D){throw this.client.logger.error(D),this.client.session.delete(C,Re("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(C),D}return this.client.core.eventClient.deleteEvent({eventId:v.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:g.metadata}),await this.client.proposal.delete(a,Re("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(C,dt(_r)),{topic:C,acknowledged:()=>Promise.resolve(this.client.session.get(C))}}),M(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:r}=t;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:r,rpcOpts:yt.wc_sessionPropose.reject}),await this.client.proposal.delete(i,Re("USER_DISCONNECTED")))}),M(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:i,namespaces:r}=t,{done:n,resolve:o,reject:a}=Yi(),c=h.payloadId(),l=h.getBigIntRpcId().toString(),u=this.client.session.get(i).namespaces;return this.events.once(Pe("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(i,{namespaces:r}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(i,{namespaces:u}),a(d)}),{acknowledged:n}}),M(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=t,r=h.payloadId(),{done:n,resolve:o,reject:a}=Yi();return this.events.once(Pe("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,dt(_r)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),M(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(v){throw this.client.logger.error("request() -> isValidRequest() failed"),v}const{chainId:i,request:r,topic:n,expiry:o=yt.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);a?.transportType===Qe.relay&&await this.confirmOnlineStateOrThrow();const c=h.payloadId(),l=h.getBigIntRpcId().toString(),{done:u,resolve:d,reject:p}=Yi(o,"Request expired. Please try again.");this.events.once(Pe("session_request",c),({error:v,result:m})=>{v?p(v):d(m)});const f="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:f,params:{request:Vt(et({},r),{expiryTimestamp:dt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(v=>p(v)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),await u();const w={request:Vt(et({},r),{expiryTimestamp:dt(o)}),chainId:i},b=this.shouldSetTVF(f,w);return await Promise.all([new Promise(async v=>{await this.sendRequest(et({clientRpcId:c,relayRpcId:l,topic:n,method:f,params:w,expiry:o,throwOnFailedPublish:!0},b&&{tvf:this.getTVFParams(c,w)})).catch(m=>p(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),v()}),new Promise(async v=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const A=await E0(this.client.core.storage,zd);await b0({id:c,topic:n,wcDeepLink:A})}v()}),u()]).then(v=>v[2])}),M(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:r}=t,{id:n}=r,o=this.client.session.get(i);o.transportType===Qe.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);h.isJsonRpcResult(r)?await this.sendResult({id:n,topic:i,result:r.result,throwOnFailedPublish:!0,appLink:a}):h.isJsonRpcError(r)&&await this.sendError({id:n,topic:i,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),M(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:i}=t;if(this.client.session.keys.includes(i)){const r=h.payloadId(),n=h.getBigIntRpcId().toString(),{done:o,resolve:a,reject:c}=Yi();this.events.once(Pe("session_ping",r),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(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:i}))}),M(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:r,chainId:n}=t,o=h.getBigIntRpcId().toString(),a=h.payloadId();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),M(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:Re("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:r}=U("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(r)}}),M(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>O1(i,t)))),M(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),M(this,"authenticate",async(t,i)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?Qe.link_mode:Qe.relay;o===Qe.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:p,exp:f,nbf:g,methods:w=[],expiry:b}=t,v=[...t.resources||[]],{topic:m,uri:A}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:A}});const C=await this.client.core.crypto.generateKeyPair(),S=xa(C);if(await Promise.all([this.client.auth.authKeys.set(Ma,{responseTopic:S,publicKey:C}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:m})]),await this.client.core.relayer.subscribe(S,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),w.length>0){const{namespace:_}=fn(a[0]);let z=dI(_,"request",w);Pa(v)&&(z=gI(z,v.pop())),v.push(z)}const $=b&&b>yt.wc_sessionAuthenticate.req.ttl?b:yt.wc_sessionAuthenticate.req.ttl,O={authPayload:{type:p??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:f,nbf:g,resources:v},requester:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:dt($)},D={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},T={requiredNamespaces:{},optionalNamespaces:D,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:dt(yt.wc_sessionPropose.req.ttl),id:h.payloadId()},{done:q,resolve:j,reject:G}=Yi($,"Request expired"),B=h.payloadId(),W=Pe("session_connect",T.id),V=Pe("session_request",B),H=async({error:_,session:z})=>{this.events.off(V,K),_?G(_):z&&j({session:z})},K=async _=>{var z,ee,J;if(await this.deletePendingAuthRequest(B,{message:"fulfilled",code:0}),_.error){const ke=Re("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return _.error.code===ke.code?void 0:(this.events.off(W,H),G(_.error.message))}await this.deleteProposal(T.id),this.events.off(W,H);const{cacaos:ve,responder:pe}=_.result,te=[],st=[];for(const ke of ve){await Vu({cacao:ke,projectId:this.client.core.projectId})||(this.client.logger.error(ke,"Signature verification failed"),G(Re("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ks}=ke,js=Pa(ks.resources),Zs=[_l(ks.iss)],vr=qa(ks.iss);if(js){const Rs=Ku(js),Mn=Gu(js);te.push(...Rs),Zs.push(...Mn)}for(const Rs of Zs)st.push(`${Rs}:${vr}`)}const Le=await this.client.core.crypto.generateSharedKey(C,pe.publicKey);let Ie;te.length>0&&(Ie={topic:Le,acknowledged:!0,self:{publicKey:C,metadata:this.client.metadata},peer:pe,controller:pe.publicKey,expiry:dt(_r),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:pd([...new Set(te)],[...new Set(st)]),transportType:o},await this.client.core.relayer.subscribe(Le,{transportType:o}),await this.client.session.set(Le,Ie),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:pe.metadata}),Ie=this.client.session.get(Le)),(z=this.client.metadata.redirect)!=null&&z.linkMode&&(ee=pe.metadata.redirect)!=null&&ee.linkMode&&(J=pe.metadata.redirect)!=null&&J.universal&&i&&(this.client.core.addLinkModeSupportedApp(pe.metadata.redirect.universal),this.client.session.update(Le,{transportType:Qe.link_mode})),j({auths:ve,session:Ie})};this.events.once(W,H),this.events.once(V,K);let Q;try{if(n){const _=h.formatJsonRpcRequest("wc_sessionAuthenticate",O,B);this.client.core.history.set(m,_);const z=await this.client.core.crypto.encode("",_,{type:zo,encoding:Ln});Q=la(i,m,z)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:O,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:B}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:T,expiry:yt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:T.id})])}catch(_){throw this.events.off(W,H),this.events.off(V,K),_}return await this.setProposal(T.id,T),await this.setAuthRequest(B,{request:Vt(et({},O),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:Q??A,response:q}}),M(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Vi.authenticated_session_approve_started]}});try{this.isInitialized()}catch(b){throw n.setError(qn.no_internet_connection),b}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(qn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Qe.relay;a===Qe.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=xa(c),d={type:di,receiverPublicKey:c,senderPublicKey:l},p=[],f=[];for(const b of r){if(!await Vu({cacao:b,projectId:this.client.core.projectId})){n.setError(qn.invalid_cacao);const S=Re("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:S,encodeOpts:d}),new Error(S.message)}n.addTrace(Vi.cacaos_verified);const{p:v}=b,m=Pa(v.resources),A=[_l(v.iss)],C=qa(v.iss);if(m){const S=Ku(m),$=Gu(m);p.push(...S),A.push(...$)}for(const S of A)f.push(`${S}:${C}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Vi.create_authenticated_session_topic);let w;if(p?.length>0){w={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:dt(_r),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:pd([...new Set(p)],[...new Set(f)]),transportType:a},n.addTrace(Vi.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(b){throw n.setError(qn.subscribe_authenticated_session_topic_failure),b}n.addTrace(Vi.subscribe_authenticated_session_topic_success),await this.client.session.set(g,w),n.addTrace(Vi.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Vi.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(b){throw n.setError(qn.authenticated_session_approve_publish_failure),b}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:w}}),M(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:i,reason:r}=t,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===Qe.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=xa(o),l={type:di,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:r,encodeOpts:l,rpcOpts:yt.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,Re("USER_DISCONNECTED"))}),M(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:r}=t;return Wf(i,r)}),M(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),M(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===t.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),M(this,"deleteSession",async t=>{var i;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Re("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),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(zd).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,Re("USER_DISCONNECTED"))}),r===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=qs.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),M(this,"deleteProposal",async(t,i)=>{if(i)try{const r=this.client.proposal.get(t);this.client.core.eventClient.getEvent({topic:r.pairingTopic})?.setError(Wi.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Re("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),M(this,"deletePendingSessionRequest",async(t,i,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),r&&(this.sessionRequestQueue.state=qs.idle,this.client.events.emit("session_request_expire",{id:t}))}),M(this,"deletePendingAuthRequest",async(t,i,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),r?Promise.resolve():this.client.core.expirer.del(t)])}),M(this,"setExpiry",async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))}),M(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,dt(yt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),M(this,"setAuthRequest",async(t,i)=>{const{request:r,pairingTopic:n,transportType:o=Qe.relay}=i;this.client.core.expirer.set(t,r.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:t,pairingTopic:n,verifyContext:r.verifyContext,transportType:o})}),M(this,"setPendingSessionRequest",async t=>{const{id:i,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||dt(yt.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:r,params:n,verifyContext:o})}),M(this,"sendRequest",async t=>{const{topic:i,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d}=t,p=h.formatJsonRpcRequest(r,n,c);let f;const g=!!u;try{const v=g?Ln:Ti;f=await this.client.core.crypto.encode(i,p,{encoding:v})}catch(v){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),v}let w;if(AC.includes(r)){const v=hi(JSON.stringify(p)),m=hi(f);w=await this.client.core.verify.register({id:m,decryptedId:v})}const b=yt[r].req;if(b.attestation=w,o&&(b.ttl=o),a&&(b.id=a),this.client.core.history.set(i,p),g){const v=la(u,i,f);await N.global.Linking.openURL(v,this.client.name)}else{const v=yt[r].req;o&&(v.ttl=o),a&&(v.id=a),v.tvf=Vt(et({},d),{correlationId:p.id}),l?(v.internal=Vt(et({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,v)):this.client.core.relayer.publish(i,f,v).catch(m=>this.client.logger.error(m))}return p.id}),M(this,"sendResult",async t=>{const{id:i,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,l=h.formatJsonRpcResult(i,n);let u;const d=c&&typeof(N.global==null?void 0:N.global.Linking)<"u";try{const g=d?Ln:Ti;u=await this.client.core.crypto.encode(r,l,Vt(et({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let p,f;try{p=await this.client.core.history.get(r,i);const g=p.request;try{this.shouldSetTVF(g.method,g.params)&&(f=this.getTVFParams(i,g.params,n))}catch(w){this.client.logger.warn("sendResult() -> getTVFParams() failed",w)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${i}) failed`),g}if(d){const g=la(c,r,u);await N.global.Linking.openURL(g,this.client.name)}else{const g=p.request.method,w=yt[g].res;w.tvf=Vt(et({},f),{correlationId:i}),o?(w.internal=Vt(et({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,u,w)):this.client.core.relayer.publish(r,u,w).catch(b=>this.client.logger.error(b))}await this.client.core.history.resolve(l)}),M(this,"sendError",async t=>{const{id:i,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,l=h.formatJsonRpcError(i,n);let u;const d=c&&typeof(N.global==null?void 0:N.global.Linking)<"u";try{const f=d?Ln:Ti;u=await this.client.core.crypto.encode(r,l,Vt(et({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),f}let p;try{p=await this.client.core.history.get(r,i)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${r}, ${i}) failed`),f}if(d){const f=la(c,r,u);await N.global.Linking.openURL(f,this.client.name)}else{const f=p.request.method,g=a||yt[f].res;this.client.core.relayer.publish(r,u,g)}await this.client.core.history.resolve(l)}),M(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(r=>{let n=!1;Ci(r.expiry)&&(n=!0),this.client.core.crypto.keychain.has(r.topic)||(n=!0),n&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Ci(r.expiryTimestamp)&&i.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...i.map(r=>this.deleteProposal(r))])}),M(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),M(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===qs.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=qs.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=qs.idle}),M(this,"processRequest",async t=>{const{topic:i,payload:r,attestation:n,transportType:o,encryptedId:a}=t,c=r.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,r);case"wc_sessionPing":return await this.onSessionPingRequest(i,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),M(this,"onRelayEventResponse",async t=>{const{topic:i,payload:r,transportType:n}=t,o=(await this.client.core.history.get(i,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,r);case"wc_sessionExtend":return this.onSessionExtendResponse(i,r);case"wc_sessionPing":return this.onSessionPingResponse(i,r);case"wc_sessionRequest":return this.onSessionRequestResponse(i,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),M(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:r}=U("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),M(this,"shouldIgnorePairingRequest",t=>{const{topic:i,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),M(this,"onSessionProposeRequest",async t=>{const{topic:i,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:c}=r;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(ai.proposal_listener_not_found)),this.isValidConnect(et({},r.params));const u=a.expiryTimestamp||dt(yt.wc_sessionPropose.req.ttl),d=et({id:c,pairingTopic:i,expiryTimestamp:u},a);await this.setProposal(c,d);const p=await this.getVerifyContext({attestationId:n,hash:hi(JSON.stringify(r)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(Ks.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:p})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:yt.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),M(this,"onSessionProposeResponse",async(t,i,r)=>{const{id:n}=i;if(h.isJsonRpcResult(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:t,proposalId:n,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:t})}else if(h.isJsonRpcError(i)){await this.client.proposal.delete(n,Re("USER_DISCONNECTED"));const o=Pe("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),M(this,"onSessionSettleRequest",async(t,i)=>{const{id:r,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,sessionConfig:d}=i.params,p=[...this.pendingSessions.values()].find(w=>w.sessionTopic===t);if(!p)return this.client.logger.error(`Pending session not found for topic ${t}`);const f=this.client.proposal.get(p.proposalId),g=Vt(et(et({topic:t,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{sessionConfig:d}),{transportType:Qe.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(Pe("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),M(this,"onSessionSettleResponse",async(t,i)=>{const{id:r}=i;h.isJsonRpcResult(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Pe("session_approve",r),{})):h.isJsonRpcError(i)&&(await this.client.session.delete(t,Re("USER_DISCONNECTED")),this.events.emit(Pe("session_approve",r),{error:i.error}))}),M(this,"onSessionUpdateRequest",async(t,i)=>{const{params:r,id:n}=i;try{const o=`${t}_session_update`,a=zn.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:Re("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(et({topic:t},r));try{zn.set(o,n),await this.client.session.update(t,{namespaces:r.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(c){throw zn.delete(o),c}this.client.events.emit("session_update",{id:n,topic:t,params:r})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),M(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),M(this,"onSessionUpdateResponse",(t,i)=>{const{id:r}=i,n=Pe("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);h.isJsonRpcResult(i)?this.events.emit(Pe("session_update",r),{}):h.isJsonRpcError(i)&&this.events.emit(Pe("session_update",r),{error:i.error})}),M(this,"onSessionExtendRequest",async(t,i)=>{const{id:r}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,dt(_r)),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),M(this,"onSessionExtendResponse",(t,i)=>{const{id:r}=i,n=Pe("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);h.isJsonRpcResult(i)?this.events.emit(Pe("session_extend",r),{}):h.isJsonRpcError(i)&&this.events.emit(Pe("session_extend",r),{error:i.error})}),M(this,"onSessionPingRequest",async(t,i)=>{const{id:r}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:t})}catch(n){await this.sendError({id:r,topic:t,error:n}),this.client.logger.error(n)}}),M(this,"onSessionPingResponse",(t,i)=>{const{id:r}=i,n=Pe("session_ping",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);setTimeout(()=>{h.isJsonRpcResult(i)?this.events.emit(Pe("session_ping",r),{}):h.isJsonRpcError(i)&&this.events.emit(Pe("session_ping",r),{error:i.error})},500)}),M(this,"onSessionDeleteRequest",async(t,i)=>{const{id:r}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(It.publish,async()=>{n(await this.deleteSession({topic:t,id:r}))})}),this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Re("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),M(this,"onSessionRequest",async t=>{var i,r,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=t,{id:d,params:p}=a;try{await this.isValidRequest(et({topic:o},p));const f=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:hi(JSON.stringify(h.formatJsonRpcRequest("wc_sessionRequest",p,d))),encryptedId:l,metadata:f.peer.metadata,transportType:u}),w={id:d,topic:o,params:p,verifyContext:g};await this.setPendingSessionRequest(w),u===Qe.link_mode&&(i=f.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((r=f.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(f){await this.sendError({id:d,topic:o,error:f}),this.client.logger.error(f)}}),M(this,"onSessionRequestResponse",(t,i)=>{const{id:r}=i,n=Pe("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);h.isJsonRpcResult(i)?this.events.emit(Pe("session_request",r),{result:i.result}):h.isJsonRpcError(i)&&this.events.emit(Pe("session_request",r),{error:i.error})}),M(this,"onSessionEventRequest",async(t,i)=>{const{id:r,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=zn.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(et({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),zn.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),M(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:r}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),h.isJsonRpcResult(i)?this.events.emit(Pe("session_request",r),{result:i.result}):h.isJsonRpcError(i)&&this.events.emit(Pe("session_request",r),{error:i.error})}),M(this,"onSessionAuthenticateRequest",async t=>{var i;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:l,authPayload:u,expiryTimestamp:d}=n.params,p=await this.getVerifyContext({attestationId:o,hash:hi(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),f={requester:l,pairingTopic:r,id:n.id,authPayload:u,verifyContext:p,expiryTimestamp:d};await this.setAuthRequest(n.id,{request:f,pairingTopic:r,transportType:c}),c===Qe.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:p})}catch(l){this.client.logger.error(l);const u=n.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),f={type:di,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:n.id,topic:r,error:l,encodeOpts:f,rpcOpts:yt.wc_sessionAuthenticate.autoReject,appLink:p})}}),M(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),M(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=qs.idle,this.processSessionRequestQueue()},h.cjsExports$1.toMiliseconds(this.requestQueueDelay))}),M(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:i})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=Pe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Pe("session_request",n.request.id),{error:i})})}),M(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===qs.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=qs.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),M(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),M(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:h.formatJsonRpcRequest("wc_sessionPropose",{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties},i.id)})}),M(this,"isValidConnect",async t=>{if(!Qt(t)){const{message:c}=U("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(c)}const{pairingTopic:i,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,relays:a}=t;if(Bt(i)||await this.isValidPairingTopic(i),!W1(a)){const{message:c}=U("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!Bt(r)&&Co(r)!==0&&this.validateNamespaces(r,"requiredNamespaces"),!Bt(n)&&Co(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Bt(o)||this.validateSessionProps(o,"sessionProperties")}),M(this,"validateNamespaces",(t,i)=>{const r=H1(t,"connect()",i);if(r)throw new Error(r.message)}),M(this,"isValidApprove",async t=>{if(!Qt(t))throw new Error(U("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:r,relayProtocol:n,sessionProperties:o}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const a=this.client.proposal.get(i),c=jc(r,"approve()");if(c)throw new Error(c.message);const l=wd(a.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!nt(n,!0)){const{message:u}=U("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}Bt(o)||this.validateSessionProps(o,"sessionProperties")}),M(this,"isValidReject",async t=>{if(!Qt(t)){const{message:n}=U("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:r}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!K1(r)){const{message:n}=U("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),M(this,"isValidSessionSettleRequest",t=>{if(!Qt(t)){const{message:l}=U("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(l)}const{relay:i,controller:r,namespaces:n,expiry:o}=t;if(!cw(i)){const{message:l}=U("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=U1(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=jc(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Ci(o)){const{message:l}=U("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),M(this,"isValidUpdate",async t=>{if(!Qt(t)){const{message:c}=U("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:i,namespaces:r}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=jc(r,"update()");if(o)throw new Error(o.message);const a=wd(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),M(this,"isValidExtend",async t=>{if(!Qt(t)){const{message:r}=U("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),M(this,"isValidRequest",async t=>{if(!Qt(t)){const{message:c}=U("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:i,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!fd(a,n)){const{message:c}=U("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!G1(r)){const{message:c}=U("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!J1(a,n,r.method)){const{message:c}=U("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!tE(o,qc)){const{message:c}=U("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${qc.min} and ${qc.max}`);throw new Error(c)}}),M(this,"isValidRespond",async t=>{var i;if(!Qt(t)){const{message:o}=U("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(i=t?.response)!=null&&i.id&&this.cleanupAfterResponse(t),o}if(!Y1(n)){const{message:o}=U("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),M(this,"isValidPing",async t=>{if(!Qt(t)){const{message:r}=U("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),M(this,"isValidEmit",async t=>{if(!Qt(t)){const{message:a}=U("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:r,chainId:n}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!fd(o,n)){const{message:a}=U("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Q1(r)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Z1(o,n,r.name)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),M(this,"isValidDisconnect",async t=>{if(!Qt(t)){const{message:r}=U("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),M(this,"isValidAuthenticate",t=>{const{chains:i,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!nt(r,!1))throw new Error("uri is required parameter");if(!nt(n,!1))throw new Error("domain is required parameter");if(!nt(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>fn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=fn(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),M(this,"getVerifyContext",async t=>{const{attestationId:i,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||uo,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Qe.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:i,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),M(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach(r=>{if(!nt(r,!1)){const{message:n}=U("MISSING_OR_INVALID",`${i} must be in Record<string, string> format. Received: ${JSON.stringify(r)}`);throw new Error(n)}})}),M(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),M(this,"addToRecentlyDeleted",(t,i)=>{if(this.recentlyDeletedMap.set(t,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=n)break;this.recentlyDeletedMap.delete(o)}}}),M(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:r}=U("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(r)}}),M(this,"isLinkModeEnabled",(t,i)=>{var r,n,o,a,c,l,u,d,p;return!t||i!==Qe.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=t?.redirect)==null?void 0:u.universal)!==void 0&&((d=t?.redirect)==null?void 0:d.universal)!==""&&((p=t?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(N.global==null?void 0:N.global.Linking)<"u"}),M(this,"getAppLinkIfEnabled",(t,i)=>{var r;return this.isLinkModeEnabled(t,i)?(r=t?.redirect)==null?void 0:r.universal:void 0}),M(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Ru(t,"topic")||"",r=decodeURIComponent(Ru(t,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:Qe.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:r,sessionExists:n})}),M(this,"registerLinkModeListeners",async()=>{var t;if($h()||Ui()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=N.global==null?void 0:N.global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await i.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),M(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:r}=i;return Object.keys(qd).includes(r.method)}),M(this,"getTVFParams",(t,i,r)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,r);return Vt(et({correlationId:t,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),M(this,"isValidContractData",t=>{var i;if(!t)return!1;try{const r=t?.data||((i=t?.[0])==null?void 0:i.data);if(!r.startsWith("0x"))return!1;const n=r.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),M(this,"extractTxHashesFromResult",(t,i)=>{try{const r=qd[t];if(typeof i=="string")return[i];const n=i[r.key];if(lr(n))return n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(It.message,e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):this.onRelayMessage(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Ma)?this.client.auth.authKeys.get(Ma):{publicKey:void 0},a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===Qe.link_mode?Ln:Ti});try{h.isJsonRpcRequest(a)?(this.client.core.history.set(t,a),this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:hi(i)})):h.isJsonRpcResponse(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n})}catch(c){this.client.logger.error(c)}}registerExpirerEvents(){this.client.core.expirer.on(ms.expired,async e=>{const{topic:t,id:i}=jf(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,U("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,U("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Xi.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Xi.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!nt(e,!1)){const{message:t}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Ci(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=U("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!nt(e,!1)){const{message:t}=U("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=U("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Ci(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=U("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=U("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(nt(e,!1)){const{message:t}=U("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=U("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!V1(e)){const{message:t}=U("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=U("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Ci(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=U("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}},kC=class extends fr{constructor(e,t){super(e,t,bC,Rh),this.core=e,this.logger=t}},jC=class extends fr{constructor(e,t){super(e,t,vC,Rh),this.core=e,this.logger=t}},RC=class extends fr{constructor(e,t){super(e,t,EC,Rh,i=>i.id),this.core=e,this.logger=t}},UC=class extends fr{constructor(e,t){super(e,t,_C,cc,()=>Ma),this.core=e,this.logger=t}},LC=class extends fr{constructor(e,t){super(e,t,SC,cc),this.core=e,this.logger=t}},zC=class extends fr{constructor(e,t){super(e,t,$C,cc,i=>i.id),this.core=e,this.logger=t}};var FC=Object.defineProperty,qC=(s,e,t)=>e in s?FC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Bc=(s,e,t)=>qC(s,typeof e!="symbol"?e+"":e,t);let BC=class{constructor(e,t){this.core=e,this.logger=t,Bc(this,"authKeys"),Bc(this,"pairingTopics"),Bc(this,"requests"),this.authKeys=new UC(this.core,this.logger),this.pairingTopics=new LC(this.core,this.logger),this.requests=new zC(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}};var HC=Object.defineProperty,WC=(s,e,t)=>e in s?HC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,we=(s,e,t)=>WC(s,typeof e!="symbol"?e+"":e,t);let VC=class $w extends yC{constructor(e){super(e),we(this,"protocol",Cw),we(this,"version",_w),we(this,"name",Fc.name),we(this,"metadata"),we(this,"core"),we(this,"logger"),we(this,"events",new h.eventsExports.EventEmitter),we(this,"engine"),we(this,"session"),we(this,"proposal"),we(this,"pendingRequest"),we(this,"auth"),we(this,"signConfig"),we(this,"on",(i,r)=>this.events.on(i,r)),we(this,"once",(i,r)=>this.events.once(i,r)),we(this,"off",(i,r)=>this.events.off(i,r)),we(this,"removeListener",(i,r)=>this.events.removeListener(i,r)),we(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),we(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"update",async i=>{try{return await this.engine.update(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"request",async i=>{try{return await this.engine.request(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"find",i=>{try{return this.engine.find(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),we(this,"authenticate",async(i,r)=>{try{return await this.engine.authenticate(i,r)}catch(n){throw this.logger.error(n.message),n}}),we(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),we(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(r){throw this.logger.error(r.message),r}}),this.name=e?.name||Fc.name,this.metadata=e?.metadata||xf(),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:h.Ot(h.k({level:e?.logger||Fc.logger}));this.core=e?.core||new gC(e),this.logger=h.E(t,this.name),this.session=new jC(this.core,this.logger),this.proposal=new kC(this.core,this.logger),this.pendingRequest=new RC(this.core,this.logger),this.engine=new DC(this),this.auth=new BC(this.core,this.logger)}static async init(e){const t=new $w(e);return await t.initialize(),t}get context(){return h.y(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},h.cjsExports$1.toMiliseconds(h.cjsExports$1.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Hd="error",KC="wss://relay.walletconnect.org",GC="wc",YC="universal_provider",Wd=`${GC}@2:${YC}:`,Tw="https://rpc.walletconnect.org/v1/",tn="generic",QC=`${Tw}bundler`,As={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var ua=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof N.global<"u"?N.global:typeof self<"u"?self:{};function JC(){this.__data__=[],this.size=0}var ZC=JC;function XC(s,e){return s===e||s!==s&&e!==e}var lc=XC,e_=lc;function t_(s,e){for(var t=s.length;t--;)if(e_(s[t][0],e))return t;return-1}var hc=t_,s_=hc,i_=Array.prototype,r_=i_.splice;function n_(s){var e=this.__data__,t=s_(e,s);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():r_.call(e,t,1),--this.size,!0}var o_=n_,a_=hc;function c_(s){var e=this.__data__,t=a_(e,s);return t<0?void 0:e[t][1]}var l_=c_,h_=hc;function u_(s){return h_(this.__data__,s)>-1}var d_=u_,p_=hc;function g_(s,e){var t=this.__data__,i=p_(t,s);return i<0?(++this.size,t.push([s,e])):t[i][1]=e,this}var f_=g_,w_=ZC,y_=o_,m_=l_,b_=d_,v_=f_;function sn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}sn.prototype.clear=w_,sn.prototype.delete=y_,sn.prototype.get=m_,sn.prototype.has=b_,sn.prototype.set=v_;var uc=sn,I_=uc;function E_(){this.__data__=new I_,this.size=0}var A_=E_;function N_(s){var e=this.__data__,t=e.delete(s);return this.size=e.size,t}var C_=N_;function __(s){return this.__data__.get(s)}var S_=__;function $_(s){return this.__data__.has(s)}var T_=$_,P_=typeof ua=="object"&&ua&&ua.Object===Object&&ua,Pw=P_,x_=Pw,M_=typeof self=="object"&&self&&self.Object===Object&&self,O_=x_||M_||Function("return this")(),$n=O_,D_=$n,k_=D_.Symbol,xw=k_,Vd=xw,Mw=Object.prototype,j_=Mw.hasOwnProperty,R_=Mw.toString,Wn=Vd?Vd.toStringTag:void 0;function U_(s){var e=j_.call(s,Wn),t=s[Wn];try{s[Wn]=void 0;var i=!0}catch{}var r=R_.call(s);return i&&(e?s[Wn]=t:delete s[Wn]),r}var L_=U_,z_=Object.prototype,F_=z_.toString;function q_(s){return F_.call(s)}var B_=q_,Kd=xw,H_=L_,W_=B_,V_="[object Null]",K_="[object Undefined]",Gd=Kd?Kd.toStringTag:void 0;function G_(s){return s==null?s===void 0?K_:V_:Gd&&Gd in Object(s)?H_(s):W_(s)}var dc=G_;function Y_(s){var e=typeof s;return s!=null&&(e=="object"||e=="function")}var wr=Y_,Q_=dc,J_=wr,Z_="[object AsyncFunction]",X_="[object Function]",eS="[object GeneratorFunction]",tS="[object Proxy]";function sS(s){if(!J_(s))return!1;var e=Q_(s);return e==X_||e==eS||e==Z_||e==tS}var Uh=sS,iS=$n,rS=iS["__core-js_shared__"],nS=rS,Hc=nS,Yd=(function(){var s=/[^.]+$/.exec(Hc&&Hc.keys&&Hc.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""})();function oS(s){return!!Yd&&Yd in s}var aS=oS,cS=Function.prototype,lS=cS.toString;function hS(s){if(s!=null){try{return lS.call(s)}catch{}try{return s+""}catch{}}return""}var uS=hS,dS=Uh,pS=aS,gS=wr,fS=uS,wS=/[\\^$.*+?()[\]{}|]/g,yS=/^\[object .+?Constructor\]$/,mS=Function.prototype,bS=Object.prototype,vS=mS.toString,IS=bS.hasOwnProperty,ES=RegExp("^"+vS.call(IS).replace(wS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function AS(s){if(!gS(s)||pS(s))return!1;var e=dS(s)?ES:yS;return e.test(fS(s))}var NS=AS;function CS(s,e){return s?.[e]}var _S=CS,SS=NS,$S=_S;function TS(s,e){var t=$S(s,e);return SS(t)?t:void 0}var Lh=TS,PS=Lh,xS=$n,MS=PS(xS,"Map"),Ow=MS,OS=Lh,DS=OS(Object,"create"),pc=DS,Qd=pc;function kS(){this.__data__=Qd?Qd(null):{},this.size=0}var jS=kS;function RS(s){var e=this.has(s)&&delete this.__data__[s];return this.size-=e?1:0,e}var US=RS,LS=pc,zS="__lodash_hash_undefined__",FS=Object.prototype,qS=FS.hasOwnProperty;function BS(s){var e=this.__data__;if(LS){var t=e[s];return t===zS?void 0:t}return qS.call(e,s)?e[s]:void 0}var HS=BS,WS=pc,VS=Object.prototype,KS=VS.hasOwnProperty;function GS(s){var e=this.__data__;return WS?e[s]!==void 0:KS.call(e,s)}var YS=GS,QS=pc,JS="__lodash_hash_undefined__";function ZS(s,e){var t=this.__data__;return this.size+=this.has(s)?0:1,t[s]=QS&&e===void 0?JS:e,this}var XS=ZS,e$=jS,t$=US,s$=HS,i$=YS,r$=XS;function rn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}rn.prototype.clear=e$,rn.prototype.delete=t$,rn.prototype.get=s$,rn.prototype.has=i$,rn.prototype.set=r$;var n$=rn,Jd=n$,o$=uc,a$=Ow;function c$(){this.size=0,this.__data__={hash:new Jd,map:new(a$||o$),string:new Jd}}var l$=c$;function h$(s){var e=typeof s;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?s!=="__proto__":s===null}var u$=h$,d$=u$;function p$(s,e){var t=s.__data__;return d$(e)?t[typeof e=="string"?"string":"hash"]:t.map}var gc=p$,g$=gc;function f$(s){var e=g$(this,s).delete(s);return this.size-=e?1:0,e}var w$=f$,y$=gc;function m$(s){return y$(this,s).get(s)}var b$=m$,v$=gc;function I$(s){return v$(this,s).has(s)}var E$=I$,A$=gc;function N$(s,e){var t=A$(this,s),i=t.size;return t.set(s,e),this.size+=t.size==i?0:1,this}var C$=N$,_$=l$,S$=w$,$$=b$,T$=E$,P$=C$;function nn(s){var e=-1,t=s==null?0:s.length;for(this.clear();++e<t;){var i=s[e];this.set(i[0],i[1])}}nn.prototype.clear=_$,nn.prototype.delete=S$,nn.prototype.get=$$,nn.prototype.has=T$,nn.prototype.set=P$;var x$=nn,M$=uc,O$=Ow,D$=x$,k$=200;function j$(s,e){var t=this.__data__;if(t instanceof M$){var i=t.__data__;if(!O$||i.length<k$-1)return i.push([s,e]),this.size=++t.size,this;t=this.__data__=new D$(i)}return t.set(s,e),this.size=t.size,this}var R$=j$,U$=uc,L$=A_,z$=C_,F$=S_,q$=T_,B$=R$;function on(s){var e=this.__data__=new U$(s);this.size=e.size}on.prototype.clear=L$,on.prototype.delete=z$,on.prototype.get=F$,on.prototype.has=q$,on.prototype.set=B$;var H$=on,W$=Lh,V$=(function(){try{var s=W$(Object,"defineProperty");return s({},"",{}),s}catch{}})(),Dw=V$,Zd=Dw;function K$(s,e,t){e=="__proto__"&&Zd?Zd(s,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):s[e]=t}var zh=K$,G$=zh,Y$=lc;function Q$(s,e,t){(t!==void 0&&!Y$(s[e],t)||t===void 0&&!(e in s))&&G$(s,e,t)}var kw=Q$;function J$(s){return function(e,t,i){for(var r=-1,n=Object(e),o=i(e),a=o.length;a--;){var c=o[s?a:++r];if(t(n[c],c,n)===!1)break}return e}}var Z$=J$,X$=Z$,eT=X$(),tT=eT,Hl={exports:{}};(function(s,e){var t=$n,i=e&&!e.nodeType&&e,r=i&&!0&&s&&!s.nodeType&&s,n=r&&r.exports===i,o=n?t.Buffer:void 0,a=o?o.allocUnsafe:void 0;function c(l,u){if(u)return l.slice();var d=l.length,p=a?a(d):new l.constructor(d);return l.copy(p),p}s.exports=c})(Hl,Hl.exports);var sT=$n,iT=sT.Uint8Array,rT=iT,Xd=rT;function nT(s){var e=new s.constructor(s.byteLength);return new Xd(e).set(new Xd(s)),e}var oT=nT,aT=oT;function cT(s,e){var t=e?aT(s.buffer):s.buffer;return new s.constructor(t,s.byteOffset,s.length)}var lT=cT;function hT(s,e){var t=-1,i=s.length;for(e||(e=Array(i));++t<i;)e[t]=s[t];return e}var uT=hT,dT=wr,ep=Object.create,pT=(function(){function s(){}return function(e){if(!dT(e))return{};if(ep)return ep(e);s.prototype=e;var t=new s;return s.prototype=void 0,t}})(),gT=pT;function fT(s,e){return function(t){return s(e(t))}}var wT=fT,yT=wT,mT=yT(Object.getPrototypeOf,Object),jw=mT,bT=Object.prototype;function vT(s){var e=s&&s.constructor,t=typeof e=="function"&&e.prototype||bT;return s===t}var Rw=vT,IT=gT,ET=jw,AT=Rw;function NT(s){return typeof s.constructor=="function"&&!AT(s)?IT(ET(s)):{}}var CT=NT;function _T(s){return s!=null&&typeof s=="object"}var qo=_T,ST=dc,$T=qo,TT="[object Arguments]";function PT(s){return $T(s)&&ST(s)==TT}var xT=PT,tp=xT,MT=qo,Uw=Object.prototype,OT=Uw.hasOwnProperty,DT=Uw.propertyIsEnumerable,kT=tp((function(){return arguments})())?tp:function(s){return MT(s)&&OT.call(s,"callee")&&!DT.call(s,"callee")},Lw=kT,jT=Array.isArray,zw=jT,RT=9007199254740991;function UT(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=RT}var Fw=UT,LT=Uh,zT=Fw;function FT(s){return s!=null&&zT(s.length)&&!LT(s)}var Fh=FT,qT=Fh,BT=qo;function HT(s){return BT(s)&&qT(s)}var WT=HT,Wa={exports:{}};function VT(){return!1}var KT=VT;(function(s,e){var t=$n,i=KT,r=e&&!e.nodeType&&e,n=r&&!0&&s&&!s.nodeType&&s,o=n&&n.exports===r,a=o?t.Buffer:void 0,c=a?a.isBuffer:void 0,l=c||i;s.exports=l})(Wa,Wa.exports);var GT=dc,YT=jw,QT=qo,JT="[object Object]",ZT=Function.prototype,XT=Object.prototype,qw=ZT.toString,eP=XT.hasOwnProperty,tP=qw.call(Object);function sP(s){if(!QT(s)||GT(s)!=JT)return!1;var e=YT(s);if(e===null)return!0;var t=eP.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&qw.call(t)==tP}var iP=sP,rP=dc,nP=Fw,oP=qo,aP="[object Arguments]",cP="[object Array]",lP="[object Boolean]",hP="[object Date]",uP="[object Error]",dP="[object Function]",pP="[object Map]",gP="[object Number]",fP="[object Object]",wP="[object RegExp]",yP="[object Set]",mP="[object String]",bP="[object WeakMap]",vP="[object ArrayBuffer]",IP="[object DataView]",EP="[object Float32Array]",AP="[object Float64Array]",NP="[object Int8Array]",CP="[object Int16Array]",_P="[object Int32Array]",SP="[object Uint8Array]",$P="[object Uint8ClampedArray]",TP="[object Uint16Array]",PP="[object Uint32Array]",Ye={};Ye[EP]=Ye[AP]=Ye[NP]=Ye[CP]=Ye[_P]=Ye[SP]=Ye[$P]=Ye[TP]=Ye[PP]=!0,Ye[aP]=Ye[cP]=Ye[vP]=Ye[lP]=Ye[IP]=Ye[hP]=Ye[uP]=Ye[dP]=Ye[pP]=Ye[gP]=Ye[fP]=Ye[wP]=Ye[yP]=Ye[mP]=Ye[bP]=!1;function xP(s){return oP(s)&&nP(s.length)&&!!Ye[rP(s)]}var MP=xP;function OP(s){return function(e){return s(e)}}var DP=OP,Wl={exports:{}};(function(s,e){var t=Pw,i=e&&!e.nodeType&&e,r=i&&!0&&s&&!s.nodeType&&s,n=r&&r.exports===i,o=n&&t.process,a=(function(){try{var c=r&&r.require&&r.require("util").types;return c||o&&o.binding&&o.binding("util")}catch{}})();s.exports=a})(Wl,Wl.exports);var kP=MP,jP=DP,sp=Wl.exports,ip=sp&&sp.isTypedArray,RP=ip?jP(ip):kP,Bw=RP;function UP(s,e){if(!(e==="constructor"&&typeof s[e]=="function")&&e!="__proto__")return s[e]}var Hw=UP,LP=zh,zP=lc,FP=Object.prototype,qP=FP.hasOwnProperty;function BP(s,e,t){var i=s[e];(!(qP.call(s,e)&&zP(i,t))||t===void 0&&!(e in s))&&LP(s,e,t)}var HP=BP,WP=HP,VP=zh;function KP(s,e,t,i){var r=!t;t||(t={});for(var n=-1,o=e.length;++n<o;){var a=e[n],c=i?i(t[a],s[a],a,t,s):void 0;c===void 0&&(c=s[a]),r?VP(t,a,c):WP(t,a,c)}return t}var GP=KP;function YP(s,e){for(var t=-1,i=Array(s);++t<s;)i[t]=e(t);return i}var QP=YP,JP=9007199254740991,ZP=/^(?:0|[1-9]\d*)$/;function XP(s,e){var t=typeof s;return e=e??JP,!!e&&(t=="number"||t!="symbol"&&ZP.test(s))&&s>-1&&s%1==0&&s<e}var Ww=XP,ex=QP,tx=Lw,sx=zw,ix=Wa.exports,rx=Ww,nx=Bw,ox=Object.prototype,ax=ox.hasOwnProperty;function cx(s,e){var t=sx(s),i=!t&&tx(s),r=!t&&!i&&ix(s),n=!t&&!i&&!r&&nx(s),o=t||i||r||n,a=o?ex(s.length,String):[],c=a.length;for(var l in s)(e||ax.call(s,l))&&!(o&&(l=="length"||r&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||rx(l,c)))&&a.push(l);return a}var lx=cx;function hx(s){var e=[];if(s!=null)for(var t in Object(s))e.push(t);return e}var ux=hx,dx=wr,px=Rw,gx=ux,fx=Object.prototype,wx=fx.hasOwnProperty;function yx(s){if(!dx(s))return gx(s);var e=px(s),t=[];for(var i in s)i=="constructor"&&(e||!wx.call(s,i))||t.push(i);return t}var mx=yx,bx=lx,vx=mx,Ix=Fh;function Ex(s){return Ix(s)?bx(s,!0):vx(s)}var Vw=Ex,Ax=GP,Nx=Vw;function Cx(s){return Ax(s,Nx(s))}var _x=Cx,rp=kw,Sx=Hl.exports,$x=lT,Tx=uT,Px=CT,np=Lw,op=zw,xx=WT,Mx=Wa.exports,Ox=Uh,Dx=wr,kx=iP,jx=Bw,ap=Hw,Rx=_x;function Ux(s,e,t,i,r,n,o){var a=ap(s,t),c=ap(e,t),l=o.get(c);if(l){rp(s,t,l);return}var u=n?n(a,c,t+"",s,e,o):void 0,d=u===void 0;if(d){var p=op(c),f=!p&&Mx(c),g=!p&&!f&&jx(c);u=c,p||f||g?op(a)?u=a:xx(a)?u=Tx(a):f?(d=!1,u=Sx(c,!0)):g?(d=!1,u=$x(c,!0)):u=[]:kx(c)||np(c)?(u=a,np(a)?u=Rx(a):(!Dx(a)||Ox(a))&&(u=Px(c))):d=!1}d&&(o.set(c,u),r(u,c,i,n,o),o.delete(c)),rp(s,t,u)}var Lx=Ux,zx=H$,Fx=kw,qx=tT,Bx=Lx,Hx=wr,Wx=Vw,Vx=Hw;function Kw(s,e,t,i,r){s!==e&&qx(e,function(n,o){if(r||(r=new zx),Hx(n))Bx(s,e,o,t,Kw,i,r);else{var a=i?i(Vx(s,o),n,o+"",s,e,r):void 0;a===void 0&&(a=n),Fx(s,o,a)}},Wx)}var Kx=Kw;function Gx(s){return s}var Gw=Gx;function Yx(s,e,t){switch(t.length){case 0:return s.call(e);case 1:return s.call(e,t[0]);case 2:return s.call(e,t[0],t[1]);case 3:return s.call(e,t[0],t[1],t[2])}return s.apply(e,t)}var Qx=Yx,Jx=Qx,cp=Math.max;function Zx(s,e,t){return e=cp(e===void 0?s.length-1:e,0),function(){for(var i=arguments,r=-1,n=cp(i.length-e,0),o=Array(n);++r<n;)o[r]=i[e+r];r=-1;for(var a=Array(e+1);++r<e;)a[r]=i[r];return a[e]=t(o),Jx(s,this,a)}}var Xx=Zx;function e2(s){return function(){return s}}var t2=e2,s2=t2,lp=Dw,i2=Gw,r2=lp?function(s,e){return lp(s,"toString",{configurable:!0,enumerable:!1,value:s2(e),writable:!0})}:i2,n2=r2,o2=800,a2=16,c2=Date.now;function l2(s){var e=0,t=0;return function(){var i=c2(),r=a2-(i-t);if(t=i,r>0){if(++e>=o2)return arguments[0]}else e=0;return s.apply(void 0,arguments)}}var h2=l2,u2=n2,d2=h2,p2=d2(u2),g2=p2,f2=Gw,w2=Xx,y2=g2;function m2(s,e){return y2(w2(s,e,f2),s+"")}var b2=m2,v2=lc,I2=Fh,E2=Ww,A2=wr;function N2(s,e,t){if(!A2(t))return!1;var i=typeof e;return(i=="number"?I2(t)&&E2(e,t.length):i=="string"&&e in t)?v2(t[e],s):!1}var C2=N2,_2=b2,S2=C2;function $2(s){return _2(function(e,t){var i=-1,r=t.length,n=r>1?t[r-1]:void 0,o=r>2?t[2]:void 0;for(n=s.length>3&&typeof n=="function"?(r--,n):void 0,o&&S2(t[0],t[1],o)&&(n=r<3?void 0:n,r=1),e=Object(e);++i<r;){var a=t[i];a&&s(e,a,i,n)}return e})}var T2=$2,P2=Kx,x2=T2,M2=x2(function(s,e,t){P2(s,e,t)}),O2=M2,D2=Object.defineProperty,k2=Object.defineProperties,j2=Object.getOwnPropertyDescriptors,hp=Object.getOwnPropertySymbols,R2=Object.prototype.hasOwnProperty,U2=Object.prototype.propertyIsEnumerable,up=(s,e,t)=>e in s?D2(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,da=(s,e)=>{for(var t in e||(e={}))R2.call(e,t)&&up(s,t,e[t]);if(hp)for(var t of hp(e))U2.call(e,t)&&up(s,t,e[t]);return s},L2=(s,e)=>k2(s,j2(e));function hs(s,e,t){var i;const r=fn(s);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${Tw}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function yr(s){return s.includes(":")?s.split(":")[1]:s}function Yw(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function z2(s,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(s));if(!t.length)return[];const i=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;i.push(...n)}),i}function Wc(s={},e={}){const t=dp(s),i=dp(e);return O2(t,i)}function dp(s){var e,t,i,r;const n={};if(!Co(s))return n;for(const[o,a]of Object.entries(s)){const c=kh(o)?[o]:a.chains,l=a.methods||[],u=a.events||[],d=a.rpcMap||{},p=io(o);n[p]=L2(da(da({},n[p]),a),{chains:Ta(c,(e=n[p])==null?void 0:e.chains),methods:Ta(l,(t=n[p])==null?void 0:t.methods),events:Ta(u,(i=n[p])==null?void 0:i.events),rpcMap:da(da({},d),(r=n[p])==null?void 0:r.rpcMap)})}return n}function F2(s){return s.includes(":")?s.split(":")[2]:s}function pp(s){const e={};for(const[t,i]of Object.entries(s)){const r=i.methods||[],n=i.events||[],o=i.accounts||[],a=kh(t)?[t]:i.chains?i.chains:Yw(i.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Vc(s){return typeof s=="number"?s:s.includes("0x")?parseInt(s,16):(s=s.includes(":")?s.split(":")[1]:s,isNaN(Number(s))?s:Number(s))}const Qw={},Se=s=>Qw[s],Kc=(s,e)=>{Qw[s]=e};var q2=Object.defineProperty,B2=(s,e,t)=>e in s?q2(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Sr=(s,e,t)=>B2(s,typeof e!="symbol"?e+"":e,t);class H2{constructor(e){Sr(this,"name","polkadot"),Sr(this,"client"),Sr(this,"httpProviders"),Sr(this,"events"),Sr(this,"namespace"),Sr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=yr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||hs(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(i,Se("disableProviderPing")))}}var W2=Object.defineProperty,V2=Object.defineProperties,K2=Object.getOwnPropertyDescriptors,gp=Object.getOwnPropertySymbols,G2=Object.prototype.hasOwnProperty,Y2=Object.prototype.propertyIsEnumerable,Vl=(s,e,t)=>e in s?W2(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fp=(s,e)=>{for(var t in e||(e={}))G2.call(e,t)&&Vl(s,t,e[t]);if(gp)for(var t of gp(e))Y2.call(e,t)&&Vl(s,t,e[t]);return s},wp=(s,e)=>V2(s,K2(e)),$r=(s,e,t)=>Vl(s,typeof e!="symbol"?e+"":e,t);class Q2{constructor(e){$r(this,"name","eip155"),$r(this,"client"),$r(this,"chainId"),$r(this,"namespace"),$r(this,"httpProviders"),$r(this,"events"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||hs(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(i,Se("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=parseInt(yr(t));e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let r=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,i,r;const n=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!n)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const o=this.client.session.get(e.topic),a=((r=o?.sessionProperties)==null?void 0:r.capabilities)||{};if(a!=null&&a[n])return a?.[n];const c=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:wp(fp({},o.sessionProperties||{}),{capabilities:wp(fp({},a||{}),{[n]:c})})})}catch(l){console.warn("Failed to update session with capabilities",l)}return c}async getCallStatus(e){var t,i;const r=this.client.session.get(e.topic),n=(t=r.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=r.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h.formatJsonRpcRequest("eth_getUserOperationReceipt",[(i=t.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${QC}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var J2=Object.defineProperty,Z2=(s,e,t)=>e in s?J2(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Tr=(s,e,t)=>Z2(s,typeof e!="symbol"?e+"":e,t);class X2{constructor(e){Tr(this,"name","solana"),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=yr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||hs(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(i,Se("disableProviderPing")))}}var eM=Object.defineProperty,tM=(s,e,t)=>e in s?eM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pr=(s,e,t)=>tM(s,typeof e!="symbol"?e+"":e,t);class sM{constructor(e){Pr(this,"name","cosmos"),Pr(this,"client"),Pr(this,"httpProviders"),Pr(this,"events"),Pr(this,"namespace"),Pr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=yr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||hs(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(i,Se("disableProviderPing")))}}var iM=Object.defineProperty,rM=(s,e,t)=>e in s?iM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,xr=(s,e,t)=>rM(s,typeof e!="symbol"?e+"":e,t);class nM{constructor(e){xr(this,"name","algorand"),xr(this,"client"),xr(this,"httpProviders"),xr(this,"events"),xr(this,"namespace"),xr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||hs(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||hs(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new h.o(new h.f$1(i,Se("disableProviderPing")))}}var oM=Object.defineProperty,aM=(s,e,t)=>e in s?oM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Mr=(s,e,t)=>aM(s,typeof e!="symbol"?e+"":e,t);class cM{constructor(e){Mr(this,"name","cip34"),Mr(this,"client"),Mr(this,"httpProviders"),Mr(this,"events"),Mr(this,"namespace"),Mr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),r=yr(t);e[r]=this.createHttpProvider(r,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(i,Se("disableProviderPing")))}}var lM=Object.defineProperty,hM=(s,e,t)=>e in s?lM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Or=(s,e,t)=>hM(s,typeof e!="symbol"?e+"":e,t);class uM{constructor(e){Or(this,"name","elrond"),Or(this,"client"),Or(this,"httpProviders"),Or(this,"events"),Or(this,"namespace"),Or(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=yr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||hs(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(i,Se("disableProviderPing")))}}var dM=Object.defineProperty,pM=(s,e,t)=>e in s?dM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Dr=(s,e,t)=>pM(s,typeof e!="symbol"?e+"":e,t);class gM{constructor(e){Dr(this,"name","multiversx"),Dr(this,"client"),Dr(this,"httpProviders"),Dr(this,"events"),Dr(this,"namespace"),Dr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const r=yr(t);e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||hs(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(i,Se("disableProviderPing")))}}var fM=Object.defineProperty,wM=(s,e,t)=>e in s?fM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,kr=(s,e,t)=>wM(s,typeof e!="symbol"?e+"":e,t);class yM{constructor(e){kr(this,"name","near"),kr(this,"client"),kr(this,"httpProviders"),kr(this,"events"),kr(this,"namespace"),kr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||hs(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||hs(e,this.namespace);return typeof i>"u"?void 0:new h.o(new h.f$1(i,Se("disableProviderPing")))}}var mM=Object.defineProperty,bM=(s,e,t)=>e in s?mM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,jr=(s,e,t)=>bM(s,typeof e!="symbol"?e+"":e,t);class vM{constructor(e){jr(this,"name","tezos"),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||hs(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||hs(e,this.namespace);return typeof i>"u"?void 0:new h.o(new h.f$1(i))}}var IM=Object.defineProperty,EM=(s,e,t)=>e in s?IM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Rr=(s,e,t)=>EM(s,typeof e!="symbol"?e+"":e,t);class AM{constructor(e){Rr(this,"name",tn),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Se("events"),this.client=Se("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(As.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=fn(r);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||hs(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new h.o(new h.f$1(i,Se("disableProviderPing")))}}var NM=Object.defineProperty,CM=Object.defineProperties,_M=Object.getOwnPropertyDescriptors,yp=Object.getOwnPropertySymbols,SM=Object.prototype.hasOwnProperty,$M=Object.prototype.propertyIsEnumerable,Kl=(s,e,t)=>e in s?NM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,pa=(s,e)=>{for(var t in e||(e={}))SM.call(e,t)&&Kl(s,t,e[t]);if(yp)for(var t of yp(e))$M.call(e,t)&&Kl(s,t,e[t]);return s},Gc=(s,e)=>CM(s,_M(e)),Ts=(s,e,t)=>Kl(s,typeof e!="symbol"?e+"":e,t);class qh{constructor(e){Ts(this,"client"),Ts(this,"namespaces"),Ts(this,"optionalNamespaces"),Ts(this,"sessionProperties"),Ts(this,"events",new h.Nt),Ts(this,"rpcProviders",{}),Ts(this,"session"),Ts(this,"providerOpts"),Ts(this,"logger"),Ts(this,"uri"),Ts(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:h.Ot(h.k({level:e?.logger||Hd})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new qh(e);return await t.initialize(),t}async request(e,t,i){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:pa({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,r){const n=new Date().getTime();this.request(e,i,r).then(o=>t(null,h.formatJsonRpcResult(n,o))).catch(o=>t(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}),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:Re("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:r}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await r();if(this.session=n.session,this.session){const o=pp(this.session.namespaces);this.namespaces=Wc(this.namespaces,o),this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await i();this.session=r;const n=pp(r.namespaces);return this.namespaces=Wc(this.namespaces,n),this.persist("namespaces",this.namespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,r]=this.validateChain(e),n=this.getProvider(i);n.name===tn?n.setDefaultChain(`${i}:${r}`,t):n.setDefaultChain(r,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(lr(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){if(this.namespaces=await this.getFromStore("namespaces"),this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.client.session.length){const e=this.client.session.keys.length-1;this.session=this.client.session.get(this.client.session.keys[e]),this.createProviders()}}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){this.client=this.providerOpts.client||await VC.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Hd,relayUrl:this.providerOpts.relayUrl||KC,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.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(t=>io(t)))];Kc("client",this.client),Kc("events",this.events),Kc("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=z2(t,this.session),r=Yw(i),n=Wc(this.namespaces,this.optionalNamespaces),o=Gc(pa({},n[t]),{accounts:i,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new Q2({namespace:o});break;case"algorand":this.rpcProviders[t]=new nM({namespace:o});break;case"solana":this.rpcProviders[t]=new X2({namespace:o});break;case"cosmos":this.rpcProviders[t]=new sM({namespace:o});break;case"polkadot":this.rpcProviders[t]=new H2({namespace:o});break;case"cip34":this.rpcProviders[t]=new cM({namespace:o});break;case"elrond":this.rpcProviders[t]=new uM({namespace:o});break;case"multiversx":this.rpcProviders[t]=new gM({namespace:o});break;case"near":this.rpcProviders[t]=new yM({namespace:o});break;case"tezos":this.rpcProviders[t]=new vM({namespace:o});break;default:this.rpcProviders[tn]?this.rpcProviders[tn].updateNamespace(o):this.rpcProviders[tn]=new AM({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{const{params:t}=e,{event:i}=t;if(i.name==="accountsChanged"){const r=i.data;r&&lr(r)&&this.events.emit("accountsChanged",r.map(F2))}else if(i.name==="chainChanged"){const r=t.chainId,n=t.event.data,o=io(r),a=Vc(r)!==Vc(n)?`${o}:${Vc(n)}`:r;this.onChainChanged(a)}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i;const{namespaces:r}=t,n=(i=this.client)==null?void 0:i.session.get(e);this.session=Gc(pa({},n),{namespaces:r}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Gc(pa({},Re("USER_DISCONNECTED")),{data:e.topic}))}),this.on(As.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[tn]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:r}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=r,this.persist("namespaces",t),this.persist("optionalNamespaces",i)}validateChain(e){const[t,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>io(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const r=io(Object.keys(this.namespaces)[0]),n=this.rpcProviders[r].getDefaultChain();return[r,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,r]=this.validateChain(e);r&&(t||this.getProvider(i).setDefaultChain(r),this.namespaces[i]?this.namespaces[i].defaultChain=r:this.namespaces[`${i}:${r}`]?this.namespaces[`${i}:${r}`].defaultChain=r:this.namespaces[`${i}:${r}`]={defaultChain:r},this.persist("namespaces",this.namespaces),this.events.emit("chainChanged",r))}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.session=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,this.persist("namespaces",void 0),this.persist("optionalNamespaces",void 0),this.persist("sessionProperties",void 0),await this.cleanupPendingPairings({deletePairings:!0})}persist(e,t){this.client.core.storage.setItem(`${Wd}/${e}`,t)}async getFromStore(e){return await this.client.core.storage.getItem(`${Wd}/${e}`)}}const TM=qh,Jw={caipNetworkIdToNumber(s){return s?Number(s.split(":")[1]):void 0},parseEvmChainId(s){return typeof s=="string"?this.caipNetworkIdToNumber(s):s},getNetworksByNamespace(s,e){return s?.filter(t=>t.chainNamespace===e)||[]},getFirstNetworkByNamespace(s,e){return this.getNetworksByNamespace(s,e)[0]}},ga={bigNumber(s){return s?new k.Big(s):new k.Big(0)},multiply(s,e){if(s===void 0||e===void 0)return new k.Big(0);const t=new k.Big(s),i=new k.Big(e);return t.times(i)},formatNumberToLocalString(s,e=2){return s===void 0?"0.00":typeof s=="number"?s.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(s).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(s){return s===void 0?0:parseFloat(s.replace(/,/gu,""))}},PM=[{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"}]}],xM=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],MM=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],ie={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network"},OM={getERC20Abi:s=>ie.USDT_CONTRACT_ADDRESSES.includes(s)?MM:PM,getSwapAbi:()=>xM},vi={validateCaipAddress(s){if(s.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return s},parseCaipAddress(s){const e=s.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${s}`);const[t,i,r]=e;if(!t||!i||!r)throw new Error(`Invalid CAIP-10 address: ${s}`);return{chainNamespace:t,chainId:i,address:r}},parseCaipNetworkId(s){const e=s.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${s}`);const[t,i]=e;if(!t||!i)throw new Error(`Invalid CAIP-2 network id: ${s}`);return{chainNamespace:t,chainId:i}}},de={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache"};function Yc(s){if(!s)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${s}:connected_connector_id`}const ce={setItem(s,e){no()&&e!==void 0&&localStorage.setItem(s,e)},getItem(s){if(no())return localStorage.getItem(s)||void 0},removeItem(s){no()&&localStorage.removeItem(s)},clear(){no()&&localStorage.clear()}};function no(){return typeof window<"u"&&typeof localStorage<"u"}function Pi(s,e){return e==="light"?{"--w3m-accent":s?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":s?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const Qc=(typeof N.process$1<"u"&&typeof N.process$1.env<"u"?N.process$1.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Ht={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:Qc,SECURE_SITE_DASHBOARD:`${Qc}/dashboard`,SECURE_SITE_FAVICON:`${Qc}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",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"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],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:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155","solana"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in a new browser tab"},DEFAULT_FEATURES:{swaps:!0,onramp:!0,receive:!0,send:!0,email:!0,emailShowWallets:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],history:!0,analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0},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"}},X={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(s,e){return Date.now()-s>e},getActiveNetworkProps(){const s=X.getActiveNamespace(),e=X.getActiveCaipNetworkId(),t=e?e.split(":")[1]:void 0,i=t?isNaN(Number(t))?t:Number(t):void 0;return{namespace:s,caipNetworkId:e,chainId:i}},setWalletConnectDeepLink({name:s,href:e}){try{ce.setItem(de.DEEPLINK_CHOICE,JSON.stringify({href:e,name:s}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const s=ce.getItem(de.DEEPLINK_CHOICE);if(s)return JSON.parse(s)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{ce.removeItem(de.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(s){try{ce.setItem(de.ACTIVE_NAMESPACE,s)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(s){try{ce.setItem(de.ACTIVE_CAIP_NETWORK_ID,s),X.setActiveNamespace(s.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return ce.getItem(de.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{ce.removeItem(de.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(s){try{const e=Yc(s);ce.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(s){try{const e=X.getRecentWallets();e.find(i=>i.id===s.id)||(e.unshift(s),e.length>2&&e.pop(),ce.setItem(de.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const s=ce.getItem(de.RECENT_WALLETS);return s?JSON.parse(s):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(s,e){try{const t=Yc(s);ce.setItem(t,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return ce.getItem(de.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(s){if(s)try{const e=Yc(s);return ce.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",s)}},setConnectedSocialProvider(s){try{ce.setItem(de.CONNECTED_SOCIAL,s)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return ce.getItem(de.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{ce.removeItem(de.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return ce.getItem(de.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return ce.getItem(de.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(s){try{ce.setItem(de.CONNECTION_STATUS,s)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return ce.getItem(de.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const s=ce.getItem(de.CONNECTED_NAMESPACES);return s?.length?s.split(","):[]}catch{return[]}},setConnectedNamespaces(s){try{const e=Array.from(new Set(s));ce.setItem(de.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(s){try{const e=X.getConnectedNamespaces();e.includes(s)||(e.push(s),X.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(s){try{const e=X.getConnectedNamespaces(),t=e.indexOf(s);t>-1&&(e.splice(t,1),X.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return ce.getItem(de.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(s){try{ce.setItem(de.TELEGRAM_SOCIAL_PROVIDER,s)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{ce.removeItem(de.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let s={};try{const e=ce.getItem(de.PORTFOLIO_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromBalanceCache(s){try{const e=X.getBalanceCache();ce.setItem(de.PORTFOLIO_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove address from balance cache",s)}},getBalanceCacheForCaipAddress(s){try{const t=X.getBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.portfolio))return t.balance;X.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateBalanceCache(s){try{const e=X.getBalanceCache();e[s.caipAddress]=s,ce.setItem(de.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getNativeBalanceCache(){let s={};try{const e=ce.getItem(de.NATIVE_BALANCE_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return s},removeAddressFromNativeBalanceCache(s){try{const e=X.getBalanceCache();ce.setItem(de.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove address from balance cache",s)}},getNativeBalanceCacheForCaipAddress(s){try{const t=X.getNativeBalanceCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.nativeBalance))return t;console.info("Discarding cache for address",s),X.removeAddressFromBalanceCache(s)}catch{console.info("Unable to get balance cache for address",s)}},updateNativeBalanceCache(s){try{const e=X.getNativeBalanceCache();e[s.caipAddress]=s,ce.setItem(de.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",s)}},getEnsCache(){let s={};try{const e=ce.getItem(de.ENS_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return s},getEnsFromCacheForAddress(s){try{const t=X.getEnsCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.ens))return t.ens;X.removeEnsFromCache(s)}catch{console.info("Unable to get ens name from cache",s)}},updateEnsCache(s){try{const e=X.getEnsCache();e[s.address]=s,ce.setItem(de.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",s)}},removeEnsFromCache(s){try{const e=X.getEnsCache();ce.setItem(de.ENS_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove ens name from cache",s)}},getIdentityCache(){let s={};try{const e=ce.getItem(de.IDENTITY_CACHE);s=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return s},getIdentityFromCacheForAddress(s){try{const t=X.getIdentityCache()[s];if(t&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.identity))return t.identity;X.removeIdentityFromCache(s)}catch{console.info("Unable to get identity from cache",s)}},updateIdentityCache(s){try{const e=X.getIdentityCache();e[s.address]={identity:s.identity,timestamp:s.timestamp},ce.setItem(de.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",s)}},removeIdentityFromCache(s){try{const e=X.getIdentityCache();ce.setItem(de.IDENTITY_CACHE,JSON.stringify({...e,[s]:void 0}))}catch{console.info("Unable to remove identity from cache",s)}},clearAddressCache(){try{ce.removeItem(de.PORTFOLIO_CACHE),ce.removeItem(de.NATIVE_BALANCE_CACHE),ce.removeItem(de.ENS_CACHE),ce.removeItem(de.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}}},he={isMobile(){return this.isClient()?!!(window?.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(s,e=""){return s?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const s=window?.navigator.userAgent.toLowerCase();return he.isMobile()&&s.includes("android")},isIos(){if(!this.isMobile())return!1;const s=window?.navigator.userAgent.toLowerCase();return s.includes("iphone")||s.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(s){return s?s-Date.now()<=Ht.TEN_SEC_MS:!0},isAllowedRetry(s,e=Ht.ONE_SEC_MS){return Date.now()-s>=e},copyToClopboard(s){navigator.clipboard.writeText(s)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},getPairingExpiry(){return Date.now()+Ht.FOUR_MINUTES_MS},getNetworkId(s){return s?.split(":")[1]},getPlainAddress(s){return s?.split(":")[2]},async wait(s){return new Promise(e=>{setTimeout(e,s)})},debounce(s,e=500){let t;return(...i)=>{function r(){s(...i)}t&&clearTimeout(t),t=setTimeout(r,e)}},isHttpUrl(s){return s.startsWith("http://")||s.startsWith("https://")},formatNativeUrl(s,e){if(he.isHttpUrl(s))return this.formatUniversalUrl(s,e);let t=s;t.includes("://")||(t=s.replaceAll("/","").replaceAll(":",""),t=`${t}://`),t.endsWith("/")||(t=`${t}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${t}wc?uri=${i}`,href:t}},formatUniversalUrl(s,e){if(!he.isHttpUrl(s))return this.formatNativeUrl(s,e);let t=s;t.endsWith("/")||(t=`${t}/`);const i=encodeURIComponent(e);return{redirect:`${t}wc?uri=${i}`,href:t}},getOpenTargetForPlatform(s){return s==="popupWindow"?s:this.isTelegram()?X.getTelegramSocialProvider()?"_top":"_blank":s},openHref(s,e,t){window?.open(s,this.getOpenTargetForPlatform(e),t||"noreferrer noopener")},returnOpenHref(s,e,t){return window?.open(s,this.getOpenTargetForPlatform(e),t||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},async preloadImage(s){const e=new Promise((t,i)=>{const r=new Image;r.onload=t,r.onerror=i,r.crossOrigin="anonymous",r.src=s});return Promise.race([e,he.wait(2e3)])},formatBalance(s,e){let t="0.000";if(typeof s=="string"){const i=Number(s);if(i){const r=Math.floor(i*1e3)/1e3;r&&(t=r.toString())}}return`${t}${e?` ${e}`:""}`},formatBalance2(s,e){let t;if(s==="0")t="0";else if(typeof s=="string"){const i=Number(s);i&&(t=i.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}return{value:t??"0",rest:t==="0"?"000":"",symbol:e}},getApiUrl(){return ie.W3M_API_URL},getBlockchainApiUrl(){return ie.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return ie.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})},parseError(s){return typeof s=="string"?s:typeof s?.issues?.[0]?.message=="string"?s.issues[0].message:s instanceof Error?s.message:"Unknown error"},sortRequestedNetworks(s,e=[]){const t={};return e&&s&&(s.forEach((i,r)=>{t[i]=r}),e.sort((i,r)=>{const n=t[i.id],o=t[r.id];return n!==void 0&&o!==void 0?n-o:n!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(s){let e=0;for(const t of s)e+=t.value??0;return e},formatTokenBalance(s){const e=s.toFixed(2),[t,i]=e.split(".");return{dollars:t,pennies:i}},isAddress(s,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(s)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(s)||/^(?:0x)?[0-9A-F]{40}$/iu.test(s))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(s);default:return!1}},uniqueBy(s,e){const t=new Set;return s.filter(i=>{const r=i[e];return t.has(r)?!1:(t.add(r),!0)})},generateSdkVersion(s,e,t){const r=s.length===0?Ht.ADAPTER_TYPES.UNIVERSAL:s.map(n=>n.adapterType).join(",");return`${e}-${r}-${t}`},createAccount(s,e,t,i,r){return{namespace:s,address:e,type:t,publicKey:i,path:r}},isCaipAddress(s){if(typeof s!="string")return!1;const e=s.split(":"),t=e[0];return e.filter(Boolean).length===3&&t in ie.CHAIN_NAME_MAP},isMac(){const s=window?.navigator.userAgent.toLowerCase();return s.includes("macintosh")&&!s.includes("safari")},formatTelegramSocialLoginUrl(s){const e=`--${encodeURIComponent(window?.location.href)}`,t="state=";if(new URL(s).host==="auth.magic.link"){const r="provider_authorization_url=",n=s.substring(s.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(n),t,e);return s.replace(n,encodeURIComponent(o))}return this.injectIntoUrl(s,t,e)},injectIntoUrl(s,e,t){const i=s.indexOf(e);if(i===-1)throw new Error(`${e} parameter not found in the URL: ${s}`);const r=s.indexOf("&",i),n=e.length,o=r!==-1?r:s.length,a=s.substring(0,i+n),c=s.substring(i+n,o),l=s.substring(r),u=c+t;return a+u+l}};async function Vn(...s){const e=await fetch(...s);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class fc{constructor({baseUrl:e,clientId:t}){this.baseUrl=e,this.clientId=t}async get({headers:e,signal:t,cache:i,...r}){const n=this.createUrl(r);return(await Vn(n,{method:"GET",headers:e,signal:t,cache:i})).json()}async getBlob({headers:e,signal:t,...i}){const r=this.createUrl(i);return(await Vn(r,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await Vn(n,{method:"POST",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}async put({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await Vn(n,{method:"PUT",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}async delete({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await Vn(n,{method:"DELETE",headers:t,body:e?JSON.stringify(e):void 0,signal:i})).json()}createUrl({path:e,params:t}){const i=new URL(e,this.baseUrl);return t&&Object.entries(t).forEach(([r,n])=>{n&&i.searchParams.append(r,n)}),this.clientId&&i.searchParams.append("clientId",this.clientId),i}}const DM={handleSolanaDeeplinkRedirect(s){if(I.state.activeChain===ie.CHAIN.SOLANA){const e=window.location.href,t=encodeURIComponent(e);if(s==="Phantom"&&!("phantom"in window)){const i=e.startsWith("https")?"https":"http",r=e.split("/")[2],n=encodeURIComponent(`${i}://${r}`);window.location.href=`https://phantom.app/ul/browse/${t}?ref=${n}`}s==="Coinbase Wallet"&&!("coinbaseSolana"in window)&&(window.location.href=`https://go.cb-w.com/dapp?cb_url=${t}`)}}},ts=k.proxy({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Is={state:ts,subscribeNetworkImages(s){return k.subscribe(ts.networkImages,()=>s(ts.networkImages))},subscribeKey(s,e){return k.subscribeKey(ts,s,e)},subscribe(s){return k.subscribe(ts,()=>s(ts))},setWalletImage(s,e){ts.walletImages[s]=e},setNetworkImage(s,e){ts.networkImages[s]=e},setChainImage(s,e){ts.chainImages[s]=e},setConnectorImage(s,e){ts.connectorImages={...ts.connectorImages,[s]:e}},setTokenImage(s,e){ts.tokenImages[s]=e},setCurrencyImage(s,e){ts.currencyImages[s]=e}},kM={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},Jc=k.proxy({networkImagePromises:{}}),Bh={async fetchWalletImage(s){if(s)return await ue._fetchWalletImage(s),this.getWalletImageById(s)},async fetchNetworkImage(s){if(!s)return;const e=this.getNetworkImageById(s);return e||(Jc.networkImagePromises[s]||(Jc.networkImagePromises[s]=ue._fetchNetworkImage(s)),await Jc.networkImagePromises[s],this.getNetworkImageById(s))},getWalletImageById(s){if(s)return Is.state.walletImages[s]},getWalletImage(s){if(s?.image_url)return s?.image_url;if(s?.image_id)return Is.state.walletImages[s.image_id]},getNetworkImage(s){if(s?.assets?.imageUrl)return s?.assets?.imageUrl;if(s?.assets?.imageId)return Is.state.networkImages[s.assets.imageId]},getNetworkImageById(s){if(s)return Is.state.networkImages[s]},getConnectorImage(s){if(s?.imageUrl)return s.imageUrl;if(s?.imageId)return Is.state.connectorImages[s.imageId]},getChainImage(s){return Is.state.networkImages[kM[s]]}},jM={getFeatureValue(s,e){const t=e?.[s];return t===void 0?Ht.DEFAULT_FEATURES[s]:t},filterSocialsByPlatform(s){if(!s||!s.length)return s;if(he.isTelegram()){if(he.isIos())return s.filter(e=>e!=="google");if(he.isMac())return s.filter(e=>e!=="x");if(he.isAndroid())return s.filter(e=>!["facebook","x"].includes(e))}return s}},ne=k.proxy({features:Ht.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Ht.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0}),R={state:ne,subscribeKey(s,e){return k.subscribeKey(ne,s,e)},setOptions(s){Object.assign(ne,s)},setFeatures(s){if(!s)return;ne.features||(ne.features=Ht.DEFAULT_FEATURES);const e={...ne.features,...s};ne.features=e,ne.features.socials&&(ne.features.socials=jM.filterSocialsByPlatform(ne.features.socials))},setProjectId(s){ne.projectId=s},setCustomRpcUrls(s){ne.customRpcUrls=s},setAllWallets(s){ne.allWallets=s},setIncludeWalletIds(s){ne.includeWalletIds=s},setExcludeWalletIds(s){ne.excludeWalletIds=s},setFeaturedWalletIds(s){ne.featuredWalletIds=s},setTokens(s){ne.tokens=s},setTermsConditionsUrl(s){ne.termsConditionsUrl=s},setPrivacyPolicyUrl(s){ne.privacyPolicyUrl=s},setCustomWallets(s){ne.customWallets=s},setIsSiweEnabled(s){ne.isSiweEnabled=s},setIsUniversalProvider(s){ne.isUniversalProvider=s},setSdkVersion(s){ne.sdkVersion=s},setMetadata(s){ne.metadata=s},setDisableAppend(s){ne.disableAppend=s},setEIP6963Enabled(s){ne.enableEIP6963=s},setDebug(s){ne.debug=s},setEnableWalletConnect(s){ne.enableWalletConnect=s},setEnableWalletGuide(s){ne.enableWalletGuide=s},setEnableAuthLogger(s){ne.enableAuthLogger=s},setEnableWallets(s){ne.enableWallets=s},setHasMultipleAddresses(s){ne.hasMultipleAddresses=s},setSIWX(s){ne.siwx=s},setConnectMethodsOrder(s){ne.features={...ne.features,connectMethodsOrder:s}},setWalletFeaturesOrder(s){ne.features={...ne.features,walletFeaturesOrder:s}},setSocialsOrder(s){ne.features={...ne.features,socials:s}},setCollapseWallets(s){ne.features={...ne.features,collapseWallets:s}},setEnableEmbedded(s){ne.enableEmbedded=s},setAllowUnsupportedChain(s){ne.allowUnsupportedChain=s},setManualWCControl(s){ne.manualWCControl=s},setEnableNetworkSwitch(s){ne.enableNetworkSwitch=s},setDefaultAccountTypes(s={}){Object.entries(s).forEach(([e,t])=>{t&&(ne.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(s){ne.universalProviderConfigOverride=s},getUniversalProviderConfigOverride(){return ne.universalProviderConfigOverride},getSnapshot(){return k.snapshot(ne)}},Ii=k.proxy({message:"",variant:"info",open:!1}),po={state:Ii,subscribeKey(s,e){return k.subscribeKey(Ii,s,e)},open(s,e){const{debug:t}=R.state,{shortMessage:i,longMessage:r}=s;t&&(Ii.message=i,Ii.variant=e,Ii.open=!0),r&&console.error(typeof r=="function"?r():r)},close(){Ii.open=!1,Ii.message="",Ii.variant="info"}},RM=he.getAnalyticsUrl(),UM=new fc({baseUrl:RM,clientId:null}),LM=["MODAL_CREATED"],ii=k.proxy({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Be={state:ii,subscribe(s){return k.subscribe(ii,()=>s(ii))},getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=R.state;return{projectId:s,st:e,sv:t||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(s){try{const e=re.state.address;if(LM.includes(s.data.event)||typeof window>"u")return;await UM.post({path:"/e",params:Be.getSdkProperties(),body:{eventId:he.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:s.timestamp,props:{...s.data,address:e}}}),ii.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===ie.HTTP_STATUS_CODES.FORBIDDEN&&!ii.reportedErrors.FORBIDDEN&&(po.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${no()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),ii.reportedErrors.FORBIDDEN=!0)}},sendEvent(s){ii.timestamp=Date.now(),ii.data=s,R.state.features?.analytics&&Be._sendAnalyticsEvent(ii)}},zM=he.getApiUrl(),Rt=new fc({baseUrl:zM,clientId:null}),FM="40",mp="4",qM=20,Oe=k.proxy({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),ue={state:Oe,subscribeKey(s,e){return k.subscribeKey(Oe,s,e)},_getSdkProperties(){const{projectId:s,sdkType:e,sdkVersion:t}=R.state;return{projectId:s,st:e||"appkit",sv:t||"html-wagmi-4.2.2"}},_filterOutExtensions(s){return R.state.isUniversalProvider?s.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):s},async _fetchWalletImage(s){const e=`${Rt.baseUrl}/getWalletImage/${s}`,t=await Rt.getBlob({path:e,params:ue._getSdkProperties()});Is.setWalletImage(s,URL.createObjectURL(t))},async _fetchNetworkImage(s){const e=`${Rt.baseUrl}/public/getAssetImage/${s}`,t=await Rt.getBlob({path:e,params:ue._getSdkProperties()});Is.setNetworkImage(s,URL.createObjectURL(t))},async _fetchConnectorImage(s){const e=`${Rt.baseUrl}/public/getAssetImage/${s}`,t=await Rt.getBlob({path:e,params:ue._getSdkProperties()});Is.setConnectorImage(s,URL.createObjectURL(t))},async _fetchCurrencyImage(s){const e=`${Rt.baseUrl}/public/getCurrencyImage/${s}`,t=await Rt.getBlob({path:e,params:ue._getSdkProperties()});Is.setCurrencyImage(s,URL.createObjectURL(t))},async _fetchTokenImage(s){const e=`${Rt.baseUrl}/public/getTokenImage/${s}`,t=await Rt.getBlob({path:e,params:ue._getSdkProperties()});Is.setTokenImage(s,URL.createObjectURL(t))},async fetchNetworkImages(){const e=I.getAllRequestedCaipNetworks()?.map(({assets:t})=>t?.imageId).filter(Boolean).filter(t=>!Bh.getNetworkImageById(t));e&&await Promise.allSettled(e.map(t=>ue._fetchNetworkImage(t)))},async fetchConnectorImages(){const{connectors:s}=le.state,e=s.map(({imageId:t})=>t).filter(Boolean);await Promise.allSettled(e.map(t=>ue._fetchConnectorImage(t)))},async fetchCurrencyImages(s=[]){await Promise.allSettled(s.map(e=>ue._fetchCurrencyImage(e)))},async fetchTokenImages(s=[]){await Promise.allSettled(s.map(e=>ue._fetchTokenImage(e)))},async fetchFeaturedWallets(){const{featuredWalletIds:s}=R.state;if(s?.length){const{data:e}=await Rt.get({path:"/getWallets",params:{...ue._getSdkProperties(),page:"1",entries:s?.length?String(s.length):mp,include:s?.join(",")}});e.sort((i,r)=>s.indexOf(i.id)-s.indexOf(r.id));const t=e.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(t.map(i=>ue._fetchWalletImage(i))),Oe.featured=e,Oe.allFeatured=e}},async fetchRecommendedWallets(){try{Oe.isFetchingRecommendedWallets=!0;const{includeWalletIds:s,excludeWalletIds:e,featuredWalletIds:t}=R.state,i=[...e??[],...t??[]].filter(Boolean),r=I.getRequestedCaipNetworkIds().join(","),{data:n,count:o}=await Rt.get({path:"/getWallets",params:{...ue._getSdkProperties(),page:"1",chains:r,entries:mp,include:s?.join(","),exclude:i?.join(",")}}),a=X.getRecentWallets(),c=n.map(u=>u.image_id).filter(Boolean),l=a.map(u=>u.image_id).filter(Boolean);await Promise.allSettled([...c,...l].map(u=>ue._fetchWalletImage(u))),Oe.recommended=n,Oe.allRecommended=n,Oe.count=o??0}catch{}finally{Oe.isFetchingRecommendedWallets=!1}},async fetchWallets({page:s}){const{includeWalletIds:e,excludeWalletIds:t,featuredWalletIds:i}=R.state,r=I.getRequestedCaipNetworkIds().join(","),n=[...Oe.recommended.map(({id:l})=>l),...t??[],...i??[]].filter(Boolean),{data:o,count:a}=await Rt.get({path:"/getWallets",params:{...ue._getSdkProperties(),page:String(s),entries:FM,chains:r,include:e?.join(","),exclude:n.join(",")}}),c=o.slice(0,qM).map(l=>l.image_id).filter(Boolean);await Promise.allSettled(c.map(l=>ue._fetchWalletImage(l))),Oe.wallets=he.uniqueBy([...Oe.wallets,...ue._filterOutExtensions(o)],"id"),Oe.count=a>Oe.count?a:Oe.count,Oe.page=s},async initializeExcludedWallets({ids:s}){const e=I.getRequestedCaipNetworkIds().join(","),{data:t}=await Rt.get({path:"/getWallets",params:{...ue._getSdkProperties(),page:"1",entries:String(s.length),chains:e,include:s?.join(",")}});t&&t.forEach(i=>{i?.rdns&&Oe.excludedWallets.push({rdns:i.rdns,name:i.name})})},async searchWallet({search:s,badge:e}){const{includeWalletIds:t,excludeWalletIds:i}=R.state;Oe.search=[];const r=I.getRequestedCaipNetworkIds().join(","),{data:n}=await Rt.get({path:"/getWallets",params:{...ue._getSdkProperties(),page:"1",entries:"100",search:s?.trim(),badge_type:e,chains:r,include:t?.join(","),exclude:i?.join(",")}});Be.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:s??""}});const o=n.map(a=>a.image_id).filter(Boolean);await Promise.allSettled([...o.map(a=>ue._fetchWalletImage(a)),he.wait(300)]),Oe.search=ue._filterOutExtensions(n)},initPromise(s,e){const t=Oe.promises[s];return t||(Oe.promises[s]=e())},prefetch({fetchConnectorImages:s=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:t=!0,fetchNetworkImages:i=!0}={}){const r=[s&&ue.initPromise("connectorImages",ue.fetchConnectorImages),e&&ue.initPromise("featuredWallets",ue.fetchFeaturedWallets),t&&ue.initPromise("recommendedWallets",ue.fetchRecommendedWallets),i&&ue.initPromise("networkImages",ue.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(r)},prefetchAnalyticsConfig(){R.state.features?.analytics&&ue.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:s}=await Rt.get({path:"/getAnalyticsConfig",params:ue._getSdkProperties()});R.setFeatures({analytics:s})}catch{R.setFeatures({analytics:!1})}},setFilterByNamespace(s){if(!s){Oe.featured=Oe.allFeatured,Oe.recommended=Oe.allRecommended;return}const e=I.getRequestedCaipNetworkIds().join(",");Oe.featured=Oe.allFeatured.filter(t=>t.chains?.some(i=>e.includes(i))),Oe.recommended=Oe.allRecommended.filter(t=>t.chains?.some(i=>e.includes(i)))}},Te=k.proxy({view:"Connect",history:["Connect"],transactionStack:[]}),Me={state:Te,subscribeKey(s,e){return k.subscribeKey(Te,s,e)},pushTransactionStack(s){Te.transactionStack.push(s)},popTransactionStack(s){const e=Te.transactionStack.pop();if(e)if(s)this.goBack(),e?.onCancel?.();else{if(e.goBack)this.goBack();else if(e.replace){const i=Te.history.indexOf("ConnectingSiwe");i>0?this.goBackToIndex(i-1):(ot.close(),Te.history=[])}else e.view&&this.reset(e.view);e?.onSuccess?.()}},push(s,e){s!==Te.view&&(Te.view=s,Te.history.push(s),Te.data=e)},reset(s,e){Te.view=s,Te.history=[s],Te.data=e},replace(s,e){Te.history.at(-1)===s||(Te.view=s,Te.history[Te.history.length-1]=s,Te.data=e)},goBack(){const s=!I.state.activeCaipAddress&&this.state.view==="ConnectingFarcaster";if(Te.history.length>1&&!Te.history.includes("UnsupportedChain")){Te.history.pop();const[e]=Te.history.slice(-1);e&&(Te.view=e)}else ot.close();Te.data?.wallet&&(Te.data.wallet=void 0),setTimeout(()=>{if(s){re.setFarcasterUrl(void 0,I.state.activeChain);const e=le.getAuthConnector();e?.provider?.reload();const t=k.snapshot(R.state);e?.provider?.syncDappData?.({metadata:t.metadata,sdkVersion:t.sdkVersion,projectId:t.projectId,sdkType:t.sdkType})}},100)},goBackToIndex(s){if(Te.history.length>1){Te.history=Te.history.slice(0,s+1);const[e]=Te.history.slice(-1);e&&(Te.view=e)}}},ri=k.proxy({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Lt={state:ri,subscribe(s){return k.subscribe(ri,()=>s(ri))},setThemeMode(s){ri.themeMode=s;try{const e=le.getAuthConnector();if(e){const t=Lt.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:s,themeVariables:t,w3mThemeVariables:Pi(t,s)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(s){ri.themeVariables={...ri.themeVariables,...s};try{const e=le.getAuthConnector();if(e){const t=Lt.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:Pi(ri.themeVariables,ri.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return k.snapshot(ri)}},Zw={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0},De=k.proxy({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...Zw}}),le={state:De,subscribe(s){return k.subscribe(De,()=>{s(De)})},subscribeKey(s,e){return k.subscribeKey(De,s,e)},initialize(s){s.forEach(e=>{const t=X.getConnectedConnectorId(e);t&&this.setConnectorId(t,e)})},setActiveConnector(s){s&&(De.activeConnector=k.ref(s))},setConnectors(s){s.filter(t=>!De.allConnectors.some(i=>i.id===t.id&&this.getConnectorName(i.name)===this.getConnectorName(t.name)&&i.chain===t.chain)).forEach(t=>{t.type!=="MULTI_CHAIN"&&De.allConnectors.push(k.ref(t))}),De.connectors=this.mergeMultiChainConnectors(De.allConnectors)},removeAdapter(s){De.allConnectors=De.allConnectors.filter(e=>e.chain!==s),De.connectors=this.mergeMultiChainConnectors(De.allConnectors)},mergeMultiChainConnectors(s){const e=this.generateConnectorMapByName(s),t=[];return e.forEach(i=>{const r=i[0],n=r?.id===ie.CONNECTOR_ID.AUTH;i.length>1&&r?t.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...i],type:n?"AUTH":"MULTI_CHAIN",chain:"eip155",id:r?.id||""}):r&&t.push(r)}),t},generateConnectorMapByName(s){const e=new Map;return s.forEach(t=>{const{name:i}=t,r=this.getConnectorName(i);if(!r)return;const n=e.get(r)||[];n.find(a=>a.chain===t.chain)||n.push(t),e.set(r,n)}),e},getConnectorName(s){return s&&({"Trust Wallet":"Trust"}[s]||s)},getUniqueConnectorsByName(s){const e=[];return s.forEach(t=>{e.find(i=>i.chain===t.chain)||e.push(t)}),e},addConnector(s){if(s.id===ie.CONNECTOR_ID.AUTH){const e=s,t=k.snapshot(R.state),i=Lt.getSnapshot().themeMode,r=Lt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:t.metadata,sdkVersion:t.sdkVersion,projectId:t.projectId,sdkType:t.sdkType}),e?.provider?.syncTheme({themeMode:i,themeVariables:r,w3mThemeVariables:Pi(r,i)}),this.setConnectors([s])}else this.setConnectors([s])},getAuthConnector(s){const e=s||I.state.activeChain,t=De.connectors.find(i=>i.id===ie.CONNECTOR_ID.AUTH);if(t)return t?.connectors?.length?t.connectors.find(r=>r.chain===e):t},getAnnouncedConnectorRdns(){return De.connectors.filter(s=>s.type==="ANNOUNCED").map(s=>s.info?.rdns)},getConnectorById(s){return De.allConnectors.find(e=>e.id===s)},getConnector(s,e){return De.allConnectors.filter(i=>i.chain===I.state.activeChain).find(i=>i.explorerId===s||i.info?.rdns===e)},syncIfAuthConnector(s){if(s.id!=="ID_AUTH")return;const e=s,t=k.snapshot(R.state),i=Lt.getSnapshot().themeMode,r=Lt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:t.metadata,sdkVersion:t.sdkVersion,sdkType:t.sdkType,projectId:t.projectId}),e.provider.syncTheme({themeMode:i,themeVariables:r,w3mThemeVariables:Pi(r,i)})},getConnectorsByNamespace(s){const e=De.allConnectors.filter(t=>t.chain===s);return this.mergeMultiChainConnectors(e)},selectWalletConnector(s){const e=le.getConnector(s.id,s.rdns);I.state.activeChain===ie.CHAIN.SOLANA&&DM.handleSolanaDeeplinkRedirect(e?.name||s.name||""),e?Me.push("ConnectingExternal",{connector:e}):Me.push("ConnectingWalletConnect",{wallet:s})},getConnectors(s){return s?this.getConnectorsByNamespace(s):this.mergeMultiChainConnectors(De.allConnectors)},setFilterByNamespace(s){De.filterByNamespace=s,De.connectors=this.getConnectors(s),ue.setFilterByNamespace(s)},setConnectorId(s,e){s&&(De.activeConnectorIds={...De.activeConnectorIds,[e]:s},X.setConnectedConnectorId(e,s))},removeConnectorId(s){De.activeConnectorIds={...De.activeConnectorIds,[s]:void 0},X.deleteConnectedConnectorId(s)},getConnectorId(s){if(s)return De.activeConnectorIds[s]},isConnected(s){return s?!!De.activeConnectorIds[s]:Object.values(De.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){De.activeConnectorIds={...Zw}}};function fa(s,e){return le.getConnectorId(s)===e}function BM(s){const e=Array.from(I.state.chains.keys());let t=[];return s?(t.push([s,I.state.chains.get(s)]),fa(s,ie.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(i=>{i!==s&&fa(i,ie.CONNECTOR_ID.WALLET_CONNECT)&&t.push([i,I.state.chains.get(i)])}):fa(s,ie.CONNECTOR_ID.AUTH)&&e.forEach(i=>{i!==s&&fa(i,ie.CONNECTOR_ID.AUTH)&&t.push([i,I.state.chains.get(i)])})):t=Array.from(I.state.chains.entries()),t}var HM=Object.defineProperty,WM=(s,e,t)=>e in s?HM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,bp=(s,e,t)=>WM(s,typeof e!="symbol"?e+"":e,t);class VM extends h.IEvents{constructor(e){super(),this.opts=e,bp(this,"protocol","wc"),bp(this,"version",2)}}var KM=Object.defineProperty,GM=(s,e,t)=>e in s?KM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,YM=(s,e,t)=>GM(s,e+"",t);let QM=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,YM(this,"records",new Map)}},JM=class{constructor(e,t){this.logger=e,this.core=t}};class ZM extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}let XM=class extends h.IEvents{constructor(e){super()}},eO=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},tO=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},sO=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},iO=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},rO=class{constructor(e,t){this.projectId=e,this.logger=t}},nO=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};var oO=Object.defineProperty,aO=(s,e,t)=>e in s?oO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,vp=(s,e,t)=>aO(s,typeof e!="symbol"?e+"":e,t);let cO=class{constructor(e){this.opts=e,vp(this,"protocol","wc"),vp(this,"version",2)}},lO=class{constructor(e){this.client=e}};const hO="https://secure.walletconnect.org/sdk";typeof N.process$1<"u"&&typeof N.process$1.env<"u"&&N.process$1.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL;typeof N.process$1<"u"&&typeof N.process$1.env<"u"&&N.process$1.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL;typeof N.process$1<"u"&&typeof N.process$1.env<"u"&&N.process$1.env.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION;const _i={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"}},Qi=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),ut=k.proxy({...Qi}),vt={state:ut,subscribeKey(s,e){return k.subscribeKey(ut,s,e)},showLoading(s,e={}){this._showMessage({message:s,variant:"loading",...e})},showSuccess(s){this._showMessage({message:s,variant:"success"})},showSvg(s,e){this._showMessage({message:s,svg:e})},showError(s){const e=he.parseError(s);this._showMessage({message:e,variant:"error"})},hide(){ut.message=Qi.message,ut.variant=Qi.variant,ut.svg=Qi.svg,ut.open=Qi.open,ut.autoClose=Qi.autoClose},_showMessage({message:s,svg:e,variant:t="success",autoClose:i=Qi.autoClose}){ut.open?(ut.open=!1,setTimeout(()=>{ut.message=s,ut.variant=t,ut.svg=e,ut.open=!0,ut.autoClose=i},150)):(ut.message=s,ut.variant=t,ut.svg=e,ut.open=!0,ut.autoClose=i)}},wn={getSIWX(){return R.state.siwx},async initializeIfEnabled(){const s=R.state.siwx,e=I.getActiveCaipAddress();if(!(s&&e))return;const[t,i,r]=e.split(":");if(I.checkIfSupportedNetwork(t))try{if((await s.getSessions(`${t}:${i}`,r)).length)return;await ot.open({view:"SIWXSignMessage"})}catch(n){console.error("SIWXUtil:initializeIfEnabled",n),Be.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await qe._getClient()?.disconnect().catch(console.error),Me.reset("Connect"),vt.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const s=R.state.siwx,e=he.getPlainAddress(I.getActiveCaipAddress()),t=I.getActiveCaipNetwork(),i=qe._getClient();if(!s)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!t)throw new Error("No ActiveCaipNetwork or client found");if(!i)throw new Error("No ConnectionController client found");try{const r=await s.createMessage({chainId:t.caipNetworkId,accountAddress:e}),n=r.toString();le.getConnectorId(t.chainNamespace)===ie.CONNECTOR_ID.AUTH&&Me.pushTransactionStack({view:null,goBack:!1,replace:!0});const a=await i.signMessage(n);await s.addSession({data:r,message:n,signature:a}),ot.close(),Be.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){const n=this.getSIWXEventProperties();(!ot.state.open||Me.state.view==="ApproveTransaction")&&await ot.open({view:"SIWXSignMessage"}),n.isSmartAccount?vt.showError("This application might not support Smart Accounts"):vt.showError("Signature declined"),Be.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:n}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){try{this.getSIWX()?.getRequired?.()?await qe.disconnect():ot.close(),Me.reset("Connect"),Be.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(s){console.error("SIWXUtil:cancelSignMessage",s)}},async getSessions(){const s=R.state.siwx,e=he.getPlainAddress(I.getActiveCaipAddress()),t=I.getActiveCaipNetwork();return s&&e&&t?s.getSessions(t.caipNetworkId,e):[]},async isSIWXCloseDisabled(){const s=this.getSIWX();if(s){const e=Me.state.view==="ApproveTransaction",t=Me.state.view==="SIWXSignMessage";if(e||t)return s.getRequired?.()&&(await this.getSessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:s,chains:e,methods:t}){const i=wn.getSIWX(),r=new Set(e.map(a=>a.split(":")[0]));if(!i||r.size!==1||!r.has("eip155"))return!1;const n=await i.createMessage({chainId:I.getActiveCaipNetwork()?.caipNetworkId||"",accountAddress:""}),o=await s.authenticate({nonce:n.nonce,domain:n.domain,uri:n.uri,exp:n.expirationTime,iat:n.issuedAt,nbf:n.notBefore,requestId:n.requestId,version:n.version,resources:n.resources,statement:n.statement,chainId:n.chainId,methods:t,chains:[n.chainId,...e.filter(a=>a!==n.chainId)]});if(vt.showLoading("Authenticating...",{autoClose:!1}),re.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:o.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"},Array.from(r)[0]),o?.auths?.length){const a=o.auths.map(c=>{const l=s.client.formatAuthMessage({request:c.p,iss:c.p.iss});return{data:{...c.p,accountAddress:c.p.iss.split(":").slice(-1).join(""),chainId:c.p.iss.split(":").slice(2,4).join(":"),uri:c.p.aud,version:c.p.version||n.version,expirationTime:c.p.exp,issuedAt:c.p.iat,notBefore:c.p.nbf},message:l,signature:c.s.s,cacao:c}});try{await i.setSessions(a),Be.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:wn.getSIWXEventProperties()})}catch(c){throw console.error("SIWX:universalProviderAuth - failed to set sessions",c),Be.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:wn.getSIWXEventProperties()}),await s.disconnect().catch(console.error),c}finally{vt.hide()}}return!0},getSIWXEventProperties(){return{network:I.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:re.state.preferredAccountType===_i.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const s=this.getSIWX();s&&await s.setSessions([])}},We=k.proxy({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),uO={state:We,subscribe(s){return k.subscribe(We,()=>s(We))},setLastNetworkInView(s){We.lastNetworkInView=s},async fetchTransactions(s,e){if(!s)throw new Error("Transactions can't be fetched without an accountAddress");We.loading=!0;try{const t=await oe.fetchTransactions({account:s,cursor:We.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:I.state.activeCaipNetwork?.caipNetworkId}),i=this.filterSpamTransactions(t.data),r=this.filterByConnectedChain(i),n=[...We.transactions,...r];We.loading=!1,e==="coinbase"?We.coinbaseTransactions=this.groupTransactionsByYearAndMonth(We.coinbaseTransactions,t.data):(We.transactions=n,We.transactionsByYear=this.groupTransactionsByYearAndMonth(We.transactionsByYear,r)),We.empty=n.length===0,We.next=t.next?t.next:void 0}catch{Be.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:s,projectId:R.state.projectId,cursor:We.next,isSmartAccount:re.state.preferredAccountType===_i.ACCOUNT_TYPES.SMART_ACCOUNT}}),vt.showError("Failed to fetch transactions"),We.loading=!1,We.empty=!0,We.next=void 0}},groupTransactionsByYearAndMonth(s={},e=[]){const t=s;return e.forEach(i=>{const r=new Date(i.metadata.minedAt).getFullYear(),n=new Date(i.metadata.minedAt).getMonth(),o=t[r]??{},c=(o[n]??[]).filter(l=>l.id!==i.id);t[r]={...o,[n]:[...c,i].sort((l,u)=>new Date(u.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),t},filterSpamTransactions(s){return s.filter(e=>!e.transfers.every(i=>i.nft_info?.flags.is_spam===!0))},filterByConnectedChain(s){const e=I.state.activeCaipNetwork?.caipNetworkId;return s.filter(i=>i.metadata.chain===e)},clearCursor(){We.next=void 0},resetTransactions(){We.transactions=[],We.transactionsByYear={},We.lastNetworkInView=void 0,We.loading=!1,We.empty=!1,We.next=void 0}},Ze=k.proxy({wcError:!1,buffering:!1,status:"disconnected"});let Ur;const qe={state:Ze,subscribeKey(s,e){return k.subscribeKey(Ze,s,e)},_getClient(){return Ze._client},setClient(s){Ze._client=k.ref(s)},async connectWalletConnect(){if(he.isTelegram()||he.isSafari()&&he.isIos()){if(Ur){await Ur,Ur=void 0;return}if(!he.isPairingExpired(Ze?.wcPairingExpiry)){const s=Ze.wcUri;Ze.wcUri=s;return}Ur=this._getClient()?.connectWalletConnect?.().catch(()=>{}),this.state.status="connecting",await Ur,Ur=void 0,Ze.wcPairingExpiry=void 0,this.state.status="connected"}else await this._getClient()?.connectWalletConnect?.()},async connectExternal(s,e,t=!0){await this._getClient()?.connectExternal?.(s),t&&I.setActiveNamespace(e)},async reconnectExternal(s){await this._getClient()?.reconnectExternal?.(s);const e=s.chain||I.state.activeChain;e&&le.setConnectorId(s.id,e)},async setPreferredAccountType(s){ot.setLoading(!0,I.state.activeChain);const e=le.getAuthConnector();e&&(await e?.provider.setPreferredAccount(s),await this.reconnectExternal(e),ot.setLoading(!1,I.state.activeChain),Be.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:s,network:I.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(s){return this._getClient()?.signMessage(s)},parseUnits(s,e){return this._getClient()?.parseUnits(s,e)},formatUnits(s,e){return this._getClient()?.formatUnits(s,e)},async sendTransaction(s){return this._getClient()?.sendTransaction(s)},async getCapabilities(s){return this._getClient()?.getCapabilities(s)},async grantPermissions(s){return this._getClient()?.grantPermissions(s)},async walletGetAssets(s){return this._getClient()?.walletGetAssets(s)??{}},async estimateGas(s){return this._getClient()?.estimateGas(s)},async writeContract(s){return this._getClient()?.writeContract(s)},async getEnsAddress(s){return this._getClient()?.getEnsAddress(s)},async getEnsAvatar(s){return this._getClient()?.getEnsAvatar(s)},checkInstalled(s){return this._getClient()?.checkInstalled?.(s)||!1},resetWcConnection(){Ze.wcUri=void 0,Ze.wcPairingExpiry=void 0,Ze.wcLinking=void 0,Ze.recentWallet=void 0,Ze.status="disconnected",uO.resetTransactions(),X.deleteWalletConnectDeepLink()},resetUri(){Ze.wcUri=void 0,Ze.wcPairingExpiry=void 0},finalizeWcConnection(){const{wcLinking:s,recentWallet:e}=qe.state;s&&X.setWalletConnectDeepLink(s),e&&X.setAppKitRecent(e),Be.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:s?"mobile":"qrcode",name:Me.state.data?.wallet?.name||"Unknown"}})},setWcBasic(s){Ze.wcBasic=s},setUri(s){Ze.wcUri=s,Ze.wcPairingExpiry=he.getPairingExpiry()},setWcLinking(s){Ze.wcLinking=s},setWcError(s){Ze.wcError=s,Ze.buffering=!1},setRecentWallet(s){Ze.recentWallet=s},setBuffering(s){Ze.buffering=s},setStatus(s){Ze.status=s},async disconnect(s){try{ot.setLoading(!0,s),await wn.clearSessions(),await I.disconnect(s),ot.setLoading(!1,s),le.setFilterByNamespace(void 0)}catch{throw new Error("Failed to disconnect")}}},Kn=k.proxy({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),pi={state:Kn,subscribe(s){return k.subscribe(Kn,()=>s(Kn))},set(s){Object.assign(Kn,{...Kn,...s})}},Zc={createBalance(s,e){const t={name:s.metadata.name||"",symbol:s.metadata.symbol||"",decimals:s.metadata.decimals||0,value:s.metadata.value||0,price:s.metadata.price||0,iconUrl:s.metadata.iconUrl||""};return{name:t.name,symbol:t.symbol,chainId:e,address:s.address==="native"?void 0:this.convertAddressToCAIP10Address(s.address,e),value:t.value,price:t.price,quantity:{decimals:t.decimals.toString(),numeric:this.convertHexToBalance({hex:s.balance,decimals:t.decimals})},iconUrl:t.iconUrl}},convertHexToBalance({hex:s,decimals:e}){return gn.formatUnits(BigInt(s),e)},convertAddressToCAIP10Address(s,e){return`${e}:${s}`},createCAIP2ChainId(s,e){return`${e}:${parseInt(s,16)}`},getChainIdHexFromCAIP2ChainId(s){const e=s.split(":");if(e.length<2||!e[1])return"0x0";const t=e[1],i=parseInt(t,10);return isNaN(i)?"0x0":`0x${i.toString(16)}`},isWalletGetAssetsResponse(s){return typeof s!="object"||s===null?!1:Object.values(s).every(e=>Array.isArray(e)&&e.every(t=>this.isValidAsset(t)))},isValidAsset(s){return typeof s=="object"&&s!==null&&typeof s.address=="string"&&typeof s.balance=="string"&&(s.type==="ERC20"||s.type==="NATIVE")&&typeof s.metadata=="object"&&s.metadata!==null&&typeof s.metadata.name=="string"&&typeof s.metadata.symbol=="string"&&typeof s.metadata.decimals=="number"&&typeof s.metadata.price=="number"&&typeof s.metadata.iconUrl=="string"}},Ip={async getMyTokensWithBalance(s){const e=re.state.address,t=I.state.activeCaipNetwork;if(!e||!t)return[];if(t.chainNamespace==="eip155"){const r=await this.getEIP155Balances(e,t);if(r)return this.filterLowQualityTokens(r)}const i=await oe.getBalance(e,t.caipNetworkId,s);return this.filterLowQualityTokens(i.balances)},async getEIP155Balances(s,e){try{const t=Zc.getChainIdHexFromCAIP2ChainId(e.caipNetworkId);if(!(await qe.getCapabilities(s))?.[t]?.assetDiscovery?.supported)return null;const r=await qe.walletGetAssets({account:s,chainFilter:[t]});return Zc.isWalletGetAssetsResponse(r)?(r[t]||[]).map(o=>Zc.createBalance(o,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(s){return s.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(s){return s?.map(e=>({...e,address:e?.address?e.address:I.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]}},be=k.proxy({tokenBalances:[],loading:!1}),Ep={state:be,subscribe(s){return k.subscribe(be,()=>s(be))},subscribeKey(s,e){return k.subscribeKey(be,s,e)},setToken(s){s&&(be.token=k.ref(s))},setTokenAmount(s){be.sendTokenAmount=s},setReceiverAddress(s){be.receiverAddress=s},setReceiverProfileImageUrl(s){be.receiverProfileImageUrl=s},setReceiverProfileName(s){be.receiverProfileName=s},setGasPrice(s){be.gasPrice=s},setGasPriceInUsd(s){be.gasPriceInUSD=s},setNetworkBalanceInUsd(s){be.networkBalanceInUSD=s},setLoading(s){be.loading=s},sendToken(){switch(I.state.activeCaipNetwork?.chainNamespace){case"eip155":this.sendEvmToken();return;case"solana":this.sendSolanaToken();return;default:throw new Error("Unsupported chain")}},sendEvmToken(){this.state.token?.address&&this.state.sendTokenAmount&&this.state.receiverAddress?(Be.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:re.state.preferredAccountType===_i.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token.address,amount:this.state.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),this.sendERC20Token({receiverAddress:this.state.receiverAddress,tokenAddress:this.state.token.address,sendTokenAmount:this.state.sendTokenAmount,decimals:this.state.token.quantity.decimals})):this.state.receiverAddress&&this.state.sendTokenAmount&&this.state.gasPrice&&this.state.token?.quantity.decimals&&(Be.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:re.state.preferredAccountType===_i.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token?.symbol,amount:this.state.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),this.sendNativeToken({receiverAddress:this.state.receiverAddress,sendTokenAmount:this.state.sendTokenAmount,gasPrice:this.state.gasPrice,decimals:this.state.token.quantity.decimals}))},async fetchTokenBalance(s){be.loading=!0;const e=I.state.activeCaipNetwork?.caipNetworkId,t=I.state.activeCaipNetwork?.chainNamespace,i=I.state.activeCaipAddress,r=i?he.getPlainAddress(i):void 0;if(be.lastRetry&&!he.isAllowedRetry(be.lastRetry,30*Ht.ONE_SEC_MS))return be.loading=!1,[];try{if(r&&e&&t){const n=await Ip.getMyTokensWithBalance();return be.tokenBalances=n,be.lastRetry=void 0,n}}catch(n){be.lastRetry=Date.now(),s?.(n),vt.showError("Token Balance Unavailable")}finally{be.loading=!1}return[]},fetchNetworkBalance(){if(be.tokenBalances.length===0)return;const s=Ip.mapBalancesToSwapTokens(be.tokenBalances);if(!s)return;const e=s.find(t=>t.address===I.getActiveNetworkTokenAddress());e&&(be.networkBalanceInUSD=e?ga.multiply(e.quantity.numeric,e.price).toString():"0")},isInsufficientNetworkTokenForGas(s,e){const t=e||"0";return ga.bigNumber(s).eq(0)?!0:ga.bigNumber(ga.bigNumber(t)).gt(s)},hasInsufficientGasFunds(){let s=!0;return re.state.preferredAccountType===_i.ACCOUNT_TYPES.SMART_ACCOUNT?s=!1:be.networkBalanceInUSD&&(s=this.isInsufficientNetworkTokenForGas(be.networkBalanceInUSD,be.gasPriceInUSD)),s},async sendNativeToken(s){Me.pushTransactionStack({view:"Account",goBack:!1});const e=s.receiverAddress,t=re.state.address,i=qe.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals)),r="0x";try{await qe.sendTransaction({chainNamespace:"eip155",to:e,address:t,data:r,value:i??BigInt(0),gasPrice:s.gasPrice}),vt.showSuccess("Transaction started"),Be.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:re.state.preferredAccountType===_i.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token?.symbol||"",amount:s.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),this.resetSend()}catch(n){console.error("SendController:sendERC20Token - failed to send native token",n);const o=n instanceof Error?n.message:"Unknown error";Be.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:o,isSmartAccount:re.state.preferredAccountType===_i.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token?.symbol||"",amount:s.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),vt.showError("Something went wrong")}},async sendERC20Token(s){Me.pushTransactionStack({view:"Account",goBack:!1});const e=qe.parseUnits(s.sendTokenAmount.toString(),Number(s.decimals));try{if(re.state.address&&s.sendTokenAmount&&s.receiverAddress&&s.tokenAddress){const t=he.getPlainAddress(s.tokenAddress);await qe.writeContract({fromAddress:re.state.address,tokenAddress:t,args:[s.receiverAddress,e??BigInt(0)],method:"transfer",abi:OM.getERC20Abi(t),chainNamespace:"eip155"}),vt.showSuccess("Transaction started"),this.resetSend()}}catch(t){console.error("SendController:sendERC20Token - failed to send erc20 token",t);const i=t instanceof Error?t.message:"Unknown error";Be.sendEvent({type:"track",event:"SEND_ERROR",properties:{message:i,isSmartAccount:re.state.preferredAccountType===_i.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token?.symbol||"",amount:s.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),vt.showError("Something went wrong")}},sendSolanaToken(){if(!this.state.sendTokenAmount||!this.state.receiverAddress){vt.showError("Please enter a valid amount and receiver address");return}Me.pushTransactionStack({view:"Account",goBack:!1}),qe.sendTransaction({chainNamespace:"solana",to:this.state.receiverAddress,value:this.state.sendTokenAmount}).then(()=>{this.resetSend(),re.fetchTokenBalance()}).catch(s=>{vt.showError("Failed to send transaction. Please try again."),console.error("SendController:sendToken - failed to send solana transaction",s)})},resetSend(){be.token=void 0,be.sendTokenAmount=void 0,be.receiverAddress=void 0,be.receiverProfileImageUrl=void 0,be.receiverProfileName=void 0,be.loading=!1,be.tokenBalances=[]}},Xc={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},wa={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},F=k.proxy({chains:k.proxyMap(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),I={state:F,subscribe(s){return k.subscribe(F,()=>{s(F)})},subscribeKey(s,e){return k.subscribeKey(F,s,e)},subscribeChainProp(s,e,t){let i;return k.subscribe(F.chains,()=>{const r=t||F.activeChain;if(r){const n=F.chains.get(r)?.[s];i!==n&&(i=n,e(n))}})},initialize(s,e,t){const{chainId:i,namespace:r}=X.getActiveNetworkProps(),n=e?.find(l=>l.id.toString()===i?.toString()),a=s.find(l=>l?.namespace===r)||s?.[0],c=new Set([...e?.map(l=>l.chainNamespace)??[]]);(s?.length===0||!a)&&(F.noAdapters=!0),F.noAdapters||(F.activeChain=a?.namespace,F.activeCaipNetwork=n,this.setChainNetworkData(a?.namespace,{caipNetwork:n}),F.activeChain&&pi.set({activeChain:a?.namespace})),c.forEach(l=>{const u=e?.filter(d=>d.chainNamespace===l);I.state.chains.set(l,{namespace:l,networkState:k.proxy({...wa,caipNetwork:u?.[0]}),accountState:k.proxy(Xc),caipNetworks:u??[],...t}),this.setRequestedCaipNetworks(u??[],l)})},removeAdapter(s){if(F.activeChain===s){const e=Array.from(F.chains.entries()).find(([t])=>t!==s);if(e){const t=e[1]?.caipNetworks?.[0];t&&this.setActiveCaipNetwork(t)}}F.chains.delete(s)},addAdapter(s,{networkControllerClient:e,connectionControllerClient:t},i){F.chains.set(s.namespace,{namespace:s.namespace,networkState:{...wa,caipNetwork:i[0]},accountState:Xc,caipNetworks:i,connectionControllerClient:t,networkControllerClient:e}),this.setRequestedCaipNetworks(i?.filter(r=>r.chainNamespace===s.namespace)??[],s.namespace)},addNetwork(s){const e=F.chains.get(s.chainNamespace);if(e){const t=[...e.caipNetworks||[]];e.caipNetworks?.find(i=>i.id===s.id)||t.push(s),F.chains.set(s.chainNamespace,{...e,caipNetworks:t}),this.setRequestedCaipNetworks(t,s.chainNamespace)}},removeNetwork(s,e){const t=F.chains.get(s);if(t){const i=F.activeCaipNetwork?.id===e,r=[...t.caipNetworks?.filter(n=>n.id!==e)||[]];i&&t?.caipNetworks?.[0]&&this.setActiveCaipNetwork(t.caipNetworks[0]),F.chains.set(s,{...t,caipNetworks:r}),this.setRequestedCaipNetworks(r||[],s)}},setAdapterNetworkState(s,e){const t=F.chains.get(s);t&&(t.networkState={...t.networkState||wa,...e},F.chains.set(s,t))},setChainAccountData(s,e,t=!0){if(!s)throw new Error("Chain is required to update chain account data");const i=F.chains.get(s);if(i){const r={...i.accountState||Xc,...e};F.chains.set(s,{...i,accountState:r}),(F.chains.size===1||F.activeChain===s)&&(e.caipAddress&&(F.activeCaipAddress=e.caipAddress),re.replaceState(r))}},setChainNetworkData(s,e){if(!s)return;const t=F.chains.get(s);if(t){const i={...t.networkState||wa,...e};F.chains.set(s,{...t,networkState:i})}},setAccountProp(s,e,t,i=!0){this.setChainAccountData(t,{[s]:e},i),s==="status"&&e==="disconnected"&&t&&le.removeConnectorId(t)},setActiveNamespace(s){F.activeChain=s;const e=s?F.chains.get(s):void 0,t=e?.networkState?.caipNetwork;t?.id&&s&&(F.activeCaipAddress=e?.accountState?.caipAddress,F.activeCaipNetwork=t,this.setChainNetworkData(s,{caipNetwork:t}),X.setActiveCaipNetworkId(t?.caipNetworkId),pi.set({activeChain:s,selectedNetworkId:t?.caipNetworkId}))},setActiveCaipNetwork(s){if(!s)return;F.activeChain!==s.chainNamespace&&this.setIsSwitchingNamespace(!0);const e=F.chains.get(s.chainNamespace);F.activeChain=s.chainNamespace,F.activeCaipNetwork=s,this.setChainNetworkData(s.chainNamespace,{caipNetwork:s}),e?.accountState?.address?F.activeCaipAddress=`${s.chainNamespace}:${s.id}:${e?.accountState?.address}`:F.activeCaipAddress=void 0,this.setAccountProp("caipAddress",F.activeCaipAddress,s.chainNamespace),e&&re.replaceState(e.accountState),Ep.resetSend(),pi.set({activeChain:F.activeChain,selectedNetworkId:F.activeCaipNetwork?.caipNetworkId}),X.setActiveCaipNetworkId(s.caipNetworkId),!this.checkIfSupportedNetwork(s.chainNamespace)&&R.state.enableNetworkSwitch&&!R.state.allowUnsupportedChain&&!qe.state.wcBasic&&this.showUnsupportedChainUI()},addCaipNetwork(s){if(!s)return;const e=F.chains.get(s.chainNamespace);e&&e?.caipNetworks?.push(s)},async switchActiveNamespace(s){if(!s)return;const e=s!==I.state.activeChain,t=I.getNetworkData(s)?.caipNetwork,i=I.getCaipNetworkByNamespace(s,t?.id);e&&i&&await I.switchActiveNetwork(i)},async switchActiveNetwork(s){!I.state.chains.get(I.state.activeChain)?.caipNetworks?.some(r=>r.id===F.activeCaipNetwork?.id)&&Me.goBack();const i=this.getNetworkControllerClient(s.chainNamespace);i&&(await i.switchCaipNetwork(s),Be.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:s.caipNetworkId}}))},getNetworkControllerClient(s){const e=s||F.activeChain,t=F.chains.get(e);if(!t)throw new Error("Chain adapter not found");if(!t.networkControllerClient)throw new Error("NetworkController client not set");return t.networkControllerClient},getConnectionControllerClient(s){const e=s||F.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const t=F.chains.get(e);if(!t?.connectionControllerClient)throw new Error("ConnectionController client not set");return t.connectionControllerClient},getAccountProp(s,e){let t=F.activeChain;if(e&&(t=e),!t)return;const i=F.chains.get(t)?.accountState;if(i)return i[s]},getNetworkProp(s,e){const t=F.chains.get(e)?.networkState;if(t)return t[s]},getRequestedCaipNetworks(s){const e=F.chains.get(s),{approvedCaipNetworkIds:t=[],requestedCaipNetworks:i=[]}=e?.networkState||{};return he.sortRequestedNetworks(t,i)},getAllRequestedCaipNetworks(){const s=[];return F.chains.forEach(e=>{const t=this.getRequestedCaipNetworks(e.namespace);s.push(...t)}),s},setRequestedCaipNetworks(s,e){this.setAdapterNetworkState(e,{requestedCaipNetworks:s})},getAllApprovedCaipNetworkIds(){const s=[];return F.chains.forEach(e=>{const t=this.getApprovedCaipNetworkIds(e.namespace);s.push(...t)}),s},getActiveCaipNetwork(){return F.activeCaipNetwork},getActiveCaipAddress(){return F.activeCaipAddress},getApprovedCaipNetworkIds(s){return F.chains.get(s)?.networkState?.approvedCaipNetworkIds||[]},async setApprovedCaipNetworksData(s){const t=await this.getNetworkControllerClient()?.getApprovedCaipNetworksData();this.setAdapterNetworkState(s,{approvedCaipNetworkIds:t?.approvedCaipNetworkIds,supportsAllNetworks:t?.supportsAllNetworks})},checkIfSupportedNetwork(s,e){const t=e||F.activeCaipNetwork,i=this.getRequestedCaipNetworks(s);return i.length?i?.some(r=>r.id===t?.id):!0},checkIfSupportedChainId(s){return F.activeChain?this.getRequestedCaipNetworks(F.activeChain)?.some(t=>t.id===s):!0},setSmartAccountEnabledNetworks(s,e){this.setAdapterNetworkState(e,{smartAccountEnabledNetworks:s})},checkIfSmartAccountEnabled(){const s=Jw.caipNetworkIdToNumber(F.activeCaipNetwork?.caipNetworkId),e=F.activeChain;return!e||!s?!1:!!this.getNetworkProp("smartAccountEnabledNetworks",e)?.includes(Number(s))},getActiveNetworkTokenAddress(){const s=F.activeCaipNetwork?.chainNamespace||"eip155",e=F.activeCaipNetwork?.id||1,t=Ht.NATIVE_TOKEN_ADDRESS[s];return`${s}:${e}:${t}`},showUnsupportedChainUI(){ot.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const s=F.activeCaipNetwork;return!!(s?.chainNamespace&&Ht.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(s.chainNamespace))},resetNetwork(s){this.setAdapterNetworkState(s,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(s){const e=s;if(!e)throw new Error("Chain is required to set account prop");F.activeCaipAddress=void 0,this.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:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),le.removeConnectorId(e)},async disconnect(s){const e=BM(s);try{Ep.resetSend();const t=await Promise.allSettled(e.map(async([r,n])=>{try{const{caipAddress:o}=this.getAccountData(r)||{};o&&n.connectionControllerClient?.disconnect&&await n.connectionControllerClient.disconnect(r),this.resetAccount(r),this.resetNetwork(r)}catch(o){throw new Error(`Failed to disconnect chain ${r}: ${o.message}`)}}));qe.resetWcConnection();const i=t.filter(r=>r.status==="rejected");if(i.length>0)throw new Error(i.map(r=>r.reason.message).join(", "));X.deleteConnectedSocialProvider(),s?le.removeConnectorId(s):le.resetConnectorIds(),Be.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:s||"all"}})}catch(t){console.error(t.message||"Failed to disconnect chains"),Be.sendEvent({type:"track",event:"DISCONNECT_ERROR",properties:{message:t.message||"Failed to disconnect chains"}})}},setIsSwitchingNamespace(s){F.isSwitchingNamespace=s},getFirstCaipNetworkSupportsAuthConnector(){const s=[];let e;if(F.chains.forEach(t=>{ie.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(i=>i===t.namespace)&&t.namespace&&s.push(t.namespace)}),s.length>0){const t=s[0];return e=t?F.chains.get(t)?.caipNetworks?.[0]:void 0,e}},getAccountData(s){return s?I.state.chains.get(s)?.accountState:re.state},getNetworkData(s){const e=s||F.activeChain;if(e)return I.state.chains.get(e)?.networkState},getCaipNetworkByNamespace(s,e){if(!s)return;const t=I.state.chains.get(s),i=t?.caipNetworks?.find(r=>r.id===e);return i||t?.networkState?.caipNetwork||t?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const s=le.state.filterByNamespace;return(s?[F.chains.get(s)]:Array.from(F.chains.values())).flatMap(t=>t?.caipNetworks||[]).map(t=>t.caipNetworkId)}},dO={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"}]}]},Xw=he.getBlockchainApiUrl(),ss=k.proxy({clientId:null,api:new fc({baseUrl:Xw,clientId:null}),supportedChains:{http:[],ws:[]}}),oe={state:ss,async get(s){const{st:e,sv:t}=oe.getSdkProperties(),i=R.state.projectId,r={...s.params||{},st:e,sv:t,projectId:i};return ss.api.get({...s,params:r})},getSdkProperties(){const{sdkType:s,sdkVersion:e}=R.state;return{st:s||"unknown",sv:e||"unknown"}},async isNetworkSupported(s){if(!s)return!1;try{ss.supportedChains.http.length||await oe.getSupportedNetworks()}catch{return!1}return ss.supportedChains.http.includes(s)},async getSupportedNetworks(){const s=await oe.get({path:"v1/supported-chains"});return ss.supportedChains=s,s},async fetchIdentity({address:s,caipNetworkId:e}){if(!await oe.isNetworkSupported(e))return{avatar:"",name:""};const i=X.getIdentityFromCacheForAddress(s);if(i)return i;const r=await oe.get({path:`/v1/identity/${s}`,params:{sender:I.state.activeCaipAddress?he.getPlainAddress(I.state.activeCaipAddress):void 0}});return X.updateIdentityCache({address:s,identity:r,timestamp:Date.now()}),r},async fetchTransactions({account:s,cursor:e,onramp:t,signal:i,cache:r,chainId:n}){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?oe.get({path:`/v1/account/${s}/history`,params:{cursor:e,onramp:t,chainId:n},signal:i,cache:r}):{data:[],next:void 0}},async fetchSwapQuote({amount:s,userAddress:e,from:t,to:i,gasPrice:r}){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?oe.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:s,userAddress:e,from:t,to:i,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:s}){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?oe.get({path:"/v1/convert/tokens",params:{chainId:s}}):{tokens:[]}},async fetchTokenPrice({addresses:s}){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ss.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:s,projectId:R.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:s,userAddress:e}){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?oe.get({path:"/v1/convert/allowance",params:{tokenAddress:s,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:s}){const{st:e,sv:t}=oe.getSdkProperties();if(!await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return oe.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:s,st:e,sv:t}})},async generateSwapCalldata({amount:s,from:e,to:t,userAddress:i,disableEstimate:r}){if(!await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ss.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:s,eip155:{slippage:Ht.CONVERT_SLIPPAGE_TOLERANCE},projectId:R.state.projectId,from:e,to:t,userAddress:i,disableEstimate:r}})},async generateApproveCalldata({from:s,to:e,userAddress:t}){const{st:i,sv:r}=oe.getSdkProperties();if(!await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return oe.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:t,from:s,to:e,st:i,sv:r}})},async getBalance(s,e,t){const{st:i,sv:r}=oe.getSdkProperties();if(!await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))return vt.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${s}`,a=X.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await oe.get({path:`/v1/account/${s}/balance`,params:{currency:"usd",chainId:e,forceUpdate:t,st:i,sv:r}});return X.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(s){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?oe.get({path:`/v1/profile/account/${s}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:s}){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?oe.get({path:`/v1/profile/reverse/${s}`,params:{sender:re.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(s){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?oe.get({path:`/v1/profile/suggestions/${s}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:s,address:e,message:t,signature:i}){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ss.api.post({path:"/v1/profile/account",body:{coin_type:s,address:e,message:t,signature:i},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:s,partnerUserId:e,defaultNetwork:t,purchaseAmount:i,paymentAmount:r}){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?(await ss.api.post({path:"/v1/generators/onrampurl",params:{projectId:R.state.projectId},body:{destinationWallets:s,defaultNetwork:t,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:i,presetFiatAmount:r}})).url:""},async getOnrampOptions(){if(!await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await oe.get({path:"/v1/onramp/options"})}catch{return dO}},async getOnrampQuote({purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}){try{return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?await ss.api.post({path:"/v1/onramp/quote",params:{projectId:R.state.projectId},body:{purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}}):null}catch{return{coinbaseFee:{amount:t,currency:e.id},networkFee:{amount:t,currency:e.id},paymentSubtotal:{amount:t,currency:e.id},paymentTotal:{amount:t,currency:e.id},purchaseAmount:{amount:t,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(s){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?oe.get({path:`/v1/sessions/${s}`}):[]},async revokeSmartSession(s,e,t){return await oe.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ss.api.post({path:`/v1/sessions/${s}/revoke`,params:{projectId:R.state.projectId},body:{pci:e,signature:t}}):{success:!1}},setClientId(s){ss.clientId=s,ss.api=new fc({baseUrl:Xw,clientId:s})}},Bs=k.proxy({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),re={state:Bs,replaceState(s){s&&Object.assign(Bs,k.ref(s))},subscribe(s){return I.subscribeChainProp("accountState",e=>{if(e)return s(e)})},subscribeKey(s,e,t){let i;return I.subscribeChainProp("accountState",r=>{if(r){const n=r[s];i!==n&&(i=n,e(n))}},t)},setStatus(s,e){I.setAccountProp("status",s,e)},getCaipAddress(s){return I.getAccountProp("caipAddress",s)},setCaipAddress(s,e){const t=s?he.getPlainAddress(s):void 0;e===I.state.activeChain&&(I.state.activeCaipAddress=s),I.setAccountProp("caipAddress",s,e),I.setAccountProp("address",t,e)},setBalance(s,e,t){I.setAccountProp("balance",s,t),I.setAccountProp("balanceSymbol",e,t)},setProfileName(s,e){I.setAccountProp("profileName",s,e)},setProfileImage(s,e){I.setAccountProp("profileImage",s,e)},setUser(s,e){I.setAccountProp("user",s,e)},setAddressExplorerUrl(s,e){I.setAccountProp("addressExplorerUrl",s,e)},setSmartAccountDeployed(s,e){I.setAccountProp("smartAccountDeployed",s,e)},setCurrentTab(s){I.setAccountProp("currentTab",s,I.state.activeChain)},setTokenBalance(s,e){s&&I.setAccountProp("tokenBalance",s,e)},setShouldUpdateToAddress(s,e){I.setAccountProp("shouldUpdateToAddress",s,e)},setAllAccounts(s,e){I.setAccountProp("allAccounts",s,e)},addAddressLabel(s,e,t){const i=I.getAccountProp("addressLabels",t)||new Map;i.set(s,e),I.setAccountProp("addressLabels",i,t)},removeAddressLabel(s,e){const t=I.getAccountProp("addressLabels",e)||new Map;t.delete(s),I.setAccountProp("addressLabels",t,e)},setConnectedWalletInfo(s,e){I.setAccountProp("connectedWalletInfo",s,e,!1)},setPreferredAccountType(s,e){I.setAccountProp("preferredAccountType",s,e)},setSocialProvider(s,e){s&&I.setAccountProp("socialProvider",s,e)},setSocialWindow(s,e){I.setAccountProp("socialWindow",s?k.ref(s):void 0,e)},setFarcasterUrl(s,e){I.setAccountProp("farcasterUrl",s,e)},async fetchTokenBalance(s){Bs.balanceLoading=!0;const e=I.state.activeCaipNetwork?.caipNetworkId,t=I.state.activeCaipNetwork?.chainNamespace,i=I.state.activeCaipAddress,r=i?he.getPlainAddress(i):void 0;if(Bs.lastRetry&&!he.isAllowedRetry(Bs.lastRetry,30*Ht.ONE_SEC_MS))return Bs.balanceLoading=!1,[];try{if(r&&e&&t){const o=(await oe.getBalance(r,e)).balances.filter(a=>a.quantity.decimals!=="0");return this.setTokenBalance(o,t),Bs.lastRetry=void 0,Bs.balanceLoading=!1,o}}catch(n){Bs.lastRetry=Date.now(),s?.(n),vt.showError("Token Balance Unavailable")}finally{Bs.balanceLoading=!1}return[]},resetAccount(s){I.resetAccount(s)}},Kt=k.proxy({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),ot={state:Kt,subscribe(s){return k.subscribe(Kt,()=>s(Kt))},subscribeKey(s,e){return k.subscribeKey(Kt,s,e)},async open(s){const e=re.state.status==="connected";qe.state.wcBasic?ue.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await ue.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),s?.namespace?(await I.switchActiveNamespace(s.namespace),ot.setLoading(!0,s.namespace)):ot.setLoading(!0),le.setFilterByNamespace(s?.namespace);const t=I.getAccountData(s?.namespace)?.caipAddress;I.state.noAdapters&&!t?he.isMobile()?Me.reset("AllWallets"):Me.reset("ConnectingWalletConnectBasic"):s?.view?Me.reset(s.view):t?Me.reset("Account"):Me.reset("Connect"),Kt.open=!0,pi.set({open:!0}),Be.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!t}})},close(){const s=R.state.enableEmbedded,e=!!I.state.activeCaipAddress;Kt.open&&Be.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),Kt.open=!1,ot.clearLoading(),s?e?Me.replace("Account"):Me.push("Connect"):pi.set({open:!1}),qe.resetUri()},setLoading(s,e){e&&Kt.loadingNamespaceMap.set(e,s),Kt.loading=s,pi.set({loading:s})},clearLoading(){Kt.loadingNamespaceMap.clear(),Kt.loading=!1},shake(){Kt.shake||(Kt.shake=!0,setTimeout(()=>{Kt.shake=!1},500))}},Ap=2147483648,pO={convertEVMChainIdToCoinType(s){if(s>=Ap)throw new Error("Invalid chainId");return(Ap|s)>>>0}},fs=k.proxy({suggestions:[],loading:!1}),ey={state:fs,subscribe(s){return k.subscribe(fs,()=>s(fs))},subscribeKey(s,e){return k.subscribeKey(fs,s,e)},async resolveName(s){try{return await oe.lookupEnsName(s)}catch(e){const t=e;throw new Error(t?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(s){try{return await oe.lookupEnsName(s),!0}catch{return!1}},async getSuggestions(s){try{fs.loading=!0,fs.suggestions=[];const e=await oe.getEnsNameSuggestions(s);return fs.suggestions=e.suggestions.map(t=>({...t,name:t.name}))||[],fs.suggestions}catch(e){const t=this.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(t)}finally{fs.loading=!1}},async getNamesForAddress(s){try{if(!I.state.activeCaipNetwork)return[];const t=X.getEnsFromCacheForAddress(s);if(t)return t;const i=await oe.reverseLookupEnsName({address:s});return X.updateEnsCache({address:s,ens:i,timestamp:Date.now()}),i}catch(e){const t=this.parseEnsApiError(e,"Error fetching names for address");throw new Error(t)}},async registerName(s){const e=I.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const t=re.state.address,i=le.getAuthConnector();if(!t||!i)throw new Error("Address or auth connector not found");fs.loading=!0;try{const r=JSON.stringify({name:s,attributes:{},timestamp:Math.floor(Date.now()/1e3)});Me.pushTransactionStack({view:"RegisterAccountNameSuccess",goBack:!1,replace:!0,onCancel(){fs.loading=!1}});const n=await qe.signMessage(r),o=e.id;if(!o)throw new Error("Network not found");const a=pO.convertEVMChainIdToCoinType(Number(o));await oe.registerEnsName({coinType:a,address:t,signature:n,message:r}),re.setProfileName(s,e.chainNamespace),Me.replace("RegisterAccountNameSuccess")}catch(r){const n=this.parseEnsApiError(r,`Error registering name ${s}`);throw Me.replace("RegisterAccountName"),new Error(n)}finally{fs.loading=!1}},validateName(s){return/^[a-zA-Z0-9-]{4,}$/u.test(s)},parseEnsApiError(s,e){return s?.reasons?.[0]?.description||e}};function _o(s,{strict:e=!0}={}){return!s||typeof s!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(s):s.startsWith("0x")}function Np(s){return _o(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const ty="2.23.2";let el={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${ty}`};class hr extends Error{constructor(e,t={}){const i=t.cause instanceof hr?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof hr&&t.cause.docsPath||t.docsPath,n=el.getDocsUrl?.({...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...el.version?[`Version: ${el.version}`]:[]].join(`
12
- `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=ty}walk(e){return sy(this,e)}}function sy(s,e){return e?.(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?sy(s.cause,e):e?null:s}class iy extends hr{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Tn(s,{dir:e,size:t=32}={}){return typeof s=="string"?gO(s,{dir:e,size:t}):fO(s,{dir:e,size:t})}function gO(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new iy({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function fO(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new iy({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}class wO extends hr{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class yO extends hr{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Pn(s,{size:e}){if(Np(s)>e)throw new yO({givenSize:Np(s),maxSize:e})}function Gl(s,e={}){const{signed:t}=e;e.size&&Pn(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function mO(s,e={}){return Number(Gl(s,e))}const bO=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Yl(s,e={}){return typeof s=="number"||typeof s=="bigint"?ny(s,e):typeof s=="string"?EO(s,e):typeof s=="boolean"?vO(s,e):ry(s,e)}function vO(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(Pn(t,{size:e.size}),Tn(t,{size:e.size})):t}function ry(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=bO[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(Pn(i,{size:e.size}),Tn(i,{dir:"right",size:e.size})):i}function ny(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof s=="bigint"?"n":"";throw new wO({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${s}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?Tn(a,{size:i}):a}const IO=new TextEncoder;function EO(s,e={}){const t=IO.encode(s);return ry(t,e)}const AO=new TextEncoder;function NO(s,e={}){return typeof s=="number"||typeof s=="bigint"?_O(s,e):typeof s=="boolean"?CO(s,e):_o(s)?oy(s,e):ay(s,e)}function CO(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(Pn(t,{size:e.size}),Tn(t,{size:e.size})):t}const ni={zero:48,nine:57,A:65,F:70,a:97,f:102};function Cp(s){if(s>=ni.zero&&s<=ni.nine)return s-ni.zero;if(s>=ni.A&&s<=ni.F)return s-(ni.A-10);if(s>=ni.a&&s<=ni.f)return s-(ni.a-10)}function oy(s,e={}){let t=s;e.size&&(Pn(t,{size:e.size}),t=Tn(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Cp(i.charCodeAt(a++)),l=Cp(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new hr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function _O(s,e){const t=ny(s,e);return oy(t)}function ay(s,e={}){const t=AO.encode(s);return typeof e.size=="number"?(Pn(t,{size:e.size}),Tn(t,{dir:"right",size:e.size})):t}function Va(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function SO(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Bo(s,...e){if(!SO(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function $O(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Va(s.outputLen),Va(s.blockLen)}function Ql(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function cy(s,e){Bo(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ya=BigInt(2**32-1),_p=BigInt(32);function TO(s,e=!1){return e?{h:Number(s&ya),l:Number(s>>_p&ya)}:{h:Number(s>>_p&ya)|0,l:Number(s&ya)|0}}function PO(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=TO(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const xO=(s,e,t)=>s<<t|e>>>32-t,MO=(s,e,t)=>e<<t|s>>>32-t,OO=(s,e,t)=>e<<t-32|s>>>64-t,DO=(s,e,t)=>s<<t-32|e>>>64-t,Lr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function kO(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function jO(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function RO(s,e){return s<<32-e|s>>>e}const Sp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function UO(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function $p(s){for(let e=0;e<s.length;e++)s[e]=UO(s[e])}function LO(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Hh(s){return typeof s=="string"&&(s=LO(s)),Bo(s),s}function zO(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Bo(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}class ly{clone(){return this._cloneInto()}}function hy(s){const e=i=>s().update(Hh(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function FO(s=32){if(Lr&&typeof Lr.getRandomValues=="function")return Lr.getRandomValues(new Uint8Array(s));if(Lr&&typeof Lr.randomBytes=="function")return Lr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const uy=[],dy=[],py=[],qO=BigInt(0),Gn=BigInt(1),BO=BigInt(2),HO=BigInt(7),WO=BigInt(256),VO=BigInt(113);for(let s=0,e=Gn,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],uy.push(2*(5*i+t)),dy.push((s+1)*(s+2)/2%64);let r=qO;for(let n=0;n<7;n++)e=(e<<Gn^(e>>HO)*VO)%WO,e&BO&&(r^=Gn<<(Gn<<BigInt(n))-Gn);py.push(r)}const[KO,GO]=PO(py,!0),Tp=(s,e,t)=>t>32?OO(s,e,t):xO(s,e,t),Pp=(s,e,t)=>t>32?DO(s,e,t):MO(s,e,t);function YO(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],u=t[c+1],d=Tp(l,u,1)^t[a],p=Pp(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=dy[o],c=Tp(r,n,a),l=Pp(r,n,a),u=uy[o];r=s[u],n=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=KO[i],s[1]^=GO[i]}t.fill(0)}class Wh extends ly{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Va(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=kO(this.state)}keccak(){Sp||$p(this.state32),YO(this.state32,this.rounds),Sp||$p(this.state32),this.posOut=0,this.pos=0}update(e){Ql(this);const{blockLen:t,state:i}=this;e=Hh(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(t&128)!==0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Ql(this,!1),Bo(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.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 Va(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(cy(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Wh(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const QO=(s,e,t)=>hy(()=>new Wh(e,s,t)),JO=QO(1,136,256/8);function gy(s,e){const t=e||"hex",i=JO(_o(s,{strict:!1})?NO(s):s);return t==="bytes"?i:Yl(i)}class ZO extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const tl=new ZO(8192);function XO(s,e){if(tl.has(`${s}.${e}`))return tl.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=gy(ay(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return tl.set(`${s}.${e}`,n),n}function eD(s){const e=gy(`0x${s.substring(4)}`).substring(26);return XO(`0x${e}`)}async function tD({hash:s,signature:e}){const t=_o(s)?s:Yl(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-Bb6lbAjK.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:d,yParity:p}=e,f=Number(p??d),g=xp(f);return new i.Signature(Gl(l),Gl(u)).addRecoveryBit(g)}const o=_o(e)?e:Yl(e),a=mO(`0x${o.slice(130)}`),c=xp(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function xp(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function sD({hash:s,signature:e}){return eD(await tD({hash:s,signature:e}))}function iD(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const u=s.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,u++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let m=l[p],A=0;for(let C=g-1;(m!==0||A<d)&&C!==-1;C--,A++)m+=256*w[C]>>>0,w[C]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let b=g-d;for(;b!==g&&w[b]===0;)b++;let v=i.repeat(u);for(;b<g;++b)v+=s.charAt(w[b]);return v}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,p=0;for(;l[u]===i;)d++,u++;const f=(l.length-u)*r+1>>>0,g=new Uint8Array(f);for(;u<l.length;){const m=l.charCodeAt(u);if(m>255)return;let A=e[m];if(A===255)return;let C=0;for(let S=f-1;(A!==0||C<p)&&S!==-1;S--,C++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=C,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const b=new Uint8Array(d+(f-w));let v=d;for(;w!==f;)b[v++]=g[w++];return b}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var rD="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const fy=iD(rD),nD=":";function yn(s){const[e,t]=s.split(nD);return{namespace:e,reference:t}}function wy(s,e){return s.includes(":")?[s]:e.chains||[]}const oD="ReactNative",ls={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},aD="js";function Ka(){return typeof N.process$1<"u"&&typeof N.process$1.versions<"u"&&typeof N.process$1.versions.node<"u"}function Li(){return!h.cjsExports$2.getDocument()&&!!h.cjsExports$2.getNavigator()&&navigator.product===oD}function cD(){return Li()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"&&(N.global==null?void 0:N.global.Platform.OS)==="android"}function lD(){return Li()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"&&(N.global==null?void 0:N.global.Platform.OS)==="ios"}function Ho(){return!Ka()&&!!h.cjsExports$2.getNavigator()&&!!h.cjsExports$2.getDocument()}function Wo(){return Li()?ls.reactNative:Ka()?ls.node:Ho()?ls.browser:ls.unknown}function Mp(){var s;try{return Li()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Application)<"u"?(s=N.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function hD(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function yy(){return h.cjsExports.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function uD(){if(Wo()===ls.reactNative&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"){const{OS:t,Version:i}=N.global.Platform;return[t,i].join("-")}const s=h.detect();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function dD(){var s;const e=Wo();return e===ls.browser?[e,((s=h.cjsExports$2.getLocation())==null?void 0:s.host)||"unknown"].join(":"):e}function my(s,e,t){const i=uD(),r=dD();return[[s,e].join("-"),[aD,t].join("-"),i,r].join("/")}function pD({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),u=my(s,e,i),d={auth:r,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=hD(l[1]||"",d);return l[0]+"?"+p}function rr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Jl(s){return Object.fromEntries(s.entries())}function Zl(s){return new Map(Object.entries(s))}function Ji(s=h.cjsExports$1.FIVE_MINUTES,e){const t=h.cjsExports$1.toMiliseconds(s||h.cjsExports$1.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},t),i=a,r=c})}}function xi(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function by(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.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: ${s}`)}function gD(s){return by("topic",s)}function fD(s){return by("id",s)}function vy(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function pt(s,e){return h.cjsExports$1.fromMiliseconds(Date.now()+h.cjsExports$1.toMiliseconds(s))}function Si(s){return Date.now()>=h.cjsExports$1.toMiliseconds(s)}function xe(s,e){return`${s}${e?`:${e}`:""}`}function Oa(s=[],e=[]){return[...new Set([...s,...e])]}async function wD({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r?.href;if(typeof n!="string")return;const o=yD(n,s,e),a=Wo();if(a===ls.browser){if(!((i=h.cjsExports$2.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}mD(o)}else a===ls.reactNative&&typeof(N.global==null?void 0:N.global.Linking)<"u"&&await N.global.Linking.openURL(o)}catch(r){console.error(r)}}function yD(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${ED(i,!0)}`}else r=`${r}/wc?${i}`;return r}function mD(s){let e="_self";ID()?e="_top":(vD()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function bD(s,e){let t="";try{if(Ho()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Op(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Dp(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function Vh(){return typeof N.process$1<"u"&&N.process$1.env.IS_VITEST==="true"}function vD(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function ID(){try{return window.self!==window.top}catch{return!1}}function ED(s,e=!1){const t=N.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Iy(s){return N.Buffer.from(s,"base64").toString("utf-8")}function AD(s){return new Promise(e=>setTimeout(e,s))}function So(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function ND(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function wc(s,...e){if(!ND(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Kh(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");So(s.outputLen),So(s.blockLen)}function En(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ey(s,e){wc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ma=BigInt(2**32-1),kp=BigInt(32);function CD(s,e=!1){return e?{h:Number(s&ma),l:Number(s>>kp&ma)}:{h:Number(s>>kp&ma)|0,l:Number(s&ma)|0}}function _D(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=CD(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const SD=(s,e,t)=>s<<t|e>>>32-t,$D=(s,e,t)=>e<<t|s>>>32-t,TD=(s,e,t)=>e<<t-32|s>>>64-t,PD=(s,e,t)=>s<<t-32|e>>>64-t,zr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function xD(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function sl(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Hs(s,e){return s<<32-e|s>>>e}const jp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function MD(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Rp(s){for(let e=0;e<s.length;e++)s[e]=MD(s[e])}function OD(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function An(s){return typeof s=="string"&&(s=OD(s)),wc(s),s}let Gh=class{clone(){return this._cloneInto()}};function Ay(s){const e=i=>s().update(An(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Vo(s=32){if(zr&&typeof zr.getRandomValues=="function")return zr.getRandomValues(new Uint8Array(s));if(zr&&typeof zr.randomBytes=="function")return zr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Ny=[],Cy=[],_y=[],DD=BigInt(0),Yn=BigInt(1),kD=BigInt(2),jD=BigInt(7),RD=BigInt(256),UD=BigInt(113);for(let s=0,e=Yn,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Ny.push(2*(5*i+t)),Cy.push((s+1)*(s+2)/2%64);let r=DD;for(let n=0;n<7;n++)e=(e<<Yn^(e>>jD)*UD)%RD,e&kD&&(r^=Yn<<(Yn<<BigInt(n))-Yn);_y.push(r)}const[LD,zD]=_D(_y,!0),Up=(s,e,t)=>t>32?TD(s,e,t):SD(s,e,t),Lp=(s,e,t)=>t>32?PD(s,e,t):$D(s,e,t);function FD(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],u=t[c+1],d=Up(l,u,1)^t[a],p=Lp(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Cy[o],c=Up(r,n,a),l=Lp(r,n,a),u=Ny[o];r=s[u],n=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=LD[i],s[1]^=zD[i]}t.fill(0)}let qD=class Sy extends Gh{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,So(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=xD(this.state)}keccak(){jp||Rp(this.state32),FD(this.state32,this.rounds),jp||Rp(this.state32),this.posOut=0,this.pos=0}update(e){En(this);const{blockLen:t,state:i}=this;e=An(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(t&128)!==0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){En(this,!1),wc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.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 So(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ey(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Sy(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const BD=(s,e,t)=>Ay(()=>new qD(e,s,t)),HD=BD(1,136,256/8),WD="https://rpc.walletconnect.org/v1";function $y(s){const e=`Ethereum Signed Message:
12
+ `);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=ty}walk(e){return sy(this,e)}}function sy(s,e){return e?.(s)?s:s&&typeof s=="object"&&"cause"in s&&s.cause!==void 0?sy(s.cause,e):e?null:s}class iy extends hr{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Tn(s,{dir:e,size:t=32}={}){return typeof s=="string"?gO(s,{dir:e,size:t}):fO(s,{dir:e,size:t})}function gO(s,{dir:e,size:t=32}={}){if(t===null)return s;const i=s.replace("0x","");if(i.length>t*2)throw new iy({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function fO(s,{dir:e,size:t=32}={}){if(t===null)return s;if(s.length>t)throw new iy({size:s.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";i[n?r:t-r-1]=s[n?r:s.length-r-1]}return i}class wO extends hr{constructor({max:e,min:t,signed:i,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class yO extends hr{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Pn(s,{size:e}){if(Np(s)>e)throw new yO({givenSize:Np(s),maxSize:e})}function Gl(s,e={}){const{signed:t}=e;e.size&&Pn(s,{size:e.size});const i=BigInt(s);if(!t)return i;const r=(s.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function mO(s,e={}){return Number(Gl(s,e))}const bO=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Yl(s,e={}){return typeof s=="number"||typeof s=="bigint"?ny(s,e):typeof s=="string"?EO(s,e):typeof s=="boolean"?vO(s,e):ry(s,e)}function vO(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(Pn(t,{size:e.size}),Tn(t,{size:e.size})):t}function ry(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=bO[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(Pn(i,{size:e.size}),Tn(i,{dir:"right",size:e.size})):i}function ny(s,e={}){const{signed:t,size:i}=e,r=BigInt(s);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof s=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&r>n||r<o){const c=typeof s=="bigint"?"n":"";throw new wO({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${s}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(i*8))+BigInt(r):r).toString(16)}`;return i?Tn(a,{size:i}):a}const IO=new TextEncoder;function EO(s,e={}){const t=IO.encode(s);return ry(t,e)}const AO=new TextEncoder;function NO(s,e={}){return typeof s=="number"||typeof s=="bigint"?_O(s,e):typeof s=="boolean"?CO(s,e):_o(s)?oy(s,e):ay(s,e)}function CO(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(Pn(t,{size:e.size}),Tn(t,{size:e.size})):t}const ni={zero:48,nine:57,A:65,F:70,a:97,f:102};function Cp(s){if(s>=ni.zero&&s<=ni.nine)return s-ni.zero;if(s>=ni.A&&s<=ni.F)return s-(ni.A-10);if(s>=ni.a&&s<=ni.f)return s-(ni.a-10)}function oy(s,e={}){let t=s;e.size&&(Pn(t,{size:e.size}),t=Tn(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const r=i.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=Cp(i.charCodeAt(a++)),l=Cp(i.charCodeAt(a++));if(c===void 0||l===void 0)throw new hr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function _O(s,e){const t=ny(s,e);return oy(t)}function ay(s,e={}){const t=AO.encode(s);return typeof e.size=="number"?(Pn(t,{size:e.size}),Tn(t,{dir:"right",size:e.size})):t}function Va(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function SO(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Bo(s,...e){if(!SO(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function $O(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Va(s.outputLen),Va(s.blockLen)}function Ql(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function cy(s,e){Bo(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ya=BigInt(2**32-1),_p=BigInt(32);function TO(s,e=!1){return e?{h:Number(s&ya),l:Number(s>>_p&ya)}:{h:Number(s>>_p&ya)|0,l:Number(s&ya)|0}}function PO(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=TO(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const xO=(s,e,t)=>s<<t|e>>>32-t,MO=(s,e,t)=>e<<t|s>>>32-t,OO=(s,e,t)=>e<<t-32|s>>>64-t,DO=(s,e,t)=>s<<t-32|e>>>64-t,Lr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function kO(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function jO(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function RO(s,e){return s<<32-e|s>>>e}const Sp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function UO(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function $p(s){for(let e=0;e<s.length;e++)s[e]=UO(s[e])}function LO(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Hh(s){return typeof s=="string"&&(s=LO(s)),Bo(s),s}function zO(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Bo(r),e+=r.length}const t=new Uint8Array(e);for(let i=0,r=0;i<s.length;i++){const n=s[i];t.set(n,r),r+=n.length}return t}class ly{clone(){return this._cloneInto()}}function hy(s){const e=i=>s().update(Hh(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function FO(s=32){if(Lr&&typeof Lr.getRandomValues=="function")return Lr.getRandomValues(new Uint8Array(s));if(Lr&&typeof Lr.randomBytes=="function")return Lr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const uy=[],dy=[],py=[],qO=BigInt(0),Gn=BigInt(1),BO=BigInt(2),HO=BigInt(7),WO=BigInt(256),VO=BigInt(113);for(let s=0,e=Gn,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],uy.push(2*(5*i+t)),dy.push((s+1)*(s+2)/2%64);let r=qO;for(let n=0;n<7;n++)e=(e<<Gn^(e>>HO)*VO)%WO,e&BO&&(r^=Gn<<(Gn<<BigInt(n))-Gn);py.push(r)}const[KO,GO]=PO(py,!0),Tp=(s,e,t)=>t>32?OO(s,e,t):xO(s,e,t),Pp=(s,e,t)=>t>32?DO(s,e,t):MO(s,e,t);function YO(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],u=t[c+1],d=Tp(l,u,1)^t[a],p=Pp(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=dy[o],c=Tp(r,n,a),l=Pp(r,n,a),u=uy[o];r=s[u],n=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=KO[i],s[1]^=GO[i]}t.fill(0)}class Wh extends ly{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Va(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=kO(this.state)}keccak(){Sp||$p(this.state32),YO(this.state32,this.rounds),Sp||$p(this.state32),this.posOut=0,this.pos=0}update(e){Ql(this);const{blockLen:t,state:i}=this;e=Hh(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(t&128)!==0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Ql(this,!1),Bo(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.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 Va(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(cy(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Wh(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const QO=(s,e,t)=>hy(()=>new Wh(e,s,t)),JO=QO(1,136,256/8);function gy(s,e){const t=e||"hex",i=JO(_o(s,{strict:!1})?NO(s):s);return t==="bytes"?i:Yl(i)}class ZO extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const tl=new ZO(8192);function XO(s,e){if(tl.has(`${s}.${e}`))return tl.get(`${s}.${e}`);const t=s.substring(2).toLowerCase(),i=gy(ay(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(i[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return tl.set(`${s}.${e}`,n),n}function eD(s){const e=gy(`0x${s.substring(4)}`).substring(26);return XO(`0x${e}`)}async function tD({hash:s,signature:e}){const t=_o(s)?s:Yl(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-Ds1M1Mtb.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:d,yParity:p}=e,f=Number(p??d),g=xp(f);return new i.Signature(Gl(l),Gl(u)).addRecoveryBit(g)}const o=_o(e)?e:Yl(e),a=mO(`0x${o.slice(130)}`),c=xp(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function xp(s){if(s===0||s===1)return s;if(s===27)return 0;if(s===28)return 1;throw new Error("Invalid yParityOrV value")}async function sD({hash:s,signature:e}){return eD(await tD({hash:s,signature:e}))}function iD(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const u=s.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,u++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let m=l[p],A=0;for(let C=g-1;(m!==0||A<d)&&C!==-1;C--,A++)m+=256*w[C]>>>0,w[C]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let b=g-d;for(;b!==g&&w[b]===0;)b++;let v=i.repeat(u);for(;b<g;++b)v+=s.charAt(w[b]);return v}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,p=0;for(;l[u]===i;)d++,u++;const f=(l.length-u)*r+1>>>0,g=new Uint8Array(f);for(;u<l.length;){const m=l.charCodeAt(u);if(m>255)return;let A=e[m];if(A===255)return;let C=0;for(let S=f-1;(A!==0||C<p)&&S!==-1;S--,C++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=C,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const b=new Uint8Array(d+(f-w));let v=d;for(;w!==f;)b[v++]=g[w++];return b}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var rD="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const fy=iD(rD),nD=":";function yn(s){const[e,t]=s.split(nD);return{namespace:e,reference:t}}function wy(s,e){return s.includes(":")?[s]:e.chains||[]}const oD="ReactNative",ls={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},aD="js";function Ka(){return typeof N.process$1<"u"&&typeof N.process$1.versions<"u"&&typeof N.process$1.versions.node<"u"}function Li(){return!h.cjsExports$2.getDocument()&&!!h.cjsExports$2.getNavigator()&&navigator.product===oD}function cD(){return Li()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"&&(N.global==null?void 0:N.global.Platform.OS)==="android"}function lD(){return Li()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"&&(N.global==null?void 0:N.global.Platform.OS)==="ios"}function Ho(){return!Ka()&&!!h.cjsExports$2.getNavigator()&&!!h.cjsExports$2.getDocument()}function Wo(){return Li()?ls.reactNative:Ka()?ls.node:Ho()?ls.browser:ls.unknown}function Mp(){var s;try{return Li()&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Application)<"u"?(s=N.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function hD(s,e){const t=new URLSearchParams(s);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const r=e[i];r!==void 0&&t.set(i,r)}return t.toString()}function yy(){return h.cjsExports.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function uD(){if(Wo()===ls.reactNative&&typeof N.global<"u"&&typeof(N.global==null?void 0:N.global.Platform)<"u"){const{OS:t,Version:i}=N.global.Platform;return[t,i].join("-")}const s=h.detect();if(s===null)return"unknown";const e=s.os?s.os.replace(" ","").toLowerCase():"unknown";return s.type==="browser"?[e,s.name,s.version].join("-"):[e,s.version].join("-")}function dD(){var s;const e=Wo();return e===ls.browser?[e,((s=h.cjsExports$2.getLocation())==null?void 0:s.host)||"unknown"].join(":"):e}function my(s,e,t){const i=uD(),r=dD();return[[s,e].join("-"),[aD,t].join("-"),i,r].join("/")}function pD({protocol:s,version:e,relayUrl:t,sdkVersion:i,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=t.split("?"),u=my(s,e,i),d={auth:r,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=hD(l[1]||"",d);return l[0]+"?"+p}function rr(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Jl(s){return Object.fromEntries(s.entries())}function Zl(s){return new Map(Object.entries(s))}function Ji(s=h.cjsExports$1.FIVE_MINUTES,e){const t=h.cjsExports$1.toMiliseconds(s||h.cjsExports$1.FIVE_MINUTES);let i,r,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&r&&(clearTimeout(n),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},t),i=a,r=c})}}function xi(s,e,t){return new Promise(async(i,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await s;i(o)}catch(o){r(o)}clearTimeout(n)})}function by(s,e){if(typeof e=="string"&&e.startsWith(`${s}:`))return e;if(s.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(s.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: ${s}`)}function gD(s){return by("topic",s)}function fD(s){return by("id",s)}function vy(s){const[e,t]=s.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function pt(s,e){return h.cjsExports$1.fromMiliseconds(Date.now()+h.cjsExports$1.toMiliseconds(s))}function Si(s){return Date.now()>=h.cjsExports$1.toMiliseconds(s)}function xe(s,e){return`${s}${e?`:${e}`:""}`}function Oa(s=[],e=[]){return[...new Set([...s,...e])]}async function wD({id:s,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r?.href;if(typeof n!="string")return;const o=yD(n,s,e),a=Wo();if(a===ls.browser){if(!((i=h.cjsExports$2.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}mD(o)}else a===ls.reactNative&&typeof(N.global==null?void 0:N.global.Linking)<"u"&&await N.global.Linking.openURL(o)}catch(r){console.error(r)}}function yD(s,e,t){const i=`requestId=${e}&sessionTopic=${t}`;s.endsWith("/")&&(s=s.slice(0,-1));let r=`${s}`;if(s.startsWith("https://t.me")){const n=s.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${ED(i,!0)}`}else r=`${r}/wc?${i}`;return r}function mD(s){let e="_self";ID()?e="_top":(vD()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function bD(s,e){let t="";try{if(Ho()&&(t=localStorage.getItem(e),t))return t;t=await s.getItem(e)}catch(i){console.error(i)}return t}function Op(s,e){if(!s.includes(e))return null;const t=s.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Dp(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}function Vh(){return typeof N.process$1<"u"&&N.process$1.env.IS_VITEST==="true"}function vD(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function ID(){try{return window.self!==window.top}catch{return!1}}function ED(s,e=!1){const t=N.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Iy(s){return N.Buffer.from(s,"base64").toString("utf-8")}function AD(s){return new Promise(e=>setTimeout(e,s))}function So(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function ND(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function wc(s,...e){if(!ND(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Kh(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");So(s.outputLen),So(s.blockLen)}function En(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ey(s,e){wc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ma=BigInt(2**32-1),kp=BigInt(32);function CD(s,e=!1){return e?{h:Number(s&ma),l:Number(s>>kp&ma)}:{h:Number(s>>kp&ma)|0,l:Number(s&ma)|0}}function _D(s,e=!1){let t=new Uint32Array(s.length),i=new Uint32Array(s.length);for(let r=0;r<s.length;r++){const{h:n,l:o}=CD(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const SD=(s,e,t)=>s<<t|e>>>32-t,$D=(s,e,t)=>e<<t|s>>>32-t,TD=(s,e,t)=>e<<t-32|s>>>64-t,PD=(s,e,t)=>s<<t-32|e>>>64-t,zr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function xD(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function sl(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Hs(s,e){return s<<32-e|s>>>e}const jp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function MD(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Rp(s){for(let e=0;e<s.length;e++)s[e]=MD(s[e])}function OD(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function An(s){return typeof s=="string"&&(s=OD(s)),wc(s),s}let Gh=class{clone(){return this._cloneInto()}};function Ay(s){const e=i=>s().update(An(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Vo(s=32){if(zr&&typeof zr.getRandomValues=="function")return zr.getRandomValues(new Uint8Array(s));if(zr&&typeof zr.randomBytes=="function")return zr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Ny=[],Cy=[],_y=[],DD=BigInt(0),Yn=BigInt(1),kD=BigInt(2),jD=BigInt(7),RD=BigInt(256),UD=BigInt(113);for(let s=0,e=Yn,t=1,i=0;s<24;s++){[t,i]=[i,(2*t+3*i)%5],Ny.push(2*(5*i+t)),Cy.push((s+1)*(s+2)/2%64);let r=DD;for(let n=0;n<7;n++)e=(e<<Yn^(e>>jD)*UD)%RD,e&kD&&(r^=Yn<<(Yn<<BigInt(n))-Yn);_y.push(r)}const[LD,zD]=_D(_y,!0),Up=(s,e,t)=>t>32?TD(s,e,t):SD(s,e,t),Lp=(s,e,t)=>t>32?PD(s,e,t):$D(s,e,t);function FD(s,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=t[c],u=t[c+1],d=Up(l,u,1)^t[a],p=Lp(l,u,1)^t[a+1];for(let f=0;f<50;f+=10)s[o+f]^=d,s[o+f+1]^=p}let r=s[2],n=s[3];for(let o=0;o<24;o++){const a=Cy[o],c=Up(r,n,a),l=Lp(r,n,a),u=Ny[o];r=s[u],n=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}s[0]^=LD[i],s[1]^=zD[i]}t.fill(0)}let qD=class Sy extends Gh{constructor(e,t,i,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,So(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=xD(this.state)}keccak(){jp||Rp(this.state32),FD(this.state32,this.rounds),jp||Rp(this.state32),this.posOut=0,this.pos=0}update(e){En(this);const{blockLen:t,state:i}=this;e=An(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(t-this.pos,r-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:r}=this;e[i]^=t,(t&128)!==0&&i===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){En(this,!1),wc(e),this.finish();const t=this.state,{blockLen:i}=this;for(let r=0,n=e.length;r<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-r);e.set(t.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 So(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ey(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Sy(t,i,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const BD=(s,e,t)=>Ay(()=>new qD(e,s,t)),HD=BD(1,136,256/8),WD="https://rpc.walletconnect.org/v1";function $y(s){const e=`Ethereum Signed Message:
13
13
  ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+N.Buffer.from(HD(t)).toString("hex")}async function VD(s,e,t,i,r,n){switch(t.t){case"eip191":return await KD(s,e,t.s);case"eip1271":return await GD(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function KD(s,e,t){return(await sD({hash:$y(e),signature:t})).toLowerCase()===s.toLowerCase()}async function GD(s,e,t,i,r,n){const o=yn(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l="0000000000000000000000000000000000000000000000000000000000000041",u=t.substring(2),d=$y(e).substring(2),p=a+d+c+l+u,f=await fetch(`${n||WD}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:YD(),jsonrpc:"2.0",method:"eth_call",params:[{to:s,data:p},"latest"]})}),{result:g}=await f.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function YD(){return Date.now()+Math.floor(Math.random()*1e3)}function QD(s){const e=atob(s),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const i=t[0];if(i===0)throw new Error("No signatures found");const r=1+i*64;if(t.length<r)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const n=N.Buffer.from(s,"base64").slice(1,65);return fy.encode(n)}var JD=Object.defineProperty,ZD=Object.defineProperties,XD=Object.getOwnPropertyDescriptors,zp=Object.getOwnPropertySymbols,ek=Object.prototype.hasOwnProperty,tk=Object.prototype.propertyIsEnumerable,Fp=(s,e,t)=>e in s?JD(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,sk=(s,e)=>{for(var t in e||(e={}))ek.call(e,t)&&Fp(s,t,e[t]);if(zp)for(var t of zp(e))tk.call(e,t)&&Fp(s,t,e[t]);return s},ik=(s,e)=>ZD(s,XD(e));const rk="did:pkh:",Yh=s=>s?.split(":"),nk=s=>{const e=s&&Yh(s);if(e)return s.includes(rk)?e[3]:e[1]},Xl=s=>{const e=s&&Yh(s);if(e)return e[2]+":"+e[3]},Ga=s=>{const e=s&&Yh(s);if(e)return e.pop()};async function qp(s){const{cacao:e,projectId:t}=s,{s:i,p:r}=e,n=Ty(r,r.iss),o=Ga(r.iss);return await VD(o,n,i,Xl(r.iss),t)}const Ty=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=Ga(e);if(!s.aud&&!s.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=s.statement||void 0;const n=`URI: ${s.aud||s.uri}`,o=`Version: ${s.version}`,a=`Chain ID: ${nk(e)}`,c=`Nonce: ${s.nonce}`,l=`Issued At: ${s.iat}`,u=s.exp?`Expiration Time: ${s.exp}`:void 0,d=s.nbf?`Not Before: ${s.nbf}`:void 0,p=s.requestId?`Request ID: ${s.requestId}`:void 0,f=s.resources?`Resources:${s.resources.map(w=>`
14
14
  - ${w}`).join("")}`:void 0,g=Da(s.resources);if(g){const w=$o(g);r=gk(r,w)}return[t,i,"",r,"",n,o,a,c,l,u,d,p,f].filter(w=>w!=null).join(`
15
15
  `)};function ok(s){return N.Buffer.from(JSON.stringify(s)).toString("base64")}function ak(s){return JSON.parse(N.Buffer.from(s,"base64").toString("utf-8"))}function ur(s){if(!s)throw new Error("No recap provided, value is undefined");if(!s.att)throw new Error("No `att` property found");const e=Object.keys(s.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=s.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(r=>{const n=i[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function ck(s,e,t,i={}){return t?.sort((r,n)=>r.localeCompare(n)),{att:{[s]:lk(e,t,i)}}}function lk(s,e,t={}){e=e?.sort((r,n)=>r.localeCompare(n));const i=e.map(r=>({[`${s}/${r}`]:[t]}));return Object.assign({},...i)}function Py(s){return ur(s),`urn:recap:${ok(s).replace(/=/g,"")}`}function $o(s){const e=ak(s.replace("urn:recap:",""));return ur(e),e}function hk(s,e,t){const i=ck(s,e,t);return Py(i)}function uk(s){return s&&s.includes("urn:recap:")}function dk(s,e){const t=$o(s),i=$o(e),r=pk(t,i);return Py(r)}function pk(s,e){ur(s),ur(e);const t=Object.keys(s.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),i={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=s.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;i.att[r]=ik(sk({},i.att[r]),{[a]:((c=s.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),i}function gk(s="",e){ur(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(s.includes(t))return s;const i=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,p)=>d.action.localeCompare(p.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const u=Object.keys(l).map(d=>(r++,`(${r}) '${d}': '${l[d].join("', '")}' for '${a}'.`));i.push(u.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${s?s+" ":""}${o}`}function Bp(s){var e;const t=$o(s);ur(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(r=>r.split("/")[1]):[]}function Hp(s){const e=$o(s);ur(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(r=>{var n;(n=r?.[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function Da(s){if(!s)return;const e=s?.[s.length-1];return uk(e)?e:void 0}function il(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function xy(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function as(s,...e){if(!xy(s))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(s.length))throw new Error("Uint8Array expected of length "+e+", got length="+s.length)}function Wp(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function fk(s,e){as(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Vp(s){if(typeof s!="boolean")throw new Error(`boolean expected, not ${s}`)}const Di=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),wk=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),yk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!yk)throw new Error("Non little-endian hardware is not supported");function mk(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function eh(s){if(typeof s=="string")s=mk(s);else if(xy(s))s=th(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function bk(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function vk(s,e){if(s.length!==e.length)return!1;let t=0;for(let i=0;i<s.length;i++)t|=s[i]^e[i];return t===0}const Ik=(s,e)=>{function t(i,...r){if(as(i),s.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");s.varSizeNonce?as(l):as(l,s.nonceLength)}const n=s.tagLength;n&&r[1]!==void 0&&as(r[1]);const o=e(i,...r),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");as(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,as(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(as(l),n&&l.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(t,s),t};function Kp(s,e,t=!0){if(e===void 0)return new Uint8Array(s);if(e.length!==s)throw new Error("invalid output length, expected "+s+", got: "+e.length);if(t&&!Ek(e))throw new Error("invalid output, must be aligned");return e}function Gp(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);s.setUint32(e+4,o,i),s.setUint32(e+0,a,i)}function Ek(s){return s.byteOffset%4===0}function th(s){return Uint8Array.from(s)}function Nn(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}const My=s=>Uint8Array.from(s.split("").map(e=>e.charCodeAt(0))),Ak=My("expand 16-byte k"),Nk=My("expand 32-byte k"),Ck=Di(Ak),_k=Di(Nk);function Ne(s,e){return s<<e|s>>>32-e}function sh(s){return s.byteOffset%4===0}const ba=64,Sk=16,Oy=2**32-1,Yp=new Uint32Array;function $k(s,e,t,i,r,n,o,a){const c=r.length,l=new Uint8Array(ba),u=Di(l),d=sh(r)&&sh(n),p=d?Di(r):Yp,f=d?Di(n):Yp;for(let g=0;g<c;o++){if(s(e,t,i,u,o,a),o>=Oy)throw new Error("arx: counter overflow");const w=Math.min(ba,c-g);if(d&&w===ba){const b=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let v=0,m;v<Sk;v++)m=b+v,f[m]=p[m]^u[v];g+=ba;continue}for(let b=0,v;b<w;b++)v=g+b,n[v]=r[v]^l[b];g+=w}}function Tk(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=bk({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return il(r),il(o),Vp(n),Vp(t),(a,c,l,u,d=0)=>{as(a),as(c),as(l);const p=l.length;if(u===void 0&&(u=new Uint8Array(p)),as(u),il(d),d<0||d>=Oy)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);const f=[];let g=a.length,w,b;if(g===32)f.push(w=th(a)),b=_k;else if(g===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),b=Ck,f.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);sh(c)||f.push(c=th(c));const v=Di(w);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(b,v,Di(c.subarray(0,16)),v),c=c.subarray(16)}const m=16-r;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const C=new Uint8Array(12);C.set(c,n?0:12-c.length),c=C,f.push(c)}const A=Di(c);return $k(s,b,v,A,l,u,d,o),Nn(...f),u}}const St=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let Pk=class{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=eh(e),as(e,32);const t=St(e,0),i=St(e,2),r=St(e,4),n=St(e,6),o=St(e,8),a=St(e,10),c=St(e,12),l=St(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|r<<6)&7939,this.r[3]=(r>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=St(e,16+2*u)}process(e,t,i=!1){const r=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],p=o[5],f=o[6],g=o[7],w=o[8],b=o[9],v=St(e,t+0),m=St(e,t+2),A=St(e,t+4),C=St(e,t+6),S=St(e,t+8),$=St(e,t+10),O=St(e,t+12),D=St(e,t+14);let T=n[0]+(v&8191),q=n[1]+((v>>>13|m<<3)&8191),j=n[2]+((m>>>10|A<<6)&8191),G=n[3]+((A>>>7|C<<9)&8191),B=n[4]+((C>>>4|S<<12)&8191),W=n[5]+(S>>>1&8191),V=n[6]+((S>>>14|$<<2)&8191),H=n[7]+(($>>>11|O<<5)&8191),K=n[8]+((O>>>8|D<<8)&8191),Q=n[9]+(D>>>5|r),_=0,z=_+T*a+q*(5*b)+j*(5*w)+G*(5*g)+B*(5*f);_=z>>>13,z&=8191,z+=W*(5*p)+V*(5*d)+H*(5*u)+K*(5*l)+Q*(5*c),_+=z>>>13,z&=8191;let ee=_+T*c+q*a+j*(5*b)+G*(5*w)+B*(5*g);_=ee>>>13,ee&=8191,ee+=W*(5*f)+V*(5*p)+H*(5*d)+K*(5*u)+Q*(5*l),_+=ee>>>13,ee&=8191;let J=_+T*l+q*c+j*a+G*(5*b)+B*(5*w);_=J>>>13,J&=8191,J+=W*(5*g)+V*(5*f)+H*(5*p)+K*(5*d)+Q*(5*u),_+=J>>>13,J&=8191;let ve=_+T*u+q*l+j*c+G*a+B*(5*b);_=ve>>>13,ve&=8191,ve+=W*(5*w)+V*(5*g)+H*(5*f)+K*(5*p)+Q*(5*d),_+=ve>>>13,ve&=8191;let pe=_+T*d+q*u+j*l+G*c+B*a;_=pe>>>13,pe&=8191,pe+=W*(5*b)+V*(5*w)+H*(5*g)+K*(5*f)+Q*(5*p),_+=pe>>>13,pe&=8191;let te=_+T*p+q*d+j*u+G*l+B*c;_=te>>>13,te&=8191,te+=W*a+V*(5*b)+H*(5*w)+K*(5*g)+Q*(5*f),_+=te>>>13,te&=8191;let st=_+T*f+q*p+j*d+G*u+B*l;_=st>>>13,st&=8191,st+=W*c+V*a+H*(5*b)+K*(5*w)+Q*(5*g),_+=st>>>13,st&=8191;let Le=_+T*g+q*f+j*p+G*d+B*u;_=Le>>>13,Le&=8191,Le+=W*l+V*c+H*a+K*(5*b)+Q*(5*w),_+=Le>>>13,Le&=8191;let Ie=_+T*w+q*g+j*f+G*p+B*d;_=Ie>>>13,Ie&=8191,Ie+=W*u+V*l+H*c+K*a+Q*(5*b),_+=Ie>>>13,Ie&=8191;let ke=_+T*b+q*w+j*g+G*f+B*p;_=ke>>>13,ke&=8191,ke+=W*d+V*u+H*l+K*c+Q*a,_+=ke>>>13,ke&=8191,_=(_<<2)+_|0,_=_+z|0,z=_&8191,_=_>>>13,ee+=_,n[0]=z,n[1]=ee,n[2]=J,n[3]=ve,n[4]=pe,n[5]=te,n[6]=st,n[7]=Le,n[8]=Ie,n[9]=ke}finalize(){const{h:e,pad:t}=this,i=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,i[0]=e[0]+5,r=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+r,r=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[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]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;Nn(i)}update(e){Wp(this);const{buffer:t,blockLen:i}=this;e=eh(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(i-this.pos,r-n);if(o===i){for(;i<=r-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Nn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Wp(this),fk(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}};function xk(s){const e=(i,r)=>s(r).update(eh(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const Mk=xk(s=>new Pk(s));function Ok(s,e,t,i,r,n=20){let o=s[0],a=s[1],c=s[2],l=s[3],u=e[0],d=e[1],p=e[2],f=e[3],g=e[4],w=e[5],b=e[6],v=e[7],m=r,A=t[0],C=t[1],S=t[2],$=o,O=a,D=c,T=l,q=u,j=d,G=p,B=f,W=g,V=w,H=b,K=v,Q=m,_=A,z=C,ee=S;for(let ve=0;ve<n;ve+=2)$=$+q|0,Q=Ne(Q^$,16),W=W+Q|0,q=Ne(q^W,12),$=$+q|0,Q=Ne(Q^$,8),W=W+Q|0,q=Ne(q^W,7),O=O+j|0,_=Ne(_^O,16),V=V+_|0,j=Ne(j^V,12),O=O+j|0,_=Ne(_^O,8),V=V+_|0,j=Ne(j^V,7),D=D+G|0,z=Ne(z^D,16),H=H+z|0,G=Ne(G^H,12),D=D+G|0,z=Ne(z^D,8),H=H+z|0,G=Ne(G^H,7),T=T+B|0,ee=Ne(ee^T,16),K=K+ee|0,B=Ne(B^K,12),T=T+B|0,ee=Ne(ee^T,8),K=K+ee|0,B=Ne(B^K,7),$=$+j|0,ee=Ne(ee^$,16),H=H+ee|0,j=Ne(j^H,12),$=$+j|0,ee=Ne(ee^$,8),H=H+ee|0,j=Ne(j^H,7),O=O+G|0,Q=Ne(Q^O,16),K=K+Q|0,G=Ne(G^K,12),O=O+G|0,Q=Ne(Q^O,8),K=K+Q|0,G=Ne(G^K,7),D=D+B|0,_=Ne(_^D,16),W=W+_|0,B=Ne(B^W,12),D=D+B|0,_=Ne(_^D,8),W=W+_|0,B=Ne(B^W,7),T=T+q|0,z=Ne(z^T,16),V=V+z|0,q=Ne(q^V,12),T=T+q|0,z=Ne(z^T,8),V=V+z|0,q=Ne(q^V,7);let J=0;i[J++]=o+$|0,i[J++]=a+O|0,i[J++]=c+D|0,i[J++]=l+T|0,i[J++]=u+q|0,i[J++]=d+j|0,i[J++]=p+G|0,i[J++]=f+B|0,i[J++]=g+W|0,i[J++]=w+V|0,i[J++]=b+H|0,i[J++]=v+K|0,i[J++]=m+Q|0,i[J++]=A+_|0,i[J++]=C+z|0,i[J++]=S+ee|0}const Dk=Tk(Ok,{counterRight:!1,counterLength:4,allowShortKeys:!1}),kk=new Uint8Array(16),Qp=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(kk.subarray(t))},jk=new Uint8Array(32);function Jp(s,e,t,i,r){const n=s(e,t,jk),o=Mk.create(n);r&&Qp(o,r),Qp(o,i);const a=new Uint8Array(16),c=wk(a);Gp(c,0,BigInt(r?r.length:0),!0),Gp(c,8,BigInt(i.length),!0),o.update(a);const l=o.digest();return Nn(n,a),l}const Rk=s=>(e,t,i)=>({encrypt(r,n){const o=r.length;n=Kp(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);s(e,t,a,a,1);const c=Jp(s,e,t,a,i);return n.set(c,o),Nn(c),n},decrypt(r,n){n=Kp(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Jp(s,e,t,o,i);if(!vk(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),Nn(c),n}}),Dy=Ik({blockSize:64,nonceLength:12,tagLength:16},Rk(Dk));let ky=class extends Gh{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Kh(e);const i=An(t);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,n=new Uint8Array(r);n.set(i.length>r?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return En(this),this.iHash.update(e),this}digestInto(e){En(this),wc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:r,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Qh=(s,e,t)=>new ky(s,e).update(t).digest();Qh.create=(s,e)=>new ky(s,e);function Uk(s,e,t){return Kh(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Qh(s,An(t),An(e))}const rl=new Uint8Array([0]),Zp=new Uint8Array;function Lk(s,e,t,i=32){if(Kh(s),So(i),i>255*s.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(i/s.outputLen);t===void 0&&(t=Zp);const n=new Uint8Array(r*s.outputLen),o=Qh.create(s,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)rl[0]=l+1,a.update(l===0?Zp:c).update(t).update(rl).digestInto(c),n.set(c,s.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),rl.fill(0),n.slice(0,i)}const zk=(s,e,t,i,r)=>Lk(s,Uk(s,e,t),i,r);function Fk(s,e,t,i){if(typeof s.setBigUint64=="function")return s.setBigUint64(e,t,i);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=i?4:0,l=i?0:4;s.setUint32(e+c,o,i),s.setUint32(e+l,a,i)}function qk(s,e,t){return s&e^~s&t}function Bk(s,e,t){return s&e^s&t^e&t}class Hk extends Gh{constructor(e,t,i,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=sl(this.buffer)}update(e){En(this);const{view:t,buffer:i,blockLen:r}=this;e=An(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(r-this.pos,n-o);if(a===r){const c=sl(e);for(;r<=n-o;o+=r)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){En(this),Ey(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(i,0),o=0);for(let d=o;d<r;d++)t[d]=0;Fk(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=sl(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:r,finished:n,destroyed:o,pos:a}=this;return e.length=r,e.pos=a,e.finished=n,e.destroyed=o,r%t&&e.buffer.set(i),e}}const Wk=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ei=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ai=new Uint32Array(64);let Vk=class extends Hk{constructor(){super(64,32,8,!1),this.A=Ei[0]|0,this.B=Ei[1]|0,this.C=Ei[2]|0,this.D=Ei[3]|0,this.E=Ei[4]|0,this.F=Ei[5]|0,this.G=Ei[6]|0,this.H=Ei[7]|0}get(){const{A:e,B:t,C:i,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,i,r,n,o,a,c]}set(e,t,i,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=i|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)Ai[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const p=Ai[d-15],f=Ai[d-2],g=Hs(p,7)^Hs(p,18)^p>>>3,w=Hs(f,17)^Hs(f,19)^f>>>10;Ai[d]=w+Ai[d-7]+g+Ai[d-16]|0}let{A:i,B:r,C:n,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const p=Hs(a,6)^Hs(a,11)^Hs(a,25),f=u+p+qk(a,c,l)+Wk[d]+Ai[d]|0,g=(Hs(i,2)^Hs(i,13)^Hs(i,22))+Bk(i,r,n)|0;u=l,l=c,c=a,a=o+f|0,o=n,n=r,r=i,i=f+g|0}i=i+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(i,r,n,o,a,c,l,u)}roundClean(){Ai.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const yc=Ay(()=>new Vk);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const jy=BigInt(0);function Jh(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ry(s){if(!Jh(s))throw new Error("Uint8Array expected")}const Kk=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Gk(s){Ry(s);let e="";for(let t=0;t<s.length;t++)e+=Kk[s[t]];return e}function Yk(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?jy:BigInt("0x"+s)}const oi={_0:48,_9:57,A:65,F:70,a:97,f:102};function Xp(s){if(s>=oi._0&&s<=oi._9)return s-oi._0;if(s>=oi.A&&s<=oi.F)return s-(oi.A-10);if(s>=oi.a&&s<=oi.f)return s-(oi.a-10)}function Uy(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=Xp(s.charCodeAt(n)),a=Xp(s.charCodeAt(n+1));if(o===void 0||a===void 0){const c=s[n]+s[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[r]=o*16+a}return i}function eg(s){return Ry(s),Yk(Gk(Uint8Array.from(s).reverse()))}function Qk(s,e){return Uy(s.toString(16).padStart(e*2,"0"))}function Jk(s,e){return Qk(s,e).reverse()}function tg(s,e,t){let i;if(typeof e=="string")try{i=Uy(e)}catch(n){throw new Error(s+" must be hex string or Uint8Array, cause: "+n)}else if(Jh(e))i=Uint8Array.from(e);else throw new Error(s+" must be hex string or Uint8Array");const r=i.length;if(typeof t=="number"&&r!==t)throw new Error(s+" of length "+t+" expected, got "+r);return i}const nl=s=>typeof s=="bigint"&&jy<=s;function Zk(s,e,t){return nl(s)&&nl(e)&&nl(t)&&e<=s&&s<t}function sg(s,e,t,i){if(!Zk(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const Xk={bigint:s=>typeof s=="bigint",function:s=>typeof s=="function",boolean:s=>typeof s=="boolean",string:s=>typeof s=="string",stringOrUint8Array:s=>typeof s=="string"||Jh(s),isSafeInteger:s=>Number.isSafeInteger(s),array:s=>Array.isArray(s),field:(s,e)=>e.Fp.isValid(s),hash:s=>typeof s=="function"&&Number.isSafeInteger(s.outputLen)};function e3(s,e,t={}){const i=(r,n,o)=>{const a=Xk[n];if(typeof a!="function")throw new Error("invalid validator function");const c=s[r];if(!(o&&c===void 0)&&!a(c,s))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))i(r,n,!1);for(const[r,n]of Object.entries(t))i(r,n,!0);return s}const un=BigInt(0),va=BigInt(1);function Ly(s,e){const t=s%e;return t>=un?t:e+t}function t3(s,e,t){if(e<un)throw new Error("invalid exponent, negatives unsupported");if(t<=un)throw new Error("invalid modulus");if(t===va)return un;let i=va;for(;e>un;)e&va&&(i=i*s%t),s=s*s%t,e>>=va;return i}function Ds(s,e,t){let i=s;for(;e-- >un;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Fr=BigInt(0),ol=BigInt(1);function s3(s){return e3(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function i3(s){const e=s3(s),{P:t}=e,i=m=>Ly(m,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),c=e.powPminus2||(m=>t3(m,t-BigInt(2),t));function l(m,A,C){const S=i(m*(A-C));return A=i(A-S),C=i(C+S),[A,C]}const u=(e.a-BigInt(2))/BigInt(4);function d(m,A){sg("u",m,Fr,t),sg("scalar",A,Fr,t);const C=A,S=m;let $=ol,O=Fr,D=m,T=ol,q=Fr,j;for(let B=BigInt(r-1);B>=Fr;B--){const W=C>>B&ol;q^=W,j=l(q,$,D),$=j[0],D=j[1],j=l(q,O,T),O=j[0],T=j[1],q=W;const V=$+O,H=i(V*V),K=$-O,Q=i(K*K),_=H-Q,z=D+T,ee=D-T,J=i(ee*V),ve=i(z*K),pe=J+ve,te=J-ve;D=i(pe*pe),T=i(S*i(te*te)),$=i(H*Q),O=i(_*(H+i(u*_)))}j=l(q,$,D),$=j[0],D=j[1],j=l(q,O,T),O=j[0],T=j[1];const G=c(O);return i($*G)}function p(m){return Jk(i(m),n)}function f(m){const A=tg("u coordinate",m,n);return o===32&&(A[31]&=127),eg(A)}function g(m){const A=tg("scalar",m),C=A.length;if(C!==n&&C!==o){let S=""+n+" or "+o;throw new Error("invalid scalar, expected "+S+" bytes, got "+C)}return eg(a(A))}function w(m,A){const C=f(A),S=g(m),$=d(C,S);if($===Fr)throw new Error("invalid private or public key received");return p($)}const b=p(e.Gu);function v(m){return w(m,b)}return{scalarMult:w,scalarMultBase:v,getSharedSecret:(m,A)=>w(m,A),getPublicKey:m=>v(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:b}}const ih=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const r3=BigInt(1),ig=BigInt(2),n3=BigInt(3),o3=BigInt(5);BigInt(8);function a3(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=ih,o=s*s%n*s%n,a=Ds(o,ig,n)*o%n,c=Ds(a,r3,n)*s%n,l=Ds(c,o3,n)*c%n,u=Ds(l,e,n)*l%n,d=Ds(u,t,n)*u%n,p=Ds(d,i,n)*d%n,f=Ds(p,r,n)*p%n,g=Ds(f,r,n)*p%n,w=Ds(g,e,n)*l%n;return{pow_p_5_8:Ds(w,ig,n)*s%n,b2:o}}function c3(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const rh=i3({P:ih,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=ih,{pow_p_5_8:t,b2:i}=a3(s);return Ly(Ds(t,n3,e)*i,e)},adjustScalarBytes:c3,randomBytes:Vo}),zy="base10",Ft="base16",Mi="base64pad",Qn="base64url",Ko="utf8",Fy=0,gi=1,Go=2,l3=0,rg=1,go=12,Zh=32;function h3(){const s=rh.utils.randomPrivateKey(),e=rh.getPublicKey(s);return{privateKey:h.toString(s,Ft),publicKey:h.toString(e,Ft)}}function nh(){const s=Vo(Zh);return h.toString(s,Ft)}function u3(s,e){const t=rh.getSharedSecret(h.fromString(s,Ft),h.fromString(e,Ft)),i=zk(yc,t,void 0,void 0,Zh);return h.toString(i,Ft)}function ka(s){const e=yc(h.fromString(s,Ft));return h.toString(e,Ft)}function Ys(s){const e=yc(h.fromString(s,Ko));return h.toString(e,Ft)}function qy(s){return h.fromString(`${s}`,zy)}function dr(s){return Number(h.toString(s,zy))}function d3(s){const e=qy(typeof s.type<"u"?s.type:Fy);if(dr(e)===gi&&typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof s.senderPublicKey<"u"?h.fromString(s.senderPublicKey,Ft):void 0,i=typeof s.iv<"u"?h.fromString(s.iv,Ft):Vo(go),r=h.fromString(s.symKey,Ft),n=Dy(r,i).encrypt(h.fromString(s.message,Ko));return By({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function p3(s){const e=h.fromString(s.symKey,Ft),{sealed:t,iv:i}=To(s),r=Dy(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return h.toString(r,Ko)}function g3(s,e){const t=qy(Go),i=Vo(go),r=h.fromString(s,Ko);return By({type:t,sealed:r,iv:i,encoding:e})}function f3(s,e){const{sealed:t}=To({encoded:s,encoding:e});return h.toString(t,Ko)}function By(s){const{encoding:e=Mi}=s;if(dr(s.type)===Go)return h.toString(h.concat([s.type,s.sealed]),e);if(dr(s.type)===gi){if(typeof s.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return h.toString(h.concat([s.type,s.senderPublicKey,s.iv,s.sealed]),e)}return h.toString(h.concat([s.type,s.iv,s.sealed]),e)}function To(s){const{encoded:e,encoding:t=Mi}=s,i=h.fromString(e,t),r=i.slice(l3,rg),n=rg;if(dr(r)===gi){const l=n+Zh,u=l+go,d=i.slice(n,l),p=i.slice(l,u),f=i.slice(u);return{type:r,sealed:f,iv:p,senderPublicKey:d}}if(dr(r)===Go){const l=i.slice(n),u=Vo(go);return{type:r,sealed:l,iv:u}}const o=n+go,a=i.slice(n,o),c=i.slice(o);return{type:r,sealed:c,iv:a}}function w3(s,e){const t=To({encoded:s,encoding:e?.encoding});return Hy({type:dr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?h.toString(t.senderPublicKey,Ft):void 0,receiverPublicKey:e?.receiverPublicKey})}function Hy(s){const e=s?.type||Fy;if(e===gi){if(typeof s?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof s?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:s?.senderPublicKey,receiverPublicKey:s?.receiverPublicKey}}function ng(s){return s.type===gi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function og(s){return s.type===Go}function y3(s){return new $f.ec("p256").keyFromPublic({x:N.Buffer.from(s.x,"base64").toString("hex"),y:N.Buffer.from(s.y,"base64").toString("hex")},"hex")}function m3(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function b3(s){return N.Buffer.from(m3(s),"base64")}function v3(s,e){const[t,i,r]=s.split("."),n=b3(r);if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32).toString("hex"),a=n.slice(32,64).toString("hex"),c=`${t}.${i}`,l=yc(c),u=y3(e),d=h.toString(l,Ft);if(!u.verify(d,{r:o,s:a}))throw new Error("Invalid signature");return h.sn(s).payload}const I3="irn";function Ya(s){return s?.relay||{protocol:I3}}function oo(s){const e=h.C[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function E3(s,e="-"){const t={},i="relay"+e;return Object.keys(s).forEach(r=>{if(r.startsWith(i)){const n=r.replace(i,""),o=s[r];t[n]=o}}),t}function ag(s){if(!s.includes("wc:")){const l=Iy(s);l!=null&&l.includes("wc:")&&(s=l)}s=s.includes("wc://")?s.replace("wc://",""):s,s=s.includes("wc:")?s.replace("wc:",""):s;const e=s.indexOf(":"),t=s.indexOf("?")!==-1?s.indexOf("?"):void 0,i=s.substring(0,e),r=s.substring(e+1,t).split("@"),n=typeof t<"u"?s.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((l,u)=>{a[u]=l});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:A3(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:E3(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function A3(s){return s.startsWith("//")?s.substring(2):s}function N3(s,e="-"){const t="relay",i={};return Object.keys(s).forEach(r=>{const n=r,o=t+e+n;s[n]&&(i[o]=s[n])}),i}function cg(s){const e=new URLSearchParams,t=N3(s.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",s.symKey),s.expiryTimestamp&&e.set("expiryTimestamp",s.expiryTimestamp.toString()),s.methods&&e.set("methods",s.methods.join(","));const i=e.toString();return`${s.protocol}:${s.topic}@${s.version}?${i}`}function Ia(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function xn(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function C3(s){const e=[];return Object.values(s).forEach(t=>{e.push(...xn(t.accounts))}),e}function _3(s,e){const t=[];return Object.values(s).forEach(i=>{xn(i.accounts).includes(e)&&t.push(...i.methods)}),t}function S3(s,e){const t=[];return Object.values(s).forEach(i=>{xn(i.accounts).includes(e)&&t.push(...i.events)}),t}function Xh(s){return s.includes(":")}function ao(s){return Xh(s)?s.split(":")[0]:s}function $3(s){const e={};return s?.forEach(t=>{var i;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(i=e[r].chains)==null||i.push(`${r}:${n}`)}),e}function lg(s,e){e=e.map(i=>i.replace("did:pkh:",""));const t=$3(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=Oa(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const T3={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}},P3={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 L(s,e){const{message:t,code:i}=P3[s];return{message:e?`${t} ${e}`:t,code:i}}function Ue(s,e){const{message:t,code:i}=T3[s];return{message:e?`${t} ${e}`:t,code:i}}function pr(s,e){return!!Array.isArray(s)}function Po(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function xt(s){return typeof s>"u"}function ht(s,e){return e&&xt(s)?!0:typeof s=="string"&&!!s.trim().length}function eu(s,e){return e&&xt(s)?!0:typeof s=="number"&&!isNaN(s)}function x3(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return rr(r,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=s.namespaces[o],u=xn(a),d=t[o];(!rr(wy(o,d),u)||!rr(d.methods,c)||!rr(d.events,l))&&(n=!1)}),n):!1}function Qa(s){return ht(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function M3(s){if(ht(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Qa(t)}}return!1}function O3(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ht(s,!1)){if(e(s))return!0;const t=Iy(s);return e(t)}}catch{}return!1}function D3(s){var e;return(e=s?.proposer)==null?void 0:e.publicKey}function k3(s){return s?.topic}function j3(s,e){let t=null;return ht(s?.publicKey,!1)||(t=L("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function hg(s){let e=!0;return pr(s)?s.length&&(e=s.every(t=>ht(t,!1))):e=!1,e}function R3(s,e,t){let i=null;return pr(e)&&e.length?e.forEach(r=>{i||Qa(r)||(i=Ue("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Qa(s)||(i=Ue("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function U3(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=R3(r,wy(r,n),`${e} ${t}`);o&&(i=o)}),i}function L3(s,e){let t=null;return pr(s)?s.forEach(i=>{t||M3(i)||(t=Ue("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=Ue("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function z3(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=L3(i?.accounts,`${e} namespace`);r&&(t=r)}),t}function F3(s,e){let t=null;return hg(s?.methods)?hg(s?.events)||(t=Ue("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Ue("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Wy(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=F3(i,`${e}, namespace`);r&&(t=r)}),t}function q3(s,e,t){let i=null;if(s&&Po(s)){const r=Wy(s,e);r&&(i=r);const n=U3(s,e,t);n&&(i=n)}else i=L("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function al(s,e){let t=null;if(s&&Po(s)){const i=Wy(s,e);i&&(t=i);const r=z3(s,e);r&&(t=r)}else t=L("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Vy(s){return ht(s.protocol,!0)}function B3(s,e){let t=!1;return s?s&&pr(s)&&s.length&&s.forEach(i=>{t=Vy(i)}):t=!0,t}function H3(s){return typeof s=="number"}function Jt(s){return typeof s<"u"&&typeof s!==null}function W3(s){return!(!s||typeof s!="object"||!s.code||!eu(s.code,!1)||!s.message||!ht(s.message,!1))}function V3(s){return!(xt(s)||!ht(s.method,!1))}function K3(s){return!(xt(s)||xt(s.result)&&xt(s.error)||!eu(s.id,!1)||!ht(s.jsonrpc,!1))}function G3(s){return!(xt(s)||!ht(s.name,!1))}function ug(s,e){return!(!Qa(e)||!C3(s).includes(e))}function Y3(s,e,t){return ht(t,!1)?_3(s,e).includes(t):!1}function Q3(s,e,t){return ht(t,!1)?S3(s,e).includes(t):!1}function dg(s,e,t){let i=null;const r=J3(s),n=Z3(e),o=Object.keys(r),a=Object.keys(n),c=pg(Object.keys(s)),l=pg(Object.keys(e)),u=c.filter(d=>!l.includes(d));return u.length&&(i=L("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
@@ -894,7 +894,7 @@ ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+N.Buffer.from(HD(t)).toS
894
894
  .wui-color-fg-350 {
895
895
  background-color: var(--wui-color-fg-350);
896
896
  }
897
- `,Sa={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};function Qo(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}const Ih=Qo({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"}),Eh=Qo({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"}),JL=Qo({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"});Qo({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Qo({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const ZL={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"]},Cm={getMethodsByChainNamespace(s){return ZL[s]||[]},createDefaultNamespace(s){return{methods:this.getMethodsByChainNamespace(s),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(s,e){if(!e)return{...s};const t={...s},i=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>i.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>i.add(r)),e.events&&Object.keys(e.events).forEach(r=>i.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[n]=r.split(":");n&&i.add(n)}),i.forEach(r=>{t[r]||(t[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,n])=>{t[r]&&(t[r].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([r,n])=>{t[r]&&(t[r].chains=n)}),e.events&&Object.entries(e.events).forEach(([r,n])=>{t[r]&&(t[r].events=n)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,c]=n.split(":");!a||!c||!t[a]||(t[a].rpcMap||(t[a].rpcMap={}),r.has(a)||(t[a].rpcMap={},r.add(a)),t[a].rpcMap[c]=o)})}return t},createNamespaces(s,e){const t=s.reduce((i,r)=>{const{id:n,chainNamespace:o,rpcUrls:a}=r,c=a.default.http[0];i[o]||(i[o]=this.createDefaultNamespace(o));const l=`${o}:${n}`,u=i[o];switch(u.chains.push(l),l){case Ih.caipNetworkId:u.chains.push(Ih.deprecatedCaipNetworkId);break;case Eh.caipNetworkId:u.chains.push(Eh.deprecatedCaipNetworkId);break}return u?.rpcMap&&c&&(u.rpcMap[n]=c),i},{});return this.applyNamespaceOverrides(t,e)},resolveReownName:async s=>{const e=await ey.resolveName(s);return(Object.values(e?.addresses)||[])[0]?.address||!1},getChainsFromNamespaces(s={}){return Object.values(s).flatMap(e=>{const t=e.chains||[],i=e.accounts.map(r=>{const[n,o]=r.split(":");return`${n}:${o}`});return Array.from(new Set([...t,...i]))})},isSessionEventData(s){return typeof s=="object"&&s!==null&&"id"in s&&"topic"in s&&"params"in s&&typeof s.params=="object"&&s.params!==null&&"chainId"in s.params&&"event"in s.params&&typeof s.params.event=="object"&&s.params.event!==null}};class _m{constructor({provider:e,caipNetworks:t,namespace:i}){this.id=ie.CONNECTOR_ID.WALLET_CONNECT,this.name=Ja.ConnectorNamesMap[ie.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Ja.ConnectorImageIds[ie.CONNECTOR_ID.WALLET_CONNECT],this.caipNetworks=t,this.provider=e,this.chain=i}get chains(){return this.caipNetworks}async connectWalletConnect(){if(!await this.authenticate()){const t=R.state.universalProviderConfigOverride,i=Cm.createNamespaces(this.caipNetworks,t);await this.provider.connect({optionalNamespaces:i})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(t=>t.caipNetworkId);return wn.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:XL})}}const XL=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"];class ez{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,e&&this.construct(e)}construct(e){this.caipNetworks=e.networks,this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.caipNetworks||[]}setAuthProvider(e){this.addConnector({id:ie.CONNECTOR_ID.AUTH,type:"AUTH",name:ie.CONNECTOR_NAMES.AUTH,provider:e,imageId:Ja.ConnectorImageIds[ie.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(i=>t.has(i.id)?!1:(t.add(i.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){re.setStatus(e,t)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(t)}off(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,t){const i=this.eventListeners.get(e);i&&i.forEach(r=>r(t))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:t,providerType:i}=e;if(!e.provider)return;const r="provider"in e.provider?e.provider.provider:e.provider;if(i==="WALLET_CONNECT"){r.setDefaultChain(t.caipNetworkId);return}if(r&&i==="AUTH"){const n=r;await n.switchNetwork(t.caipNetworkId);const o=await n.getUser({chainId:t.caipNetworkId,preferredAccountType:R.state.defaultAccountTypes[t.chainNamespace]});this.emit("switchNetwork",o)}}getWalletConnectConnector(){const e=this.connectors.find(t=>t instanceof _m);if(!e)throw new Error("WalletConnectConnector not found");return e}}class tz extends ez{setUniversalProvider(e){this.addConnector(new _m({provider:e,caipNetworks:this.caipNetworks||[],namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){const i=this.provider?.session?.namespaces?.[e]?.accounts?.map(r=>{const[,,n]=r.split(":");return n}).filter((r,n,o)=>o.indexOf(r)===n)||[];return Promise.resolve({accounts:i.map(r=>he.createAccount(e,r,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&Ht.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(re.state.balanceLoading&&e.chainId===I.state.activeCaipNetwork?.id)return{balance:re.state.balance||"0.00",symbol:re.state.balanceSymbol||""};const r=(await re.fetchTokenBalance()).find(n=>n.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&n.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:r?.quantity.numeric||"0.00",symbol:r?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:t,message:i,address:r}=e;if(!t)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return I.state.activeCaipNetwork?.chainNamespace===ie.CHAIN.SOLANA?n=(await t.request({method:"solana_signMessage",params:{message:fy.encode(new TextEncoder().encode(i)),pubkey:r}},I.state.activeCaipNetwork?.caipNetworkId)).signature:n=await t.request({method:"personal_sign",params:[i,r]},I.state.activeCaipNetwork?.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async getProfile(){return Promise.resolve({profileImage:"",profileName:""})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}async getEnsAddress(){return Promise.resolve({address:!1})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:t}=e,i=this.getWalletConnectConnector();if(t.chainNamespace===ie.CHAIN.EVM)try{await i.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:gn.toHex(t.id)}]})}catch(r){if(r.code===Sa.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||r.code===Sa.ERROR_INVALID_CHAIN_ID||r.code===Sa.ERROR_CODE_DEFAULT||r?.data?.originalError?.code===Sa.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await i.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:gn.toHex(t.id),rpcUrls:[t?.rpcUrls.chainDefault?.http],chainName:t.name,nativeCurrency:t.nativeCurrency,blockExplorerUrls:[t.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}i.provider.setDefaultChain(t.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(i=>i.type==="WALLET_CONNECT")?.provider}}class sz{constructor(e){this.hasSwitchedToPreferredAccountTypeOnConnect=!1,this.chainNamespaces=[],this.reportedAlertErrors={},this.getCaipNetwork=t=>{if(t){const i=I.getNetworkData(t)?.caipNetwork;return i||I.getRequestedCaipNetworks(t).filter(r=>r.chainNamespace===t)?.[0]}return I.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const t=this.getCaipNetwork();if(t)return t.id},this.getCaipNetworks=t=>I.getRequestedCaipNetworks(t),this.getActiveChainNamespace=()=>I.state.activeChain,this.setRequestedCaipNetworks=(t,i)=>{I.setRequestedCaipNetworks(t,i)},this.getApprovedCaipNetworkIds=()=>I.getAllApprovedCaipNetworkIds(),this.getCaipAddress=t=>I.state.activeChain===t||!t?I.state.activeCaipAddress:I.getAccountProp("caipAddress",t),this.setClientId=t=>{oe.setClientId(t)},this.getProvider=t=>tt.getProvider(t),this.getProviderType=t=>tt.getProviderId(t),this.getPreferredAccountType=()=>re.state.preferredAccountType,this.setCaipAddress=(t,i)=>{re.setCaipAddress(t,i)},this.setBalance=(t,i,r)=>{re.setBalance(t,i,r)},this.setProfileName=(t,i)=>{re.setProfileName(t,i)},this.setProfileImage=(t,i)=>{re.setProfileImage(t,i)},this.setUser=(t,i)=>{re.setUser(t,i),R.state.enableEmbedded&&ot.close()},this.resetAccount=t=>{re.resetAccount(t)},this.setCaipNetwork=t=>{I.setActiveCaipNetwork(t)},this.setCaipNetworkOfNamespace=(t,i)=>{I.setChainNetworkData(i,{caipNetwork:t})},this.setAllAccounts=(t,i)=>{re.setAllAccounts(t,i),R.setHasMultipleAddresses(t?.length>1)},this.setStatus=(t,i)=>{re.setStatus(t,i),le.isConnected()?X.setConnectionStatus("connected"):X.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=t=>I.getAccountProp("address",t),this.setConnectors=t=>{const i=[...le.getConnectors(),...t];le.setConnectors(i)},this.fetchIdentity=t=>oe.fetchIdentity(t),this.getReownName=t=>ey.getNamesForAddress(t),this.getConnectors=()=>le.getConnectors(),this.getConnectorImage=t=>Bh.getConnectorImage(t),this.setConnectedWalletInfo=(t,i)=>{const r=tt.getProviderId(i),n=t?{...t,type:r}:void 0;re.setConnectedWalletInfo(n,i)},this.getIsConnectedState=()=>!!I.state.activeCaipAddress,this.addAddressLabel=(t,i,r)=>{re.addAddressLabel(t,i,r)},this.removeAddressLabel=(t,i)=>{re.removeAddressLabel(t,i)},this.getAddress=t=>I.state.activeChain===t||!t?re.state.address:I.getAccountProp("address",t),this.setApprovedCaipNetworksData=t=>I.setApprovedCaipNetworksData(t),this.resetNetwork=t=>{I.resetNetwork(t)},this.addConnector=t=>{le.addConnector(t)},this.resetWcConnection=()=>{qe.resetWcConnection()},this.setAddressExplorerUrl=(t,i)=>{re.setAddressExplorerUrl(t,i)},this.setSmartAccountDeployed=(t,i)=>{re.setSmartAccountDeployed(t,i)},this.setSmartAccountEnabledNetworks=(t,i)=>{I.setSmartAccountEnabledNetworks(t,i)},this.setPreferredAccountType=(t,i)=>{re.setPreferredAccountType(t,i)},this.setEIP6963Enabled=t=>{R.setEIP6963Enabled(t)},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=[...new Set(this.caipNetworks?.map(t=>t.chainNamespace))],this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.initialize(e),this.sendInitializeEvent(e)}async initialize(e){this.initControllers(e),await this.initChainAdapters(),await this.injectModalUi(),await this.syncExistingConnection(),pi.set({initialized:!0})}sendInitializeEvent(e){const{...t}=e;delete t.adapters,Be.sendEvent({type:"track",event:"INITIALIZE",properties:{...t,networks:e.networks.map(i=>i.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&Lt.setThemeMode(e.themeMode),e.themeVariables&&Lt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");I.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&I.setActiveCaipNetwork(t)}initializeConnectionController(e){qe.setWcBasic(e.basic??!1)}initializeConnectorController(){le.initialize(this.chainNamespaces)}initializeOptionsController(e){R.setDebug(e.debug!==!1),R.setEnableWalletConnect(e.enableWalletConnect!==!1),R.setEnableWalletGuide(e.enableWalletGuide!==!1),R.setEnableWallets(e.enableWallets!==!1),R.setEIP6963Enabled(e.enableEIP6963!==!1),R.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),R.setEnableAuthLogger(e.enableAuthLogger!==!1),R.setCustomRpcUrls(e.customRpcUrls),R.setSdkVersion(e.sdkVersion),R.setProjectId(e.projectId),R.setEnableEmbedded(e.enableEmbedded),R.setAllWallets(e.allWallets),R.setIncludeWalletIds(e.includeWalletIds),R.setExcludeWalletIds(e.excludeWalletIds),R.setFeaturedWalletIds(e.featuredWalletIds),R.setTokens(e.tokens),R.setTermsConditionsUrl(e.termsConditionsUrl),R.setPrivacyPolicyUrl(e.privacyPolicyUrl),R.setCustomWallets(e.customWallets),R.setFeatures(e.features),R.setAllowUnsupportedChain(e.allowUnsupportedChain),R.setDefaultAccountTypes(e.defaultAccountTypes),R.setUniversalProviderConfigOverride(e.universalProviderConfigOverride);const t=this.getDefaultMetaData();if(!e.metadata&&t&&(e.metadata=t),R.setMetadata(e.metadata),R.setDisableAppend(e.disableAppend),R.setEnableEmbedded(e.enableEmbedded),R.setSIWX(e.siwx),!e.projectId){po.open(_a.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(r=>r.namespace===ie.CHAIN.EVM)&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");R.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return typeof window<"u"&&typeof document<"u"?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const i=cn.getUnsupportedNetwork(`${t}:${e}`);I.setActiveCaipNetwork(i)}}getDefaultNetwork(){return cn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return cn.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return cn.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find(r=>r.id===e.defaultNetwork?.id);return t?cn.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=I.state.activeChain,t=this.getAdapter(e),i=this.getCaipNetwork(e)?.id;if(!t)throw new Error("Adapter not found");const r=await t.connectWalletConnect(i);this.close(),this.setClientId(r?.clientId||null),X.setConnectedNamespaces([...I.state.chains.keys()]),this.chainNamespaces.forEach(n=>{le.setConnectorId(Ni.CONNECTOR_TYPE_WALLET_CONNECT,n)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:i,provider:r,chain:n,caipNetwork:o})=>{const a=I.state.activeChain,c=n||a,l=this.getAdapter(c);if(n&&n!==a&&!o){const f=this.caipNetworks?.find(g=>g.chainNamespace===n);f&&this.setCaipNetwork(f)}if(!l)throw new Error("Adapter not found");const u=this.getCaipNetwork(c),d=await l.connect({id:e,info:t,type:i,provider:r,chainId:o?.id||u?.id,rpcUrl:o?.rpcUrls?.default?.http?.[0]||u?.rpcUrls?.default?.http?.[0]});if(!d)return;X.addConnectedNamespace(c),this.syncProvider({...d,chainNamespace:c}),await this.syncAccount({...d,chainNamespace:c});const{accounts:p}=await l.getAccounts({namespace:c,id:e});this.setAllAccounts(p,c)},reconnectExternal:async({id:e,info:t,type:i,provider:r})=>{const n=I.state.activeChain,o=this.getAdapter(n);o?.reconnect&&(await o?.reconnect({id:e,info:t,type:i,provider:r,chainId:this.getCaipNetwork()?.id}),X.addConnectedNamespace(n))},disconnect:async e=>{const t=e||I.state.activeChain,i=this.getAdapter(t),r=tt.getProvider(t),n=tt.getProviderId(t);await i?.disconnect({provider:r,providerType:n}),X.removeConnectedNamespace(t),tt.resetChain(t),this.setUser(void 0,t),this.setStatus("disconnected",t),this.hasSwitchedToPreferredAccountTypeOnConnect=!1},checkInstalled:e=>e?e.some(t=>!!window.ethereum?.[String(t)]):!!window.ethereum,signMessage:async e=>(await this.getAdapter(I.state.activeChain)?.signMessage({message:e,address:re.state.address,provider:tt.getProvider(I.state.activeChain)}))?.signature||"",sendTransaction:async e=>{if(e.chainNamespace===ie.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=tt.getProvider(I.state.activeChain);return(await t?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}))?.hash||""}return""},estimateGas:async e=>{if(e.chainNamespace===ie.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=tt.getProvider(I.state.activeChain),r=this.getCaipNetwork();if(!r)throw new Error("CaipNetwork is undefined");return(await t?.estimateGas({...e,provider:i,caipNetwork:r}))?.gas||0n}return 0n},getEnsAvatar:async()=>(await this.getAdapter(I.state.activeChain)?.getProfile({address:re.state.address,chainId:Number(this.getCaipNetwork()?.id)}))?.profileImage||!1,getEnsAddress:async e=>{const t=this.getAdapter(I.state.activeChain),i=this.getCaipNetwork();return i&&(await t?.getEnsAddress({name:e,caipNetwork:i}))?.address||!1},writeContract:async e=>{const t=this.getAdapter(I.state.activeChain),i=this.getCaipNetwork(),r=this.getCaipAddress(),n=tt.getProvider(I.state.activeChain);if(!i||!r)throw new Error("CaipNetwork or CaipAddress is undefined");return(await t?.writeContract({...e,caipNetwork:i,provider:n,caipAddress:r}))?.hash},parseUnits:(e,t)=>this.getAdapter(I.state.activeChain)?.parseUnits({value:e,decimals:t})??0n,formatUnits:(e,t)=>this.getAdapter(I.state.activeChain)?.formatUnits({value:e,decimals:t})??"0",getCapabilities:async e=>await this.getAdapter(I.state.activeChain)?.getCapabilities(e),grantPermissions:async e=>await this.getAdapter(I.state.activeChain)?.grantPermissions(e),revokePermissions:async e=>{const t=this.getAdapter(I.state.activeChain);return t?.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>await this.getAdapter(I.state.activeChain)?.walletGetAssets(e)??{}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},qe.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){if(tt.getProviderId(I.state.activeChain)===Ni.CONNECTOR_TYPE_WALLET_CONNECT){const t=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(t)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=tt.getProvider(t),n=tt.getProviderId(t);if(e.chainNamespace===I.state.activeChain)await this.getAdapter(t)?.switchNetwork({caipNetwork:e,provider:r,providerType:n});else if(this.setCaipNetwork(e),n===Ni.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(t);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(t=>{const i=t.chains||[],r=t.accounts.map(n=>{const{chainId:o,chainNamespace:a}=vi.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...i,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((t,i)=>{const r=e?.find(n=>n.namespace===i);return r?(t[i]=r,t[i].namespace=i,t[i].construct({namespace:i,projectId:this.options?.projectId,networks:this.caipNetworks})):t[i]=new tz({namespace:i,networks:this.caipNetworks}),t},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e),this.chainAdapters?.[e].syncConnectors(this.options,this),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){this.getAdapter(e)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const i=X.getConnectionStatus();i==="connected"?this.setStatus("connecting",e):i==="disconnected"?(X.clearAddressCache(),this.setStatus(i,e)):this.setStatus(i,e),t.on("switchNetwork",({address:r,chainId:n})=>{const o=this.caipNetworks?.find(l=>l.id===n||l.caipNetworkId===n),a=I.state.activeChain===e,c=I.getAccountProp("address",e);if(o){const l=a&&r?r:c;l&&this.syncAccount({address:l,chainId:n,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),t.on("disconnect",this.disconnect.bind(this,e)),t.on("pendingTransactions",()=>{const r=re.state.address,n=I.state.activeCaipNetwork;!r||!n?.id||this.updateNativeBalance(r,n.id,n.chainNamespace)}),t.on("accountChanged",({address:r,chainId:n})=>{const o=I.state.activeChain===e;o&&n?this.syncAccount({address:r,chainId:n,chainNamespace:e}):o&&I.state.activeCaipNetwork?.id?this.syncAccount({address:r,chainId:I.state.activeCaipNetwork?.id,chainNamespace:e}):this.syncAccountInfo(r,n,e)})}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{const t=le.getConnectorId(e);switch(this.setStatus("connecting",e),t){case ie.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case ie.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){console.warn("AppKit couldn't sync existing connection",t),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){const t=this.getAdapter(e),i=le.getConnectorId(e),r=this.getCaipNetwork(e),n=le.getConnectors(e).find(o=>o.id===i);try{if(!t||!n)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!r?.id)throw new Error("CaipNetwork not found");const o=await t?.syncConnection({namespace:e,id:n.id,chainId:r.id,rpcUrl:r?.rpcUrls?.default?.http?.[0]});if(o){const a=await t?.getAccounts({namespace:e,id:n.id});a&&a.accounts.length>0?this.setAllAccounts(a.accounts,e):this.setAllAccounts([he.createAccount(e,o.address,"eoa")],e),this.syncProvider({...o,chainNamespace:e}),await this.syncAccount({...o,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async t=>{const i=this.getAdapter(t),r=this.universalProvider?.session?.namespaces?.[t]?.accounts||[],n=I.state.activeCaipNetwork?.id,o=r.find(a=>{const{chainId:c}=vi.parseCaipAddress(a);return c===n?.toString()})||r[0];if(o){const a=vi.validateCaipAddress(o),{chainId:c,address:l}=vi.parseCaipAddress(a);if(tt.setProviderId(t,Ni.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&I.state.activeCaipNetwork&&i?.namespace!==ie.CHAIN.EVM){const u=i?.getWalletConnectProvider({caipNetworks:this.caipNetworks,provider:this.universalProvider,activeCaipNetwork:I.state.activeCaipNetwork});tt.setProvider(t,u)}else tt.setProvider(t,this.universalProvider);le.setConnectorId(ie.CONNECTOR_ID.WALLET_CONNECT,t),X.addConnectedNamespace(t),this.syncWalletConnectAccounts(t),await this.syncAccount({address:l,chainId:c,chainNamespace:t})}else this.setStatus("disconnected",t);await I.setApprovedCaipNetworksData(t)});await Promise.all(e)}syncWalletConnectAccounts(e){const t=this.universalProvider?.session?.namespaces?.[e]?.accounts?.map(i=>{const{address:r}=vi.parseCaipAddress(i);return r}).filter((i,r,n)=>n.indexOf(i)===r);t&&this.setAllAccounts(t.map(i=>he.createAccount(e,i,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:i,chainNamespace:r}){tt.setProviderId(r,e),tt.setProvider(r,t),le.setConnectorId(i,r)}async syncAccount(e){const t=e.chainNamespace===I.state.activeChain,i=I.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:n,chainNamespace:o}=e,{chainId:a}=X.getActiveNetworkProps(),c=n||a,l=I.state.activeCaipNetwork?.name===ie.UNSUPPORTED_NETWORK_NAME,u=I.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!u)&&c){let d=this.caipNetworks?.find(g=>g.id.toString()===c.toString()),p=this.caipNetworks?.find(g=>g.chainNamespace===o);if(!u&&!d&&!p){const g=this.getApprovedCaipNetworkIds()||[],w=g.find(v=>vi.parseCaipNetworkId(v)?.chainId===c.toString()),b=g.find(v=>vi.parseCaipNetworkId(v)?.chainNamespace===o);d=this.caipNetworks?.find(v=>v.caipNetworkId===w),p=this.caipNetworks?.find(v=>v.caipNetworkId===b||"deprecatedCaipNetworkId"in v&&v.deprecatedCaipNetworkId===b)}const f=d||p;f?.chainNamespace===I.state.activeChain?R.state.enableNetworkSwitch&&!R.state.allowUnsupportedChain&&I.state.activeCaipNetwork?.name===ie.UNSUPPORTED_NETWORK_NAME?I.showUnsupportedChainUI():this.setCaipNetwork(f):t||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),Em.isLowerCaseMatch(r,re.state.address)||this.syncAccountInfo(r,f?.id,o),t?await this.syncBalance({address:r,chainId:f?.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:i?.id,chainNamespace:o})}}async syncAccountInfo(e,t,i){const r=this.getCaipAddress(i),n=t||r?.split(":")[1];if(!n)return;const o=`${i}:${n}:${e}`;this.setCaipAddress(o,i),await this.syncIdentity({address:e,chainId:n,chainNamespace:i})}async syncReownName(e,t){try{const i=await this.getReownName(e);if(i[0]){const r=i[0];this.setProfileName(r.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){const t=le.getConnectorId(e),i=tt.getProviderId(e);if(i===Ni.CONNECTOR_TYPE_ANNOUNCED||i===Ni.CONNECTOR_TYPE_INJECTED){if(t){const r=this.getConnectors().find(n=>n.id===t);if(r){const{info:n,name:o,imageUrl:a}=r,c=a||this.getConnectorImage(r);this.setConnectedWalletInfo({name:o,icon:c,...n},e)}}}else if(i===Ni.CONNECTOR_TYPE_WALLET_CONNECT){const r=tt.getProvider(e);r?.session&&this.setConnectedWalletInfo({...r.session.peer.metadata,name:r.session.peer.metadata.name,icon:r.session.peer.metadata.icons?.[0]},e)}else if(t)if(t===ie.CONNECTOR_ID.COINBASE){const r=this.getConnectors().find(n=>n.id===ie.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(r)},e)}else this.setConnectedWalletInfo({name:t},e)}async syncBalance(e){!Jw.getNetworksByNamespace(this.caipNetworks,e.chainNamespace).find(i=>i.id.toString()===e.chainId?.toString())||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async updateNativeBalance(e,t,i){const r=this.getAdapter(i);if(r){const n=await r.getBalance({address:e,chainId:t,caipNetwork:this.getCaipNetwork(i),tokens:this.options.tokens});this.setBalance(n.balance,n.symbol,i)}}async initializeUniversalAdapter(){const e=BL.createLogger((i,...r)=>{i&&this.handleAlertError(i),console.error(...r)}),t={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};R.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await ru.init(t),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{qe.setUri(e)}),this.universalProvider.on("connect",qe.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),qe.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const t=this.caipNetworks?.find(r=>r.id==e),i=this.getCaipNetwork();if(!t){this.setUnsupportedNetwork(e);return}i?.id!==t?.id&&this.setCaipNetwork(t)}),this.universalProvider.on("session_event",e=>{if(Cm.isSessionEventData(e)){const{name:t,data:i}=e.params.event;t==="accountsChanged"&&Array.isArray(i)&&he.isCaipAddress(i[0])&&this.syncAccount(vi.parseCaipAddress(i[0]))}}))}createUniversalProvider(){return!this.universalProviderInitPromise&&he.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Be.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const t=Object.entries(_a.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[i,r]=t??[],{message:n,alertErrorKey:o}=r??{};if(i&&n&&!this.reportedAlertErrors[i]){const a=_a.ALERT_ERRORS[o];a&&(po.open(a,"error"),this.reportedAlertErrors[i]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const t=e.namespace;if(!t)return;this.createClients();const i=e;i.namespace=t,i.construct({namespace:t,projectId:this.options?.projectId,networks:this.caipNetworks}),this.chainNamespaces.includes(t)||this.chainNamespaces.push(t),this.chainAdapters&&(this.chainAdapters[t]=i)}async open(e){await this.injectModalUi(),e?.uri&&qe.setUri(e.uri),await ot.open(e)}async close(){await this.injectModalUi(),ot.close()}setLoading(e,t){ot.setLoading(e,t)}async disconnect(e){await qe.disconnect(e)}getError(){return""}getChainId(){return I.state.activeCaipNetwork?.id}async switchNetwork(e){const t=this.caipNetworks?.find(i=>i.id===e.id);if(!t){po.open(_a.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await I.switchActiveNetwork(t)}getWalletProvider(){return I.state.activeChain?tt.state.providers[I.state.activeChain]:null}getWalletProviderType(){return tt.getProviderId(I.state.activeChain)}subscribeProviders(e){return tt.subscribeProviders(e)}getThemeMode(){return Lt.state.themeMode}getThemeVariables(){return Lt.state.themeVariables}setThemeMode(e){Lt.setThemeMode(e),Nm(Lt.state.themeMode)}setTermsConditionsUrl(e){R.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){R.setPrivacyPolicyUrl(e)}setThemeVariables(e){Lt.setThemeVariables(e),KL(Lt.state.themeVariables)}subscribeTheme(e){return Lt.subscribe(e)}getWalletInfo(){return re.state.connectedWalletInfo}getAccount(e){const t=le.getAuthConnector(e),i=I.getAccountData(e);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:he.getPlainAddress(i.caipAddress),isConnected:!!i.caipAddress,status:i.status,embeddedWalletInfo:t?{user:i.user,authProvider:i.socialProvider||"email",accountType:i.preferredAccountType,isSmartAccountDeployed:!!i.smartAccountDeployed}:void 0}}subscribeAccount(e,t){const i=()=>{const r=this.getAccount(t);r&&e(r)};t?I.subscribeChainProp("accountState",i,t):I.subscribe(i),le.subscribe(i)}subscribeNetwork(e){return I.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t?.id,caipNetworkId:t?.caipNetworkId})})}subscribeWalletInfo(e){return re.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){re.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){I.subscribeKey("activeCaipNetwork",e)}getState(){return pi.state}subscribeState(e){return pi.subscribe(e)}showErrorMessage(e){vt.showError(e)}showSuccessMessage(e){vt.showSuccess(e)}getEvent(){return{...Be.state}}subscribeEvents(e){return Be.subscribe(e)}replace(e){Me.replace(e)}redirect(e){Me.push(e)}popTransactionStack(e){Me.popTransactionStack(e)}isOpen(){return ot.state.open}isTransactionStackEmpty(){return Me.state.transactionStack.length===0}isTransactionShouldReplaceView(){return Me.state.transactionStack[Me.state.transactionStack.length-1]?.replace}static getInstance(){return this.instance}updateFeatures(e){R.setFeatures(e)}updateOptions(e){const i={...R.state||{},...e};R.setOptions(i)}setConnectMethodsOrder(e){R.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){R.setWalletFeaturesOrder(e)}setCollapseWallets(e){R.setCollapseWallets(e)}setSocialsOrder(e){R.setSocialsOrder(e)}getConnectMethodsOrder(){return Xa.getConnectOrderMethod(R.state.features,le.getConnectors())}removeAdapter(e){const t=this.getIsConnectedState(),i=this.getAdapter(e);if(!i||!this.chainAdapters||t)return;const r=this.caipNetworks?.filter(n=>n.chainNamespace!==e);I.removeAdapter(e),le.removeAdapter(e),this.chainNamespaces=this.chainNamespaces.filter(n=>n!==e),this.caipNetworks=r,i.removeAllEventListeners(),Reflect.deleteProperty(this.chainAdapters,e)}addAdapter(e,t){const i=e.namespace;if(!this.connectionControllerClient||!this.networkControllerClient||!this.chainAdapters||!i)return;const r=this.extendCaipNetworks({...this.options,networks:t});this.caipNetworks=[...this.caipNetworks||[],...r],this.createAdapter(e),this.initChainAdapter(i),I.addAdapter(e,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient},r)}addNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const i=this.extendCaipNetwork(t,this.options);I.addNetwork(i),this.caipNetworks&&!this.caipNetworks?.find(r=>r.id===i.id)&&this.caipNetworks.push(i)}removeNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);if(!this.caipNetworks?.find(n=>n.id===t))throw new Error(`Network with ID ${t} not found`);if(!this.caipNetworks)return;const r=this.caipNetworks.filter(n=>n.chainNamespace===e&&n.id!==t);if(!r?.length)throw new Error("Cannot remove last network for a namespace");I.removeNetwork(e,t),this.caipNetworks=[...r]}}let tf=!1;class iz extends sz{async open(e){le.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&qe.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!tf&&he.isClient()){if(await Promise.resolve().then(()=>require("./basic-BdiYk8Hf.js")),await Promise.resolve().then(()=>require("./w3m-modal-DSY2qJYP.js")),!document.querySelector("w3m-modal")){const t=document.createElement("w3m-modal");!R.state.disableAppend&&!R.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",t)}tf=!0}}}const rz="1.7.2";function nz(s){return new iz({...s,basic:!0,sdkVersion:`html-core-${rz}`})}function oz(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const u=s.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,u++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let m=l[p],A=0;for(let C=g-1;(m!==0||A<d)&&C!==-1;C--,A++)m+=256*w[C]>>>0,w[C]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let b=g-d;for(;b!==g&&w[b]===0;)b++;let v=i.repeat(u);for(;b<g;++b)v+=s.charAt(w[b]);return v}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,p=0;for(;l[u]===i;)d++,u++;const f=(l.length-u)*r+1>>>0,g=new Uint8Array(f);for(;u<l.length;){const m=l.charCodeAt(u);if(m>255)return;let A=e[m];if(A===255)return;let C=0;for(let S=f-1;(A!==0||C<p)&&S!==-1;S--,C++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=C,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const b=new Uint8Array(d+(f-w));let v=d;for(;w!==f;)b[v++]=g[w++];return b}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var az="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Il=oz(az);class pn extends Error{constructor(){super(),Object.setPrototypeOf(this,pn.prototype)}}class sf extends Error{constructor(e){super(`WalletConnect Adapter - Method ${e} is not supported by the wallet`),this.name="WalletConnectFeatureNotSupportedError"}}function cz(s){let e=[s];return s===gt.Mainnet||s===gt.Deprecated_Mainnet?(e=[gt.Mainnet,gt.Deprecated_Mainnet],s===gt.Deprecated_Mainnet&&console.warn(ec.mainnet)):(s===gt.Deprecated_Devnet||s===gt.Devnet)&&(e=[gt.Devnet,gt.Deprecated_Devnet],console.warn(ec.devnet)),e}const ec={mainnet:`You are using a deprecated chain ID for Solana Mainnet, please use ${gt.Mainnet} instead.`,devnet:`You are using a deprecated chain ID for Solana Devnet, please use ${gt.Devnet} instead.`,wallet:"The connected wallet is using a deprecated chain ID for Solana. Please, contact them to upgrade. You can learn more at https://github.com/ChainAgnostic/namespaces/blob/main/solana/caip10.md#chain-ids"};function rf(s,e){const t=s.namespaces.solana?.accounts.map(i=>`solana:${i.split(":")[1]}`);if(e===gt.Mainnet)return t?.find(i=>i===gt.Mainnet)?gt.Mainnet:(console.warn(ec.wallet),gt.Deprecated_Mainnet);if(e===gt.Devnet)return t?.find(i=>i===gt.Devnet)?gt.Devnet:(console.warn(ec.wallet),gt.Deprecated_Devnet);throw Error("WalletConnect Solana Adapter: Unable to get a default chain from the session.")}function lz(s){return{optionalNamespaces:{solana:{chains:cz(s),methods:[vs.signTransaction,vs.signMessage],events:[]}}}}class nu extends Error{constructor(){super("QR Code Modal was closed by user"),Object.setPrototypeOf(this,nu.prototype),this.name="QRCodeModalError"}}class hz{_UniversalProvider;_session;_modal;_projectId;_network;_ConnectQueueResolver;constructor(e){if(this.initClient(e.options),this._network=e.network,!e.options.projectId)throw Error("WalletConnect Adapter: Project ID is undefined");this._projectId=e.options.projectId}async connect(){if(this._UniversalProvider||await new Promise(r=>{this._ConnectQueueResolver=r}),!this._UniversalProvider)throw new Error("WalletConnect Adapter - Universal Provider was undefined while calling 'connect()'");if(this._UniversalProvider.session){this._session=this._UniversalProvider.session;const r=rf(this._session,this._network);return this._network=r,this._UniversalProvider.setDefaultChain(r),{publicKey:this.publicKey}}await this.initModal();const e=lz(this._network);this._modal?.open();const t=new AbortController,i=t.signal;this._modal?.subscribeState(r=>{r.open||t.abort(new nu)});try{const r=await Promise.race([this._UniversalProvider?.connect(e),new Promise((o,a)=>{i.addEventListener("abort",()=>{a(i.reason)})})]);if(this._modal?.close(),this._session=r,!r)throw new ic;const n=rf(r,this._network);return this._network=n,this._UniversalProvider?.setDefaultChain(n),{publicKey:this.publicKey}}catch(r){throw this._modal?.close(),r}}async disconnect(){if(this._UniversalProvider?.session){if(await this.initModal(),!this._modal)throw Error("WalletConnect Adapter -Modal is undefined: unable to disconnect");await this.client.disconnect(),this._session=void 0}else throw new pn}get client(){if(this._UniversalProvider)return this._UniversalProvider;throw new pn}get session(){if(!this._session)throw new pn;return this._session}get publicKey(){if(this._UniversalProvider?.session&&this._session){const{address:e}=c0(this._session?.namespaces.solana?.accounts[0]??"");return new N.PublicKey(e)}throw new pn}async signTransaction(e){this.checkIfWalletSupportsMethod(vs.signTransaction);const t=ui(e),i=t?{}:e,{signature:r,transaction:n}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:vs.signTransaction,params:{...i,transaction:this.serialize(e)}}});return n?this.deserialize(n,t):(e.addSignature(this.publicKey,N.Buffer.from(Il.decode(r))),e)}async signMessage(e){this.checkIfWalletSupportsMethod(vs.signMessage);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:vs.signMessage,params:{pubkey:this.publicKey.toString(),message:Il.encode(e)}}});return Il.decode(t)}async signAndSendTransaction(e){this.checkIfWalletSupportsMethod(vs.signAndSendTransaction);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:vs.signAndSendTransaction,params:{transaction:this.serialize(e)}}});return t}async signAllTransactions(e){try{this.checkIfWalletSupportsMethod(vs.signAllTransactions);const t=e.map(r=>this.serialize(r)),{transactions:i}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:vs.signAllTransactions,params:{transactions:t}}});return e.map((r,n)=>ui(r)?this.deserialize(i[n]??"",!0):this.deserialize(i[n]??""))}catch(t){if(t instanceof sf){const i=e.map(n=>this.signTransaction(n));return await Promise.all(i)}throw t}}async initClient(e){const t=await TM.init(e);this._UniversalProvider=t,this._ConnectQueueResolver&&this._ConnectQueueResolver(!0)}async initModal(){if(!this._modal){if(!this._UniversalProvider)throw new Error("WalletConnect Adapter - cannot init modal when Universal Provider is undefined");this._modal=nz({projectId:this._projectId,universalProvider:this._UniversalProvider,networks:[Ih,Eh,JL],manualWCControl:!0})}}serialize(e){return N.Buffer.from(e.serialize({verifySignatures:!1})).toString("base64")}deserialize(e,t=!1){return t?N.VersionedTransaction.deserialize(N.Buffer.from(e,"base64")):N.Transaction.from(N.Buffer.from(e,"base64"))}checkIfWalletSupportsMethod(e){if(!this.session.namespaces.solana?.methods.includes(e))throw new sf(e)}}const uz="WalletConnect";class dz extends _h{name=uz;url="https://walletconnect.org";icon="data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjE4NSIgdmlld0JveD0iMCAwIDMwMCAxODUiIHdpZHRoPSIzMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTYxLjQzODU0MjkgMzYuMjU2MjYxMmM0OC45MTEyMjQxLTQ3Ljg4ODE2NjMgMTI4LjIxMTk4NzEtNDcuODg4MTY2MyAxNzcuMTIzMjA5MSAwbDUuODg2NTQ1IDUuNzYzNDE3NGMyLjQ0NTU2MSAyLjM5NDQwODEgMi40NDU1NjEgNi4yNzY1MTEyIDAgOC42NzA5MjA0bC0yMC4xMzY2OTUgMTkuNzE1NTAzYy0xLjIyMjc4MSAxLjE5NzIwNTEtMy4yMDUzIDEuMTk3MjA1MS00LjQyODA4MSAwbC04LjEwMDU4NC03LjkzMTE0NzljLTM0LjEyMTY5Mi0zMy40MDc5ODE3LTg5LjQ0Mzg4Ni0zMy40MDc5ODE3LTEyMy41NjU1Nzg4IDBsLTguNjc1MDU2MiA4LjQ5MzYwNTFjLTEuMjIyNzgxNiAxLjE5NzIwNDEtMy4yMDUzMDEgMS4xOTcyMDQxLTQuNDI4MDgwNiAwbC0yMC4xMzY2OTQ5LTE5LjcxNTUwMzFjLTIuNDQ1NTYxMi0yLjM5NDQwOTItMi40NDU1NjEyLTYuMjc2NTEyMiAwLTguNjcwOTIwNHptMjE4Ljc2Nzc5NjEgNDAuNzczNzQ0OSAxNy45MjE2OTcgMTcuNTQ2ODk3YzIuNDQ1NTQ5IDIuMzk0Mzk2OSAyLjQ0NTU2MyA2LjI3NjQ3NjkuMDAwMDMxIDguNjcwODg5OWwtODAuODEwMTcxIDc5LjEyMTEzNGMtMi40NDU1NDQgMi4zOTQ0MjYtNi40MTA1ODIgMi4zOTQ0NTMtOC44NTYxNi4wMDAwNjItLjAwMDAxLS4wMDAwMS0uMDAwMDIyLS4wMDAwMjItLjAwMDAzMi0uMDAwMDMybC01Ny4zNTQxNDMtNTYuMTU0NTcyYy0uNjExMzktLjU5ODYwMi0xLjYwMjY1LS41OTg2MDItMi4yMTQwNCAwLS4wMDAwMDQuMDAwMDA0LS4wMDAwMDcuMDAwMDA4LS4wMDAwMTEuMDAwMDExbC01Ny4zNTI5MjEyIDU2LjE1NDUzMWMtMi40NDU1MzY4IDIuMzk0NDMyLTYuNDEwNTc1NSAyLjM5NDQ3Mi04Ljg1NjE2MTIuMDAwMDg3LS4wMDAwMTQzLS4wMDAwMTQtLjAwMDAyOTYtLjAwMDAyOC0uMDAwMDQ0OS0uMDAwMDQ0bC04MC44MTI0MTk0My03OS4xMjIxODVjLTIuNDQ1NTYwMjEtMi4zOTQ0MDgtMi40NDU1NjAyMS02LjI3NjUxMTUgMC04LjY3MDkxOTdsMTcuOTIxNzI5NjMtMTcuNTQ2ODY3M2MyLjQ0NTU2MDItMi4zOTQ0MDgyIDYuNDEwNTk4OS0yLjM5NDQwODIgOC44NTYxNjAyIDBsNTcuMzU0OTc3NSA1Ni4xNTUzNTdjLjYxMTM5MDguNTk4NjAyIDEuNjAyNjQ5LjU5ODYwMiAyLjIxNDAzOTggMCAuMDAwMDA5Mi0uMDAwMDA5LjAwMDAxNzQtLjAwMDAxNy4wMDAwMjY1LS4wMDAwMjRsNTcuMzUyMTAzMS01Ni4xNTUzMzNjMi40NDU1MDUtMi4zOTQ0NjMzIDYuNDEwNTQ0LTIuMzk0NTUzMSA4Ljg1NjE2MS0uMDAwMi4wMDAwMzQuMDAwMDMzNi4wMDAwNjguMDAwMDY3My4wMDAxMDEuMDAwMTAxbDU3LjM1NDkwMiA1Ni4xNTU0MzJjLjYxMTM5LjU5ODYwMSAxLjYwMjY1LjU5ODYwMSAyLjIxNDA0IDBsNTcuMzUzOTc1LTU2LjE1NDMyNDljMi40NDU1NjEtMi4zOTQ0MDkyIDYuNDEwNTk5LTIuMzk0NDA5MiA4Ljg1NjE2IDB6IiBmaWxsPSIjM2I5OWZjIi8+PC9zdmc+";supportedTransactionVersions=new Set(["legacy",0]);_publicKey;_connecting;_wallet;_config;_readyState;_onDisconnect;constructor(e){super(),this._publicKey=null,this._connecting=!1,this._config=e,this._wallet=null,this._readyState=typeof window>"u"?ge.Unsupported:ge.Loadable,this._onDisconnect=this.disconnect.bind(this)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Loadable)throw new Ri;this._connecting=!0,this._wallet=new hz({network:this._config.network===vo.Mainnet?La.Mainnet:La.Devnet,options:this._config.options});const{publicKey:e}=await this._wallet.connect();this._publicKey=e,this.emit("connect",e),this._wallet.client.on("session_delete",this._onDisconnect)}catch(e){throw e.constructor.name==="QRCodeModalError"||e instanceof Error&&e.name==="QRCodeModalError"?new Lb:(this._connecting=!1,e)}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){e.client.off("session_delete",this._onDisconnect),this._publicKey=null;try{e.client.session&&await e.disconnect()}catch(t){console.error("WalletConnectWalletAdapter: disconnect error",t),this.emit("error",new xo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signMessage(e)}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAndSendTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAndSendTransaction(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const pz={icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgdmlld0JveD0iMCAwIDI1NiAyNTYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8yMDM1XzExMDYpIj4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IiM1NEZGRjUiLz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTEzLjQ4MDYgMTk4LjYwNUMtMjkuMzI3NiAzMTkuMDQzIDE5OS42NjEgMjg1LjAyNyAzMTkuNTA3IDI1Mi45NjRDNDQyLjE2NSAyMTIuMjU5IDM1Ny4zODYgMzIuODI2OSAyNjkuNDE1IDI4Ljg1NThDMTgxLjQ0MyAyNC44ODQ3IDI4MC4zMjIgMTExLjgyNCAyMDUuNTk1IDEzNi42NTZDMTMwLjg2OCAxNjEuNDg3IDY2Ljk5MDcgNDguMDU4MyAxMy40ODA2IDE5OC42MDVaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjxnIGZpbHRlcj0idXJsKCNmaWx0ZXIxX2ZfMjAzNV8xMTA2KSI+CjxwYXRoIGQ9Ik04NS41MTE4IC00NS44MjI1QzYzLjA1NjIgLTEwNy4xNzYgLTE2LjkxODkgLTIzLjk5NTMgLTU0LjA5OTUgMjUuMjY0M0MtODkuNTY1MiA3OC44NDc5IDMuMDA5MzcgMTI1LjE1MiAzOS4zMjA4IDEwMC4wMzdDNzUuNjMyMyA3NC45MjI3IDcuNzc0NDggNzAuMDM2MyAyOS4zNzA4IDM3LjM3ODVDNTAuOTY3MSA0LjcyMDc2IDExMy41ODEgMzAuODY5NSA4NS41MTE4IC00NS44MjI1WiIgZmlsbD0iIzAwRkZGMCIgZmlsbC1vcGFjaXR5PSIwLjY3Ii8+CjwvZz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjJfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTk2LjQ3OTYgMjI1LjQyNEM2NS44NTAyIDEyMi4zNjMgLTY2LjA4MTggMTc2LjYzNyAtMTI4LjIxOSAyMTYuNjU3Qy0xODcuOTkgMjY0LjA0MiAtNDYuMDcxMSA0MDAuMzQ4IDEyLjg3MjUgMzkzLjM3NkM3MS44MTYxIDM4Ni40MDMgLTM0LjQxMTggMzI3LjA2NSAxLjk4NzAyIDI5OC4xN0MzOC4zODU4IDI2OS4yNzYgMTM0Ljc2NiAzNTQuMjQ5IDk2LjQ3OTYgMjI1LjQyNFoiIGZpbGw9IiM5RDgxRkYiLz4KPC9nPgo8ZyBmaWx0ZXI9InVybCgjZmlsdGVyM19mXzIwMzVfMTEwNikiPgo8cGF0aCBkPSJNMjgyLjEyIC0xMDcuMzUzQzIxNi4wNDcgLTE4Ni4wMzEgMTIxLjQ2MyAtMTIwLjk3IDgyLjQyOTYgLTc4LjYwNDdDNDguMjczOSAtMzAuNjQ0NiAyMjQuMjc1IDU3LjIzMTIgMjczLjEyMSA0Mi4xNzE0QzMyMS45NjggMjcuMTExNSAyMDYuNTEyIC00LjA1MDM4IDIyNy4yOTcgLTMzLjI4NzlDMjQ4LjA4MiAtNjIuNTI1NSAzNjQuNzEyIC05LjAwNTY2IDI4Mi4xMiAtMTA3LjM1M1oiIGZpbGw9IiM0RDk0RkYiLz4KPC9nPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkzLjE4OSAxNTIuODM2SDEzNi42NzRMODcuMjA4NiAxMDMuMDUxTDEzNy4zMSA1My4yNjYzTDE1MC45NTUgNDBIMTA1LjgxOUw0OC4zMzU5IDk3Ljc3NzNDNDUuNDM0OSAxMDAuNjg5IDQ1LjQ0OTggMTA1LjQwMiA0OC4zNjU2IDEwOC4yOTlMOTMuMTg5IDE1Mi44MzZaTTExOS4zMyAxMDMuMTY4SDExOC45OTVMMTE5LjMyNiAxMDMuMTY0TDExOS4zMyAxMDMuMTY4Wk0xMTkuMzMgMTAzLjE2OEwxNjguNzkxIDE1Mi45NDlMMTE4LjY5IDIwMi43MzRMMTA1LjA0NSAyMTZIMTUwLjE4TDIwNy42NjQgMTU4LjIyNkMyMTAuNTY1IDE1NS4zMTQgMjEwLjU1IDE1MC42MDIgMjA3LjYzNCAxNDcuNzA1TDE2Mi44MTEgMTAzLjE2OEgxMTkuMzNaIiBmaWxsPSJibGFjayIvPgo8L2c+CjxkZWZzPgo8ZmlsdGVyIGlkPSJmaWx0ZXIwX2ZfMjAzNV8xMTA2IiB4PSItOTAuMjQxMSIgeT0iLTY5LjczNjkiIHdpZHRoPSI1NjkuNTU4IiBoZWlnaHQ9IjQ1MS40MzEiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyMV9mXzIwMzVfMTEwNiIgeD0iLTE2MC41MTEiIHk9Ii0xNjUuOTg3IiB3aWR0aD0iMzUxLjU5NiIgaGVpZ2h0PSIzNzEuNTA3IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxmaWx0ZXIgaWQ9ImZpbHRlcjJfZl8yMDM1XzExMDYiIHg9Ii0yNDEuMDc4IiB5PSI2Ny42NDIiIHdpZHRoPSI0NDQuODUxIiBoZWlnaHQ9IjQyNC40NTIiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyM19mXzIwMzVfMTEwNiIgeD0iLTIwLjM5NjgiIHk9Ii0yNDIuNzU4IiB3aWR0aD0iNDMwLjE5MSIgaGVpZ2h0PSIzODUuMTA1IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxjbGlwUGF0aCBpZD0iY2xpcDBfMjAzNV8xMTA2Ij4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==",name:"Bitget Wallet"},gz=[pz],fz=s=>gz.find(e=>e.name.toLocaleLowerCase().includes(s.name.toLocaleLowerCase()))||s,wz=(s,e,t)=>e[s]||t[s],nf=(s,e)=>wz(s,fz(e),e);class li extends se.Wallet{constructor(e,t){super(),this.adapter=e,this.connection=t}getAdapter(){return this.adapter}getName(){return nf("name",this.adapter)}getUrl(){return this.adapter.url}async connect(){if(this.isConnected())return this.getAddresses();const e=await new Promise((t,i)=>{this.adapter.on("connect",()=>{this.adapter.off("connect"),this.adapter.off("error"),t(this.getAddresses())}),this.adapter.on("error",r=>{this.adapter.off("connect"),this.adapter.off("error"),i(r)}),this.adapter.connect().catch(i)});return this.emit("connect"),this.adapter.on("disconnect",()=>this.emit("disconnect")),e}getNetworkInfo(){return{}}isConnected(){return this.adapter.connected}async disconnect(){this.isConnected()&&(await new Promise((e,t)=>{this.adapter.on("disconnect",()=>{this.adapter.off("disconnect"),this.adapter.off("error"),e(void 0)}),this.adapter.on("error",i=>{this.adapter.off("disconnect"),this.adapter.off("error"),t(i)}),this.adapter.disconnect().catch(t)}),this.adapter.removeAllListeners(),this.emit("disconnect"))}getChainId(){return se.CHAIN_ID_SOLANA}getAddress(){return this.adapter.publicKey?.toString()}getAddresses(){const e=this.getAddress();return e?[e]:[]}setMainAddress(){throw new Error("Not supported")}getBalance(){throw new Error("Not supported")}async signTransaction(e){if(!this.adapter.signTransaction||!this.adapter.signAllTransactions)throw new Error("Not supported");return Array.isArray(e)?this.adapter.signAllTransactions(e):this.adapter.signTransaction(e)}async sendTransaction(e){const{transaction:t}=e,i=Array.isArray(t)?t:[t];if(i.length===0)throw new Error("Empty transactions array");const r=[];for(const n of i){const o=await this.adapter.sendTransaction(n,this.connection,{...e.options});r.push(o)}return await this.connection.confirmTransaction(r[0],e.options?.commitment),{id:r[0],data:r.length===1?r[0]:r}}async signAndSendTransaction(e){return this.sendTransaction(e)}signMessage(e){if(!this.adapter.signMessage)throw new Error("Not supported");return this.adapter.signMessage(e)}getIcon(){return nf("icon",this.adapter)}getWalletState(){const e=this.adapter.readyState;if(!(e in se.WalletState))throw new Error(`Unknown wallet state ${e}`);return se.WalletState[e]}getFeatures(){const e=[se.BaseFeatures.SendTransaction,se.BaseFeatures.SignAndSendTransaction];return this.adapter.signTransaction&&this.adapter.signAllTransactions&&e.push(se.BaseFeatures.SignTransaction),this.adapter.signMessage&&e.push(se.BaseFeatures.SignMessage),e}supportsChain(e){return e===se.CHAIN_ID_SOLANA}}function yz(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const u=s.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,u++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let m=l[p],A=0;for(let C=g-1;(m!==0||A<d)&&C!==-1;C--,A++)m+=256*w[C]>>>0,w[C]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let b=g-d;for(;b!==g&&w[b]===0;)b++;let v=i.repeat(u);for(;b<g;++b)v+=s.charAt(w[b]);return v}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,p=0;for(;l[u]===i;)d++,u++;const f=(l.length-u)*r+1>>>0,g=new Uint8Array(f);for(;u<l.length;){const m=l.charCodeAt(u);if(m>255)return;let A=e[m];if(A===255)return;let C=0;for(let S=f-1;(A!==0||C<p)&&S!==-1;S--,C++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=C,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const b=new Uint8Array(d+(f-w));let v=d;for(;w!==f;)b[v++]=g[w++];return b}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var mz="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const bz=yz(mz);var Z=function(s,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!i:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(s):i?i.value:e.get(s)},lt=function(s,e,t,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(s,t):r?r.value=t:e.set(s,t),t},Pt,Zt,nr,or,Zi,lo,tc,_e,sc,Ah,Ua,Nh,bo,Ch,of,af,cf,lf;class vz extends df{get name(){return Z(this,_e,"f").name}get url(){return"https://github.com/solana-labs/wallet-standard"}get icon(){return Z(this,_e,"f").icon}get readyState(){return Z(this,sc,"f")}get publicKey(){return Z(this,nr,"f")}get connecting(){return Z(this,or,"f")}get supportedTransactionVersions(){return Z(this,tc,"f")}get wallet(){return Z(this,_e,"f")}get standard(){return!0}constructor({wallet:e}){super(),Pt.add(this),Zt.set(this,void 0),nr.set(this,void 0),or.set(this,void 0),Zi.set(this,void 0),lo.set(this,void 0),tc.set(this,void 0),_e.set(this,void 0),sc.set(this,typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.Installed),Ch.set(this,t=>{if("accounts"in t){const i=Z(this,_e,"f").accounts[0];Z(this,Zt,"f")&&!Z(this,Zi,"f")&&i!==Z(this,Zt,"f")&&(i?Z(this,Pt,"m",Ua).call(this,i):(this.emit("error",new uf),Z(this,Pt,"m",Nh).call(this)))}"features"in t&&Z(this,Pt,"m",bo).call(this)}),lt(this,_e,e,"f"),lt(this,Zt,null,"f"),lt(this,nr,null,"f"),lt(this,or,!1,"f"),lt(this,Zi,!1,"f"),lt(this,lo,Z(this,_e,"f").features[se.StandardEvents].on("change",Z(this,Ch,"f")),"f"),Z(this,Pt,"m",bo).call(this)}destroy(){lt(this,Zt,null,"f"),lt(this,nr,null,"f"),lt(this,or,!1,"f"),lt(this,Zi,!1,"f");const e=Z(this,lo,"f");e&&(lt(this,lo,null,"f"),e())}async autoConnect(){return Z(this,Pt,"m",Ah).call(this,{silent:!0})}async connect(){return Z(this,Pt,"m",Ah).call(this)}async disconnect(){if(se.StandardDisconnect in Z(this,_e,"f").features)try{lt(this,Zi,!0,"f"),await Z(this,_e,"f").features[se.StandardDisconnect].disconnect()}catch(e){this.emit("error",new xo(e?.message,e))}finally{lt(this,Zi,!1,"f")}Z(this,Pt,"m",Nh).call(this)}async sendTransaction(e,t,i={}){try{const r=Z(this,Zt,"f");if(!r)throw new Ke;let n;if(se.SolanaSignAndSendTransaction in Z(this,_e,"f").features)if(r.features.includes(se.SolanaSignAndSendTransaction))n=se.SolanaSignAndSendTransaction;else if(se.SolanaSignTransaction in Z(this,_e,"f").features&&r.features.includes(se.SolanaSignTransaction))n=se.SolanaSignTransaction;else throw new Es;else if(se.SolanaSignTransaction in Z(this,_e,"f").features){if(!r.features.includes(se.SolanaSignTransaction))throw new Es;n=se.SolanaSignTransaction}else throw new ln;const o=tv(t.rpcEndpoint);if(!r.chains.includes(o))throw new sr;try{const{signers:a,...c}=i;let l;if(ui(e)?(a?.length&&e.sign(a),l=e.serialize()):(e=await this.prepareTransaction(e,t,c),a?.length&&e.partialSign(...a),l=new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))),n===se.SolanaSignAndSendTransaction){const[u]=await Z(this,_e,"f").features[se.SolanaSignAndSendTransaction].signAndSendTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:$c(c.preflightCommitment||t.commitment),skipPreflight:c.skipPreflight,maxRetries:c.maxRetries,minContextSlot:c.minContextSlot}});return bz.encode(u.signature)}else{const[u]=await Z(this,_e,"f").features[se.SolanaSignTransaction].signTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:$c(c.preflightCommitment||t.commitment),minContextSlot:c.minContextSlot}});return await t.sendRawTransaction(u.signedTransaction,{...c,preflightCommitment:$c(c.preflightCommitment||t.commitment)})}}catch(a){throw a instanceof Mt?a:new sr(a?.message,a)}}catch(r){throw this.emit("error",r),r}}}Zt=new WeakMap,nr=new WeakMap,or=new WeakMap,Zi=new WeakMap,lo=new WeakMap,tc=new WeakMap,_e=new WeakMap,sc=new WeakMap,Ch=new WeakMap,Pt=new WeakSet,Ah=async function(e){try{if(this.connected||this.connecting)return;if(Z(this,sc,"f")!==ge.Installed)throw new Ri;if(lt(this,or,!0,"f"),!Z(this,_e,"f").accounts.length)try{await Z(this,_e,"f").features[se.StandardConnect].connect(e)}catch(i){throw new ic(i?.message,i)}const t=Z(this,_e,"f").accounts[0];if(!t)throw new Es;Z(this,Pt,"m",Ua).call(this,t)}catch(t){throw this.emit("error",t),t}finally{lt(this,or,!1,"f")}},Ua=function(e){let t;try{t=new N.PublicKey(e.address)}catch(i){throw new gr(i?.message,i)}lt(this,Zt,e,"f"),lt(this,nr,t,"f"),Z(this,Pt,"m",bo).call(this),this.emit("connect",t)},Nh=function(){lt(this,Zt,null,"f"),lt(this,nr,null,"f"),Z(this,Pt,"m",bo).call(this),this.emit("disconnect")},bo=function(){const e=se.SolanaSignAndSendTransaction in Z(this,_e,"f").features?Z(this,_e,"f").features[se.SolanaSignAndSendTransaction].supportedTransactionVersions:Z(this,_e,"f").features[se.SolanaSignTransaction].supportedTransactionVersions;lt(this,tc,jb.arraysEqual(e,["legacy"])?null:new Set(e),"f"),se.SolanaSignTransaction in Z(this,_e,"f").features&&Z(this,Zt,"f")?.features.includes(se.SolanaSignTransaction)?(this.signTransaction=Z(this,Pt,"m",of),this.signAllTransactions=Z(this,Pt,"m",af)):(delete this.signTransaction,delete this.signAllTransactions),se.SolanaSignMessage in Z(this,_e,"f").features&&Z(this,Zt,"f")?.features.includes(se.SolanaSignMessage)?this.signMessage=Z(this,Pt,"m",cf):delete this.signMessage,se.SolanaSignIn in Z(this,_e,"f").features?this.signIn=Z(this,Pt,"m",lf):delete this.signIn},of=async function(e){try{const t=Z(this,Zt,"f");if(!t)throw new Ke;if(!(se.SolanaSignTransaction in Z(this,_e,"f").features))throw new ln;if(!t.features.includes(se.SolanaSignTransaction))throw new Es;try{const r=(await Z(this,_e,"f").features[se.SolanaSignTransaction].signTransaction({account:t,transaction:ui(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return ui(e)?N.VersionedTransaction.deserialize(r):N.Transaction.from(r)}catch(i){throw i instanceof Mt?i:new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}},af=async function(e){try{const t=Z(this,Zt,"f");if(!t)throw new Ke;if(!(se.SolanaSignTransaction in Z(this,_e,"f").features))throw new ln;if(!t.features.includes(se.SolanaSignTransaction))throw new Es;try{const i=await Z(this,_e,"f").features[se.SolanaSignTransaction].signTransaction(...e.map(r=>({account:t,transaction:ui(r)?r.serialize():new Uint8Array(r.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((r,n)=>{const o=i[n].signedTransaction;return ui(r)?N.VersionedTransaction.deserialize(o):N.Transaction.from(o)})}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}},cf=async function(e){try{const t=Z(this,Zt,"f");if(!t)throw new Ke;if(!(se.SolanaSignMessage in Z(this,_e,"f").features))throw new ln;if(!t.features.includes(se.SolanaSignMessage))throw new Es;try{return(await Z(this,_e,"f").features[se.SolanaSignMessage].signMessage({account:t,message:e}))[0].signature}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}},lf=async function(e={}){try{if(!(se.SolanaSignIn in Z(this,_e,"f").features))throw new ln;let t;try{[t]=await Z(this,_e,"f").features[se.SolanaSignIn].signIn(e)}catch(i){throw new Cu(i?.message,i)}if(!t)throw new Cu;return Z(this,Pt,"m",Ua).call(this,t.account),t}catch(t){throw this.emit("error",t),t}};function Iz(s){return Rb.getWallets().get().filter(zb).map(e=>new li(new vz({wallet:e}),s))}function Ez(s){return s.includes("rpcpool.com")?"triton":s.includes("helius-rpc.com")?"helius":s.includes("rpc.ankr.com")?"ankr":"unknown"}async function Az(s,e,t,i){const r=i.transaction.transaction,n=o=>o.programId.toString()!=="ComputeBudget111111111111111111111111111111";if($a.isVersionedTransaction(r)){const o=(await Promise.all(r.message.addressTableLookups.map(c=>s.getAddressLookupTable(c.accountKey)))).map(c=>c.value).filter(c=>c!==null),a=N.TransactionMessage.decompile(r.message,{addressLookupTableAccounts:o});a.recentBlockhash=e,r.message.recentBlockhash=e,a.instructions=a.instructions.filter(n),r.message=a.compileToV0Message(o),a.instructions.push(...await hf(s,r)),r.message=a.compileToV0Message(o),r.sign(i.transaction.signers??[])}else r.recentBlockhash=e,r.lastValidBlockHeight=t,r.instructions=r.instructions.filter(n),r.add(...await hf(s,r)),i.transaction.signers&&r.partialSign(...i.transaction.signers);return r}async function hf(s,e,t){let i=2e5,r=0;const n=N.ComputeBudgetProgram.setComputeUnitLimit({units:3e5});let o;if($a.isVersionedTransaction(e)){const A=(await Promise.all(e.message.addressTableLookups.map(S=>s.getAddressLookupTable(S.accountKey)))).map(S=>S.value).filter(S=>S!==null),C=N.TransactionMessage.decompile(e.message,{addressLookupTableAccounts:A});C.instructions=[...C.instructions,n],o=new N.VersionedTransaction(C.compileToV0Message(A)),o.signatures=[...e.signatures]}else{const A=new N.Transaction;A.recentBlockhash=e.recentBlockhash,A.feePayer=e.feePayer,A.instructions=[...e.instructions,n],A.signatures=[...e.signatures],o=A}e:for(;;){if($a.isVersionedTransaction(o)&&!o.message.recentBlockhash){const{blockhash:C}=await s.getLatestBlockhash(t);o.message.recentBlockhash=C}const A=await($a.isVersionedTransaction(o)?s.simulateTransaction(o,{commitment:t,replaceRecentBlockhash:!0}):s.simulateTransaction(o));if(A.value.err){if(Nz(A.value)){if(r<5){r++,await Xt.sleep(1e3);continue e}}else if(r<3){r++,await Xt.sleep(1e3);continue e}throw new Error(`Simulation failed: ${JSON.stringify(A.value.err)}
897
+ `,Sa={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};function Qo(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}const Ih=Qo({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"}),Eh=Qo({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"}),JL=Qo({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"});Qo({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Qo({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const ZL={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"]},Cm={getMethodsByChainNamespace(s){return ZL[s]||[]},createDefaultNamespace(s){return{methods:this.getMethodsByChainNamespace(s),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(s,e){if(!e)return{...s};const t={...s},i=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>i.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>i.add(r)),e.events&&Object.keys(e.events).forEach(r=>i.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[n]=r.split(":");n&&i.add(n)}),i.forEach(r=>{t[r]||(t[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,n])=>{t[r]&&(t[r].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([r,n])=>{t[r]&&(t[r].chains=n)}),e.events&&Object.entries(e.events).forEach(([r,n])=>{t[r]&&(t[r].events=n)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,c]=n.split(":");!a||!c||!t[a]||(t[a].rpcMap||(t[a].rpcMap={}),r.has(a)||(t[a].rpcMap={},r.add(a)),t[a].rpcMap[c]=o)})}return t},createNamespaces(s,e){const t=s.reduce((i,r)=>{const{id:n,chainNamespace:o,rpcUrls:a}=r,c=a.default.http[0];i[o]||(i[o]=this.createDefaultNamespace(o));const l=`${o}:${n}`,u=i[o];switch(u.chains.push(l),l){case Ih.caipNetworkId:u.chains.push(Ih.deprecatedCaipNetworkId);break;case Eh.caipNetworkId:u.chains.push(Eh.deprecatedCaipNetworkId);break}return u?.rpcMap&&c&&(u.rpcMap[n]=c),i},{});return this.applyNamespaceOverrides(t,e)},resolveReownName:async s=>{const e=await ey.resolveName(s);return(Object.values(e?.addresses)||[])[0]?.address||!1},getChainsFromNamespaces(s={}){return Object.values(s).flatMap(e=>{const t=e.chains||[],i=e.accounts.map(r=>{const[n,o]=r.split(":");return`${n}:${o}`});return Array.from(new Set([...t,...i]))})},isSessionEventData(s){return typeof s=="object"&&s!==null&&"id"in s&&"topic"in s&&"params"in s&&typeof s.params=="object"&&s.params!==null&&"chainId"in s.params&&"event"in s.params&&typeof s.params.event=="object"&&s.params.event!==null}};class _m{constructor({provider:e,caipNetworks:t,namespace:i}){this.id=ie.CONNECTOR_ID.WALLET_CONNECT,this.name=Ja.ConnectorNamesMap[ie.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Ja.ConnectorImageIds[ie.CONNECTOR_ID.WALLET_CONNECT],this.caipNetworks=t,this.provider=e,this.chain=i}get chains(){return this.caipNetworks}async connectWalletConnect(){if(!await this.authenticate()){const t=R.state.universalProviderConfigOverride,i=Cm.createNamespaces(this.caipNetworks,t);await this.provider.connect({optionalNamespaces:i})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(t=>t.caipNetworkId);return wn.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:XL})}}const XL=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"];class ez{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,e&&this.construct(e)}construct(e){this.caipNetworks=e.networks,this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.caipNetworks||[]}setAuthProvider(e){this.addConnector({id:ie.CONNECTOR_ID.AUTH,type:"AUTH",name:ie.CONNECTOR_NAMES.AUTH,provider:e,imageId:Ja.ConnectorImageIds[ie.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const t=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(i=>t.has(i.id)?!1:(t.add(i.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,t){re.setStatus(e,t)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(t)}off(e,t){const i=this.eventListeners.get(e);i&&i.delete(t)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,t){const i=this.eventListeners.get(e);i&&i.forEach(r=>r(t))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:t,providerType:i}=e;if(!e.provider)return;const r="provider"in e.provider?e.provider.provider:e.provider;if(i==="WALLET_CONNECT"){r.setDefaultChain(t.caipNetworkId);return}if(r&&i==="AUTH"){const n=r;await n.switchNetwork(t.caipNetworkId);const o=await n.getUser({chainId:t.caipNetworkId,preferredAccountType:R.state.defaultAccountTypes[t.chainNamespace]});this.emit("switchNetwork",o)}}getWalletConnectConnector(){const e=this.connectors.find(t=>t instanceof _m);if(!e)throw new Error("WalletConnectConnector not found");return e}}class tz extends ez{setUniversalProvider(e){this.addConnector(new _m({provider:e,caipNetworks:this.caipNetworks||[],namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){const i=this.provider?.session?.namespaces?.[e]?.accounts?.map(r=>{const[,,n]=r.split(":");return n}).filter((r,n,o)=>o.indexOf(r)===n)||[];return Promise.resolve({accounts:i.map(r=>he.createAccount(e,r,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&Ht.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(re.state.balanceLoading&&e.chainId===I.state.activeCaipNetwork?.id)return{balance:re.state.balance||"0.00",symbol:re.state.balanceSymbol||""};const r=(await re.fetchTokenBalance()).find(n=>n.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&n.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:r?.quantity.numeric||"0.00",symbol:r?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:t,message:i,address:r}=e;if(!t)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return I.state.activeCaipNetwork?.chainNamespace===ie.CHAIN.SOLANA?n=(await t.request({method:"solana_signMessage",params:{message:fy.encode(new TextEncoder().encode(i)),pubkey:r}},I.state.activeCaipNetwork?.caipNetworkId)).signature:n=await t.request({method:"personal_sign",params:[i,r]},I.state.activeCaipNetwork?.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async getProfile(){return Promise.resolve({profileImage:"",profileName:""})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}async getEnsAddress(){return Promise.resolve({address:!1})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:t}=e,i=this.getWalletConnectConnector();if(t.chainNamespace===ie.CHAIN.EVM)try{await i.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:gn.toHex(t.id)}]})}catch(r){if(r.code===Sa.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||r.code===Sa.ERROR_INVALID_CHAIN_ID||r.code===Sa.ERROR_CODE_DEFAULT||r?.data?.originalError?.code===Sa.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await i.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:gn.toHex(t.id),rpcUrls:[t?.rpcUrls.chainDefault?.http],chainName:t.name,nativeCurrency:t.nativeCurrency,blockExplorerUrls:[t.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}i.provider.setDefaultChain(t.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(i=>i.type==="WALLET_CONNECT")?.provider}}class sz{constructor(e){this.hasSwitchedToPreferredAccountTypeOnConnect=!1,this.chainNamespaces=[],this.reportedAlertErrors={},this.getCaipNetwork=t=>{if(t){const i=I.getNetworkData(t)?.caipNetwork;return i||I.getRequestedCaipNetworks(t).filter(r=>r.chainNamespace===t)?.[0]}return I.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const t=this.getCaipNetwork();if(t)return t.id},this.getCaipNetworks=t=>I.getRequestedCaipNetworks(t),this.getActiveChainNamespace=()=>I.state.activeChain,this.setRequestedCaipNetworks=(t,i)=>{I.setRequestedCaipNetworks(t,i)},this.getApprovedCaipNetworkIds=()=>I.getAllApprovedCaipNetworkIds(),this.getCaipAddress=t=>I.state.activeChain===t||!t?I.state.activeCaipAddress:I.getAccountProp("caipAddress",t),this.setClientId=t=>{oe.setClientId(t)},this.getProvider=t=>tt.getProvider(t),this.getProviderType=t=>tt.getProviderId(t),this.getPreferredAccountType=()=>re.state.preferredAccountType,this.setCaipAddress=(t,i)=>{re.setCaipAddress(t,i)},this.setBalance=(t,i,r)=>{re.setBalance(t,i,r)},this.setProfileName=(t,i)=>{re.setProfileName(t,i)},this.setProfileImage=(t,i)=>{re.setProfileImage(t,i)},this.setUser=(t,i)=>{re.setUser(t,i),R.state.enableEmbedded&&ot.close()},this.resetAccount=t=>{re.resetAccount(t)},this.setCaipNetwork=t=>{I.setActiveCaipNetwork(t)},this.setCaipNetworkOfNamespace=(t,i)=>{I.setChainNetworkData(i,{caipNetwork:t})},this.setAllAccounts=(t,i)=>{re.setAllAccounts(t,i),R.setHasMultipleAddresses(t?.length>1)},this.setStatus=(t,i)=>{re.setStatus(t,i),le.isConnected()?X.setConnectionStatus("connected"):X.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=t=>I.getAccountProp("address",t),this.setConnectors=t=>{const i=[...le.getConnectors(),...t];le.setConnectors(i)},this.fetchIdentity=t=>oe.fetchIdentity(t),this.getReownName=t=>ey.getNamesForAddress(t),this.getConnectors=()=>le.getConnectors(),this.getConnectorImage=t=>Bh.getConnectorImage(t),this.setConnectedWalletInfo=(t,i)=>{const r=tt.getProviderId(i),n=t?{...t,type:r}:void 0;re.setConnectedWalletInfo(n,i)},this.getIsConnectedState=()=>!!I.state.activeCaipAddress,this.addAddressLabel=(t,i,r)=>{re.addAddressLabel(t,i,r)},this.removeAddressLabel=(t,i)=>{re.removeAddressLabel(t,i)},this.getAddress=t=>I.state.activeChain===t||!t?re.state.address:I.getAccountProp("address",t),this.setApprovedCaipNetworksData=t=>I.setApprovedCaipNetworksData(t),this.resetNetwork=t=>{I.resetNetwork(t)},this.addConnector=t=>{le.addConnector(t)},this.resetWcConnection=()=>{qe.resetWcConnection()},this.setAddressExplorerUrl=(t,i)=>{re.setAddressExplorerUrl(t,i)},this.setSmartAccountDeployed=(t,i)=>{re.setSmartAccountDeployed(t,i)},this.setSmartAccountEnabledNetworks=(t,i)=>{I.setSmartAccountEnabledNetworks(t,i)},this.setPreferredAccountType=(t,i)=>{re.setPreferredAccountType(t,i)},this.setEIP6963Enabled=t=>{R.setEIP6963Enabled(t)},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=[...new Set(this.caipNetworks?.map(t=>t.chainNamespace))],this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.initialize(e),this.sendInitializeEvent(e)}async initialize(e){this.initControllers(e),await this.initChainAdapters(),await this.injectModalUi(),await this.syncExistingConnection(),pi.set({initialized:!0})}sendInitializeEvent(e){const{...t}=e;delete t.adapters,Be.sendEvent({type:"track",event:"INITIALIZE",properties:{...t,networks:e.networks.map(i=>i.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&Lt.setThemeMode(e.themeMode),e.themeVariables&&Lt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");I.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const t=this.getDefaultNetwork();t&&I.setActiveCaipNetwork(t)}initializeConnectionController(e){qe.setWcBasic(e.basic??!1)}initializeConnectorController(){le.initialize(this.chainNamespaces)}initializeOptionsController(e){R.setDebug(e.debug!==!1),R.setEnableWalletConnect(e.enableWalletConnect!==!1),R.setEnableWalletGuide(e.enableWalletGuide!==!1),R.setEnableWallets(e.enableWallets!==!1),R.setEIP6963Enabled(e.enableEIP6963!==!1),R.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),R.setEnableAuthLogger(e.enableAuthLogger!==!1),R.setCustomRpcUrls(e.customRpcUrls),R.setSdkVersion(e.sdkVersion),R.setProjectId(e.projectId),R.setEnableEmbedded(e.enableEmbedded),R.setAllWallets(e.allWallets),R.setIncludeWalletIds(e.includeWalletIds),R.setExcludeWalletIds(e.excludeWalletIds),R.setFeaturedWalletIds(e.featuredWalletIds),R.setTokens(e.tokens),R.setTermsConditionsUrl(e.termsConditionsUrl),R.setPrivacyPolicyUrl(e.privacyPolicyUrl),R.setCustomWallets(e.customWallets),R.setFeatures(e.features),R.setAllowUnsupportedChain(e.allowUnsupportedChain),R.setDefaultAccountTypes(e.defaultAccountTypes),R.setUniversalProviderConfigOverride(e.universalProviderConfigOverride);const t=this.getDefaultMetaData();if(!e.metadata&&t&&(e.metadata=t),R.setMetadata(e.metadata),R.setDisableAppend(e.disableAppend),R.setEnableEmbedded(e.enableEmbedded),R.setSIWX(e.siwx),!e.projectId){po.open(_a.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(r=>r.namespace===ie.CHAIN.EVM)&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");R.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return typeof window<"u"&&typeof document<"u"?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const t=this.getActiveChainNamespace();if(t){const i=cn.getUnsupportedNetwork(`${t}:${e}`);I.setActiveCaipNetwork(i)}}getDefaultNetwork(){return cn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return cn.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return cn.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const t=e.networks.find(r=>r.id===e.defaultNetwork?.id);return t?cn.extendCaipNetwork(t,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=I.state.activeChain,t=this.getAdapter(e),i=this.getCaipNetwork(e)?.id;if(!t)throw new Error("Adapter not found");const r=await t.connectWalletConnect(i);this.close(),this.setClientId(r?.clientId||null),X.setConnectedNamespaces([...I.state.chains.keys()]),this.chainNamespaces.forEach(n=>{le.setConnectorId(Ni.CONNECTOR_TYPE_WALLET_CONNECT,n)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:t,type:i,provider:r,chain:n,caipNetwork:o})=>{const a=I.state.activeChain,c=n||a,l=this.getAdapter(c);if(n&&n!==a&&!o){const f=this.caipNetworks?.find(g=>g.chainNamespace===n);f&&this.setCaipNetwork(f)}if(!l)throw new Error("Adapter not found");const u=this.getCaipNetwork(c),d=await l.connect({id:e,info:t,type:i,provider:r,chainId:o?.id||u?.id,rpcUrl:o?.rpcUrls?.default?.http?.[0]||u?.rpcUrls?.default?.http?.[0]});if(!d)return;X.addConnectedNamespace(c),this.syncProvider({...d,chainNamespace:c}),await this.syncAccount({...d,chainNamespace:c});const{accounts:p}=await l.getAccounts({namespace:c,id:e});this.setAllAccounts(p,c)},reconnectExternal:async({id:e,info:t,type:i,provider:r})=>{const n=I.state.activeChain,o=this.getAdapter(n);o?.reconnect&&(await o?.reconnect({id:e,info:t,type:i,provider:r,chainId:this.getCaipNetwork()?.id}),X.addConnectedNamespace(n))},disconnect:async e=>{const t=e||I.state.activeChain,i=this.getAdapter(t),r=tt.getProvider(t),n=tt.getProviderId(t);await i?.disconnect({provider:r,providerType:n}),X.removeConnectedNamespace(t),tt.resetChain(t),this.setUser(void 0,t),this.setStatus("disconnected",t),this.hasSwitchedToPreferredAccountTypeOnConnect=!1},checkInstalled:e=>e?e.some(t=>!!window.ethereum?.[String(t)]):!!window.ethereum,signMessage:async e=>(await this.getAdapter(I.state.activeChain)?.signMessage({message:e,address:re.state.address,provider:tt.getProvider(I.state.activeChain)}))?.signature||"",sendTransaction:async e=>{if(e.chainNamespace===ie.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=tt.getProvider(I.state.activeChain);return(await t?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}))?.hash||""}return""},estimateGas:async e=>{if(e.chainNamespace===ie.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=tt.getProvider(I.state.activeChain),r=this.getCaipNetwork();if(!r)throw new Error("CaipNetwork is undefined");return(await t?.estimateGas({...e,provider:i,caipNetwork:r}))?.gas||0n}return 0n},getEnsAvatar:async()=>(await this.getAdapter(I.state.activeChain)?.getProfile({address:re.state.address,chainId:Number(this.getCaipNetwork()?.id)}))?.profileImage||!1,getEnsAddress:async e=>{const t=this.getAdapter(I.state.activeChain),i=this.getCaipNetwork();return i&&(await t?.getEnsAddress({name:e,caipNetwork:i}))?.address||!1},writeContract:async e=>{const t=this.getAdapter(I.state.activeChain),i=this.getCaipNetwork(),r=this.getCaipAddress(),n=tt.getProvider(I.state.activeChain);if(!i||!r)throw new Error("CaipNetwork or CaipAddress is undefined");return(await t?.writeContract({...e,caipNetwork:i,provider:n,caipAddress:r}))?.hash},parseUnits:(e,t)=>this.getAdapter(I.state.activeChain)?.parseUnits({value:e,decimals:t})??0n,formatUnits:(e,t)=>this.getAdapter(I.state.activeChain)?.formatUnits({value:e,decimals:t})??"0",getCapabilities:async e=>await this.getAdapter(I.state.activeChain)?.getCapabilities(e),grantPermissions:async e=>await this.getAdapter(I.state.activeChain)?.grantPermissions(e),revokePermissions:async e=>{const t=this.getAdapter(I.state.activeChain);return t?.revokePermissions?await t.revokePermissions(e):"0x"},walletGetAssets:async e=>await this.getAdapter(I.state.activeChain)?.walletGetAssets(e)??{}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},qe.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){if(tt.getProviderId(I.state.activeChain)===Ni.CONNECTOR_TYPE_WALLET_CONNECT){const t=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(t)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const t=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=tt.getProvider(t),n=tt.getProviderId(t);if(e.chainNamespace===I.state.activeChain)await this.getAdapter(t)?.switchNetwork({caipNetwork:e,provider:r,providerType:n});else if(this.setCaipNetwork(e),n===Ni.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(t);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:t})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(t=>{const i=t.chains||[],r=t.accounts.map(n=>{const{chainId:o,chainNamespace:a}=vi.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...i,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((t,i)=>{const r=e?.find(n=>n.namespace===i);return r?(t[i]=r,t[i].namespace=i,t[i].construct({namespace:i,projectId:this.options?.projectId,networks:this.caipNetworks})):t[i]=new tz({namespace:i,networks:this.caipNetworks}),t},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e),this.chainAdapters?.[e].syncConnectors(this.options,this),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){this.getAdapter(e)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const t=this.getAdapter(e);if(!t)return;const i=X.getConnectionStatus();i==="connected"?this.setStatus("connecting",e):i==="disconnected"?(X.clearAddressCache(),this.setStatus(i,e)):this.setStatus(i,e),t.on("switchNetwork",({address:r,chainId:n})=>{const o=this.caipNetworks?.find(l=>l.id===n||l.caipNetworkId===n),a=I.state.activeChain===e,c=I.getAccountProp("address",e);if(o){const l=a&&r?r:c;l&&this.syncAccount({address:l,chainId:n,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),t.on("disconnect",this.disconnect.bind(this,e)),t.on("pendingTransactions",()=>{const r=re.state.address,n=I.state.activeCaipNetwork;!r||!n?.id||this.updateNativeBalance(r,n.id,n.chainNamespace)}),t.on("accountChanged",({address:r,chainId:n})=>{const o=I.state.activeChain===e;o&&n?this.syncAccount({address:r,chainId:n,chainNamespace:e}):o&&I.state.activeCaipNetwork?.id?this.syncAccount({address:r,chainId:I.state.activeCaipNetwork?.id,chainNamespace:e}):this.syncAccountInfo(r,n,e)})}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{const t=le.getConnectorId(e);switch(this.setStatus("connecting",e),t){case ie.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case ie.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(t){console.warn("AppKit couldn't sync existing connection",t),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){const t=this.getAdapter(e),i=le.getConnectorId(e),r=this.getCaipNetwork(e),n=le.getConnectors(e).find(o=>o.id===i);try{if(!t||!n)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!r?.id)throw new Error("CaipNetwork not found");const o=await t?.syncConnection({namespace:e,id:n.id,chainId:r.id,rpcUrl:r?.rpcUrls?.default?.http?.[0]});if(o){const a=await t?.getAccounts({namespace:e,id:n.id});a&&a.accounts.length>0?this.setAllAccounts(a.accounts,e):this.setAllAccounts([he.createAccount(e,o.address,"eoa")],e),this.syncProvider({...o,chainNamespace:e}),await this.syncAccount({...o,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async t=>{const i=this.getAdapter(t),r=this.universalProvider?.session?.namespaces?.[t]?.accounts||[],n=I.state.activeCaipNetwork?.id,o=r.find(a=>{const{chainId:c}=vi.parseCaipAddress(a);return c===n?.toString()})||r[0];if(o){const a=vi.validateCaipAddress(o),{chainId:c,address:l}=vi.parseCaipAddress(a);if(tt.setProviderId(t,Ni.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&I.state.activeCaipNetwork&&i?.namespace!==ie.CHAIN.EVM){const u=i?.getWalletConnectProvider({caipNetworks:this.caipNetworks,provider:this.universalProvider,activeCaipNetwork:I.state.activeCaipNetwork});tt.setProvider(t,u)}else tt.setProvider(t,this.universalProvider);le.setConnectorId(ie.CONNECTOR_ID.WALLET_CONNECT,t),X.addConnectedNamespace(t),this.syncWalletConnectAccounts(t),await this.syncAccount({address:l,chainId:c,chainNamespace:t})}else this.setStatus("disconnected",t);await I.setApprovedCaipNetworksData(t)});await Promise.all(e)}syncWalletConnectAccounts(e){const t=this.universalProvider?.session?.namespaces?.[e]?.accounts?.map(i=>{const{address:r}=vi.parseCaipAddress(i);return r}).filter((i,r,n)=>n.indexOf(i)===r);t&&this.setAllAccounts(t.map(i=>he.createAccount(e,i,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:t,id:i,chainNamespace:r}){tt.setProviderId(r,e),tt.setProvider(r,t),le.setConnectorId(i,r)}async syncAccount(e){const t=e.chainNamespace===I.state.activeChain,i=I.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:n,chainNamespace:o}=e,{chainId:a}=X.getActiveNetworkProps(),c=n||a,l=I.state.activeCaipNetwork?.name===ie.UNSUPPORTED_NETWORK_NAME,u=I.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!u)&&c){let d=this.caipNetworks?.find(g=>g.id.toString()===c.toString()),p=this.caipNetworks?.find(g=>g.chainNamespace===o);if(!u&&!d&&!p){const g=this.getApprovedCaipNetworkIds()||[],w=g.find(v=>vi.parseCaipNetworkId(v)?.chainId===c.toString()),b=g.find(v=>vi.parseCaipNetworkId(v)?.chainNamespace===o);d=this.caipNetworks?.find(v=>v.caipNetworkId===w),p=this.caipNetworks?.find(v=>v.caipNetworkId===b||"deprecatedCaipNetworkId"in v&&v.deprecatedCaipNetworkId===b)}const f=d||p;f?.chainNamespace===I.state.activeChain?R.state.enableNetworkSwitch&&!R.state.allowUnsupportedChain&&I.state.activeCaipNetwork?.name===ie.UNSUPPORTED_NETWORK_NAME?I.showUnsupportedChainUI():this.setCaipNetwork(f):t||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),Em.isLowerCaseMatch(r,re.state.address)||this.syncAccountInfo(r,f?.id,o),t?await this.syncBalance({address:r,chainId:f?.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:i?.id,chainNamespace:o})}}async syncAccountInfo(e,t,i){const r=this.getCaipAddress(i),n=t||r?.split(":")[1];if(!n)return;const o=`${i}:${n}:${e}`;this.setCaipAddress(o,i),await this.syncIdentity({address:e,chainId:n,chainNamespace:i})}async syncReownName(e,t){try{const i=await this.getReownName(e);if(i[0]){const r=i[0];this.setProfileName(r.name,t)}else this.setProfileName(null,t)}catch{this.setProfileName(null,t)}}syncConnectedWalletInfo(e){const t=le.getConnectorId(e),i=tt.getProviderId(e);if(i===Ni.CONNECTOR_TYPE_ANNOUNCED||i===Ni.CONNECTOR_TYPE_INJECTED){if(t){const r=this.getConnectors().find(n=>n.id===t);if(r){const{info:n,name:o,imageUrl:a}=r,c=a||this.getConnectorImage(r);this.setConnectedWalletInfo({name:o,icon:c,...n},e)}}}else if(i===Ni.CONNECTOR_TYPE_WALLET_CONNECT){const r=tt.getProvider(e);r?.session&&this.setConnectedWalletInfo({...r.session.peer.metadata,name:r.session.peer.metadata.name,icon:r.session.peer.metadata.icons?.[0]},e)}else if(t)if(t===ie.CONNECTOR_ID.COINBASE){const r=this.getConnectors().find(n=>n.id===ie.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(r)},e)}else this.setConnectedWalletInfo({name:t},e)}async syncBalance(e){!Jw.getNetworksByNamespace(this.caipNetworks,e.chainNamespace).find(i=>i.id.toString()===e.chainId?.toString())||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async updateNativeBalance(e,t,i){const r=this.getAdapter(i);if(r){const n=await r.getBalance({address:e,chainId:t,caipNetwork:this.getCaipNetwork(i),tokens:this.options.tokens});this.setBalance(n.balance,n.symbol,i)}}async initializeUniversalAdapter(){const e=BL.createLogger((i,...r)=>{i&&this.handleAlertError(i),console.error(...r)}),t={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};R.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await ru.init(t),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{qe.setUri(e)}),this.universalProvider.on("connect",qe.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),qe.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const t=this.caipNetworks?.find(r=>r.id==e),i=this.getCaipNetwork();if(!t){this.setUnsupportedNetwork(e);return}i?.id!==t?.id&&this.setCaipNetwork(t)}),this.universalProvider.on("session_event",e=>{if(Cm.isSessionEventData(e)){const{name:t,data:i}=e.params.event;t==="accountsChanged"&&Array.isArray(i)&&he.isCaipAddress(i[0])&&this.syncAccount(vi.parseCaipAddress(i[0]))}}))}createUniversalProvider(){return!this.universalProviderInitPromise&&he.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Be.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const t=Object.entries(_a.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[i,r]=t??[],{message:n,alertErrorKey:o}=r??{};if(i&&n&&!this.reportedAlertErrors[i]){const a=_a.ALERT_ERRORS[o];a&&(po.open(a,"error"),this.reportedAlertErrors[i]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const t=e.namespace;if(!t)return;this.createClients();const i=e;i.namespace=t,i.construct({namespace:t,projectId:this.options?.projectId,networks:this.caipNetworks}),this.chainNamespaces.includes(t)||this.chainNamespaces.push(t),this.chainAdapters&&(this.chainAdapters[t]=i)}async open(e){await this.injectModalUi(),e?.uri&&qe.setUri(e.uri),await ot.open(e)}async close(){await this.injectModalUi(),ot.close()}setLoading(e,t){ot.setLoading(e,t)}async disconnect(e){await qe.disconnect(e)}getError(){return""}getChainId(){return I.state.activeCaipNetwork?.id}async switchNetwork(e){const t=this.caipNetworks?.find(i=>i.id===e.id);if(!t){po.open(_a.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await I.switchActiveNetwork(t)}getWalletProvider(){return I.state.activeChain?tt.state.providers[I.state.activeChain]:null}getWalletProviderType(){return tt.getProviderId(I.state.activeChain)}subscribeProviders(e){return tt.subscribeProviders(e)}getThemeMode(){return Lt.state.themeMode}getThemeVariables(){return Lt.state.themeVariables}setThemeMode(e){Lt.setThemeMode(e),Nm(Lt.state.themeMode)}setTermsConditionsUrl(e){R.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){R.setPrivacyPolicyUrl(e)}setThemeVariables(e){Lt.setThemeVariables(e),KL(Lt.state.themeVariables)}subscribeTheme(e){return Lt.subscribe(e)}getWalletInfo(){return re.state.connectedWalletInfo}getAccount(e){const t=le.getAuthConnector(e),i=I.getAccountData(e);if(i)return{allAccounts:i.allAccounts,caipAddress:i.caipAddress,address:he.getPlainAddress(i.caipAddress),isConnected:!!i.caipAddress,status:i.status,embeddedWalletInfo:t?{user:i.user,authProvider:i.socialProvider||"email",accountType:i.preferredAccountType,isSmartAccountDeployed:!!i.smartAccountDeployed}:void 0}}subscribeAccount(e,t){const i=()=>{const r=this.getAccount(t);r&&e(r)};t?I.subscribeChainProp("accountState",i,t):I.subscribe(i),le.subscribe(i)}subscribeNetwork(e){return I.subscribe(({activeCaipNetwork:t})=>{e({caipNetwork:t,chainId:t?.id,caipNetworkId:t?.caipNetworkId})})}subscribeWalletInfo(e){return re.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){re.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){I.subscribeKey("activeCaipNetwork",e)}getState(){return pi.state}subscribeState(e){return pi.subscribe(e)}showErrorMessage(e){vt.showError(e)}showSuccessMessage(e){vt.showSuccess(e)}getEvent(){return{...Be.state}}subscribeEvents(e){return Be.subscribe(e)}replace(e){Me.replace(e)}redirect(e){Me.push(e)}popTransactionStack(e){Me.popTransactionStack(e)}isOpen(){return ot.state.open}isTransactionStackEmpty(){return Me.state.transactionStack.length===0}isTransactionShouldReplaceView(){return Me.state.transactionStack[Me.state.transactionStack.length-1]?.replace}static getInstance(){return this.instance}updateFeatures(e){R.setFeatures(e)}updateOptions(e){const i={...R.state||{},...e};R.setOptions(i)}setConnectMethodsOrder(e){R.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){R.setWalletFeaturesOrder(e)}setCollapseWallets(e){R.setCollapseWallets(e)}setSocialsOrder(e){R.setSocialsOrder(e)}getConnectMethodsOrder(){return Xa.getConnectOrderMethod(R.state.features,le.getConnectors())}removeAdapter(e){const t=this.getIsConnectedState(),i=this.getAdapter(e);if(!i||!this.chainAdapters||t)return;const r=this.caipNetworks?.filter(n=>n.chainNamespace!==e);I.removeAdapter(e),le.removeAdapter(e),this.chainNamespaces=this.chainNamespaces.filter(n=>n!==e),this.caipNetworks=r,i.removeAllEventListeners(),Reflect.deleteProperty(this.chainAdapters,e)}addAdapter(e,t){const i=e.namespace;if(!this.connectionControllerClient||!this.networkControllerClient||!this.chainAdapters||!i)return;const r=this.extendCaipNetworks({...this.options,networks:t});this.caipNetworks=[...this.caipNetworks||[],...r],this.createAdapter(e),this.initChainAdapter(i),I.addAdapter(e,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient},r)}addNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const i=this.extendCaipNetwork(t,this.options);I.addNetwork(i),this.caipNetworks&&!this.caipNetworks?.find(r=>r.id===i.id)&&this.caipNetworks.push(i)}removeNetwork(e,t){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);if(!this.caipNetworks?.find(n=>n.id===t))throw new Error(`Network with ID ${t} not found`);if(!this.caipNetworks)return;const r=this.caipNetworks.filter(n=>n.chainNamespace===e&&n.id!==t);if(!r?.length)throw new Error("Cannot remove last network for a namespace");I.removeNetwork(e,t),this.caipNetworks=[...r]}}let tf=!1;class iz extends sz{async open(e){le.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&qe.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!tf&&he.isClient()){if(await Promise.resolve().then(()=>require("./basic-B3aoOwRb.js")),await Promise.resolve().then(()=>require("./w3m-modal-BUP-c20y.js")),!document.querySelector("w3m-modal")){const t=document.createElement("w3m-modal");!R.state.disableAppend&&!R.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",t)}tf=!0}}}const rz="1.7.2";function nz(s){return new iz({...s,basic:!0,sdkVersion:`html-core-${rz}`})}function oz(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const u=s.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,u++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let m=l[p],A=0;for(let C=g-1;(m!==0||A<d)&&C!==-1;C--,A++)m+=256*w[C]>>>0,w[C]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let b=g-d;for(;b!==g&&w[b]===0;)b++;let v=i.repeat(u);for(;b<g;++b)v+=s.charAt(w[b]);return v}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,p=0;for(;l[u]===i;)d++,u++;const f=(l.length-u)*r+1>>>0,g=new Uint8Array(f);for(;u<l.length;){const m=l.charCodeAt(u);if(m>255)return;let A=e[m];if(A===255)return;let C=0;for(let S=f-1;(A!==0||C<p)&&S!==-1;S--,C++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=C,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const b=new Uint8Array(d+(f-w));let v=d;for(;w!==f;)b[v++]=g[w++];return b}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var az="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Il=oz(az);class pn extends Error{constructor(){super(),Object.setPrototypeOf(this,pn.prototype)}}class sf extends Error{constructor(e){super(`WalletConnect Adapter - Method ${e} is not supported by the wallet`),this.name="WalletConnectFeatureNotSupportedError"}}function cz(s){let e=[s];return s===gt.Mainnet||s===gt.Deprecated_Mainnet?(e=[gt.Mainnet,gt.Deprecated_Mainnet],s===gt.Deprecated_Mainnet&&console.warn(ec.mainnet)):(s===gt.Deprecated_Devnet||s===gt.Devnet)&&(e=[gt.Devnet,gt.Deprecated_Devnet],console.warn(ec.devnet)),e}const ec={mainnet:`You are using a deprecated chain ID for Solana Mainnet, please use ${gt.Mainnet} instead.`,devnet:`You are using a deprecated chain ID for Solana Devnet, please use ${gt.Devnet} instead.`,wallet:"The connected wallet is using a deprecated chain ID for Solana. Please, contact them to upgrade. You can learn more at https://github.com/ChainAgnostic/namespaces/blob/main/solana/caip10.md#chain-ids"};function rf(s,e){const t=s.namespaces.solana?.accounts.map(i=>`solana:${i.split(":")[1]}`);if(e===gt.Mainnet)return t?.find(i=>i===gt.Mainnet)?gt.Mainnet:(console.warn(ec.wallet),gt.Deprecated_Mainnet);if(e===gt.Devnet)return t?.find(i=>i===gt.Devnet)?gt.Devnet:(console.warn(ec.wallet),gt.Deprecated_Devnet);throw Error("WalletConnect Solana Adapter: Unable to get a default chain from the session.")}function lz(s){return{optionalNamespaces:{solana:{chains:cz(s),methods:[vs.signTransaction,vs.signMessage],events:[]}}}}class nu extends Error{constructor(){super("QR Code Modal was closed by user"),Object.setPrototypeOf(this,nu.prototype),this.name="QRCodeModalError"}}class hz{_UniversalProvider;_session;_modal;_projectId;_network;_ConnectQueueResolver;constructor(e){if(this.initClient(e.options),this._network=e.network,!e.options.projectId)throw Error("WalletConnect Adapter: Project ID is undefined");this._projectId=e.options.projectId}async connect(){if(this._UniversalProvider||await new Promise(r=>{this._ConnectQueueResolver=r}),!this._UniversalProvider)throw new Error("WalletConnect Adapter - Universal Provider was undefined while calling 'connect()'");if(this._UniversalProvider.session){this._session=this._UniversalProvider.session;const r=rf(this._session,this._network);return this._network=r,this._UniversalProvider.setDefaultChain(r),{publicKey:this.publicKey}}await this.initModal();const e=lz(this._network);this._modal?.open();const t=new AbortController,i=t.signal;this._modal?.subscribeState(r=>{r.open||t.abort(new nu)});try{const r=await Promise.race([this._UniversalProvider?.connect(e),new Promise((o,a)=>{i.addEventListener("abort",()=>{a(i.reason)})})]);if(this._modal?.close(),this._session=r,!r)throw new ic;const n=rf(r,this._network);return this._network=n,this._UniversalProvider?.setDefaultChain(n),{publicKey:this.publicKey}}catch(r){throw this._modal?.close(),r}}async disconnect(){if(this._UniversalProvider?.session){if(await this.initModal(),!this._modal)throw Error("WalletConnect Adapter -Modal is undefined: unable to disconnect");await this.client.disconnect(),this._session=void 0}else throw new pn}get client(){if(this._UniversalProvider)return this._UniversalProvider;throw new pn}get session(){if(!this._session)throw new pn;return this._session}get publicKey(){if(this._UniversalProvider?.session&&this._session){const{address:e}=c0(this._session?.namespaces.solana?.accounts[0]??"");return new N.PublicKey(e)}throw new pn}async signTransaction(e){this.checkIfWalletSupportsMethod(vs.signTransaction);const t=ui(e),i=t?{}:e,{signature:r,transaction:n}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:vs.signTransaction,params:{...i,transaction:this.serialize(e)}}});return n?this.deserialize(n,t):(e.addSignature(this.publicKey,N.Buffer.from(Il.decode(r))),e)}async signMessage(e){this.checkIfWalletSupportsMethod(vs.signMessage);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:vs.signMessage,params:{pubkey:this.publicKey.toString(),message:Il.encode(e)}}});return Il.decode(t)}async signAndSendTransaction(e){this.checkIfWalletSupportsMethod(vs.signAndSendTransaction);const{signature:t}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:vs.signAndSendTransaction,params:{transaction:this.serialize(e)}}});return t}async signAllTransactions(e){try{this.checkIfWalletSupportsMethod(vs.signAllTransactions);const t=e.map(r=>this.serialize(r)),{transactions:i}=await this.client.client.request({chainId:this._network,topic:this.session.topic,request:{method:vs.signAllTransactions,params:{transactions:t}}});return e.map((r,n)=>ui(r)?this.deserialize(i[n]??"",!0):this.deserialize(i[n]??""))}catch(t){if(t instanceof sf){const i=e.map(n=>this.signTransaction(n));return await Promise.all(i)}throw t}}async initClient(e){const t=await TM.init(e);this._UniversalProvider=t,this._ConnectQueueResolver&&this._ConnectQueueResolver(!0)}async initModal(){if(!this._modal){if(!this._UniversalProvider)throw new Error("WalletConnect Adapter - cannot init modal when Universal Provider is undefined");this._modal=nz({projectId:this._projectId,universalProvider:this._UniversalProvider,networks:[Ih,Eh,JL],manualWCControl:!0})}}serialize(e){return N.Buffer.from(e.serialize({verifySignatures:!1})).toString("base64")}deserialize(e,t=!1){return t?N.VersionedTransaction.deserialize(N.Buffer.from(e,"base64")):N.Transaction.from(N.Buffer.from(e,"base64"))}checkIfWalletSupportsMethod(e){if(!this.session.namespaces.solana?.methods.includes(e))throw new sf(e)}}const uz="WalletConnect";class dz extends _h{name=uz;url="https://walletconnect.org";icon="data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjE4NSIgdmlld0JveD0iMCAwIDMwMCAxODUiIHdpZHRoPSIzMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0ibTYxLjQzODU0MjkgMzYuMjU2MjYxMmM0OC45MTEyMjQxLTQ3Ljg4ODE2NjMgMTI4LjIxMTk4NzEtNDcuODg4MTY2MyAxNzcuMTIzMjA5MSAwbDUuODg2NTQ1IDUuNzYzNDE3NGMyLjQ0NTU2MSAyLjM5NDQwODEgMi40NDU1NjEgNi4yNzY1MTEyIDAgOC42NzA5MjA0bC0yMC4xMzY2OTUgMTkuNzE1NTAzYy0xLjIyMjc4MSAxLjE5NzIwNTEtMy4yMDUzIDEuMTk3MjA1MS00LjQyODA4MSAwbC04LjEwMDU4NC03LjkzMTE0NzljLTM0LjEyMTY5Mi0zMy40MDc5ODE3LTg5LjQ0Mzg4Ni0zMy40MDc5ODE3LTEyMy41NjU1Nzg4IDBsLTguNjc1MDU2MiA4LjQ5MzYwNTFjLTEuMjIyNzgxNiAxLjE5NzIwNDEtMy4yMDUzMDEgMS4xOTcyMDQxLTQuNDI4MDgwNiAwbC0yMC4xMzY2OTQ5LTE5LjcxNTUwMzFjLTIuNDQ1NTYxMi0yLjM5NDQwOTItMi40NDU1NjEyLTYuMjc2NTEyMiAwLTguNjcwOTIwNHptMjE4Ljc2Nzc5NjEgNDAuNzczNzQ0OSAxNy45MjE2OTcgMTcuNTQ2ODk3YzIuNDQ1NTQ5IDIuMzk0Mzk2OSAyLjQ0NTU2MyA2LjI3NjQ3NjkuMDAwMDMxIDguNjcwODg5OWwtODAuODEwMTcxIDc5LjEyMTEzNGMtMi40NDU1NDQgMi4zOTQ0MjYtNi40MTA1ODIgMi4zOTQ0NTMtOC44NTYxNi4wMDAwNjItLjAwMDAxLS4wMDAwMS0uMDAwMDIyLS4wMDAwMjItLjAwMDAzMi0uMDAwMDMybC01Ny4zNTQxNDMtNTYuMTU0NTcyYy0uNjExMzktLjU5ODYwMi0xLjYwMjY1LS41OTg2MDItMi4yMTQwNCAwLS4wMDAwMDQuMDAwMDA0LS4wMDAwMDcuMDAwMDA4LS4wMDAwMTEuMDAwMDExbC01Ny4zNTI5MjEyIDU2LjE1NDUzMWMtMi40NDU1MzY4IDIuMzk0NDMyLTYuNDEwNTc1NSAyLjM5NDQ3Mi04Ljg1NjE2MTIuMDAwMDg3LS4wMDAwMTQzLS4wMDAwMTQtLjAwMDAyOTYtLjAwMDAyOC0uMDAwMDQ0OS0uMDAwMDQ0bC04MC44MTI0MTk0My03OS4xMjIxODVjLTIuNDQ1NTYwMjEtMi4zOTQ0MDgtMi40NDU1NjAyMS02LjI3NjUxMTUgMC04LjY3MDkxOTdsMTcuOTIxNzI5NjMtMTcuNTQ2ODY3M2MyLjQ0NTU2MDItMi4zOTQ0MDgyIDYuNDEwNTk4OS0yLjM5NDQwODIgOC44NTYxNjAyIDBsNTcuMzU0OTc3NSA1Ni4xNTUzNTdjLjYxMTM5MDguNTk4NjAyIDEuNjAyNjQ5LjU5ODYwMiAyLjIxNDAzOTggMCAuMDAwMDA5Mi0uMDAwMDA5LjAwMDAxNzQtLjAwMDAxNy4wMDAwMjY1LS4wMDAwMjRsNTcuMzUyMTAzMS01Ni4xNTUzMzNjMi40NDU1MDUtMi4zOTQ0NjMzIDYuNDEwNTQ0LTIuMzk0NTUzMSA4Ljg1NjE2MS0uMDAwMi4wMDAwMzQuMDAwMDMzNi4wMDAwNjguMDAwMDY3My4wMDAxMDEuMDAwMTAxbDU3LjM1NDkwMiA1Ni4xNTU0MzJjLjYxMTM5LjU5ODYwMSAxLjYwMjY1LjU5ODYwMSAyLjIxNDA0IDBsNTcuMzUzOTc1LTU2LjE1NDMyNDljMi40NDU1NjEtMi4zOTQ0MDkyIDYuNDEwNTk5LTIuMzk0NDA5MiA4Ljg1NjE2IDB6IiBmaWxsPSIjM2I5OWZjIi8+PC9zdmc+";supportedTransactionVersions=new Set(["legacy",0]);_publicKey;_connecting;_wallet;_config;_readyState;_onDisconnect;constructor(e){super(),this._publicKey=null,this._connecting=!1,this._config=e,this._wallet=null,this._readyState=typeof window>"u"?ge.Unsupported:ge.Loadable,this._onDisconnect=this.disconnect.bind(this)}get publicKey(){return this._publicKey}get connecting(){return this._connecting}get readyState(){return this._readyState}async connect(){try{if(this.connected||this.connecting)return;if(this._readyState!==ge.Loadable)throw new Ri;this._connecting=!0,this._wallet=new hz({network:this._config.network===vo.Mainnet?La.Mainnet:La.Devnet,options:this._config.options});const{publicKey:e}=await this._wallet.connect();this._publicKey=e,this.emit("connect",e),this._wallet.client.on("session_delete",this._onDisconnect)}catch(e){throw e.constructor.name==="QRCodeModalError"||e instanceof Error&&e.name==="QRCodeModalError"?new Lb:(this._connecting=!1,e)}finally{this._connecting=!1}}async disconnect(){const e=this._wallet;if(e){e.client.off("session_delete",this._onDisconnect),this._publicKey=null;try{e.client.session&&await e.disconnect()}catch(t){console.error("WalletConnectWalletAdapter: disconnect error",t),this.emit("error",new xo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signTransaction(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signMessage(e)}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAndSendTransaction(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAndSendTransaction(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ke;try{return await t.signAllTransactions(e)}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const pz={icon:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgdmlld0JveD0iMCAwIDI1NiAyNTYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8yMDM1XzExMDYpIj4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IiM1NEZGRjUiLz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTEzLjQ4MDYgMTk4LjYwNUMtMjkuMzI3NiAzMTkuMDQzIDE5OS42NjEgMjg1LjAyNyAzMTkuNTA3IDI1Mi45NjRDNDQyLjE2NSAyMTIuMjU5IDM1Ny4zODYgMzIuODI2OSAyNjkuNDE1IDI4Ljg1NThDMTgxLjQ0MyAyNC44ODQ3IDI4MC4zMjIgMTExLjgyNCAyMDUuNTk1IDEzNi42NTZDMTMwLjg2OCAxNjEuNDg3IDY2Ljk5MDcgNDguMDU4MyAxMy40ODA2IDE5OC42MDVaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjxnIGZpbHRlcj0idXJsKCNmaWx0ZXIxX2ZfMjAzNV8xMTA2KSI+CjxwYXRoIGQ9Ik04NS41MTE4IC00NS44MjI1QzYzLjA1NjIgLTEwNy4xNzYgLTE2LjkxODkgLTIzLjk5NTMgLTU0LjA5OTUgMjUuMjY0M0MtODkuNTY1MiA3OC44NDc5IDMuMDA5MzcgMTI1LjE1MiAzOS4zMjA4IDEwMC4wMzdDNzUuNjMyMyA3NC45MjI3IDcuNzc0NDggNzAuMDM2MyAyOS4zNzA4IDM3LjM3ODVDNTAuOTY3MSA0LjcyMDc2IDExMy41ODEgMzAuODY5NSA4NS41MTE4IC00NS44MjI1WiIgZmlsbD0iIzAwRkZGMCIgZmlsbC1vcGFjaXR5PSIwLjY3Ii8+CjwvZz4KPGcgZmlsdGVyPSJ1cmwoI2ZpbHRlcjJfZl8yMDM1XzExMDYpIj4KPHBhdGggZD0iTTk2LjQ3OTYgMjI1LjQyNEM2NS44NTAyIDEyMi4zNjMgLTY2LjA4MTggMTc2LjYzNyAtMTI4LjIxOSAyMTYuNjU3Qy0xODcuOTkgMjY0LjA0MiAtNDYuMDcxMSA0MDAuMzQ4IDEyLjg3MjUgMzkzLjM3NkM3MS44MTYxIDM4Ni40MDMgLTM0LjQxMTggMzI3LjA2NSAxLjk4NzAyIDI5OC4xN0MzOC4zODU4IDI2OS4yNzYgMTM0Ljc2NiAzNTQuMjQ5IDk2LjQ3OTYgMjI1LjQyNFoiIGZpbGw9IiM5RDgxRkYiLz4KPC9nPgo8ZyBmaWx0ZXI9InVybCgjZmlsdGVyM19mXzIwMzVfMTEwNikiPgo8cGF0aCBkPSJNMjgyLjEyIC0xMDcuMzUzQzIxNi4wNDcgLTE4Ni4wMzEgMTIxLjQ2MyAtMTIwLjk3IDgyLjQyOTYgLTc4LjYwNDdDNDguMjczOSAtMzAuNjQ0NiAyMjQuMjc1IDU3LjIzMTIgMjczLjEyMSA0Mi4xNzE0QzMyMS45NjggMjcuMTExNSAyMDYuNTEyIC00LjA1MDM4IDIyNy4yOTcgLTMzLjI4NzlDMjQ4LjA4MiAtNjIuNTI1NSAzNjQuNzEyIC05LjAwNTY2IDI4Mi4xMiAtMTA3LjM1M1oiIGZpbGw9IiM0RDk0RkYiLz4KPC9nPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkzLjE4OSAxNTIuODM2SDEzNi42NzRMODcuMjA4NiAxMDMuMDUxTDEzNy4zMSA1My4yNjYzTDE1MC45NTUgNDBIMTA1LjgxOUw0OC4zMzU5IDk3Ljc3NzNDNDUuNDM0OSAxMDAuNjg5IDQ1LjQ0OTggMTA1LjQwMiA0OC4zNjU2IDEwOC4yOTlMOTMuMTg5IDE1Mi44MzZaTTExOS4zMyAxMDMuMTY4SDExOC45OTVMMTE5LjMyNiAxMDMuMTY0TDExOS4zMyAxMDMuMTY4Wk0xMTkuMzMgMTAzLjE2OEwxNjguNzkxIDE1Mi45NDlMMTE4LjY5IDIwMi43MzRMMTA1LjA0NSAyMTZIMTUwLjE4TDIwNy42NjQgMTU4LjIyNkMyMTAuNTY1IDE1NS4zMTQgMjEwLjU1IDE1MC42MDIgMjA3LjYzNCAxNDcuNzA1TDE2Mi44MTEgMTAzLjE2OEgxMTkuMzNaIiBmaWxsPSJibGFjayIvPgo8L2c+CjxkZWZzPgo8ZmlsdGVyIGlkPSJmaWx0ZXIwX2ZfMjAzNV8xMTA2IiB4PSItOTAuMjQxMSIgeT0iLTY5LjczNjkiIHdpZHRoPSI1NjkuNTU4IiBoZWlnaHQ9IjQ1MS40MzEiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyMV9mXzIwMzVfMTEwNiIgeD0iLTE2MC41MTEiIHk9Ii0xNjUuOTg3IiB3aWR0aD0iMzUxLjU5NiIgaGVpZ2h0PSIzNzEuNTA3IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxmaWx0ZXIgaWQ9ImZpbHRlcjJfZl8yMDM1XzExMDYiIHg9Ii0yNDEuMDc4IiB5PSI2Ny42NDIiIHdpZHRoPSI0NDQuODUxIiBoZWlnaHQ9IjQyNC40NTIiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4KPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4KPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNDkuMjMwOCIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzIwMzVfMTEwNiIvPgo8L2ZpbHRlcj4KPGZpbHRlciBpZD0iZmlsdGVyM19mXzIwMzVfMTEwNiIgeD0iLTIwLjM5NjgiIHk9Ii0yNDIuNzU4IiB3aWR0aD0iNDMwLjE5MSIgaGVpZ2h0PSIzODUuMTA1IiBmaWx0ZXJVbml0cz0idXNlclNwYWNlT25Vc2UiIGNvbG9yLWludGVycG9sYXRpb24tZmlsdGVycz0ic1JHQiI+CjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+CjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9InNoYXBlIi8+CjxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjQ5LjIzMDgiIHJlc3VsdD0iZWZmZWN0MV9mb3JlZ3JvdW5kQmx1cl8yMDM1XzExMDYiLz4KPC9maWx0ZXI+CjxjbGlwUGF0aCBpZD0iY2xpcDBfMjAzNV8xMTA2Ij4KPHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==",name:"Bitget Wallet"},gz=[pz],fz=s=>gz.find(e=>e.name.toLocaleLowerCase().includes(s.name.toLocaleLowerCase()))||s,wz=(s,e,t)=>e[s]||t[s],nf=(s,e)=>wz(s,fz(e),e);class li extends se.Wallet{constructor(e,t){super(),this.adapter=e,this.connection=t}getAdapter(){return this.adapter}getName(){return nf("name",this.adapter)}getUrl(){return this.adapter.url}async connect(){if(this.isConnected())return this.getAddresses();const e=await new Promise((t,i)=>{this.adapter.on("connect",()=>{this.adapter.off("connect"),this.adapter.off("error"),t(this.getAddresses())}),this.adapter.on("error",r=>{this.adapter.off("connect"),this.adapter.off("error"),i(r)}),this.adapter.connect().catch(i)});return this.emit("connect"),this.adapter.on("disconnect",()=>this.emit("disconnect")),e}getNetworkInfo(){return{}}isConnected(){return this.adapter.connected}async disconnect(){this.isConnected()&&(await new Promise((e,t)=>{this.adapter.on("disconnect",()=>{this.adapter.off("disconnect"),this.adapter.off("error"),e(void 0)}),this.adapter.on("error",i=>{this.adapter.off("disconnect"),this.adapter.off("error"),t(i)}),this.adapter.disconnect().catch(t)}),this.adapter.removeAllListeners(),this.emit("disconnect"))}getChainId(){return se.CHAIN_ID_SOLANA}getAddress(){return this.adapter.publicKey?.toString()}getAddresses(){const e=this.getAddress();return e?[e]:[]}setMainAddress(){throw new Error("Not supported")}getBalance(){throw new Error("Not supported")}async signTransaction(e){if(!this.adapter.signTransaction||!this.adapter.signAllTransactions)throw new Error("Not supported");return Array.isArray(e)?this.adapter.signAllTransactions(e):this.adapter.signTransaction(e)}async sendTransaction(e){const{transaction:t}=e,i=Array.isArray(t)?t:[t];if(i.length===0)throw new Error("Empty transactions array");const r=[];for(const n of i){const o=await this.adapter.sendTransaction(n,this.connection,{...e.options});r.push(o)}return await this.connection.confirmTransaction(r[0],e.options?.commitment),{id:r[0],data:r.length===1?r[0]:r}}async signAndSendTransaction(e){return this.sendTransaction(e)}signMessage(e){if(!this.adapter.signMessage)throw new Error("Not supported");return this.adapter.signMessage(e)}getIcon(){return nf("icon",this.adapter)}getWalletState(){const e=this.adapter.readyState;if(!(e in se.WalletState))throw new Error(`Unknown wallet state ${e}`);return se.WalletState[e]}getFeatures(){const e=[se.BaseFeatures.SendTransaction,se.BaseFeatures.SignAndSendTransaction];return this.adapter.signTransaction&&this.adapter.signAllTransactions&&e.push(se.BaseFeatures.SignTransaction),this.adapter.signMessage&&e.push(se.BaseFeatures.SignMessage),e}supportsChain(e){return e===se.CHAIN_ID_SOLANA}}function yz(s){if(s.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<s.length;l++){const u=s.charAt(l),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=l}const t=s.length,i=s.charAt(0),r=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,d=0,p=0;const f=l.length;for(;p!==f&&l[p]===0;)p++,u++;const g=(f-p)*n+1>>>0,w=new Uint8Array(g);for(;p!==f;){let m=l[p],A=0;for(let C=g-1;(m!==0||A<d)&&C!==-1;C--,A++)m+=256*w[C]>>>0,w[C]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let b=g-d;for(;b!==g&&w[b]===0;)b++;let v=i.repeat(u);for(;b<g;++b)v+=s.charAt(w[b]);return v}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,p=0;for(;l[u]===i;)d++,u++;const f=(l.length-u)*r+1>>>0,g=new Uint8Array(f);for(;u<l.length;){const m=l.charCodeAt(u);if(m>255)return;let A=e[m];if(A===255)return;let C=0;for(let S=f-1;(A!==0||C<p)&&S!==-1;S--,C++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=C,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const b=new Uint8Array(d+(f-w));let v=d;for(;w!==f;)b[v++]=g[w++];return b}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var mz="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const bz=yz(mz);var Z=function(s,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!i:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(s):i?i.value:e.get(s)},lt=function(s,e,t,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(s,t):r?r.value=t:e.set(s,t),t},Pt,Zt,nr,or,Zi,lo,tc,_e,sc,Ah,Ua,Nh,bo,Ch,of,af,cf,lf;class vz extends df{get name(){return Z(this,_e,"f").name}get url(){return"https://github.com/solana-labs/wallet-standard"}get icon(){return Z(this,_e,"f").icon}get readyState(){return Z(this,sc,"f")}get publicKey(){return Z(this,nr,"f")}get connecting(){return Z(this,or,"f")}get supportedTransactionVersions(){return Z(this,tc,"f")}get wallet(){return Z(this,_e,"f")}get standard(){return!0}constructor({wallet:e}){super(),Pt.add(this),Zt.set(this,void 0),nr.set(this,void 0),or.set(this,void 0),Zi.set(this,void 0),lo.set(this,void 0),tc.set(this,void 0),_e.set(this,void 0),sc.set(this,typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.Installed),Ch.set(this,t=>{if("accounts"in t){const i=Z(this,_e,"f").accounts[0];Z(this,Zt,"f")&&!Z(this,Zi,"f")&&i!==Z(this,Zt,"f")&&(i?Z(this,Pt,"m",Ua).call(this,i):(this.emit("error",new uf),Z(this,Pt,"m",Nh).call(this)))}"features"in t&&Z(this,Pt,"m",bo).call(this)}),lt(this,_e,e,"f"),lt(this,Zt,null,"f"),lt(this,nr,null,"f"),lt(this,or,!1,"f"),lt(this,Zi,!1,"f"),lt(this,lo,Z(this,_e,"f").features[se.StandardEvents].on("change",Z(this,Ch,"f")),"f"),Z(this,Pt,"m",bo).call(this)}destroy(){lt(this,Zt,null,"f"),lt(this,nr,null,"f"),lt(this,or,!1,"f"),lt(this,Zi,!1,"f");const e=Z(this,lo,"f");e&&(lt(this,lo,null,"f"),e())}async autoConnect(){return Z(this,Pt,"m",Ah).call(this,{silent:!0})}async connect(){return Z(this,Pt,"m",Ah).call(this)}async disconnect(){if(se.StandardDisconnect in Z(this,_e,"f").features)try{lt(this,Zi,!0,"f"),await Z(this,_e,"f").features[se.StandardDisconnect].disconnect()}catch(e){this.emit("error",new xo(e?.message,e))}finally{lt(this,Zi,!1,"f")}Z(this,Pt,"m",Nh).call(this)}async sendTransaction(e,t,i={}){try{const r=Z(this,Zt,"f");if(!r)throw new Ke;let n;if(se.SolanaSignAndSendTransaction in Z(this,_e,"f").features)if(r.features.includes(se.SolanaSignAndSendTransaction))n=se.SolanaSignAndSendTransaction;else if(se.SolanaSignTransaction in Z(this,_e,"f").features&&r.features.includes(se.SolanaSignTransaction))n=se.SolanaSignTransaction;else throw new Es;else if(se.SolanaSignTransaction in Z(this,_e,"f").features){if(!r.features.includes(se.SolanaSignTransaction))throw new Es;n=se.SolanaSignTransaction}else throw new ln;const o=tv(t.rpcEndpoint);if(!r.chains.includes(o))throw new sr;try{const{signers:a,...c}=i;let l;if(ui(e)?(a?.length&&e.sign(a),l=e.serialize()):(e=await this.prepareTransaction(e,t,c),a?.length&&e.partialSign(...a),l=new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))),n===se.SolanaSignAndSendTransaction){const[u]=await Z(this,_e,"f").features[se.SolanaSignAndSendTransaction].signAndSendTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:$c(c.preflightCommitment||t.commitment),skipPreflight:c.skipPreflight,maxRetries:c.maxRetries,minContextSlot:c.minContextSlot}});return bz.encode(u.signature)}else{const[u]=await Z(this,_e,"f").features[se.SolanaSignTransaction].signTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:$c(c.preflightCommitment||t.commitment),minContextSlot:c.minContextSlot}});return await t.sendRawTransaction(u.signedTransaction,{...c,preflightCommitment:$c(c.preflightCommitment||t.commitment)})}}catch(a){throw a instanceof Mt?a:new sr(a?.message,a)}}catch(r){throw this.emit("error",r),r}}}Zt=new WeakMap,nr=new WeakMap,or=new WeakMap,Zi=new WeakMap,lo=new WeakMap,tc=new WeakMap,_e=new WeakMap,sc=new WeakMap,Ch=new WeakMap,Pt=new WeakSet,Ah=async function(e){try{if(this.connected||this.connecting)return;if(Z(this,sc,"f")!==ge.Installed)throw new Ri;if(lt(this,or,!0,"f"),!Z(this,_e,"f").accounts.length)try{await Z(this,_e,"f").features[se.StandardConnect].connect(e)}catch(i){throw new ic(i?.message,i)}const t=Z(this,_e,"f").accounts[0];if(!t)throw new Es;Z(this,Pt,"m",Ua).call(this,t)}catch(t){throw this.emit("error",t),t}finally{lt(this,or,!1,"f")}},Ua=function(e){let t;try{t=new N.PublicKey(e.address)}catch(i){throw new gr(i?.message,i)}lt(this,Zt,e,"f"),lt(this,nr,t,"f"),Z(this,Pt,"m",bo).call(this),this.emit("connect",t)},Nh=function(){lt(this,Zt,null,"f"),lt(this,nr,null,"f"),Z(this,Pt,"m",bo).call(this),this.emit("disconnect")},bo=function(){const e=se.SolanaSignAndSendTransaction in Z(this,_e,"f").features?Z(this,_e,"f").features[se.SolanaSignAndSendTransaction].supportedTransactionVersions:Z(this,_e,"f").features[se.SolanaSignTransaction].supportedTransactionVersions;lt(this,tc,jb.arraysEqual(e,["legacy"])?null:new Set(e),"f"),se.SolanaSignTransaction in Z(this,_e,"f").features&&Z(this,Zt,"f")?.features.includes(se.SolanaSignTransaction)?(this.signTransaction=Z(this,Pt,"m",of),this.signAllTransactions=Z(this,Pt,"m",af)):(delete this.signTransaction,delete this.signAllTransactions),se.SolanaSignMessage in Z(this,_e,"f").features&&Z(this,Zt,"f")?.features.includes(se.SolanaSignMessage)?this.signMessage=Z(this,Pt,"m",cf):delete this.signMessage,se.SolanaSignIn in Z(this,_e,"f").features?this.signIn=Z(this,Pt,"m",lf):delete this.signIn},of=async function(e){try{const t=Z(this,Zt,"f");if(!t)throw new Ke;if(!(se.SolanaSignTransaction in Z(this,_e,"f").features))throw new ln;if(!t.features.includes(se.SolanaSignTransaction))throw new Es;try{const r=(await Z(this,_e,"f").features[se.SolanaSignTransaction].signTransaction({account:t,transaction:ui(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return ui(e)?N.VersionedTransaction.deserialize(r):N.Transaction.from(r)}catch(i){throw i instanceof Mt?i:new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}},af=async function(e){try{const t=Z(this,Zt,"f");if(!t)throw new Ke;if(!(se.SolanaSignTransaction in Z(this,_e,"f").features))throw new ln;if(!t.features.includes(se.SolanaSignTransaction))throw new Es;try{const i=await Z(this,_e,"f").features[se.SolanaSignTransaction].signTransaction(...e.map(r=>({account:t,transaction:ui(r)?r.serialize():new Uint8Array(r.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((r,n)=>{const o=i[n].signedTransaction;return ui(r)?N.VersionedTransaction.deserialize(o):N.Transaction.from(o)})}catch(i){throw new rt(i?.message,i)}}catch(t){throw this.emit("error",t),t}},cf=async function(e){try{const t=Z(this,Zt,"f");if(!t)throw new Ke;if(!(se.SolanaSignMessage in Z(this,_e,"f").features))throw new ln;if(!t.features.includes(se.SolanaSignMessage))throw new Es;try{return(await Z(this,_e,"f").features[se.SolanaSignMessage].signMessage({account:t,message:e}))[0].signature}catch(i){throw new Mo(i?.message,i)}}catch(t){throw this.emit("error",t),t}},lf=async function(e={}){try{if(!(se.SolanaSignIn in Z(this,_e,"f").features))throw new ln;let t;try{[t]=await Z(this,_e,"f").features[se.SolanaSignIn].signIn(e)}catch(i){throw new Cu(i?.message,i)}if(!t)throw new Cu;return Z(this,Pt,"m",Ua).call(this,t.account),t}catch(t){throw this.emit("error",t),t}};function Iz(s){return Rb.getWallets().get().filter(zb).map(e=>new li(new vz({wallet:e}),s))}function Ez(s){return s.includes("rpcpool.com")?"triton":s.includes("helius-rpc.com")?"helius":s.includes("rpc.ankr.com")?"ankr":"unknown"}async function Az(s,e,t,i){const r=i.transaction.transaction,n=o=>o.programId.toString()!=="ComputeBudget111111111111111111111111111111";if($a.isVersionedTransaction(r)){const o=(await Promise.all(r.message.addressTableLookups.map(c=>s.getAddressLookupTable(c.accountKey)))).map(c=>c.value).filter(c=>c!==null),a=N.TransactionMessage.decompile(r.message,{addressLookupTableAccounts:o});a.recentBlockhash=e,r.message.recentBlockhash=e,a.instructions=a.instructions.filter(n),r.message=a.compileToV0Message(o),a.instructions.push(...await hf(s,r)),r.message=a.compileToV0Message(o),r.sign(i.transaction.signers??[])}else r.recentBlockhash=e,r.lastValidBlockHeight=t,r.instructions=r.instructions.filter(n),r.add(...await hf(s,r)),i.transaction.signers&&r.partialSign(...i.transaction.signers);return r}async function hf(s,e,t){let i=2e5,r=0;const n=N.ComputeBudgetProgram.setComputeUnitLimit({units:3e5});let o;if($a.isVersionedTransaction(e)){const A=(await Promise.all(e.message.addressTableLookups.map(S=>s.getAddressLookupTable(S.accountKey)))).map(S=>S.value).filter(S=>S!==null),C=N.TransactionMessage.decompile(e.message,{addressLookupTableAccounts:A});C.instructions=[...C.instructions,n],o=new N.VersionedTransaction(C.compileToV0Message(A)),o.signatures=[...e.signatures]}else{const A=new N.Transaction;A.recentBlockhash=e.recentBlockhash,A.feePayer=e.feePayer,A.instructions=[...e.instructions,n],A.signatures=[...e.signatures],o=A}e:for(;;){if($a.isVersionedTransaction(o)&&!o.message.recentBlockhash){const{blockhash:C}=await s.getLatestBlockhash(t);o.message.recentBlockhash=C}const A=await($a.isVersionedTransaction(o)?s.simulateTransaction(o,{commitment:t,replaceRecentBlockhash:!0}):s.simulateTransaction(o));if(A.value.err){if(Nz(A.value)){if(r<5){r++,await Xt.sleep(1e3);continue e}}else if(r<3){r++,await Xt.sleep(1e3);continue e}throw new Error(`Simulation failed: ${JSON.stringify(A.value.err)}
898
898
  Logs:
899
899
  ${(A.value.logs||[]).join(`
900
900
  `)}`)}else{A.value.unitsConsumed&&(i=A.value.unitsConsumed);break}}const a=Math.floor(i*1.2),c=[];c.push(N.ComputeBudgetProgram.setComputeUnitLimit({units:a}));const l=Xt.config.transactionSettings?.Solana?.priorityFee||{},{percentile:u=.9,percentileMultiple:d=1,min:p=1e5,max:f=1e8}=l,g=async A=>{if(A==="triton")try{return{fee:await Nu.determinePriorityFeeTritonOne(s,e,u,d,p,f),methodUsed:"triton"}}catch(C){console.warn("Failed to determine priority fee using Triton RPC:",C)}try{return{fee:await Nu.determinePriorityFee(s,e,u,d,p,f),methodUsed:"default"}}catch(C){return console.warn("Failed to determine priority fee using Triton RPC:",C),{fee:p,methodUsed:"minimum"}}},w=Ez(s.rpcEndpoint),{fee:b,methodUsed:v}=await g(w),m=b/1e6/N.LAMPORTS_PER_SOL*a;return console.table({"RPC Provider":w,"Method used":v,"Percentile used":u,"Multiple used":d,"Compute budget":a,"Priority fee":b,"Max fee in SOL":m}),c.push(N.ComputeBudgetProgram.setComputeUnitPrice({microLamports:b})),c}function Nz(s){const e={};if(s.err==="BlockhashNotFound"&&(e.BlockhashNotFound="Blockhash not found during simulation. Trying again."),s.logs)for(const t of s.logs)t.includes("SlippageToleranceExceeded")&&(e.SlippageToleranceExceeded="Slippage failure during simulation. Trying again."),t.includes("RequireGteViolated")&&(e.RequireGteViolated="Swap instruction failure during simulation. Trying again.");return Xt.isEmptyObject(e)?!1:(console.table(e),!0)}const Cz=s=>s.getName().toLowerCase().replaceAll("wallet","").trim();function _z(s){if(s==="Solana"){const e=Xt.config.isMainnet?"mainnet-beta":"devnet",t=new N.Connection(Xt.config.rpcs.Solana||N.clusterApiUrl(e));return{...Iz(t).reduce((i,r)=>(i[Cz(r)]=r,i),{}),bitget:new li(new qb,t),clover:new li(new Hb,t),coin98:new li(new Gb,t),solong:new li(new Jb,t),torus:new li(new Xb,t),nightly:new li(new _u,t),...Xt.config.ui.walletConnectProjectId?{walletConnect:new li(new dz({network:Xt.config.isMainnet?vo.Mainnet:vo.Devnet,options:{projectId:Xt.config.ui.walletConnectProjectId,customStoragePrefix:"wh-connect-solana-adapter"}}),t)}:{}}}else if(s==="Fogo"){if(!Xt.config.rpcs.Fogo)throw new Error("Fogo RPC not found");const e=new N.Connection(Xt.config.rpcs.Fogo);return{nightly:new li(new _u,e)}}throw new Error(`Unsupported chain: ${s}`)}async function Sz(s,e,t){if(!e)throw new Error("Wallet not found");const i=Xt.config.rpcs[s.chain];if(!i)throw new Error(`${s.chain} RPC not found`);const r=t?.commitment??"finalized",n=new N.Connection(i),{blockhash:o,lastValidBlockHeight:a}=await n.getLatestBlockhash(r),c=await Az(n,o,a,s);let l=null,u=null,d=1,p="";const g=(await e.signTransaction(c)).serialize(),w={skipPreflight:!0,maxRetries:0,preFlightCommitment:r};p=await n.sendRawTransaction(g,w),l=n.confirmTransaction({signature:p,blockhash:o,lastValidBlockHeight:a},r);try{for(;!u&&(u=await Promise.race([l,new Promise(v=>setTimeout(()=>{v(null)},5e3))]),!u);){console.log(`Tx not confirmed after ${5e3*d++}ms, resending`);try{await n.sendRawTransaction(g,w)}catch(v){console.error("Failed to resend transaction:",v)}}}catch(b){if(b instanceof Error&&b.name==="TransactionExpiredBlockheightExceededError")for(let A=0;A<5;++A){try{if(await n.getTransaction(p,{commitment:"confirmed",maxSupportedTransactionVersion:0}))return p}catch{}await Xt.sleep(2e3)}throw b}if(u.value.err){let b=`Transaction failed: ${u.value.err}`;if(typeof u.value.err=="object")try{b=`Transaction failed: ${JSON.stringify(u.value.err,(v,m)=>typeof m=="bigint"?m.toString():m)}`}catch{b="Transaction failed: Unknown error"}throw new Error(`Transaction failed: ${b}`)}return p}const $z=Object.freeze(Object.defineProperty({__proto__:null,fetchOptions:_z,signAndSendTransaction:Sz},Symbol.toStringTag,{value:"Module"}));exports.AccountController=re;exports.AlertController=po;exports.ApiController=ue;exports.AssetController=Is;exports.AssetUtil=Bh;exports.ChainController=I;exports.ConnectionController=qe;exports.ConnectorController=le;exports.ConnectorUtil=yo;exports.ConstantsUtil=ie;exports.ConstantsUtil$1=Ht;exports.ConstantsUtil$2=Am;exports.CoreHelperUtil=he;exports.EventsController=Be;exports.Hash=If;exports.Hash$1=ly;exports.ModalController=ot;exports.OptionsController=R;exports.RouterController=Me;exports.SIWXUtil=wn;exports.SnackController=vt;exports.StorageUtil=X;exports.ThemeController=Lt;exports.WalletUtil=Xa;exports.abytes=ko;exports.abytes$1=Bo;exports.aexists=Cl;exports.aexists$1=Ql;exports.ahash=Mv;exports.ahash$1=$O;exports.aoutput=vf;exports.aoutput$1=cy;exports.colorStyles=QL;exports.concatBytes=Hv;exports.concatBytes$1=zO;exports.createView=zv;exports.createView$1=jO;exports.elementStyles=YL;exports.initializeTheming=VL;exports.randomBytes=Wv;exports.randomBytes$1=FO;exports.resetStyles=GL;exports.rotr=Fv;exports.rotr$1=RO;exports.solana=$z;exports.toBytes=Sh;exports.toBytes$1=Hh;exports.wrapConstructor=Ef;exports.wrapConstructor$1=hy;