@wormhole-foundation/wormhole-connect 4.2.0-beta.0-development → 5.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 (73) hide show
  1. package/dist/main.mjs +73 -73
  2. package/dist/src/telemetry/types.d.ts +2 -1
  3. package/dist/src/telemetry/types.d.ts.map +1 -1
  4. package/dist/src/utils/errors.d.ts +1 -0
  5. package/dist/src/utils/errors.d.ts.map +1 -1
  6. package/lib/{aptos-DcdKyekw.js → aptos-BnjZOhUE.js} +1 -1
  7. package/lib/{aptos-B1Gf2eCD.mjs → aptos-fTiHvXXE.mjs} +2 -2
  8. package/lib/{basic-DnhL0oWa.mjs → basic-BqusrmRE.mjs} +2 -2
  9. package/lib/{basic-C6VXQ7m-.js → basic-BrW22Cj9.js} +1 -1
  10. package/lib/{basic-CFbslwLM.mjs → basic-CK5Bsf0B.mjs} +2 -2
  11. package/lib/{basic-BS7Z1PMG.js → basic-ChOmeQQk.js} +1 -1
  12. package/lib/constants-C1w_RyOP.js +1 -0
  13. package/lib/{constants-CTJ_-E0d.mjs → constants-DcDpDarO.mjs} +5 -5
  14. package/lib/{core-DT6TBPQP.mjs → core-DQ-6Q1F1.mjs} +5 -5
  15. package/lib/{core-RRp0K__1.js → core-FA2gBc-s.js} +3 -3
  16. package/lib/{evm-DlOCiplA.mjs → evm-BJ4Lx-r9.mjs} +3 -3
  17. package/lib/{evm-BwCfQIyJ.js → evm-BTgO_HRP.js} +2 -2
  18. package/lib/{evm-BxF9XPn4.mjs → evm-C-vXMfGr.mjs} +3 -3
  19. package/lib/{evm-C3B8jHD7.js → evm-qxndAh3z.js} +1 -1
  20. package/lib/hosted.js +1 -1
  21. package/lib/hosted.mjs +1 -1
  22. package/lib/{hypercore-DbqOAqKF.js → hypercore-D7kZiwbe.js} +1 -1
  23. package/lib/{hypercore-H7pw_pN4.mjs → hypercore-DKqayfki.mjs} +9 -9
  24. package/lib/{index-mikg85u5.js → index-3Zg1AdoI.js} +1 -1
  25. package/lib/{index-BuEKhdrW.mjs → index-B1URQBlH.mjs} +1 -1
  26. package/lib/{index-pn6NZmOS.js → index-B7b8sctd.js} +1 -1
  27. package/lib/{index-CsLyPoC6.mjs → index-BVciucyT.mjs} +1 -1
  28. package/lib/{index-BNpkgexR.js → index-BfzaCmg7.js} +1 -1
  29. package/lib/{index-DVm_f5E1.js → index-C-F8_8dY.js} +1 -1
  30. package/lib/{index-BmP0jPVN.mjs → index-C6MalNd5.mjs} +9 -9
  31. package/lib/{index-BbE02hdW.js → index-Cb_8WAm1.js} +8 -8
  32. package/lib/{index-BnKf2rOm.mjs → index-CgqBQ88K.mjs} +178 -175
  33. package/lib/{index-BtU67kjy.mjs → index-CowAVUcg.mjs} +1 -1
  34. package/lib/{index-CGqJokTg.mjs → index-DcFL403C.mjs} +1 -1
  35. package/lib/{index-DAJZN12d.js → index-Oxm0y6-t.js} +1 -1
  36. package/lib/{index-t_koRpGi.js → index-XjDX4fWv.js} +1 -1
  37. package/lib/{index-NAUBlFLG.mjs → index-mNO1mk2F.mjs} +1 -1
  38. package/lib/{index.es-B3FwsRfN.js → index.es-B9kBDkCQ.js} +3 -3
  39. package/lib/{index.es-ClIr5Gv-.js → index.es-BZRO-bNH.js} +1 -1
  40. package/lib/{index.es-CYyuSfPG.mjs → index.es-CF3YY88z.mjs} +3 -3
  41. package/lib/{index.es-3KAM8l3G.mjs → index.es-CaAL5X4E.mjs} +2 -2
  42. package/lib/index.js +2 -2
  43. package/lib/index.mjs +16 -15
  44. package/lib/lifi.js +1 -1
  45. package/lib/lifi.mjs +2 -2
  46. package/lib/mayan.js +1 -1
  47. package/lib/mayan.mjs +2 -2
  48. package/lib/{secp256k1-BZFiBDHQ.mjs → secp256k1-1o6o1kFy.mjs} +1 -1
  49. package/lib/{secp256k1-D3i7kc2M.mjs → secp256k1-BjlnTj1_.mjs} +1 -1
  50. package/lib/{secp256k1-B2G0zB-5.js → secp256k1-CeYT4ndf.js} +1 -1
  51. package/lib/{secp256k1-Cteng3v9.mjs → secp256k1-Cw_BiEuN.mjs} +1 -1
  52. package/lib/{secp256k1-CxjctkO3.js → secp256k1-D5cKS6q_.js} +1 -1
  53. package/lib/{secp256k1-Bz-QjKBU.js → secp256k1-_QlJc7sK.js} +1 -1
  54. package/lib/{solana-BE2DAanS.js → solana-DvHFhri3.js} +4 -4
  55. package/lib/{solana-Df231Yni.mjs → solana-TgPr9kpk.mjs} +8 -8
  56. package/lib/{solanaEmbed.esm-B9WG-Afi.mjs → solanaEmbed.esm-Bh1-aAL4.mjs} +2 -2
  57. package/lib/{solanaEmbed.esm-BqcrHrhl.js → solanaEmbed.esm-C8TjRcIV.js} +1 -1
  58. package/lib/src/telemetry/types.d.ts +2 -1
  59. package/lib/src/telemetry/types.d.ts.map +1 -1
  60. package/lib/src/utils/errors.d.ts +1 -0
  61. package/lib/src/utils/errors.d.ts.map +1 -1
  62. package/lib/{sui-B9tYcgyb.mjs → sui-CoWRa3vr.mjs} +2 -2
  63. package/lib/{sui-BVwNcgQT.js → sui-DwFrGd2Y.js} +1 -1
  64. package/lib/{tokenHelpers-DITWDel1.js → tokenHelpers-CeTyb4rG.js} +1 -1
  65. package/lib/{tokenHelpers-C53sepsl.mjs → tokenHelpers-VYjmKUxj.mjs} +1 -1
  66. package/lib/{tokens-CO0YQ3R2.mjs → tokens-D6uJqrsR.mjs} +1 -1
  67. package/lib/{tokens-CiSHS7oi.js → tokens-mXZqt-qL.js} +1 -1
  68. package/lib/{w3m-modal-SlcSCSnx.mjs → w3m-modal-BEe8ji9_.mjs} +2 -2
  69. package/lib/{w3m-modal-5v-rsnN8.mjs → w3m-modal-D3eqrCT1.mjs} +2 -2
  70. package/lib/{w3m-modal-B0Lu-6W8.js → w3m-modal-Duc13ei7.js} +1 -1
  71. package/lib/{w3m-modal-B2xHxAWg.js → w3m-modal-f_sUVzPx.js} +1 -1
  72. package/package.json +1 -1
  73. package/lib/constants-BCFTvlgh.js +0 -1
@@ -1,5 +1,5 @@
1
- "use strict";const Ke=require("./unsignedTransaction-qRBv5Cnd.js"),ti=require("./hypercore-DbqOAqKF.js"),oe=require("./index-t_koRpGi.js"),zb=require("./util-G2vxTeU2.js"),Fb=require("./wallets-DLkIKXkb.js"),di=require("./index-BbE02hdW.js"),_=require("./platform-DCcL7jHP.js"),h=require("./index.es-ClIr5Gv-.js"),k=require("./lit-element-Cpy16KIW.js"),wn=require("./http-D4VeaDBj.js");class qb extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}function Bb(s,{signal:e}={}){return new Promise((t,i)=>{const r=()=>{i(new qb)},n=()=>{clearTimeout(o),r()};if(e?.aborted)return r();const o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},s);e?.addEventListener("abort",n,{once:!0})})}const Cu=0,Hb=Number.POSITIVE_INFINITY;async function Wb(s,e){let t,i,r;typeof e=="number"?(t=Cu,i=e,r=void 0):(t=e?.delay??Cu,i=e?.retries??Hb,r=e?.signal);let n;for(let o=0;o<i;o++){if(r?.aborted)throw n??new Error("The retry operation was aborted due to an abort signal.");try{return await s()}catch(a){n=a;const c=typeof t=="function"?t(o):t;await Bb(c)}}throw n}class Ot extends Error{constructor(e,t){super(e),this.error=t}}class Li extends Ot{constructor(){super(...arguments),this.name="WalletNotReadyError"}}class Vb extends Ot{constructor(){super(...arguments),this.name="WalletLoadError"}}class un extends Ot{constructor(){super(...arguments),this.name="WalletConfigError"}}class rc extends Ot{constructor(){super(...arguments),this.name="WalletConnectionError"}}class hf extends Ot{constructor(){super(...arguments),this.name="WalletDisconnectedError"}}class Oo extends Ot{constructor(){super(...arguments),this.name="WalletDisconnectionError"}}class Es extends Ot{constructor(){super(...arguments),this.name="WalletAccountError"}}class wr extends Ot{constructor(){super(...arguments),this.name="WalletPublicKeyError"}}class Ge extends Ot{constructor(){super(...arguments),this.name="WalletNotConnectedError"}}class rr extends Ot{constructor(){super(...arguments),this.name="WalletSendTransactionError"}}class nt extends Ot{constructor(){super(...arguments),this.name="WalletSignTransactionError"}}class Do extends Ot{constructor(){super(...arguments),this.name="WalletSignMessageError"}}class _u extends Ot{constructor(){super(...arguments),this.name="WalletSignInError"}}class Kb extends Ot{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 uf extends Ke.EventEmitter{get connected(){return!!this.publicKey}async autoConnect(){await this.connect()}async prepareTransaction(e,t,i={}){const r=this.publicKey;if(!r)throw new Ge;return e.feePayer=e.feePayer||r,e.recentBlockhash=e.recentBlockhash||(await t.getLatestBlockhash({commitment:i.preflightCommitment,minContextSlot:i.minContextSlot})).blockhash,e}}function ko(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 pi(s){return"version"in s}class Sh extends uf{async sendTransaction(e,t,i={}){let r=!0;try{if(pi(e)){if(!this.supportedTransactionVersions)throw new rr("Sending versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(e.version))throw new rr(`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 nt?(r=!1,n):new rr(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 nt?(r=!1,n):new rr(n?.message,n)}}catch(n){throw r&&this.emit("error",n),n}}async signAllTransactions(e){for(const i of e)if(pi(i)){if(!this.supportedTransactionVersions)throw new nt("Signing versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(i.version))throw new nt(`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 jo extends Sh{}function Gb(s){return oe.StandardConnect in s.features&&oe.StandardEvents in s.features&&(oe.SolanaSignAndSendTransaction in s.features||oe.SolanaSignTransaction in s.features)}var Eo;(function(s){s.Mainnet="mainnet-beta",s.Testnet="testnet",s.Devnet="devnet"})(Eo||(Eo={}));const Yb="Bitget";class Qb extends jo{constructor(e={}){super(),this.name=Yb,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&&ko(()=>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 Li;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 Ke.PublicKey(t)}catch(r){throw new wr(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 Oo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{const{signature:i}=await t.signMessage(e);return i}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Jb="Clover";class Zb extends jo{constructor(e={}){super(),this.name=Jb,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&&ko(()=>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 Li;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 Ke.PublicKey(t)}catch(r){throw new wr(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 Ge;try{return await t.signTransaction(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{const{signature:i}=await t.signMessage(e);return Uint8Array.from(i)}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}function Xb(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 N=g-1;(m!==0||A<d)&&N!==-1;N--,A++)m+=256*w[N]>>>0,w[N]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(u);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,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 N=0;for(let S=f-1;(A!==0||N<p)&&S!==-1;S--,N++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=N,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 ev="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const $c=Xb(ev),tv="Coin98";class sv extends jo{constructor(e={}){super(),this.name=tv,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&&ko(()=>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 Li;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 Ke.PublicKey(t)}catch(r){throw new wr(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 Oo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{const i=await t.request({method:"sol_sign",params:[e]}),r=new Ke.PublicKey(i.publicKey),n=$c.decode(i.signature);return e.addSignature(r,_.Buffer.from(n)),e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{const i=await t.request({method:"sol_signAllTransactions",params:[e]}),r=new Ke.PublicKey(i.publicKey),n=i.signatures;return e.map((o,a)=>{const c=$c.decode(n[a]);return o.addSignature(r,_.Buffer.from(c)),o})}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{const i=await t.request({method:"sol_signMessage",params:[e]});return $c.decode(i.signature)}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const iv="Nightly";class df extends jo{constructor(){super(),this.name=iv,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&&ko(()=>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 Li;this._connecting=!0;const e=window.nightly.solana;try{await e.connect()}catch(i){throw new rc(i?.message,i)}if(e.publicKey.toString()==="11111111111111111111111111111111")throw new Es;let t;try{t=new Ke.PublicKey(e.publicKey.toBytes())}catch(i){throw new wr(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 hf)}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{return t.signMessage(new TextDecoder().decode(e))}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const rv="Solong";class nv extends Sh{constructor(e={}){super(),this.name=rv,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&&ko(()=>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 Li;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 Ke.PublicKey(t)}catch(r){throw new wr(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 Ge;try{return await t.signTransaction(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const ov="Torus";class av extends jo{constructor({params:e={showTorusButton:!1}}={params:{showTorusButton:!1}}){super(),this.name=ov,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 Li;this._connecting=!0;let e;try{e=(await Promise.resolve().then(()=>require("./solanaEmbed.esm-BqcrHrhl.js"))).default}catch(n){throw new Vb(n?.message,n)}let t;try{t=window.torus||new e}catch(n){throw new un(n?.message,n)}if(!t.isInitialized)try{await t.init(this._params)}catch(n){throw new rc(n?.message,n)}let i;try{i=await t.login()}catch(n){throw new Es(n?.message,n)}let r;try{r=new Ke.PublicKey(i[0])}catch(n){throw new wr(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 Oo(t?.message,t))}}this.emit("disconnect")}async sendTransaction(e,t,i={}){try{const r=this._wallet;if(!r)throw new Ge;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 Ot?n:new rr(n?.message,n)}}catch(r){throw this.emit("error",r),r}}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signMessage(e)}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}function Tc(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 cv="https://api.mainnet-beta.solana.com";function lv(s){return s.includes(cv)?oe.SOLANA_MAINNET_CHAIN:/\bdevnet\b/i.test(s)?oe.SOLANA_DEVNET_CHAIN:/\btestnet\b/i.test(s)?oe.SOLANA_TESTNET_CHAIN:/\blocalhost\b/i.test(s)||/\b127\.0\.0\.1\b/.test(s)?oe.SOLANA_LOCALNET_CHAIN:oe.SOLANA_MAINNET_CHAIN}var za;(function(s){s.Mainnet="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",s.Devnet="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",s.Deprecated_Mainnet="solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",s.Deprecated_Devnet="solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})(za||(za={}));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 ft={Mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Deprecated_Mainnet:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",Deprecated_Devnet:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"};var hv=Object.defineProperty,uv=(s,e,t)=>e in s?hv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Su=(s,e,t)=>uv(s,typeof e!="symbol"?e+"":e,t);let dv=class extends h.IEvents{constructor(e){super(),this.opts=e,Su(this,"protocol","wc"),Su(this,"version",2)}};var pv=Object.defineProperty,gv=(s,e,t)=>e in s?pv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fv=(s,e,t)=>gv(s,e+"",t);let wv=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,fv(this,"records",new Map)}},yv=class{constructor(e,t){this.logger=e,this.core=t}},mv=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},bv=class extends h.IEvents{constructor(e){super()}},vv=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},Iv=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},Ev=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},Av=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},Nv=class{constructor(e,t){this.projectId=e,this.logger=t}},Cv=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};function Ao(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 Ao(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const pf="2.23.2";let Pc={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${pf}`},nc=class Al extends Error{constructor(e,t={}){const i=t.cause instanceof Al?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof Al&&t.cause.docsPath||t.docsPath,n=Pc.getDocsUrl?.({...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...Pc.version?[`Version: ${Pc.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 nc{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 Sn(s,{dir:e,size:t=32}={}){return typeof s=="string"?_v(s,{dir:e,size:t}):Sv(s,{dir:e,size:t})}function _v(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 Sv(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 $v=class extends nc{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"})}},Tv=class extends nc{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 Tv({givenSize:$u(s),maxSize:e})}function Nl(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 Pv(s,e={}){return Number(Nl(s,e))}const xv=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Cl(s,e={}){return typeof s=="number"||typeof s=="bigint"?yf(s,e):typeof s=="string"?Dv(s,e):typeof s=="boolean"?Mv(s,e):wf(s,e)}function Mv(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?($n(t,{size:e.size}),Sn(t,{size:e.size})):t}function wf(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=xv[s[r]];const i=`0x${t}`;return typeof e.size=="number"?($n(i,{size:e.size}),Sn(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 $v({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?Sn(a,{size:i}):a}const Ov=new TextEncoder;function Dv(s,e={}){const t=Ov.encode(s);return wf(t,e)}const kv=new TextEncoder;function jv(s,e={}){return typeof s=="number"||typeof s=="bigint"?Uv(s,e):typeof s=="boolean"?Rv(s,e):Ao(s)?mf(s,e):bf(s,e)}function Rv(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?($n(t,{size:e.size}),Sn(t,{size:e.size})):t}const si={zero:48,nine:57,A:65,F:70,a:97,f:102};function Tu(s){if(s>=si.zero&&s<=si.nine)return s-si.zero;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 mf(s,e={}){let t=s;e.size&&($n(t,{size:e.size}),t=Sn(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 nc(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function Uv(s,e){const t=yf(s,e);return mf(t)}function bf(s,e={}){const t=kv.encode(s);return typeof e.size=="number"?($n(t,{size:e.size}),Sn(t,{dir:"right",size:e.size})):t}function Fa(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Lv(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ro(s,...e){if(!Lv(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 zv(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Fa(s.outputLen),Fa(s.blockLen)}function _l(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){Ro(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const aa=BigInt(2**32-1),Pu=BigInt(32);function Fv(s,e=!1){return e?{h:Number(s&aa),l:Number(s>>Pu&aa)}:{h:Number(s>>Pu&aa)|0,l:Number(s&aa)|0}}function qv(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}=Fv(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const Bv=(s,e,t)=>s<<t|e>>>32-t,Hv=(s,e,t)=>e<<t|s>>>32-t,Wv=(s,e,t)=>e<<t-32|s>>>64-t,Vv=(s,e,t)=>s<<t-32|e>>>64-t,Nr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Kv(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Gv(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Yv(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 Jv(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function $h(s){return typeof s=="string"&&(s=Jv(s)),Ro(s),s}function Zv(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Ro(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($h(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Xv(s=32){if(Nr&&typeof Nr.getRandomValues=="function")return Nr.getRandomValues(new Uint8Array(s));if(Nr&&typeof Nr.randomBytes=="function")return Nr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Af=[],Nf=[],Cf=[],e0=BigInt(0),Ln=BigInt(1),t0=BigInt(2),s0=BigInt(7),i0=BigInt(256),r0=BigInt(113);for(let s=0,e=Ln,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=e0;for(let n=0;n<7;n++)e=(e<<Ln^(e>>s0)*r0)%i0,e&t0&&(r^=Ln<<(Ln<<BigInt(n))-Ln);Cf.push(r)}const[n0,o0]=qv(Cf,!0),Ou=(s,e,t)=>t>32?Wv(s,e,t):Bv(s,e,t),Du=(s,e,t)=>t>32?Vv(s,e,t):Hv(s,e,t);function a0(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]^=n0[i],s[1]^=o0[i]}t.fill(0)}let c0=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,Fa(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Kv(this.state)}keccak(){xu||Mu(this.state32),a0(this.state32,this.rounds),xu||Mu(this.state32),this.posOut=0,this.pos=0}update(e){_l(this);const{blockLen:t,state:i}=this;e=$h(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){_l(this,!1),Ro(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 Fa(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 l0=(s,e,t)=>Ef(()=>new c0(e,s,t)),h0=l0(1,136,256/8);function Sf(s,e){const t=e||"hex",i=h0(Ao(s,{strict:!1})?jv(s):s);return t==="bytes"?i:Cl(i)}let u0=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 xc=new u0(8192);function d0(s,e){if(xc.has(`${s}.${e}`))return xc.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 xc.set(`${s}.${e}`,n),n}function p0(s){const e=Sf(`0x${s.substring(4)}`).substring(26);return d0(`0x${e}`)}async function g0({hash:s,signature:e}){const t=Ao(s)?s:Cl(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-CxjctkO3.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(Nl(l),Nl(u)).addRecoveryBit(g)}const o=Ao(e)?e:Cl(e),a=Pv(`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 f0({hash:s,signature:e}){return p0(await g0({hash:s,signature:e}))}var $f=di.requireElliptic();const Tf=":";function yn(s){const[e,t]=s.split(Tf);return{namespace:e,reference:t}}function w0(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 y0="ReactNative",cs={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},m0="js";function qa(){return typeof _.process$1<"u"&&typeof _.process$1.versions<"u"&&typeof _.process$1.versions.node<"u"}function zi(){return!h.cjsExports$2.getDocument()&&!!h.cjsExports$2.getNavigator()&&navigator.product===y0}function b0(){return zi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="android"}function v0(){return zi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="ios"}function Uo(){return!qa()&&!!h.cjsExports$2.getNavigator()&&!!h.cjsExports$2.getDocument()}function Lo(){return zi()?cs.reactNative:qa()?cs.node:Uo()?cs.browser:cs.unknown}function ju(){var s;try{return zi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Application)<"u"?(s=_.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function I0(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 E0(){if(Lo()===cs.reactNative&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"){const{OS:t,Version:i}=_.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 A0(){var s;const e=Lo();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=E0(),r=A0();return[[s,e].join("-"),[m0,t].join("-"),i,r].join("/")}function N0({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=I0(l[1]||"",d);return l[0]+"?"+p}function nr(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 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 Pi(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 C0(s){return kf("topic",s)}function _0(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 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 Pe(s,e){return`${s}${e?`:${e}`:""}`}function Pa(s=[],e=[]){return[...new Set([...s,...e])]}async function S0({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=$0(n,s,e),a=Lo();if(a===cs.browser){if(!((i=h.cjsExports$2.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}T0(o)}else a===cs.reactNative&&typeof(_.global==null?void 0:_.global.Linking)<"u"&&await _.global.Linking.openURL(o)}catch(r){console.error(r)}}function $0(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}${O0(i,!0)}`}else r=`${r}/wc?${i}`;return r}function T0(s){let e="_self";M0()?e="_top":(x0()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function P0(s,e){let t="";try{if(Uo()&&(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 Th(){return typeof _.process$1<"u"&&_.process$1.env.IS_VITEST==="true"}function x0(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function M0(){try{return window.self!==window.top}catch{return!1}}function O0(s,e=!1){const t=_.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Rf(s){return _.Buffer.from(s,"base64").toString("utf-8")}function D0(s){return new Promise(e=>setTimeout(e,s))}function No(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function k0(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function oc(s,...e){if(!k0(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 Ph(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");No(s.outputLen),No(s.blockLen)}function In(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){oc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ca=BigInt(2**32-1),Lu=BigInt(32);function j0(s,e=!1){return e?{h:Number(s&ca),l:Number(s>>Lu&ca)}:{h:Number(s>>Lu&ca)|0,l:Number(s&ca)|0}}function R0(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}=j0(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const U0=(s,e,t)=>s<<t|e>>>32-t,L0=(s,e,t)=>e<<t|s>>>32-t,z0=(s,e,t)=>e<<t-32|s>>>64-t,F0=(s,e,t)=>s<<t-32|e>>>64-t,Cr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function q0(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Mc(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 B0(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]=B0(s[e])}function H0(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function En(s){return typeof s=="string"&&(s=H0(s)),oc(s),s}let xh=class{clone(){return this._cloneInto()}};function Lf(s){const e=i=>s().update(En(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function zo(s=32){if(Cr&&typeof Cr.getRandomValues=="function")return Cr.getRandomValues(new Uint8Array(s));if(Cr&&typeof Cr.randomBytes=="function")return Cr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const zf=[],Ff=[],qf=[],W0=BigInt(0),zn=BigInt(1),V0=BigInt(2),K0=BigInt(7),G0=BigInt(256),Y0=BigInt(113);for(let s=0,e=zn,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=W0;for(let n=0;n<7;n++)e=(e<<zn^(e>>K0)*Y0)%G0,e&V0&&(r^=zn<<(zn<<BigInt(n))-zn);qf.push(r)}const[Q0,J0]=R0(qf,!0),qu=(s,e,t)=>t>32?z0(s,e,t):U0(s,e,t),Bu=(s,e,t)=>t>32?F0(s,e,t):L0(s,e,t);function Z0(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]^=J0[i]}t.fill(0)}let X0=class Bf extends xh{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,No(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=q0(this.state)}keccak(){zu||Fu(this.state32),Z0(this.state32,this.rounds),zu||Fu(this.state32),this.posOut=0,this.pos=0}update(e){In(this);const{blockLen:t,state:i}=this;e=En(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){In(this,!1),oc(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 No(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 eI=(s,e,t)=>Lf(()=>new X0(e,s,t)),tI=eI(1,136,256/8),sI="https://rpc.walletconnect.org/v1";function Hf(s){const e=`Ethereum Signed Message:
1
+ "use strict";const Ke=require("./unsignedTransaction-qRBv5Cnd.js"),ti=require("./hypercore-D7kZiwbe.js"),oe=require("./index-XjDX4fWv.js"),zb=require("./util-G2vxTeU2.js"),Fb=require("./wallets-DLkIKXkb.js"),di=require("./index-Cb_8WAm1.js"),_=require("./platform-DCcL7jHP.js"),h=require("./index.es-BZRO-bNH.js"),k=require("./lit-element-Cpy16KIW.js"),wn=require("./http-D4VeaDBj.js");class qb extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}function Bb(s,{signal:e}={}){return new Promise((t,i)=>{const r=()=>{i(new qb)},n=()=>{clearTimeout(o),r()};if(e?.aborted)return r();const o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},s);e?.addEventListener("abort",n,{once:!0})})}const Cu=0,Hb=Number.POSITIVE_INFINITY;async function Wb(s,e){let t,i,r;typeof e=="number"?(t=Cu,i=e,r=void 0):(t=e?.delay??Cu,i=e?.retries??Hb,r=e?.signal);let n;for(let o=0;o<i;o++){if(r?.aborted)throw n??new Error("The retry operation was aborted due to an abort signal.");try{return await s()}catch(a){n=a;const c=typeof t=="function"?t(o):t;await Bb(c)}}throw n}class Ot extends Error{constructor(e,t){super(e),this.error=t}}class Li extends Ot{constructor(){super(...arguments),this.name="WalletNotReadyError"}}class Vb extends Ot{constructor(){super(...arguments),this.name="WalletLoadError"}}class un extends Ot{constructor(){super(...arguments),this.name="WalletConfigError"}}class rc extends Ot{constructor(){super(...arguments),this.name="WalletConnectionError"}}class hf extends Ot{constructor(){super(...arguments),this.name="WalletDisconnectedError"}}class Oo extends Ot{constructor(){super(...arguments),this.name="WalletDisconnectionError"}}class Es extends Ot{constructor(){super(...arguments),this.name="WalletAccountError"}}class wr extends Ot{constructor(){super(...arguments),this.name="WalletPublicKeyError"}}class Ge extends Ot{constructor(){super(...arguments),this.name="WalletNotConnectedError"}}class rr extends Ot{constructor(){super(...arguments),this.name="WalletSendTransactionError"}}class nt extends Ot{constructor(){super(...arguments),this.name="WalletSignTransactionError"}}class Do extends Ot{constructor(){super(...arguments),this.name="WalletSignMessageError"}}class _u extends Ot{constructor(){super(...arguments),this.name="WalletSignInError"}}class Kb extends Ot{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 uf extends Ke.EventEmitter{get connected(){return!!this.publicKey}async autoConnect(){await this.connect()}async prepareTransaction(e,t,i={}){const r=this.publicKey;if(!r)throw new Ge;return e.feePayer=e.feePayer||r,e.recentBlockhash=e.recentBlockhash||(await t.getLatestBlockhash({commitment:i.preflightCommitment,minContextSlot:i.minContextSlot})).blockhash,e}}function ko(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 pi(s){return"version"in s}class Sh extends uf{async sendTransaction(e,t,i={}){let r=!0;try{if(pi(e)){if(!this.supportedTransactionVersions)throw new rr("Sending versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(e.version))throw new rr(`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 nt?(r=!1,n):new rr(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 nt?(r=!1,n):new rr(n?.message,n)}}catch(n){throw r&&this.emit("error",n),n}}async signAllTransactions(e){for(const i of e)if(pi(i)){if(!this.supportedTransactionVersions)throw new nt("Signing versioned transactions isn't supported by this wallet");if(!this.supportedTransactionVersions.has(i.version))throw new nt(`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 jo extends Sh{}function Gb(s){return oe.StandardConnect in s.features&&oe.StandardEvents in s.features&&(oe.SolanaSignAndSendTransaction in s.features||oe.SolanaSignTransaction in s.features)}var Eo;(function(s){s.Mainnet="mainnet-beta",s.Testnet="testnet",s.Devnet="devnet"})(Eo||(Eo={}));const Yb="Bitget";class Qb extends jo{constructor(e={}){super(),this.name=Yb,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&&ko(()=>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 Li;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 Ke.PublicKey(t)}catch(r){throw new wr(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 Oo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{const{signature:i}=await t.signMessage(e);return i}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Jb="Clover";class Zb extends jo{constructor(e={}){super(),this.name=Jb,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&&ko(()=>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 Li;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 Ke.PublicKey(t)}catch(r){throw new wr(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 Ge;try{return await t.signTransaction(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{const{signature:i}=await t.signMessage(e);return Uint8Array.from(i)}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}function Xb(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 N=g-1;(m!==0||A<d)&&N!==-1;N--,A++)m+=256*w[N]>>>0,w[N]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(u);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,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 N=0;for(let S=f-1;(A!==0||N<p)&&S!==-1;S--,N++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=N,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 ev="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const $c=Xb(ev),tv="Coin98";class sv extends jo{constructor(e={}){super(),this.name=tv,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&&ko(()=>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 Li;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 Ke.PublicKey(t)}catch(r){throw new wr(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 Oo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{const i=await t.request({method:"sol_sign",params:[e]}),r=new Ke.PublicKey(i.publicKey),n=$c.decode(i.signature);return e.addSignature(r,_.Buffer.from(n)),e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{const i=await t.request({method:"sol_signAllTransactions",params:[e]}),r=new Ke.PublicKey(i.publicKey),n=i.signatures;return e.map((o,a)=>{const c=$c.decode(n[a]);return o.addSignature(r,_.Buffer.from(c)),o})}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{const i=await t.request({method:"sol_signMessage",params:[e]});return $c.decode(i.signature)}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const iv="Nightly";class df extends jo{constructor(){super(),this.name=iv,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&&ko(()=>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 Li;this._connecting=!0;const e=window.nightly.solana;try{await e.connect()}catch(i){throw new rc(i?.message,i)}if(e.publicKey.toString()==="11111111111111111111111111111111")throw new Es;let t;try{t=new Ke.PublicKey(e.publicKey.toBytes())}catch(i){throw new wr(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 hf)}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{return t.signMessage(new TextDecoder().decode(e))}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const rv="Solong";class nv extends Sh{constructor(e={}){super(),this.name=rv,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&&ko(()=>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 Li;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 Ke.PublicKey(t)}catch(r){throw new wr(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 Ge;try{return await t.signTransaction(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const ov="Torus";class av extends jo{constructor({params:e={showTorusButton:!1}}={params:{showTorusButton:!1}}){super(),this.name=ov,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 Li;this._connecting=!0;let e;try{e=(await Promise.resolve().then(()=>require("./solanaEmbed.esm-C8TjRcIV.js"))).default}catch(n){throw new Vb(n?.message,n)}let t;try{t=window.torus||new e}catch(n){throw new un(n?.message,n)}if(!t.isInitialized)try{await t.init(this._params)}catch(n){throw new rc(n?.message,n)}let i;try{i=await t.login()}catch(n){throw new Es(n?.message,n)}let r;try{r=new Ke.PublicKey(i[0])}catch(n){throw new wr(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 Oo(t?.message,t))}}this.emit("disconnect")}async sendTransaction(e,t,i={}){try{const r=this._wallet;if(!r)throw new Ge;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 Ot?n:new rr(n?.message,n)}}catch(r){throw this.emit("error",r),r}}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)||e}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signMessage(e)}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}function Tc(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 cv="https://api.mainnet-beta.solana.com";function lv(s){return s.includes(cv)?oe.SOLANA_MAINNET_CHAIN:/\bdevnet\b/i.test(s)?oe.SOLANA_DEVNET_CHAIN:/\btestnet\b/i.test(s)?oe.SOLANA_TESTNET_CHAIN:/\blocalhost\b/i.test(s)||/\b127\.0\.0\.1\b/.test(s)?oe.SOLANA_LOCALNET_CHAIN:oe.SOLANA_MAINNET_CHAIN}var za;(function(s){s.Mainnet="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",s.Devnet="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",s.Deprecated_Mainnet="solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",s.Deprecated_Devnet="solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"})(za||(za={}));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 ft={Mainnet:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",Devnet:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",Deprecated_Mainnet:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ",Deprecated_Devnet:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"};var hv=Object.defineProperty,uv=(s,e,t)=>e in s?hv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Su=(s,e,t)=>uv(s,typeof e!="symbol"?e+"":e,t);let dv=class extends h.IEvents{constructor(e){super(),this.opts=e,Su(this,"protocol","wc"),Su(this,"version",2)}};var pv=Object.defineProperty,gv=(s,e,t)=>e in s?pv(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fv=(s,e,t)=>gv(s,e+"",t);let wv=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,fv(this,"records",new Map)}},yv=class{constructor(e,t){this.logger=e,this.core=t}},mv=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},bv=class extends h.IEvents{constructor(e){super()}},vv=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},Iv=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},Ev=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},Av=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},Nv=class{constructor(e,t){this.projectId=e,this.logger=t}},Cv=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};function Ao(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 Ao(s,{strict:!1})?Math.ceil((s.length-2)/2):s.length}const pf="2.23.2";let Pc={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${pf}`},nc=class Al extends Error{constructor(e,t={}){const i=t.cause instanceof Al?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof Al&&t.cause.docsPath||t.docsPath,n=Pc.getDocsUrl?.({...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...Pc.version?[`Version: ${Pc.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 nc{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 Sn(s,{dir:e,size:t=32}={}){return typeof s=="string"?_v(s,{dir:e,size:t}):Sv(s,{dir:e,size:t})}function _v(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 Sv(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 $v=class extends nc{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"})}},Tv=class extends nc{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 Tv({givenSize:$u(s),maxSize:e})}function Nl(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 Pv(s,e={}){return Number(Nl(s,e))}const xv=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Cl(s,e={}){return typeof s=="number"||typeof s=="bigint"?yf(s,e):typeof s=="string"?Dv(s,e):typeof s=="boolean"?Mv(s,e):wf(s,e)}function Mv(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?($n(t,{size:e.size}),Sn(t,{size:e.size})):t}function wf(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=xv[s[r]];const i=`0x${t}`;return typeof e.size=="number"?($n(i,{size:e.size}),Sn(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 $v({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?Sn(a,{size:i}):a}const Ov=new TextEncoder;function Dv(s,e={}){const t=Ov.encode(s);return wf(t,e)}const kv=new TextEncoder;function jv(s,e={}){return typeof s=="number"||typeof s=="bigint"?Uv(s,e):typeof s=="boolean"?Rv(s,e):Ao(s)?mf(s,e):bf(s,e)}function Rv(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?($n(t,{size:e.size}),Sn(t,{size:e.size})):t}const si={zero:48,nine:57,A:65,F:70,a:97,f:102};function Tu(s){if(s>=si.zero&&s<=si.nine)return s-si.zero;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 mf(s,e={}){let t=s;e.size&&($n(t,{size:e.size}),t=Sn(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 nc(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function Uv(s,e){const t=yf(s,e);return mf(t)}function bf(s,e={}){const t=kv.encode(s);return typeof e.size=="number"?($n(t,{size:e.size}),Sn(t,{dir:"right",size:e.size})):t}function Fa(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function Lv(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ro(s,...e){if(!Lv(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 zv(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Fa(s.outputLen),Fa(s.blockLen)}function _l(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){Ro(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const aa=BigInt(2**32-1),Pu=BigInt(32);function Fv(s,e=!1){return e?{h:Number(s&aa),l:Number(s>>Pu&aa)}:{h:Number(s>>Pu&aa)|0,l:Number(s&aa)|0}}function qv(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}=Fv(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const Bv=(s,e,t)=>s<<t|e>>>32-t,Hv=(s,e,t)=>e<<t|s>>>32-t,Wv=(s,e,t)=>e<<t-32|s>>>64-t,Vv=(s,e,t)=>s<<t-32|e>>>64-t,Nr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Kv(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Gv(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function Yv(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 Jv(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function $h(s){return typeof s=="string"&&(s=Jv(s)),Ro(s),s}function Zv(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Ro(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($h(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Xv(s=32){if(Nr&&typeof Nr.getRandomValues=="function")return Nr.getRandomValues(new Uint8Array(s));if(Nr&&typeof Nr.randomBytes=="function")return Nr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Af=[],Nf=[],Cf=[],e0=BigInt(0),Ln=BigInt(1),t0=BigInt(2),s0=BigInt(7),i0=BigInt(256),r0=BigInt(113);for(let s=0,e=Ln,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=e0;for(let n=0;n<7;n++)e=(e<<Ln^(e>>s0)*r0)%i0,e&t0&&(r^=Ln<<(Ln<<BigInt(n))-Ln);Cf.push(r)}const[n0,o0]=qv(Cf,!0),Ou=(s,e,t)=>t>32?Wv(s,e,t):Bv(s,e,t),Du=(s,e,t)=>t>32?Vv(s,e,t):Hv(s,e,t);function a0(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]^=n0[i],s[1]^=o0[i]}t.fill(0)}let c0=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,Fa(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Kv(this.state)}keccak(){xu||Mu(this.state32),a0(this.state32,this.rounds),xu||Mu(this.state32),this.posOut=0,this.pos=0}update(e){_l(this);const{blockLen:t,state:i}=this;e=$h(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){_l(this,!1),Ro(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 Fa(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 l0=(s,e,t)=>Ef(()=>new c0(e,s,t)),h0=l0(1,136,256/8);function Sf(s,e){const t=e||"hex",i=h0(Ao(s,{strict:!1})?jv(s):s);return t==="bytes"?i:Cl(i)}let u0=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 xc=new u0(8192);function d0(s,e){if(xc.has(`${s}.${e}`))return xc.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 xc.set(`${s}.${e}`,n),n}function p0(s){const e=Sf(`0x${s.substring(4)}`).substring(26);return d0(`0x${e}`)}async function g0({hash:s,signature:e}){const t=Ao(s)?s:Cl(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-D5cKS6q_.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(Nl(l),Nl(u)).addRecoveryBit(g)}const o=Ao(e)?e:Cl(e),a=Pv(`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 f0({hash:s,signature:e}){return p0(await g0({hash:s,signature:e}))}var $f=di.requireElliptic();const Tf=":";function yn(s){const[e,t]=s.split(Tf);return{namespace:e,reference:t}}function w0(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 y0="ReactNative",cs={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},m0="js";function qa(){return typeof _.process$1<"u"&&typeof _.process$1.versions<"u"&&typeof _.process$1.versions.node<"u"}function zi(){return!h.cjsExports$2.getDocument()&&!!h.cjsExports$2.getNavigator()&&navigator.product===y0}function b0(){return zi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="android"}function v0(){return zi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="ios"}function Uo(){return!qa()&&!!h.cjsExports$2.getNavigator()&&!!h.cjsExports$2.getDocument()}function Lo(){return zi()?cs.reactNative:qa()?cs.node:Uo()?cs.browser:cs.unknown}function ju(){var s;try{return zi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Application)<"u"?(s=_.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function I0(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 E0(){if(Lo()===cs.reactNative&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"){const{OS:t,Version:i}=_.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 A0(){var s;const e=Lo();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=E0(),r=A0();return[[s,e].join("-"),[m0,t].join("-"),i,r].join("/")}function N0({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=I0(l[1]||"",d);return l[0]+"?"+p}function nr(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 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 Pi(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 C0(s){return kf("topic",s)}function _0(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 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 Pe(s,e){return`${s}${e?`:${e}`:""}`}function Pa(s=[],e=[]){return[...new Set([...s,...e])]}async function S0({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=$0(n,s,e),a=Lo();if(a===cs.browser){if(!((i=h.cjsExports$2.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}T0(o)}else a===cs.reactNative&&typeof(_.global==null?void 0:_.global.Linking)<"u"&&await _.global.Linking.openURL(o)}catch(r){console.error(r)}}function $0(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}${O0(i,!0)}`}else r=`${r}/wc?${i}`;return r}function T0(s){let e="_self";M0()?e="_top":(x0()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function P0(s,e){let t="";try{if(Uo()&&(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 Th(){return typeof _.process$1<"u"&&_.process$1.env.IS_VITEST==="true"}function x0(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function M0(){try{return window.self!==window.top}catch{return!1}}function O0(s,e=!1){const t=_.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Rf(s){return _.Buffer.from(s,"base64").toString("utf-8")}function D0(s){return new Promise(e=>setTimeout(e,s))}function No(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function k0(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function oc(s,...e){if(!k0(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 Ph(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");No(s.outputLen),No(s.blockLen)}function In(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){oc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ca=BigInt(2**32-1),Lu=BigInt(32);function j0(s,e=!1){return e?{h:Number(s&ca),l:Number(s>>Lu&ca)}:{h:Number(s>>Lu&ca)|0,l:Number(s&ca)|0}}function R0(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}=j0(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const U0=(s,e,t)=>s<<t|e>>>32-t,L0=(s,e,t)=>e<<t|s>>>32-t,z0=(s,e,t)=>e<<t-32|s>>>64-t,F0=(s,e,t)=>s<<t-32|e>>>64-t,Cr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function q0(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Mc(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 B0(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]=B0(s[e])}function H0(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function En(s){return typeof s=="string"&&(s=H0(s)),oc(s),s}let xh=class{clone(){return this._cloneInto()}};function Lf(s){const e=i=>s().update(En(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function zo(s=32){if(Cr&&typeof Cr.getRandomValues=="function")return Cr.getRandomValues(new Uint8Array(s));if(Cr&&typeof Cr.randomBytes=="function")return Cr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const zf=[],Ff=[],qf=[],W0=BigInt(0),zn=BigInt(1),V0=BigInt(2),K0=BigInt(7),G0=BigInt(256),Y0=BigInt(113);for(let s=0,e=zn,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=W0;for(let n=0;n<7;n++)e=(e<<zn^(e>>K0)*Y0)%G0,e&V0&&(r^=zn<<(zn<<BigInt(n))-zn);qf.push(r)}const[Q0,J0]=R0(qf,!0),qu=(s,e,t)=>t>32?z0(s,e,t):U0(s,e,t),Bu=(s,e,t)=>t>32?F0(s,e,t):L0(s,e,t);function Z0(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]^=J0[i]}t.fill(0)}let X0=class Bf extends xh{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,No(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=q0(this.state)}keccak(){zu||Fu(this.state32),Z0(this.state32,this.rounds),zu||Fu(this.state32),this.posOut=0,this.pos=0}update(e){In(this);const{blockLen:t,state:i}=this;e=En(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){In(this,!1),oc(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 No(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 eI=(s,e,t)=>Lf(()=>new X0(e,s,t)),tI=eI(1,136,256/8),sI="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"+_.Buffer.from(tI(t)).toString("hex")}async function iI(s,e,t,i,r,n){switch(t.t){case"eip191":return await rI(s,e,t.s);case"eip1271":return await nI(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function rI(s,e,t){return(await f0({hash:Hf(e),signature:t})).toLowerCase()===s.toLowerCase()}async function nI(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=Hf(e).substring(2),p=a+d+c+l+u,f=await fetch(`${n||sI}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:oI(),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 oI(){return Date.now()+Math.floor(Math.random()*1e3)}var aI=Object.defineProperty,cI=Object.defineProperties,lI=Object.getOwnPropertyDescriptors,Hu=Object.getOwnPropertySymbols,hI=Object.prototype.hasOwnProperty,uI=Object.prototype.propertyIsEnumerable,Wu=(s,e,t)=>e in s?aI(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,dI=(s,e)=>{for(var t in e||(e={}))hI.call(e,t)&&Wu(s,t,e[t]);if(Hu)for(var t of Hu(e))uI.call(e,t)&&Wu(s,t,e[t]);return s},pI=(s,e)=>cI(s,lI(e));const gI="did:pkh:",Mh=s=>s?.split(":"),fI=s=>{const e=s&&Mh(s);if(e)return s.includes(gI)?e[3]:e[1]},Sl=s=>{const e=s&&Mh(s);if(e)return e[2]+":"+e[3]},Ba=s=>{const e=s&&Mh(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=Ba(r.iss);return await iI(o,n,i,Sl(r.iss),t)}const Wf=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=Ba(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: ${fI(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=xa(s.resources);if(g){const w=Co(g);r=NI(r,w)}return[t,i,"",r,"",n,o,a,c,l,u,d,p,f].filter(w=>w!=null).join(`
5
5
  `)};function wI(s){return _.Buffer.from(JSON.stringify(s)).toString("base64")}function yI(s){return JSON.parse(_.Buffer.from(s,"base64").toString("utf-8"))}function lr(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 mI(s,e,t,i={}){return t?.sort((r,n)=>r.localeCompare(n)),{att:{[s]:bI(e,t,i)}}}function bI(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 lr(s),`urn:recap:${wI(s).replace(/=/g,"")}`}function Co(s){const e=yI(s.replace("urn:recap:",""));return lr(e),e}function vI(s,e,t){const i=mI(s,e,t);return Vf(i)}function II(s){return s&&s.includes("urn:recap:")}function EI(s,e){const t=Co(s),i=Co(e),r=AI(t,i);return Vf(r)}function AI(s,e){lr(s),lr(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]=pI(dI({},i.att[r]),{[a]:((c=s.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),i}function NI(s="",e){lr(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=Co(s);lr(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=Co(s);lr(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 xa(s){if(!s)return;const e=s?.[s.length-1];return II(e)?e:void 0}function Oc(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 CI(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 ki=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),_I=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),SI=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!SI)throw new Error("Non little-endian hardware is not supported");function $I(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function $l(s){if(typeof s=="string")s=$I(s);else if(Kf(s))s=Tl(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function TI(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function PI(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 xI=(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&&!MI(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 MI(s){return s.byteOffset%4===0}function Tl(s){return Uint8Array.from(s)}function An(...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))),OI=Gf("expand 16-byte k"),DI=Gf("expand 32-byte k"),kI=ki(OI),jI=ki(DI);function Ee(s,e){return s<<e|s>>>32-e}function Pl(s){return s.byteOffset%4===0}const la=64,RI=16,Yf=2**32-1,Xu=new Uint32Array;function UI(s,e,t,i,r,n,o,a){const c=r.length,l=new Uint8Array(la),u=ki(l),d=Pl(r)&&Pl(n),p=d?ki(r):Xu,f=d?ki(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(la,c-g);if(d&&w===la){const v=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let b=0,m;b<RI;b++)m=v+b,f[m]=p[m]^u[b];g+=la;continue}for(let v=0,b;v<w;v++)b=g+v,n[b]=r[b]^l[v];g+=w}}function LI(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=TI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return Oc(r),Oc(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),Oc(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,v;if(g===32)f.push(w=Tl(a)),v=jI;else if(g===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),v=kI,f.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Pl(c)||f.push(c=Tl(c));const b=ki(w);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(v,b,ki(c.subarray(0,16)),b),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 N=new Uint8Array(12);N.set(c,n?0:12-c.length),c=N,f.push(c)}const A=ki(c);return UI(s,v,b,A,l,u,d,o),An(...f),u}}const Ct=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let zI=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=$l(e),os(e,32);const t=Ct(e,0),i=Ct(e,2),r=Ct(e,4),n=Ct(e,6),o=Ct(e,8),a=Ct(e,10),c=Ct(e,12),l=Ct(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]=Ct(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],v=o[9],b=Ct(e,t+0),m=Ct(e,t+2),A=Ct(e,t+4),N=Ct(e,t+6),S=Ct(e,t+8),$=Ct(e,t+10),O=Ct(e,t+12),D=Ct(e,t+14);let T=n[0]+(b&8191),q=n[1]+((b>>>13|m<<3)&8191),j=n[2]+((m>>>10|A<<6)&8191),G=n[3]+((A>>>7|N<<9)&8191),B=n[4]+((N>>>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),C=0,z=C+T*a+q*(5*v)+j*(5*w)+G*(5*g)+B*(5*f);C=z>>>13,z&=8191,z+=W*(5*p)+V*(5*d)+H*(5*u)+K*(5*l)+Q*(5*c),C+=z>>>13,z&=8191;let ee=C+T*c+q*a+j*(5*v)+G*(5*w)+B*(5*g);C=ee>>>13,ee&=8191,ee+=W*(5*f)+V*(5*p)+H*(5*d)+K*(5*u)+Q*(5*l),C+=ee>>>13,ee&=8191;let J=C+T*l+q*c+j*a+G*(5*v)+B*(5*w);C=J>>>13,J&=8191,J+=W*(5*g)+V*(5*f)+H*(5*p)+K*(5*d)+Q*(5*u),C+=J>>>13,J&=8191;let ve=C+T*u+q*l+j*c+G*a+B*(5*v);C=ve>>>13,ve&=8191,ve+=W*(5*w)+V*(5*g)+H*(5*f)+K*(5*p)+Q*(5*d),C+=ve>>>13,ve&=8191;let pe=C+T*d+q*u+j*l+G*c+B*a;C=pe>>>13,pe&=8191,pe+=W*(5*v)+V*(5*w)+H*(5*g)+K*(5*f)+Q*(5*p),C+=pe>>>13,pe&=8191;let te=C+T*p+q*d+j*u+G*l+B*c;C=te>>>13,te&=8191,te+=W*a+V*(5*v)+H*(5*w)+K*(5*g)+Q*(5*f),C+=te>>>13,te&=8191;let it=C+T*f+q*p+j*d+G*u+B*l;C=it>>>13,it&=8191,it+=W*c+V*a+H*(5*v)+K*(5*w)+Q*(5*g),C+=it>>>13,it&=8191;let Le=C+T*g+q*f+j*p+G*d+B*u;C=Le>>>13,Le&=8191,Le+=W*l+V*c+H*a+K*(5*v)+Q*(5*w),C+=Le>>>13,Le&=8191;let Ie=C+T*w+q*g+j*f+G*p+B*d;C=Ie>>>13,Ie&=8191,Ie+=W*u+V*l+H*c+K*a+Q*(5*v),C+=Ie>>>13,Ie&=8191;let ke=C+T*v+q*w+j*g+G*f+B*p;C=ke>>>13,ke&=8191,ke+=W*d+V*u+H*l+K*c+Q*a,C+=ke>>>13,ke&=8191,C=(C<<2)+C|0,C=C+z|0,z=C&8191,C=C>>>13,ee+=C,n[0]=z,n[1]=ee,n[2]=J,n[3]=ve,n[4]=pe,n[5]=te,n[6]=it,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;An(i)}update(e){Yu(this);const{buffer:t,blockLen:i}=this;e=$l(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(){An(this.h,this.r,this.buffer,this.pad)}digestInto(e){Yu(this),CI(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 FI(s){const e=(i,r)=>s(r).update($l(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const qI=FI(s=>new zI(s));function BI(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],v=e[6],b=e[7],m=r,A=t[0],N=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=v,K=b,Q=m,C=A,z=N,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,C=Ee(C^O,16),V=V+C|0,j=Ee(j^V,12),O=O+j|0,C=Ee(C^O,8),V=V+C|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,C=Ee(C^D,16),W=W+C|0,B=Ee(B^W,12),D=D+B|0,C=Ee(C^D,8),W=W+C|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++]=v+H|0,i[J++]=b+K|0,i[J++]=m+Q|0,i[J++]=A+C|0,i[J++]=N+z|0,i[J++]=S+ee|0}const HI=LI(BI,{counterRight:!1,counterLength:4,allowShortKeys:!1}),WI=new Uint8Array(16),ed=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(WI.subarray(t))},VI=new Uint8Array(32);function td(s,e,t,i,r){const n=s(e,t,VI),o=qI.create(n);r&&ed(o,r),ed(o,i);const a=new Uint8Array(16),c=_I(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 An(n,a),l}const KI=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),An(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(!PI(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),An(c),n}}),Qf=xI({blockSize:64,nonceLength:12,tagLength:16},KI(HI));let Jf=class extends xh{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ph(e);const i=En(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 In(this),this.iHash.update(e),this}digestInto(e){In(this),oc(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 Oh=(s,e,t)=>new Jf(s,e).update(t).digest();Oh.create=(s,e)=>new Jf(s,e);function GI(s,e,t){return Ph(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Oh(s,En(t),En(e))}const Dc=new Uint8Array([0]),sd=new Uint8Array;function YI(s,e,t,i=32){if(Ph(s),No(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=Oh.create(s,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)Dc[0]=l+1,a.update(l===0?sd:c).update(t).update(Dc).digestInto(c),n.set(c,s.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Dc.fill(0),n.slice(0,i)}const QI=(s,e,t,i,r)=>YI(s,GI(s,e,t),i,r);function JI(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 ZI(s,e,t){return s&e^~s&t}function XI(s,e,t){return s&e^s&t^e&t}let e1=class extends xh{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=Mc(this.buffer)}update(e){In(this);const{view:t,buffer:i,blockLen:r}=this;e=En(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=Mc(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){In(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;JI(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=Mc(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 t1=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]),vi=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ii=new Uint32Array(64);let s1=class extends e1{constructor(){super(64,32,8,!1),this.A=vi[0]|0,this.B=vi[1]|0,this.C=vi[2]|0,this.D=vi[3]|0,this.E=vi[4]|0,this.F=vi[5]|0,this.G=vi[6]|0,this.H=vi[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)Ii[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const p=Ii[d-15],f=Ii[d-2],g=Ls(p,7)^Ls(p,18)^p>>>3,w=Ls(f,17)^Ls(f,19)^f>>>10;Ii[d]=w+Ii[d-7]+g+Ii[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+ZI(a,c,l)+t1[d]+Ii[d]|0,g=(Ls(i,2)^Ls(i,13)^Ls(i,22))+XI(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(){Ii.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const ac=Lf(()=>new s1);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Zf=BigInt(0);function Dh(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Xf(s){if(!Dh(s))throw new Error("Uint8Array expected")}const i1=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function r1(s){Xf(s);let e="";for(let t=0;t<s.length;t++)e+=i1[s[t]];return e}function n1(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Zf:BigInt("0x"+s)}const ii={_0:48,_9:57,A:65,F:70,a:97,f:102};function id(s){if(s>=ii._0&&s<=ii._9)return s-ii._0;if(s>=ii.A&&s<=ii.F)return s-(ii.A-10);if(s>=ii.a&&s<=ii.f)return s-(ii.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),n1(r1(Uint8Array.from(s).reverse()))}function o1(s,e){return ew(s.toString(16).padStart(e*2,"0"))}function a1(s,e){return o1(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(Dh(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 kc=s=>typeof s=="bigint"&&Zf<=s;function c1(s,e,t){return kc(s)&&kc(e)&&kc(t)&&e<=s&&s<t}function od(s,e,t,i){if(!c1(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const l1={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"||Dh(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 h1(s,e,t={}){const i=(r,n,o)=>{const a=l1[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 dn=BigInt(0),ha=BigInt(1);function tw(s,e){const t=s%e;return t>=dn?t:e+t}function u1(s,e,t){if(e<dn)throw new Error("invalid exponent, negatives unsupported");if(t<=dn)throw new Error("invalid modulus");if(t===ha)return dn;let i=ha;for(;e>dn;)e&ha&&(i=i*s%t),s=s*s%t,e>>=ha;return i}function Os(s,e,t){let i=s;for(;e-- >dn;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const _r=BigInt(0),jc=BigInt(1);function d1(s){return h1(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function p1(s){const e=d1(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=>u1(m,t-BigInt(2),t));function l(m,A,N){const S=i(m*(A-N));return A=i(A-S),N=i(N+S),[A,N]}const u=(e.a-BigInt(2))/BigInt(4);function d(m,A){od("u",m,_r,t),od("scalar",A,_r,t);const N=A,S=m;let $=jc,O=_r,D=m,T=jc,q=_r,j;for(let B=BigInt(r-1);B>=_r;B--){const W=N>>B&jc;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),C=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(C*(H+i(u*C)))}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 a1(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),N=A.length;if(N!==n&&N!==o){let S=""+n+" or "+o;throw new Error("invalid scalar, expected "+S+" bytes, got "+N)}return rd(a(A))}function w(m,A){const N=f(A),S=g(m),$=d(N,S);if($===_r)throw new Error("invalid private or public key received");return p($)}const v=p(e.Gu);function b(m){return w(m,v)}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(m,A)=>w(m,A),getPublicKey:m=>b(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}const xl=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const g1=BigInt(1),ad=BigInt(2),f1=BigInt(3),w1=BigInt(5);BigInt(8);function y1(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=xl,o=s*s%n*s%n,a=Os(o,ad,n)*o%n,c=Os(a,g1,n)*s%n,l=Os(c,w1,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 m1(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const Ml=p1({P:xl,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=xl,{pow_p_5_8:t,b2:i}=y1(s);return tw(Os(t,f1,e)*i,e)},adjustScalarBytes:m1,randomBytes:zo}),sw="base10",Ft="base16",xi="base64pad",Fn="base64url",Fo="utf8",iw=0,gi=1,qo=2,b1=0,cd=1,po=12,kh=32;function v1(){const s=Ml.utils.randomPrivateKey(),e=Ml.getPublicKey(s);return{privateKey:h.toString(s,Ft),publicKey:h.toString(e,Ft)}}function Ol(){const s=zo(kh);return h.toString(s,Ft)}function I1(s,e){const t=Ml.getSharedSecret(h.fromString(s,Ft),h.fromString(e,Ft)),i=QI(ac,t,void 0,void 0,kh);return h.toString(i,Ft)}function Ma(s){const e=ac(h.fromString(s,Ft));return h.toString(e,Ft)}function ui(s){const e=ac(h.fromString(s,Fo));return h.toString(e,Ft)}function rw(s){return h.fromString(`${s}`,sw)}function hr(s){return Number(h.toString(s,sw))}function E1(s){const e=rw(typeof s.type<"u"?s.type:iw);if(hr(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):zo(po),r=h.fromString(s.symKey,Ft),n=Qf(r,i).encrypt(h.fromString(s.message,Fo));return nw({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function A1(s){const e=h.fromString(s.symKey,Ft),{sealed:t,iv:i}=_o(s),r=Qf(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return h.toString(r,Fo)}function N1(s,e){const t=rw(qo),i=zo(po),r=h.fromString(s,Fo);return nw({type:t,sealed:r,iv:i,encoding:e})}function C1(s,e){const{sealed:t}=_o({encoded:s,encoding:e});return h.toString(t,Fo)}function nw(s){const{encoding:e=xi}=s;if(hr(s.type)===qo)return h.toString(h.concat([s.type,s.sealed]),e);if(hr(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 _o(s){const{encoded:e,encoding:t=xi}=s,i=h.fromString(e,t),r=i.slice(b1,cd),n=cd;if(hr(r)===gi){const l=n+kh,u=l+po,d=i.slice(n,l),p=i.slice(l,u),f=i.slice(u);return{type:r,sealed:f,iv:p,senderPublicKey:d}}if(hr(r)===qo){const l=i.slice(n),u=zo(po);return{type:r,sealed:l,iv:u}}const o=n+po,a=i.slice(n,o),c=i.slice(o);return{type:r,sealed:c,iv:a}}function _1(s,e){const t=_o({encoded:s,encoding:e?.encoding});return ow({type:hr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?h.toString(t.senderPublicKey,Ft):void 0,receiverPublicKey:e?.receiverPublicKey})}function ow(s){const e=s?.type||iw;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 ld(s){return s.type===gi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function hd(s){return s.type===qo}function S1(s){return new $f.ec("p256").keyFromPublic({x:_.Buffer.from(s.x,"base64").toString("hex"),y:_.Buffer.from(s.y,"base64").toString("hex")},"hex")}function $1(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function T1(s){return _.Buffer.from($1(s),"base64")}function P1(s,e){const[t,i,r]=s.split("."),n=T1(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=ac(c),u=S1(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 x1="irn";function Ha(s){return s?.relay||{protocol:x1}}function ro(s){const e=h.C[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function M1(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:O1(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:M1(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function O1(s){return s.startsWith("//")?s.substring(2):s}function D1(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=D1(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 ua(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function Tn(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function k1(s){const e=[];return Object.values(s).forEach(t=>{e.push(...Tn(t.accounts))}),e}function j1(s,e){const t=[];return Object.values(s).forEach(i=>{Tn(i.accounts).includes(e)&&t.push(...i.methods)}),t}function R1(s,e){const t=[];return Object.values(s).forEach(i=>{Tn(i.accounts).includes(e)&&t.push(...i.events)}),t}function jh(s){return s.includes(":")}function no(s){return jh(s)?s.split(":")[0]:s}function U1(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=U1(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=Pa(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const L1={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}},z1={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}=z1[s];return{message:e?`${t} ${e}`:t,code:i}}function Re(s,e){const{message:t,code:i}=L1[s];return{message:e?`${t} ${e}`:t,code:i}}function ur(s,e){return!!Array.isArray(s)}function So(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function Ht(s){return typeof s>"u"}function ot(s,e){return e&&Ht(s)?!0:typeof s=="string"&&!!s.trim().length}function Rh(s,e){return e&&Ht(s)?!0:typeof s=="number"&&!isNaN(s)}function F1(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return nr(r,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=s.namespaces[o],u=Tn(a),d=t[o];(!nr(Pf(o,d),u)||!nr(d.methods,c)||!nr(d.events,l))&&(n=!1)}),n):!1}function Wa(s){return ot(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function q1(s){if(ot(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Wa(t)}}return!1}function B1(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ot(s,!1)){if(e(s))return!0;const t=Rf(s);return e(t)}}catch{}return!1}function H1(s){var e;return(e=s?.proposer)==null?void 0:e.publicKey}function W1(s){return s?.topic}function V1(s,e){let t=null;return ot(s?.publicKey,!1)||(t=U("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function gd(s){let e=!0;return ur(s)?s.length&&(e=s.every(t=>ot(t,!1))):e=!1,e}function K1(s,e,t){let i=null;return ur(e)&&e.length?e.forEach(r=>{i||Wa(r)||(i=Re("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Wa(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 G1(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=K1(r,Pf(r,n),`${e} ${t}`);o&&(i=o)}),i}function Y1(s,e){let t=null;return ur(s)?s.forEach(i=>{t||q1(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=Y1(i?.accounts,`${e} namespace`);r&&(t=r)}),t}function J1(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=J1(i,`${e}, namespace`);r&&(t=r)}),t}function Z1(s,e,t){let i=null;if(s&&So(s)){const r=aw(s,e);r&&(i=r);const n=G1(s,e,t);n&&(i=n)}else i=U("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function Rc(s,e){let t=null;if(s&&So(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 ot(s.protocol,!0)}function X1(s,e){let t=!1;return s?s&&ur(s)&&s.length&&s.forEach(i=>{t=cw(i)}):t=!0,t}function eE(s){return typeof s=="number"}function Jt(s){return typeof s<"u"&&typeof s!==null}function tE(s){return!(!s||typeof s!="object"||!s.code||!Rh(s.code,!1)||!s.message||!ot(s.message,!1))}function sE(s){return!(Ht(s)||!ot(s.method,!1))}function iE(s){return!(Ht(s)||Ht(s.result)&&Ht(s.error)||!Rh(s.id,!1)||!ot(s.jsonrpc,!1))}function rE(s){return!(Ht(s)||!ot(s.name,!1))}function fd(s,e){return!(!Wa(e)||!k1(s).includes(e))}function nE(s,e,t){return ot(t,!1)?j1(s,e).includes(t):!1}function oE(s,e,t){return ot(t,!1)?R1(s,e).includes(t):!1}function wd(s,e,t){let i=null;const r=aE(s),n=cE(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"+_.Buffer.from(tI(t)).toS
9
9
  Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||i)return;const p=Tn(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||(nr(r[d].methods,n[d].methods)?nr(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 aE(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 cE(s){const e={};return Object.keys(s).forEach(t=>{t.includes(":")?e[t]=s[t]:Tn(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 lE(s,e){return Rh(s,!1)&&s<=e.max&&s>=e.min}function md(){const s=Lo();return new Promise(e=>{switch(s){case cs.browser:e(hE());break;case cs.reactNative:e(uE());break;case cs.node:e(dE());break;default:e(!0)}})}function hE(){return Uo()&&navigator?.onLine}async function uE(){return zi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo?(await(_.global==null?void 0:_.global.NetInfo.fetch()))?.isConnected:!0}function dE(){return!0}function pE(s){switch(Lo()){case cs.browser:gE(s);break;case cs.reactNative:fE(s);break}}function gE(s){!zi()&&Uo()&&(window.addEventListener("online",()=>s(!0)),window.addEventListener("offline",()=>s(!1)))}function fE(s){zi()&&typeof _.global<"u"&&_.global!=null&&_.global.NetInfo&&_.global?.NetInfo.addEventListener(e=>s(e?.isConnected))}const Uc={};let qn=class{static get(e){return Uc[e]}static set(e,t){Uc[e]=t}static delete(e){delete Uc[e]}};var oo={exports:{}};oo.exports;var bd;function wE(){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]",v="[object Number]",b="[object Null]",m="[object Object]",A="[object Promise]",N="[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]",C="[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[C]=te[z]=te[ee]=!0,te[a]=te[c]=te[j]=te[u]=te[G]=te[d]=te[p]=te[f]=te[w]=te[v]=te[m]=te[S]=te[$]=te[O]=te[q]=!1;var it=typeof Ke.commonjsGlobal=="object"&&Ke.commonjsGlobal&&Ke.commonjsGlobal.Object===Object&&Ke.commonjsGlobal,Le=typeof self=="object"&&self&&self.Object===Object&&self,Ie=it||Le||Function("return this")(),ke=e&&!e.nodeType&&e,ks=ke&&!0&&s&&!s.nodeType&&s,js=ks&&ks.exports===ke,Zs=js&&it.process,Er=(function(){try{return Zs&&Zs.binding&&Zs.binding("util")}catch{}})(),Rs=Er&&Er.isTypedArray;function Dn(y,E){for(var P=-1,Y=y==null?0:y.length,Ye=0,ae=[];++P<Y;){var rt=y[P];E(rt,P,y)&&(ae[Ye++]=rt)}return ae}function xm(y,E){for(var P=-1,Y=E.length,Ye=y.length;++P<Y;)y[Ye+P]=E[P];return y}function Mm(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 Om(y,E){for(var P=-1,Y=Array(y);++P<y;)Y[P]=E(P);return Y}function Dm(y){return function(E){return y(E)}}function km(y,E){return y.has(E)}function jm(y,E){return y?.[E]}function Rm(y){var E=-1,P=Array(y.size);return y.forEach(function(Y,Ye){P[++E]=[Ye,Y]}),P}function Um(y,E){return function(P){return y(E(P))}}function Lm(y){var E=-1,P=Array(y.size);return y.forEach(function(Y){P[++E]=Y}),P}var zm=Array.prototype,Fm=Function.prototype,Xo=Object.prototype,Ic=Ie["__core-js_shared__"],au=Fm.toString,Us=Xo.hasOwnProperty,cu=(function(){var y=/[^.]+$/.exec(Ic&&Ic.keys&&Ic.keys.IE_PROTO||"");return y?"Symbol(src)_1."+y:""})(),lu=Xo.toString,qm=RegExp("^"+au.call(Us).replace(J,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),hu=js?Ie.Buffer:void 0,ea=Ie.Symbol,uu=Ie.Uint8Array,du=Xo.propertyIsEnumerable,Bm=zm.splice,qi=ea?ea.toStringTag:void 0,pu=Object.getOwnPropertySymbols,Hm=hu?hu.isBuffer:void 0,Wm=Um(Object.keys,Object),Ec=Ar(Ie,"DataView"),kn=Ar(Ie,"Map"),Ac=Ar(Ie,"Promise"),Nc=Ar(Ie,"Set"),Cc=Ar(Ie,"WeakMap"),jn=Ar(Object,"create"),Vm=Wi(Ec),Km=Wi(kn),Gm=Wi(Ac),Ym=Wi(Nc),Qm=Wi(Cc),gu=ea?ea.prototype:void 0,_c=gu?gu.valueOf:void 0;function Bi(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 Jm(){this.__data__=jn?jn(null):{},this.size=0}function Zm(y){var E=this.has(y)&&delete this.__data__[y];return this.size-=E?1:0,E}function Xm(y){var E=this.__data__;if(jn){var P=E[y];return P===i?void 0:P}return Us.call(E,y)?E[y]:void 0}function eb(y){var E=this.__data__;return jn?E[y]!==void 0:Us.call(E,y)}function tb(y,E){var P=this.__data__;return this.size+=this.has(y)?0:1,P[y]=jn&&E===void 0?i:E,this}Bi.prototype.clear=Jm,Bi.prototype.delete=Zm,Bi.prototype.get=Xm,Bi.prototype.has=eb,Bi.prototype.set=tb;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 sb(){this.__data__=[],this.size=0}function ib(y){var E=this.__data__,P=sa(E,y);if(P<0)return!1;var Y=E.length-1;return P==Y?E.pop():Bm.call(E,P,1),--this.size,!0}function rb(y){var E=this.__data__,P=sa(E,y);return P<0?void 0:E[P][1]}function nb(y){return sa(this.__data__,y)>-1}function ob(y,E){var P=this.__data__,Y=sa(P,y);return Y<0?(++this.size,P.push([y,E])):P[Y][1]=E,this}Xs.prototype.clear=sb,Xs.prototype.delete=ib,Xs.prototype.get=rb,Xs.prototype.has=nb,Xs.prototype.set=ob;function Hi(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 ab(){this.size=0,this.__data__={hash:new Bi,map:new(kn||Xs),string:new Bi}}function cb(y){var E=ia(this,y).delete(y);return this.size-=E?1:0,E}function lb(y){return ia(this,y).get(y)}function hb(y){return ia(this,y).has(y)}function ub(y,E){var P=ia(this,y),Y=P.size;return P.set(y,E),this.size+=P.size==Y?0:1,this}Hi.prototype.clear=ab,Hi.prototype.delete=cb,Hi.prototype.get=lb,Hi.prototype.has=hb,Hi.prototype.set=ub;function ta(y){var E=-1,P=y==null?0:y.length;for(this.__data__=new Hi;++E<P;)this.add(y[E])}function db(y){return this.__data__.set(y,i),this}function pb(y){return this.__data__.has(y)}ta.prototype.add=ta.prototype.push=db,ta.prototype.has=pb;function yi(y){var E=this.__data__=new Xs(y);this.size=E.size}function gb(){this.__data__=new Xs,this.size=0}function fb(y){var E=this.__data__,P=E.delete(y);return this.size=E.size,P}function wb(y){return this.__data__.get(y)}function yb(y){return this.__data__.has(y)}function mb(y,E){var P=this.__data__;if(P instanceof Xs){var Y=P.__data__;if(!kn||Y.length<t-1)return Y.push([y,E]),this.size=++P.size,this;P=this.__data__=new Hi(Y)}return P.set(y,E),this.size=P.size,this}yi.prototype.clear=gb,yi.prototype.delete=fb,yi.prototype.get=wb,yi.prototype.has=yb,yi.prototype.set=mb;function bb(y,E){var P=ra(y),Y=!P&&Db(y),Ye=!P&&!Y&&Sc(y),ae=!P&&!Y&&!Ye&&Au(y),rt=P||Y||Ye||ae,wt=rt?Om(y.length,String):[],Nt=wt.length;for(var et in y)Us.call(y,et)&&!(rt&&(et=="length"||Ye&&(et=="offset"||et=="parent")||ae&&(et=="buffer"||et=="byteLength"||et=="byteOffset")||Tb(et,Nt)))&&wt.push(et);return wt}function sa(y,E){for(var P=y.length;P--;)if(bu(y[P][0],E))return P;return-1}function vb(y,E,P){var Y=E(y);return ra(y)?Y:xm(Y,P(y))}function Rn(y){return y==null?y===void 0?T:b:qi&&qi in Object(y)?Sb(y):Ob(y)}function fu(y){return Un(y)&&Rn(y)==a}function wu(y,E,P,Y,Ye){return y===E?!0:y==null||E==null||!Un(y)&&!Un(E)?y!==y&&E!==E:Ib(y,E,P,Y,wu,Ye)}function Ib(y,E,P,Y,Ye,ae){var rt=ra(y),wt=ra(E),Nt=rt?c:mi(y),et=wt?c:mi(E);Nt=Nt==a?m:Nt,et=et==a?m:et;var es=Nt==m,Cs=et==m,jt=Nt==et;if(jt&&Sc(y)){if(!Sc(E))return!1;rt=!0,es=!1}if(jt&&!es)return ae||(ae=new yi),rt||Au(y)?yu(y,E,P,Y,Ye,ae):Cb(y,E,Nt,P,Y,Ye,ae);if(!(P&r)){var ds=es&&Us.call(y,"__wrapped__"),ps=Cs&&Us.call(E,"__wrapped__");if(ds||ps){var bi=ds?y.value():y,ei=ps?E.value():E;return ae||(ae=new yi),Ye(bi,ei,P,Y,ae)}}return jt?(ae||(ae=new yi),_b(y,E,P,Y,Ye,ae)):!1}function Eb(y){if(!Eu(y)||xb(y))return!1;var E=vu(y)?qm:ve;return E.test(Wi(y))}function Ab(y){return Un(y)&&Iu(y.length)&&!!te[Rn(y)]}function Nb(y){if(!Mb(y))return Wm(y);var E=[];for(var P in Object(y))Us.call(y,P)&&P!="constructor"&&E.push(P);return E}function yu(y,E,P,Y,Ye,ae){var rt=P&r,wt=y.length,Nt=E.length;if(wt!=Nt&&!(rt&&Nt>wt))return!1;var et=ae.get(y);if(et&&ae.get(E))return et==E;var es=-1,Cs=!0,jt=P&n?new ta:void 0;for(ae.set(y,E),ae.set(E,y);++es<wt;){var ds=y[es],ps=E[es];if(Y)var bi=rt?Y(ps,ds,es,E,y,ae):Y(ds,ps,es,y,E,ae);if(bi!==void 0){if(bi)continue;Cs=!1;break}if(jt){if(!Mm(E,function(ei,Vi){if(!km(jt,Vi)&&(ds===ei||Ye(ds,ei,P,Y,ae)))return jt.push(Vi)})){Cs=!1;break}}else if(!(ds===ps||Ye(ds,ps,P,Y,ae))){Cs=!1;break}}return ae.delete(y),ae.delete(E),Cs}function Cb(y,E,P,Y,Ye,ae,rt){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 uu(y),new uu(E)));case u:case d:case v:return bu(+y,+E);case p:return y.name==E.name&&y.message==E.message;case S:case O:return y==E+"";case w:var wt=Rm;case $:var Nt=Y&r;if(wt||(wt=Lm),y.size!=E.size&&!Nt)return!1;var et=rt.get(y);if(et)return et==E;Y|=n,rt.set(y,E);var es=yu(wt(y),wt(E),Y,Ye,ae,rt);return rt.delete(y),es;case D:if(_c)return _c.call(y)==_c.call(E)}return!1}function _b(y,E,P,Y,Ye,ae){var rt=P&r,wt=mu(y),Nt=wt.length,et=mu(E),es=et.length;if(Nt!=es&&!rt)return!1;for(var Cs=Nt;Cs--;){var jt=wt[Cs];if(!(rt?jt in E:Us.call(E,jt)))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 bi=rt;++Cs<Nt;){jt=wt[Cs];var ei=y[jt],Vi=E[jt];if(Y)var Nu=rt?Y(Vi,ei,jt,E,y,ae):Y(ei,Vi,jt,y,E,ae);if(!(Nu===void 0?ei===Vi||Ye(ei,Vi,P,Y,ae):Nu)){ps=!1;break}bi||(bi=jt=="constructor")}if(ps&&!bi){var na=y.constructor,oa=E.constructor;na!=oa&&"constructor"in y&&"constructor"in E&&!(typeof na=="function"&&na instanceof na&&typeof oa=="function"&&oa instanceof oa)&&(ps=!1)}return ae.delete(y),ae.delete(E),ps}function mu(y){return vb(y,Rb,$b)}function ia(y,E){var P=y.__data__;return Pb(E)?P[typeof E=="string"?"string":"hash"]:P.map}function Ar(y,E){var P=jm(y,E);return Eb(P)?P:void 0}function Sb(y){var E=Us.call(y,qi),P=y[qi];try{y[qi]=void 0;var Y=!0}catch{}var Ye=lu.call(y);return Y&&(E?y[qi]=P:delete y[qi]),Ye}var $b=pu?function(y){return y==null?[]:(y=Object(y),Dn(pu(y),function(E){return du.call(y,E)}))}:Ub,mi=Rn;(Ec&&mi(new Ec(new ArrayBuffer(1)))!=G||kn&&mi(new kn)!=w||Ac&&mi(Ac.resolve())!=A||Nc&&mi(new Nc)!=$||Cc&&mi(new Cc)!=q)&&(mi=function(y){var E=Rn(y),P=E==m?y.constructor:void 0,Y=P?Wi(P):"";if(Y)switch(Y){case Vm:return G;case Km:return w;case Gm:return A;case Ym:return $;case Qm:return q}return E});function Tb(y,E){return E=E??o,!!E&&(typeof y=="number"||pe.test(y))&&y>-1&&y%1==0&&y<E}function Pb(y){var E=typeof y;return E=="string"||E=="number"||E=="symbol"||E=="boolean"?y!=="__proto__":y===null}function xb(y){return!!cu&&cu in y}function Mb(y){var E=y&&y.constructor,P=typeof E=="function"&&E.prototype||Xo;return y===P}function Ob(y){return lu.call(y)}function Wi(y){if(y!=null){try{return au.call(y)}catch{}try{return y+""}catch{}}return""}function bu(y,E){return y===E||y!==y&&E!==E}var Db=fu((function(){return arguments})())?fu:function(y){return Un(y)&&Us.call(y,"callee")&&!du.call(y,"callee")},ra=Array.isArray;function kb(y){return y!=null&&Iu(y.length)&&!vu(y)}var Sc=Hm||Lb;function jb(y,E){return wu(y,E)}function vu(y){if(!Eu(y))return!1;var E=Rn(y);return E==f||E==g||E==l||E==N}function Iu(y){return typeof y=="number"&&y>-1&&y%1==0&&y<=o}function Eu(y){var E=typeof y;return y!=null&&(E=="object"||E=="function")}function Un(y){return y!=null&&typeof y=="object"}var Au=Rs?Dm(Rs):Ab;function Rb(y){return kb(y)?bb(y):Nb(y)}function Ub(){return[]}function Lb(){return!1}s.exports=jb})(oo,oo.exports)),oo.exports}var yE=wE();const mE=Ke.getDefaultExportFromCjs(yE),lw="wc",hw=2,Dl="core",Qs=`${lw}@2:${Dl}:`,bE={logger:"error"},vE={database:":memory:"},IE="crypto",vd="client_ed25519_seed",EE=h.cjsExports$1.ONE_DAY,AE="keychain",NE="0.3",CE="messages",_E="0.3",Id=h.cjsExports$1.SIX_HOURS,SE="publisher",uw="irn",$E="error",dw="wss://relay.walletconnect.org",TE="relayer",Et={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"},PE="_subscription",gs={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},xE=.1,kl="2.19.0",Je={link_mode:"link_mode",relay:"relay"},ME="0.3",OE="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"},DE="subscription",kE="0.3",jE=h.cjsExports$1.FIVE_SECONDS*1e3,RE="pairing",UE="0.3",Bn={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}}},tr={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"},LE="history",zE="0.3",FE="expirer",ms={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},qE="0.3",BE="verify-api",HE="https://verify.walletconnect.com",pw="https://verify.walletconnect.org",go=pw,WE=`${go}/v3`,VE=[HE,pw],KE="echo",GE="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"},ci={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"},Ki={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"},Gi={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"},Hn={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"},YE=.1,QE="event-client",JE=86400,ZE="https://pulse.walletconnect.org/batch";function XE(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,v=0,b=0,m=g.length;b!==m&&g[b]===0;)b++,w++;for(var A=(m-b)*u+1>>>0,N=new Uint8Array(A);b!==m;){for(var S=g[b],$=0,O=A-1;(S!==0||$<v)&&O!==-1;O--,$++)S+=256*N[O]>>>0,N[O]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");v=$,b++}for(var D=A-v;D!==A&&N[D]===0;)D++;for(var T=c.repeat(w);D<A;++D)T+=s.charAt(N[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 v=0,b=0;g[w]===c;)v++,w++;for(var m=(g.length-w)*l+1>>>0,A=new Uint8Array(m);g[w];){var N=t[g.charCodeAt(w)];if(N===255)return;for(var S=0,$=m-1;(N!==0||S<b)&&$!==-1;$--,S++)N+=a*A[$]>>>0,A[$]=N%256>>>0,N=N/256>>>0;if(N!==0)throw new Error("Non-zero carry");b=S,w++}if(g[w]!==" "){for(var O=m-b;O!==m&&A[O]===0;)O++;for(var D=new Uint8Array(v+(m-O)),T=v;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 eA=XE,tA=eA;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")},sA=s=>new TextEncoder().encode(s),iA=s=>new TextDecoder().decode(s);let rA=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")}},nA=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)}},oA=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 oA({...s.decoders||{[s.prefix]:s},...e.decoders||{[e.prefix]:e}});let aA=class{constructor(e,t,i,r){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=r,this.encoder=new rA(e,t,i),this.decoder=new nA(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const cc=({name:s,prefix:e,encode:t,decode:i})=>new aA(s,e,t,i),Bo=({prefix:s,name:e,alphabet:t})=>{const{encode:i,decode:r}=tA(t,e);return cc({prefix:s,name:e,encode:i,decode:n=>gw(r(n))})},cA=(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},lA=(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},Dt=({name:s,prefix:e,bitsPerChar:t,alphabet:i})=>cc({prefix:e,name:s,encode(r){return lA(r,i,t)},decode(r){return cA(r,i,t,s)}}),hA=cc({prefix:"\0",name:"identity",encode:s=>iA(s),decode:s=>sA(s)});var uA=Object.freeze({__proto__:null,identity:hA});const dA=Dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var pA=Object.freeze({__proto__:null,base2:dA});const gA=Dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fA=Object.freeze({__proto__:null,base8:gA});const wA=Bo({prefix:"9",name:"base10",alphabet:"0123456789"});var yA=Object.freeze({__proto__:null,base10:wA});const mA=Dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),bA=Dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var vA=Object.freeze({__proto__:null,base16:mA,base16upper:bA});const IA=Dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),EA=Dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),AA=Dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),NA=Dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),CA=Dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_A=Dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),SA=Dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$A=Dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),TA=Dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var PA=Object.freeze({__proto__:null,base32:IA,base32upper:EA,base32pad:AA,base32padupper:NA,base32hex:CA,base32hexupper:_A,base32hexpad:SA,base32hexpadupper:$A,base32z:TA});const xA=Bo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),MA=Bo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var OA=Object.freeze({__proto__:null,base36:xA,base36upper:MA});const DA=Bo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kA=Bo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var jA=Object.freeze({__proto__:null,base58btc:DA,base58flickr:kA});const RA=Dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),UA=Dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),LA=Dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zA=Dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var FA=Object.freeze({__proto__:null,base64:RA,base64pad:UA,base64url:LA,base64urlpad:zA});const ww=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),qA=ww.reduce((s,e,t)=>(s[t]=e,s),[]),BA=ww.reduce((s,e,t)=>(s[e.codePointAt(0)]=t,s),[]);function HA(s){return s.reduce((e,t)=>(e+=qA[t],e),"")}function WA(s){const e=[];for(const t of s){const i=BA[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const VA=cc({prefix:"🚀",name:"base256emoji",encode:HA,decode:WA});var KA=Object.freeze({__proto__:null,base256emoji:VA}),GA=yw,Ad=128,YA=-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&YA;)e[t++]=s&255|Ad,s>>>=7;return e[t]=s|0,yw.bytes=t-i+1,e}var JA=jl,ZA=128,Nd=127;function jl(s,i){var t=0,i=i||0,r=0,n=i,o,a=s.length;do{if(n>=a)throw jl.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>=ZA);return jl.bytes=n-i,t}var XA=Math.pow(2,7),eN=Math.pow(2,14),tN=Math.pow(2,21),sN=Math.pow(2,28),iN=Math.pow(2,35),rN=Math.pow(2,42),nN=Math.pow(2,49),oN=Math.pow(2,56),aN=Math.pow(2,63),cN=function(s){return s<XA?1:s<eN?2:s<tN?3:s<sN?4:s<iN?5:s<rN?6:s<nN?7:s<oN?8:s<aN?9:10},lN={encode:GA,decode:JA,encodingLength:cN},mw=lN;const Cd=(s,e,t=0)=>(mw.encode(s,e,t),e),_d=s=>mw.encodingLength(s),Rl=(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 hN(s,t,e,n)};let hN=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 uN(s,e,t);let uN=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?Rl(this.code,t):t.then(i=>Rl(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)),dN=bw({name:"sha2-256",code:18,encode:vw("SHA-256")}),pN=bw({name:"sha2-512",code:19,encode:vw("SHA-512")});var gN=Object.freeze({__proto__:null,sha256:dN,sha512:pN});const Iw=0,fN="identity",Ew=gw,wN=s=>Rl(Iw,Ew(s)),yN={code:Iw,name:fN,encode:Ew,digest:wN};var mN=Object.freeze({__proto__:null,identity:yN});new TextEncoder,new TextDecoder;const Sd={...uA,...pA,...fA,...yA,...vA,...PA,...OA,...jA,...FA,...KA};({...gN,...mN});function bN(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))),Lc=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=bN(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),vN={utf8:$d,"utf-8":$d,hex:Sd.base16,latin1:Lc,ascii:Lc,binary:Lc,...Sd};function IN(s,e="utf8"){const t=vN[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 EN=Object.defineProperty,AN=(s,e,t)=>e in s?EN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,zs=(s,e,t)=>AN(s,typeof e!="symbol"?e+"":e,t);let NN=class{constructor(e,t){this.core=e,this.logger=t,zs(this,"keychain",new Map),zs(this,"name",AE),zs(this,"version",NE),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 CN=Object.defineProperty,_N=(s,e,t)=>e in s?CN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,_t=(s,e,t)=>_N(s,typeof e!="symbol"?e+"":e,t);let SN=class{constructor(e,t,i){this.core=e,this.logger=t,_t(this,"name",IE),_t(this,"keychain"),_t(this,"randomSessionIdentifier",Ol()),_t(this,"initialized",!1),_t(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),_t(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),_t(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=h.Po(r);return h.Qe(n.publicKey)}),_t(this,"generateKeyPair",()=>{this.isInitialized();const r=v1();return this.setPrivateKey(r.publicKey,r.privateKey)}),_t(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=h.Po(n),a=this.randomSessionIdentifier,c=EE;return await h.Qo(a,r,c,o)}),_t(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=I1(a,n);return this.setSymKey(c,o)}),_t(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||Ma(r);return await this.keychain.set(o,r),o}),_t(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),_t(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),_t(this,"encode",async(r,n,o)=>{this.isInitialized();const a=ow(o),c=h.safeJsonStringify(n);if(hd(a))return N1(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 E1({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),_t(this,"decode",async(r,n,o)=>{this.isInitialized();const a=_1(n,o);if(hd(a)){const c=C1(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=A1({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)}}),_t(this,"getPayloadType",(r,n=xi)=>{const o=_o({encoded:r,encoding:n});return hr(o.type)}),_t(this,"getPayloadSenderPublicKey",(r,n=xi)=>{const o=_o({encoded:r,encoding:n});return o.senderPublicKey?h.toString(o.senderPublicKey,Ft):void 0}),this.core=e,this.logger=h.E(t,this.name),this.keychain=i||new NN(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=Ol(),await this.keychain.set(vd,e)}return IN(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 $N=Object.defineProperty,TN=(s,e,t)=>e in s?$N(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Fs=(s,e,t)=>TN(s,typeof e!="symbol"?e+"":e,t);let PN=class extends yv{constructor(e,t){super(e,t),this.logger=e,this.core=t,Fs(this,"messages",new Map),Fs(this,"name",CE),Fs(this,"version",_E),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=ui(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=ui(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 xN=Object.defineProperty,MN=Object.defineProperties,ON=Object.getOwnPropertyDescriptors,Td=Object.getOwnPropertySymbols,DN=Object.prototype.hasOwnProperty,kN=Object.prototype.propertyIsEnumerable,Ul=(s,e,t)=>e in s?xN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,da=(s,e)=>{for(var t in e||(e={}))DN.call(e,t)&&Ul(s,t,e[t]);if(Td)for(var t of Td(e))kN.call(e,t)&&Ul(s,t,e[t]);return s},zc=(s,e)=>MN(s,ON(e)),$s=(s,e,t)=>Ul(s,typeof e!="symbol"?e+"":e,t);let jN=class extends mv{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,$s(this,"events",new h.eventsExports.EventEmitter),$s(this,"name",SE),$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=Ha(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 v=({id:m})=>{p.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(Et.publish,v),w(p))};this.relayer.events.on(Et.publish,v);const b=Pi(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(N=>{this.logger.warn(N,N?.message),A(N)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${u}`);try{await b,this.events.removeListener(Et.publish,v)}catch(m){this.queue.set(d,zc(da({},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 Pi(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:ro(Ha().protocol).publish,params:da({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:p},f),id:d};Ht((t=g.params)==null?void 0:t.prompt)&&((i=g.params)==null||delete i.prompt),Ht((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(Et.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,zc(da({},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(zc(da({},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(Et.connection_stalled);return}this.checkQueue()}),this.relayer.on(Et.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}};var RN=Object.defineProperty,UN=(s,e,t)=>e in s?RN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Sr=(s,e,t)=>UN(s,typeof e!="symbol"?e+"":e,t);let LN=class{constructor(){Sr(this,"map",new Map),Sr(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),Sr(this,"get",e=>this.map.get(e)||[]),Sr(this,"exists",(e,t)=>this.get(e).includes(t)),Sr(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)}),Sr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}};var zN=Object.defineProperty,FN=Object.defineProperties,qN=Object.getOwnPropertyDescriptors,Pd=Object.getOwnPropertySymbols,BN=Object.prototype.hasOwnProperty,HN=Object.prototype.propertyIsEnumerable,Ll=(s,e,t)=>e in s?zN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Wn=(s,e)=>{for(var t in e||(e={}))BN.call(e,t)&&Ll(s,t,e[t]);if(Pd)for(var t of Pd(e))HN.call(e,t)&&Ll(s,t,e[t]);return s},Fc=(s,e)=>FN(s,qN(e)),je=(s,e,t)=>Ll(s,typeof e!="symbol"?e+"":e,t);let WN=class extends Iv{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,je(this,"subscriptions",new Map),je(this,"topicMap",new LN),je(this,"events",new h.eventsExports.EventEmitter),je(this,"name",DE),je(this,"version",kE),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=Ha(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)>=jE&&(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=Ha(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===Je.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:ro(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===Je.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 Pi(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 Pi(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(Et.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:ro(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 Pi(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(Et.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:ro(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 Pi(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(Et.connection_stalled)}return r}rpcUnsubscribe(e,t,i){const r={method:ro(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,Fc(Wn({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Wn({},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,Wn({},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,Fc(Wn({},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=>Fc(Wn({},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 D0(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 ui(e+await this.getClientId())}};var VN=Object.defineProperty,xd=Object.getOwnPropertySymbols,KN=Object.prototype.hasOwnProperty,GN=Object.prototype.propertyIsEnumerable,zl=(s,e,t)=>e in s?VN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Md=(s,e)=>{for(var t in e||(e={}))KN.call(e,t)&&zl(s,t,e[t]);if(xd)for(var t of xd(e))GN.call(e,t)&&zl(s,t,e[t]);return s},Ae=(s,e,t)=>zl(s,typeof e!="symbol"?e+"":e,t);let YN=class extends bv{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",TE),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(qa())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(Et.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(Et.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||$E})),this.messages=new PN(this.logger,e.core),this.subscriber=new WN(this,this.logger),this.publisher=new jN(this,this.logger),this.relayUrl=e?.relayUrl||dw,this.projectId=e.projectId,b0()?this.packageName=ju():v0()&&(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:Je.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 Pi(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=pt(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(Et.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 Pi(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(qa())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(N0({sdkVersion:kl,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(PE))return;const t=e.params,{topic:i,message:r,publishedAt:n,attestation:o}=t.data,a={topic:i,message:r,publishedAt:n,transportType:Je.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(Et.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(this.events.emit(Et.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();pE(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(Et.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(xE)))))}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,JN=Object.prototype.hasOwnProperty,ZN=Object.prototype.propertyIsEnumerable,Fl=(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={}))JN.call(e,t)&&Fl(s,t,e[t]);if(Od)for(var t of Od(e))ZN.call(e,t)&&Fl(s,t,e[t]);return s},Vt=(s,e,t)=>Fl(s,typeof e!="symbol"?e+"":e,t);let yr=class extends vv{constructor(e,t,i,r=Qs,n=void 0){super(e,t,i,r),this.core=e,this.logger=t,this.name=i,Vt(this,"map",new Map),Vt(this,"version",ME),Vt(this,"cached",[]),Vt(this,"initialized",!1),Vt(this,"getKey"),Vt(this,"storagePrefix",Qs),Vt(this,"recentlyDeleted",[]),Vt(this,"recentlyDeletedLimit",200),Vt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ht(o)?this.map.set(this.getKey(o),o):H1(o)?this.map.set(o.id,o):W1(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Vt(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Vt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Vt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>mE(a[c],o[c]))):this.values)),Vt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Dd(Dd({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Vt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=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 XN=Object.defineProperty,eC=(s,e,t)=>e in s?XN(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fe=(s,e,t)=>eC(s,typeof e!="symbol"?e+"":e,t);let tC=class{constructor(e,t){this.core=e,this.logger=t,fe(this,"name",RE),fe(this,"version",UE),fe(this,"events",new h.Nt),fe(this,"pairings"),fe(this,"initialized",!1),fe(this,"storagePrefix",Qs),fe(this,"ignoredPayloadTypes",[gi]),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=Ol(),n=await this.core.crypto.setSymKey(r),o=pt(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(tr.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(ci.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||pt(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(tr.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(ci.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(f){throw r.setError(ci.subscribe_pairing_topic_failure),f}return r.addTrace(Ks.subscribe_pairing_topic_success),p}),fe(this,"activate",async({topic:i})=>{this.isInitialized();const r=pt(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}=Ji();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=Bn[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=Bn[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=Bn[c]?Bn[c].res:Bn.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=>Si(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(tr.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(tr.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(!Jt(i)){const{message:a}=U("MISSING_OR_INVALID",`pair() params: ${i}`);throw r.setError(ci.malformed_pairing_uri),new Error(a)}if(!B1(i.uri)){const{message:a}=U("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw r.setError(ci.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(ci.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(ci.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&h.cjsExports$1.toMiliseconds(o?.expiryTimestamp)<Date.now()){r.setError(ci.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(!Jt(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(!Jt(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(!ot(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(Si(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 yr(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(Et.message,async e=>{const{topic:t,message:i,transportType:r}=e;if(!this.pairings.keys.includes(t)||r===Je.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(tr.expire,{topic:t}))})}};var sC=Object.defineProperty,iC=(s,e,t)=>e in s?sC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,St=(s,e,t)=>iC(s,typeof e!="symbol"?e+"":e,t);let rC=class extends wv{constructor(e,t){super(e,t),this.core=e,this.logger=t,St(this,"records",new Map),St(this,"events",new h.eventsExports.EventEmitter),St(this,"name",LE),St(this,"version",zE),St(this,"cached",[]),St(this,"initialized",!1),St(this,"storagePrefix",Qs),St(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)}),St(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:pt(h.cjsExports$1.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(_s.created,o)}),St(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))}),St(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))),St(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()}),St(this,"exists",async(i,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===i:!1)),St(this,"on",(i,r)=>{this.events.on(i,r)}),St(this,"once",(i,r)=>{this.events.once(i,r)}),St(this,"off",(i,r)=>{this.events.off(i,r)}),St(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 nC=Object.defineProperty,oC=(s,e,t)=>e in s?nC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Rt=(s,e,t)=>oC(s,typeof e!="symbol"?e+"":e,t);let aC=class extends Ev{constructor(e,t){super(e,t),this.core=e,this.logger=t,Rt(this,"expirations",new Map),Rt(this,"events",new h.eventsExports.EventEmitter),Rt(this,"name",FE),Rt(this,"version",qE),Rt(this,"cached",[]),Rt(this,"initialized",!1),Rt(this,"storagePrefix",Qs),Rt(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)}),Rt(this,"has",i=>{try{const r=this.formatTarget(i);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Rt(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})}),Rt(this,"get",i=>{this.isInitialized();const r=this.formatTarget(i);return this.getExpiration(r)}),Rt(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})}}),Rt(this,"on",(i,r)=>{this.events.on(i,r)}),Rt(this,"once",(i,r)=>{this.events.once(i,r)}),Rt(this,"off",(i,r)=>{this.events.off(i,r)}),Rt(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 C0(e);if(typeof e=="number")return _0(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 cC=Object.defineProperty,lC=(s,e,t)=>e in s?cC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ct=(s,e,t)=>lC(s,typeof e!="symbol"?e+"":e,t);let hC=class extends Av{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,ct(this,"name",BE),ct(this,"abortController"),ct(this,"isDevEnv"),ct(this,"verifyUrlV3",WE),ct(this,"storagePrefix",Qs),ct(this,"version",hw),ct(this,"publicKey"),ct(this,"fetchPromise"),ct(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()))}),ct(this,"register",async r=>{if(!Uo()||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",v),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 v=b=>{if(b.data&&typeof b.data=="string")try{const m=JSON.parse(b.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",v),p(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};l.body.appendChild(w),window.addEventListener("message",v,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",d),d}catch(l){this.logger.warn(l)}return""}),ct(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)}),ct(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}),ct(this,"getVerifyUrl",r=>{let n=r||go;return VE.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${go}`),n=go),n}),ct(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)}}),ct(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),ct(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ct(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")}}),ct(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ct(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}),ct(this,"validateAttestation",(r,n)=>{const o=P1(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=Th(),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 uC=Object.defineProperty,dC=(s,e,t)=>e in s?uC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,kd=(s,e,t)=>dC(s,typeof e!="symbol"?e+"":e,t);let pC=class extends Nv{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,kd(this,"context",KE),kd(this,"registerDeviceToken",async i=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${GE}/${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 gC=Object.defineProperty,jd=Object.getOwnPropertySymbols,fC=Object.prototype.hasOwnProperty,wC=Object.prototype.propertyIsEnumerable,ql=(s,e,t)=>e in s?gC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Vn=(s,e)=>{for(var t in e||(e={}))fC.call(e,t)&&ql(s,t,e[t]);if(jd)for(var t of jd(e))wC.call(e,t)&&ql(s,t,e[t]);return s},yt=(s,e,t)=>ql(s,typeof e!="symbol"?e+"":e,t);let yC=class extends Cv{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,yt(this,"context",QE),yt(this,"storagePrefix",Qs),yt(this,"storageVersion",YE),yt(this,"events",new Map),yt(this,"shouldPersist",!1),yt(this,"init",async()=>{if(!Th())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,kl)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),yt(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=Vn({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}),yt(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 Vn(Vn({},a),this.setMethods(a.eventId))}),yt(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),yt(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)>JE&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),yt(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),yt(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)}),yt(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)}),yt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),yt(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,Vn(Vn({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),yt(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)}}),yt(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${ZE}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${kl}${n}`,{method:"POST",body:JSON.stringify(r)})}),yt(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 mC=Object.defineProperty,Rd=Object.getOwnPropertySymbols,bC=Object.prototype.hasOwnProperty,vC=Object.prototype.propertyIsEnumerable,Bl=(s,e,t)=>e in s?mC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ud=(s,e)=>{for(var t in e||(e={}))bC.call(e,t)&&Bl(s,t,e[t]);if(Rd)for(var t of Rd(e))vC.call(e,t)&&Bl(s,t,e[t]);return s},He=(s,e,t)=>Bl(s,typeof e!="symbol"?e+"":e,t);let IC=class Nw extends dv{constructor(e){var t;super(e),He(this,"protocol",lw),He(this,"version",hw),He(this,"name",Dl),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:Je.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:bE.logger,name:Dl}),{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 SN(this,this.logger,e?.keychain),this.history=new rC(this,this.logger),this.expirer=new aC(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new h.h(Ud(Ud({},vE),e?.storageOptions)),this.relayer=new YN({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new tC(this,this.logger),this.verify=new hC(this,this.logger,this.storage),this.echoClient=new pC(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new yC(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(OE,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 EC=IC;var AC=Object.defineProperty,NC=(s,e,t)=>e in s?AC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ld=(s,e,t)=>NC(s,typeof e!="symbol"?e+"":e,t);let CC=class{constructor(e){this.opts=e,Ld(this,"protocol","wc"),Ld(this,"version",2)}},_C=class{constructor(e){this.client=e}};const Cw="wc",_w=2,Sw="client",Uh=`${Cw}@${_w}:${Sw}:`,qc={name:Sw,logger:"error"},zd="WALLETCONNECT_DEEPLINK_CHOICE",SC="proposal",Fd="Proposal expired",$C="session",$r=h.cjsExports$1.SEVEN_DAYS,TC="engine",mt={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}}},Bc={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"}},PC="request",xC=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],MC="wc",OC="auth",DC="authKeys",kC="pairingTopics",jC="requests",lc=`${MC}@${1.5}:${OC}:`,Oa=`${lc}:PUB_KEY`;var RC=Object.defineProperty,UC=Object.defineProperties,LC=Object.getOwnPropertyDescriptors,Bd=Object.getOwnPropertySymbols,zC=Object.prototype.hasOwnProperty,FC=Object.prototype.propertyIsEnumerable,Hl=(s,e,t)=>e in s?RC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,tt=(s,e)=>{for(var t in e||(e={}))zC.call(e,t)&&Hl(s,t,e[t]);if(Bd)for(var t of Bd(e))FC.call(e,t)&&Hl(s,t,e[t]);return s},Kt=(s,e)=>UC(s,LC(e)),M=(s,e,t)=>Hl(s,typeof e!="symbol"?e+"":e,t);let qC=class extends _C{constructor(e){super(e),M(this,"name",TC),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(mt)}),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=Kt(tt({},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=mt.wc_sessionPropose.req.ttl||h.cjsExports$1.FIVE_MINUTES,g=pt(f),w=Kt(tt({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()}),v=Pe("session_connect",w.id),{reject:b,resolve:m,done:A}=Ji(f,Fd),N=({id:S})=>{S===w.id&&(this.client.events.off("proposal_expire",N),this.pendingSessions.delete(w.id),this.events.emit(v,{error:{message:Fd,code:0}}))};return this.client.events.on("proposal_expire",N),this.events.once(v,({error:S,session:$})=>{this.client.events.off("proposal_expire",N),S?b(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(Ki.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(Ki.proposal_not_found),D}try{await this.isValidApprove(t)}catch(D){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Ki.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:v}=p;let b=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});b||(b=(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,N=await this.client.core.crypto.generateSharedKey(m,A),S=tt(tt({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:m,metadata:this.client.metadata},expiry:pt($r)},u&&{sessionProperties:u}),d&&{sessionConfig:d}),$=Je.relay;b.addTrace(Ss.subscribing_session_topic);try{await this.client.core.relayer.subscribe(N,{transportType:$})}catch(D){throw b.setError(Ki.subscribe_session_topic_failure),D}b.addTrace(Ss.subscribe_session_topic_success);const O=Kt(tt({},S),{topic:N,requiredNamespaces:w,optionalNamespaces:v,pairingTopic:f,acknowledged:!1,self:S.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:m,transportType:Je.relay});await this.client.session.set(N,O),b.addTrace(Ss.store_session);try{b.addTrace(Ss.publishing_session_settle),await this.sendRequest({topic:N,method:"wc_sessionSettle",params:S,throwOnFailedPublish:!0}).catch(D=>{throw b?.setError(Ki.session_settle_publish_failure),D}),b.addTrace(Ss.session_settle_publish_success),b.addTrace(Ss.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:m},throwOnFailedPublish:!0}).catch(D=>{throw b?.setError(Ki.session_approve_publish_failure),D}),b.addTrace(Ss.session_approve_publish_success)}catch(D){throw this.client.logger.error(D),this.client.session.delete(N,Re("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(N),D}return this.client.core.eventClient.deleteEvent({eventId:b.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(N,pt($r)),{topic:N,acknowledged:()=>Promise.resolve(this.client.session.get(N))}}),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:mt.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}=Ji(),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}=Ji();return this.events.once(Pe("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,pt($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(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:i,request:r,topic:n,expiry:o=mt.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);a?.transportType===Je.relay&&await this.confirmOnlineStateOrThrow();const c=h.payloadId(),l=h.getBigIntRpcId().toString(),{done:u,resolve:d,reject:p}=Ji(o,"Request expired. Please try again.");this.events.once(Pe("session_request",c),({error:b,result:m})=>{b?p(b):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:Kt(tt({},r),{expiryTimestamp:pt(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(b=>p(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),await u();const w={request:Kt(tt({},r),{expiryTimestamp:pt(o)}),chainId:i},v=this.shouldSetTVF(f,w);return await Promise.all([new Promise(async b=>{await this.sendRequest(tt({clientRpcId:c,relayRpcId:l,topic:n,method:f,params:w,expiry:o,throwOnFailedPublish:!0},v&&{tvf:this.getTVFParams(c,w)})).catch(m=>p(m)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:i,id:c}),b()}),new Promise(async b=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const A=await P0(this.client.core.storage,zd);await S0({id:c,topic:n,wcDeepLink:A})}b()}),u()]).then(b=>b[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===Je.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}=Ji();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=>F1(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?Je.link_mode:Je.relay;o===Je.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:p,exp:f,nbf:g,methods:w=[],expiry:v}=t,b=[...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 N=await this.client.core.crypto.generateKeyPair(),S=Ma(N);if(await Promise.all([this.client.auth.authKeys.set(Oa,{responseTopic:S,publicKey:N}),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:C}=yn(a[0]);let z=vI(C,"request",w);xa(b)&&(z=EI(z,b.pop())),b.push(z)}const $=v&&v>mt.wc_sessionAuthenticate.req.ttl?v:mt.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:b},requester:{publicKey:N,metadata:this.client.metadata},expiryTimestamp:pt($)},D={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},T={requiredNamespaces:{},optionalNamespaces:D,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:N,metadata:this.client.metadata},expiryTimestamp:pt(mt.wc_sessionPropose.req.ttl),id:h.payloadId()},{done:q,resolve:j,reject:G}=Ji($,"Request expired"),B=h.payloadId(),W=Pe("session_connect",T.id),V=Pe("session_request",B),H=async({error:C,session:z})=>{this.events.off(V,K),C?G(C):z&&j({session:z})},K=async C=>{var z,ee,J;if(await this.deletePendingAuthRequest(B,{message:"fulfilled",code:0}),C.error){const ke=Re("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return C.error.code===ke.code?void 0:(this.events.off(W,H),G(C.error.message))}await this.deleteProposal(T.id),this.events.off(W,H);const{cacaos:ve,responder:pe}=C.result,te=[],it=[];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=xa(ks.resources),Zs=[Sl(ks.iss)],Er=Ba(ks.iss);if(js){const Rs=Ku(js),Dn=Gu(js);te.push(...Rs),Zs.push(...Dn)}for(const Rs of Zs)it.push(`${Rs}:${Er}`)}const Le=await this.client.core.crypto.generateSharedKey(N,pe.publicKey);let Ie;te.length>0&&(Ie={topic:Le,acknowledged:!0,self:{publicKey:N,metadata:this.client.metadata},peer:pe,controller:pe.publicKey,expiry:pt($r),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:pd([...new Set(te)],[...new Set(it)]),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:Je.link_mode})),j({auths:ve,session:Ie})};this.events.once(W,H),this.events.once(V,K);let Q;try{if(n){const C=h.formatJsonRpcRequest("wc_sessionAuthenticate",O,B);this.client.core.history.set(m,C);const z=await this.client.core.crypto.encode("",C,{type:qo,encoding:Fn});Q=ua(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:mt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:T.id})])}catch(C){throw this.events.off(W,H),this.events.off(V,K),C}return await this.setProposal(T.id,T),await this.setAuthRequest(B,{request:Kt(tt({},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:[Gi.authenticated_session_approve_started]}});try{this.isInitialized()}catch(v){throw n.setError(Hn.no_internet_connection),v}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(Hn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||Je.relay;a===Je.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=Ma(c),d={type:gi,receiverPublicKey:c,senderPublicKey:l},p=[],f=[];for(const v of r){if(!await Vu({cacao:v,projectId:this.client.core.projectId})){n.setError(Hn.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(Gi.cacaos_verified);const{p:b}=v,m=xa(b.resources),A=[Sl(b.iss)],N=Ba(b.iss);if(m){const S=Ku(m),$=Gu(m);p.push(...S),A.push(...$)}for(const S of A)f.push(`${S}:${N}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Gi.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:pt($r),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:pd([...new Set(p)],[...new Set(f)]),transportType:a},n.addTrace(Gi.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(v){throw n.setError(Hn.subscribe_authenticated_session_topic_failure),v}n.addTrace(Gi.subscribe_authenticated_session_topic_success),await this.client.session.set(g,w),n.addTrace(Gi.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Gi.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(v){throw n.setError(Hn.authenticated_session_approve_publish_failure),v}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===Je.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ma(o),l={type:gi,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:r,encodeOpts:l,rpcOpts:mt.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(Ki.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,pt(mt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),M(this,"setAuthRequest",async(t,i)=>{const{request:r,pairingTopic:n,transportType:o=Je.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||pt(mt.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 b=g?Fn:xi;f=await this.client.core.crypto.encode(i,p,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),b}let w;if(xC.includes(r)){const b=ui(JSON.stringify(p)),m=ui(f);w=await this.client.core.verify.register({id:m,decryptedId:b})}const v=mt[r].req;if(v.attestation=w,o&&(v.ttl=o),a&&(v.id=a),this.client.core.history.set(i,p),g){const b=ua(u,i,f);await _.global.Linking.openURL(b,this.client.name)}else{const b=mt[r].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=Kt(tt({},d),{correlationId:p.id}),l?(b.internal=Kt(tt({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,b)):this.client.core.relayer.publish(i,f,b).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(_.global==null?void 0:_.global.Linking)<"u";try{const g=d?Fn:xi;u=await this.client.core.crypto.encode(r,l,Kt(tt({},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=ua(c,r,u);await _.global.Linking.openURL(g,this.client.name)}else{const g=p.request.method,w=mt[g].res;w.tvf=Kt(tt({},f),{correlationId:i}),o?(w.internal=Kt(tt({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,u,w)):this.client.core.relayer.publish(r,u,w).catch(v=>this.client.logger.error(v))}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(_.global==null?void 0:_.global.Linking)<"u";try{const f=d?Fn:xi;u=await this.client.core.crypto.encode(r,l,Kt(tt({},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=ua(c,r,u);await _.global.Linking.openURL(f,this.client.name)}else{const f=p.request.method,g=a||mt[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;Si(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=>{Si(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(ci.proposal_listener_not_found)),this.isValidConnect(tt({},r.params));const u=a.expiryTimestamp||pt(mt.wc_sessionPropose.req.ttl),d=tt({id:c,pairingTopic:i,expiryTimestamp:u},a);await this.setProposal(c,d);const p=await this.getVerifyContext({attestationId:n,hash:ui(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:mt.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=Kt(tt(tt({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:Je.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=qn.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(tt({topic:t},r));try{qn.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 qn.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,pt($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(Et.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(tt({topic:o},p));const f=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:ui(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===Je.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=qn.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(tt({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),qn.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:ui(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===Je.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:gi,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:n.id,topic:r,error:l,encodeOpts:f,rpcOpts:mt.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(!Jt(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(Ht(i)||await this.isValidPairingTopic(i),!X1(a)){const{message:c}=U("MISSING_OR_INVALID",`connect() relays: ${a}`);throw new Error(c)}!Ht(r)&&So(r)!==0&&this.validateNamespaces(r,"requiredNamespaces"),!Ht(n)&&So(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Ht(o)||this.validateSessionProps(o,"sessionProperties")}),M(this,"validateNamespaces",(t,i)=>{const r=Z1(t,"connect()",i);if(r)throw new Error(r.message)}),M(this,"isValidApprove",async t=>{if(!Jt(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=Rc(r,"approve()");if(c)throw new Error(c.message);const l=wd(a.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!ot(n,!0)){const{message:u}=U("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}Ht(o)||this.validateSessionProps(o,"sessionProperties")}),M(this,"isValidReject",async t=>{if(!Jt(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),!tE(r)){const{message:n}=U("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),M(this,"isValidSessionSettleRequest",t=>{if(!Jt(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=V1(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Rc(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Si(o)){const{message:l}=U("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),M(this,"isValidUpdate",async t=>{if(!Jt(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=Rc(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(!Jt(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(!Jt(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(!sE(r)){const{message:c}=U("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!nE(a,n,r.method)){const{message:c}=U("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!lE(o,Bc)){const{message:c}=U("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Bc.min} and ${Bc.max}`);throw new Error(c)}}),M(this,"isValidRespond",async t=>{var i;if(!Jt(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(!iE(n)){const{message:o}=U("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),M(this,"isValidPing",async t=>{if(!Jt(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(!Jt(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(!rE(r)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!oE(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(!Jt(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(!ot(r,!1))throw new Error("uri is required parameter");if(!ot(n,!1))throw new Error("domain is required parameter");if(!ot(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>yn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=yn(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||go,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Je.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(!ot(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!==Je.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(_.global==null?void 0:_.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:Je.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:r,sessionExists:n})}),M(this,"registerLinkModeListeners",async()=>{var t;if(Th()||zi()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const i=_.global==null?void 0:_.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 Kt(tt({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(ur(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(Et.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(Oa)?this.client.auth.authKeys.get(Oa):{publicKey:void 0},a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===Je.link_mode?Fn:xi});try{h.isJsonRpcRequest(a)?(this.client.core.history.set(t,a),this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:ui(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(tr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(tr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ot(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(Si(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=U("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ot(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(Si(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(ot(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(!eE(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(Si(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=U("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}},BC=class extends yr{constructor(e,t){super(e,t,SC,Uh),this.core=e,this.logger=t}},HC=class extends yr{constructor(e,t){super(e,t,$C,Uh),this.core=e,this.logger=t}},WC=class extends yr{constructor(e,t){super(e,t,PC,Uh,i=>i.id),this.core=e,this.logger=t}},VC=class extends yr{constructor(e,t){super(e,t,DC,lc,()=>Oa),this.core=e,this.logger=t}},KC=class extends yr{constructor(e,t){super(e,t,kC,lc),this.core=e,this.logger=t}},GC=class extends yr{constructor(e,t){super(e,t,jC,lc,i=>i.id),this.core=e,this.logger=t}};var YC=Object.defineProperty,QC=(s,e,t)=>e in s?YC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Hc=(s,e,t)=>QC(s,typeof e!="symbol"?e+"":e,t);let JC=class{constructor(e,t){this.core=e,this.logger=t,Hc(this,"authKeys"),Hc(this,"pairingTopics"),Hc(this,"requests"),this.authKeys=new VC(this.core,this.logger),this.pairingTopics=new KC(this.core,this.logger),this.requests=new GC(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}};var ZC=Object.defineProperty,XC=(s,e,t)=>e in s?ZC(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,we=(s,e,t)=>XC(s,typeof e!="symbol"?e+"":e,t);let e_=class $w extends CC{constructor(e){super(e),we(this,"protocol",Cw),we(this,"version",_w),we(this,"name",qc.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||qc.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||qc.logger}));this.core=e?.core||new EC(e),this.logger=h.E(t,this.name),this.session=new HC(this.core,this.logger),this.proposal=new BC(this.core,this.logger),this.pendingRequest=new WC(this.core,this.logger),this.engine=new qC(this),this.auth=new JC(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",t_="wss://relay.walletconnect.org",s_="wc",i_="universal_provider",Wd=`${s_}@2:${i_}:`,Tw="https://rpc.walletconnect.org/v1/",rn="generic",r_=`${Tw}bundler`,As={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var pa=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof _.global<"u"?_.global:typeof self<"u"?self:{};function n_(){this.__data__=[],this.size=0}var o_=n_;function a_(s,e){return s===e||s!==s&&e!==e}var hc=a_,c_=hc;function l_(s,e){for(var t=s.length;t--;)if(c_(s[t][0],e))return t;return-1}var uc=l_,h_=uc,u_=Array.prototype,d_=u_.splice;function p_(s){var e=this.__data__,t=h_(e,s);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():d_.call(e,t,1),--this.size,!0}var g_=p_,f_=uc;function w_(s){var e=this.__data__,t=f_(e,s);return t<0?void 0:e[t][1]}var y_=w_,m_=uc;function b_(s){return m_(this.__data__,s)>-1}var v_=b_,I_=uc;function E_(s,e){var t=this.__data__,i=I_(t,s);return i<0?(++this.size,t.push([s,e])):t[i][1]=e,this}var A_=E_,N_=o_,C_=g_,__=y_,S_=v_,$_=A_;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=N_,nn.prototype.delete=C_,nn.prototype.get=__,nn.prototype.has=S_,nn.prototype.set=$_;var dc=nn,T_=dc;function P_(){this.__data__=new T_,this.size=0}var x_=P_;function M_(s){var e=this.__data__,t=e.delete(s);return this.size=e.size,t}var O_=M_;function D_(s){return this.__data__.get(s)}var k_=D_;function j_(s){return this.__data__.has(s)}var R_=j_,U_=typeof pa=="object"&&pa&&pa.Object===Object&&pa,Pw=U_,L_=Pw,z_=typeof self=="object"&&self&&self.Object===Object&&self,F_=L_||z_||Function("return this")(),Pn=F_,q_=Pn,B_=q_.Symbol,xw=B_,Vd=xw,Mw=Object.prototype,H_=Mw.hasOwnProperty,W_=Mw.toString,Kn=Vd?Vd.toStringTag:void 0;function V_(s){var e=H_.call(s,Kn),t=s[Kn];try{s[Kn]=void 0;var i=!0}catch{}var r=W_.call(s);return i&&(e?s[Kn]=t:delete s[Kn]),r}var K_=V_,G_=Object.prototype,Y_=G_.toString;function Q_(s){return Y_.call(s)}var J_=Q_,Kd=xw,Z_=K_,X_=J_,eS="[object Null]",tS="[object Undefined]",Gd=Kd?Kd.toStringTag:void 0;function sS(s){return s==null?s===void 0?tS:eS:Gd&&Gd in Object(s)?Z_(s):X_(s)}var pc=sS;function iS(s){var e=typeof s;return s!=null&&(e=="object"||e=="function")}var mr=iS,rS=pc,nS=mr,oS="[object AsyncFunction]",aS="[object Function]",cS="[object GeneratorFunction]",lS="[object Proxy]";function hS(s){if(!nS(s))return!1;var e=rS(s);return e==aS||e==cS||e==oS||e==lS}var Lh=hS,uS=Pn,dS=uS["__core-js_shared__"],pS=dS,Wc=pS,Yd=(function(){var s=/[^.]+$/.exec(Wc&&Wc.keys&&Wc.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""})();function gS(s){return!!Yd&&Yd in s}var fS=gS,wS=Function.prototype,yS=wS.toString;function mS(s){if(s!=null){try{return yS.call(s)}catch{}try{return s+""}catch{}}return""}var bS=mS,vS=Lh,IS=fS,ES=mr,AS=bS,NS=/[\\^$.*+?()[\]{}|]/g,CS=/^\[object .+?Constructor\]$/,_S=Function.prototype,SS=Object.prototype,$S=_S.toString,TS=SS.hasOwnProperty,PS=RegExp("^"+$S.call(TS).replace(NS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function xS(s){if(!ES(s)||IS(s))return!1;var e=vS(s)?PS:CS;return e.test(AS(s))}var MS=xS;function OS(s,e){return s?.[e]}var DS=OS,kS=MS,jS=DS;function RS(s,e){var t=jS(s,e);return kS(t)?t:void 0}var zh=RS,US=zh,LS=Pn,zS=US(LS,"Map"),Ow=zS,FS=zh,qS=FS(Object,"create"),gc=qS,Qd=gc;function BS(){this.__data__=Qd?Qd(null):{},this.size=0}var HS=BS;function WS(s){var e=this.has(s)&&delete this.__data__[s];return this.size-=e?1:0,e}var VS=WS,KS=gc,GS="__lodash_hash_undefined__",YS=Object.prototype,QS=YS.hasOwnProperty;function JS(s){var e=this.__data__;if(KS){var t=e[s];return t===GS?void 0:t}return QS.call(e,s)?e[s]:void 0}var ZS=JS,XS=gc,e$=Object.prototype,t$=e$.hasOwnProperty;function s$(s){var e=this.__data__;return XS?e[s]!==void 0:t$.call(e,s)}var i$=s$,r$=gc,n$="__lodash_hash_undefined__";function o$(s,e){var t=this.__data__;return this.size+=this.has(s)?0:1,t[s]=r$&&e===void 0?n$:e,this}var a$=o$,c$=HS,l$=VS,h$=ZS,u$=i$,d$=a$;function on(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])}}on.prototype.clear=c$,on.prototype.delete=l$,on.prototype.get=h$,on.prototype.has=u$,on.prototype.set=d$;var p$=on,Jd=p$,g$=dc,f$=Ow;function w$(){this.size=0,this.__data__={hash:new Jd,map:new(f$||g$),string:new Jd}}var y$=w$;function m$(s){var e=typeof s;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?s!=="__proto__":s===null}var b$=m$,v$=b$;function I$(s,e){var t=s.__data__;return v$(e)?t[typeof e=="string"?"string":"hash"]:t.map}var fc=I$,E$=fc;function A$(s){var e=E$(this,s).delete(s);return this.size-=e?1:0,e}var N$=A$,C$=fc;function _$(s){return C$(this,s).get(s)}var S$=_$,$$=fc;function T$(s){return $$(this,s).has(s)}var P$=T$,x$=fc;function M$(s,e){var t=x$(this,s),i=t.size;return t.set(s,e),this.size+=t.size==i?0:1,this}var O$=M$,D$=y$,k$=N$,j$=S$,R$=P$,U$=O$;function an(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])}}an.prototype.clear=D$,an.prototype.delete=k$,an.prototype.get=j$,an.prototype.has=R$,an.prototype.set=U$;var L$=an,z$=dc,F$=Ow,q$=L$,B$=200;function H$(s,e){var t=this.__data__;if(t instanceof z$){var i=t.__data__;if(!F$||i.length<B$-1)return i.push([s,e]),this.size=++t.size,this;t=this.__data__=new q$(i)}return t.set(s,e),this.size=t.size,this}var W$=H$,V$=dc,K$=x_,G$=O_,Y$=k_,Q$=R_,J$=W$;function cn(s){var e=this.__data__=new V$(s);this.size=e.size}cn.prototype.clear=K$,cn.prototype.delete=G$,cn.prototype.get=Y$,cn.prototype.has=Q$,cn.prototype.set=J$;var Z$=cn,X$=zh,eT=(function(){try{var s=X$(Object,"defineProperty");return s({},"",{}),s}catch{}})(),Dw=eT,Zd=Dw;function tT(s,e,t){e=="__proto__"&&Zd?Zd(s,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):s[e]=t}var Fh=tT,sT=Fh,iT=hc;function rT(s,e,t){(t!==void 0&&!iT(s[e],t)||t===void 0&&!(e in s))&&sT(s,e,t)}var kw=rT;function nT(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 oT=nT,aT=oT,cT=aT(),lT=cT,Wl={exports:{}};(function(s,e){var t=Pn,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})(Wl,Wl.exports);var hT=Pn,uT=hT.Uint8Array,dT=uT,Xd=dT;function pT(s){var e=new s.constructor(s.byteLength);return new Xd(e).set(new Xd(s)),e}var gT=pT,fT=gT;function wT(s,e){var t=e?fT(s.buffer):s.buffer;return new s.constructor(t,s.byteOffset,s.length)}var yT=wT;function mT(s,e){var t=-1,i=s.length;for(e||(e=Array(i));++t<i;)e[t]=s[t];return e}var bT=mT,vT=mr,ep=Object.create,IT=(function(){function s(){}return function(e){if(!vT(e))return{};if(ep)return ep(e);s.prototype=e;var t=new s;return s.prototype=void 0,t}})(),ET=IT;function AT(s,e){return function(t){return s(e(t))}}var NT=AT,CT=NT,_T=CT(Object.getPrototypeOf,Object),jw=_T,ST=Object.prototype;function $T(s){var e=s&&s.constructor,t=typeof e=="function"&&e.prototype||ST;return s===t}var Rw=$T,TT=ET,PT=jw,xT=Rw;function MT(s){return typeof s.constructor=="function"&&!xT(s)?TT(PT(s)):{}}var OT=MT;function DT(s){return s!=null&&typeof s=="object"}var Ho=DT,kT=pc,jT=Ho,RT="[object Arguments]";function UT(s){return jT(s)&&kT(s)==RT}var LT=UT,tp=LT,zT=Ho,Uw=Object.prototype,FT=Uw.hasOwnProperty,qT=Uw.propertyIsEnumerable,BT=tp((function(){return arguments})())?tp:function(s){return zT(s)&&FT.call(s,"callee")&&!qT.call(s,"callee")},Lw=BT,HT=Array.isArray,zw=HT,WT=9007199254740991;function VT(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=WT}var Fw=VT,KT=Lh,GT=Fw;function YT(s){return s!=null&&GT(s.length)&&!KT(s)}var qh=YT,QT=qh,JT=Ho;function ZT(s){return JT(s)&&QT(s)}var XT=ZT,Va={exports:{}};function eP(){return!1}var tP=eP;(function(s,e){var t=Pn,i=tP,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})(Va,Va.exports);var sP=pc,iP=jw,rP=Ho,nP="[object Object]",oP=Function.prototype,aP=Object.prototype,qw=oP.toString,cP=aP.hasOwnProperty,lP=qw.call(Object);function hP(s){if(!rP(s)||sP(s)!=nP)return!1;var e=iP(s);if(e===null)return!0;var t=cP.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&qw.call(t)==lP}var uP=hP,dP=pc,pP=Fw,gP=Ho,fP="[object Arguments]",wP="[object Array]",yP="[object Boolean]",mP="[object Date]",bP="[object Error]",vP="[object Function]",IP="[object Map]",EP="[object Number]",AP="[object Object]",NP="[object RegExp]",CP="[object Set]",_P="[object String]",SP="[object WeakMap]",$P="[object ArrayBuffer]",TP="[object DataView]",PP="[object Float32Array]",xP="[object Float64Array]",MP="[object Int8Array]",OP="[object Int16Array]",DP="[object Int32Array]",kP="[object Uint8Array]",jP="[object Uint8ClampedArray]",RP="[object Uint16Array]",UP="[object Uint32Array]",Qe={};Qe[PP]=Qe[xP]=Qe[MP]=Qe[OP]=Qe[DP]=Qe[kP]=Qe[jP]=Qe[RP]=Qe[UP]=!0,Qe[fP]=Qe[wP]=Qe[$P]=Qe[yP]=Qe[TP]=Qe[mP]=Qe[bP]=Qe[vP]=Qe[IP]=Qe[EP]=Qe[AP]=Qe[NP]=Qe[CP]=Qe[_P]=Qe[SP]=!1;function LP(s){return gP(s)&&pP(s.length)&&!!Qe[dP(s)]}var zP=LP;function FP(s){return function(e){return s(e)}}var qP=FP,Vl={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})(Vl,Vl.exports);var BP=zP,HP=qP,sp=Vl.exports,ip=sp&&sp.isTypedArray,WP=ip?HP(ip):BP,Bw=WP;function VP(s,e){if(!(e==="constructor"&&typeof s[e]=="function")&&e!="__proto__")return s[e]}var Hw=VP,KP=Fh,GP=hc,YP=Object.prototype,QP=YP.hasOwnProperty;function JP(s,e,t){var i=s[e];(!(QP.call(s,e)&&GP(i,t))||t===void 0&&!(e in s))&&KP(s,e,t)}var ZP=JP,XP=ZP,ex=Fh;function tx(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?ex(t,a,c):XP(t,a,c)}return t}var sx=tx;function ix(s,e){for(var t=-1,i=Array(s);++t<s;)i[t]=e(t);return i}var rx=ix,nx=9007199254740991,ox=/^(?:0|[1-9]\d*)$/;function ax(s,e){var t=typeof s;return e=e??nx,!!e&&(t=="number"||t!="symbol"&&ox.test(s))&&s>-1&&s%1==0&&s<e}var Ww=ax,cx=rx,lx=Lw,hx=zw,ux=Va.exports,dx=Ww,px=Bw,gx=Object.prototype,fx=gx.hasOwnProperty;function wx(s,e){var t=hx(s),i=!t&&lx(s),r=!t&&!i&&ux(s),n=!t&&!i&&!r&&px(s),o=t||i||r||n,a=o?cx(s.length,String):[],c=a.length;for(var l in s)(e||fx.call(s,l))&&!(o&&(l=="length"||r&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||dx(l,c)))&&a.push(l);return a}var yx=wx;function mx(s){var e=[];if(s!=null)for(var t in Object(s))e.push(t);return e}var bx=mx,vx=mr,Ix=Rw,Ex=bx,Ax=Object.prototype,Nx=Ax.hasOwnProperty;function Cx(s){if(!vx(s))return Ex(s);var e=Ix(s),t=[];for(var i in s)i=="constructor"&&(e||!Nx.call(s,i))||t.push(i);return t}var _x=Cx,Sx=yx,$x=_x,Tx=qh;function Px(s){return Tx(s)?Sx(s,!0):$x(s)}var Vw=Px,xx=sx,Mx=Vw;function Ox(s){return xx(s,Mx(s))}var Dx=Ox,rp=kw,kx=Wl.exports,jx=yT,Rx=bT,Ux=OT,np=Lw,op=zw,Lx=XT,zx=Va.exports,Fx=Lh,qx=mr,Bx=uP,Hx=Bw,ap=Hw,Wx=Dx;function Vx(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&&zx(c),g=!p&&!f&&Hx(c);u=c,p||f||g?op(a)?u=a:Lx(a)?u=Rx(a):f?(d=!1,u=kx(c,!0)):g?(d=!1,u=jx(c,!0)):u=[]:Bx(c)||np(c)?(u=a,np(a)?u=Wx(a):(!qx(a)||Fx(a))&&(u=Ux(c))):d=!1}d&&(o.set(c,u),r(u,c,i,n,o),o.delete(c)),rp(s,t,u)}var Kx=Vx,Gx=Z$,Yx=kw,Qx=lT,Jx=Kx,Zx=mr,Xx=Vw,e2=Hw;function Kw(s,e,t,i,r){s!==e&&Qx(e,function(n,o){if(r||(r=new Gx),Zx(n))Jx(s,e,o,t,Kw,i,r);else{var a=i?i(e2(s,o),n,o+"",s,e,r):void 0;a===void 0&&(a=n),Yx(s,o,a)}},Xx)}var t2=Kw;function s2(s){return s}var Gw=s2;function i2(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 r2=i2,n2=r2,cp=Math.max;function o2(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),n2(s,this,a)}}var a2=o2;function c2(s){return function(){return s}}var l2=c2,h2=l2,lp=Dw,u2=Gw,d2=lp?function(s,e){return lp(s,"toString",{configurable:!0,enumerable:!1,value:h2(e),writable:!0})}:u2,p2=d2,g2=800,f2=16,w2=Date.now;function y2(s){var e=0,t=0;return function(){var i=w2(),r=f2-(i-t);if(t=i,r>0){if(++e>=g2)return arguments[0]}else e=0;return s.apply(void 0,arguments)}}var m2=y2,b2=p2,v2=m2,I2=v2(b2),E2=I2,A2=Gw,N2=a2,C2=E2;function _2(s,e){return C2(N2(s,e,A2),s+"")}var S2=_2,$2=hc,T2=qh,P2=Ww,x2=mr;function M2(s,e,t){if(!x2(t))return!1;var i=typeof e;return(i=="number"?T2(t)&&P2(e,t.length):i=="string"&&e in t)?$2(t[e],s):!1}var O2=M2,D2=S2,k2=O2;function j2(s){return D2(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&&k2(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 R2=j2,U2=t2,L2=R2,z2=L2(function(s,e,t){U2(s,e,t)}),F2=z2,q2=Object.defineProperty,B2=Object.defineProperties,H2=Object.getOwnPropertyDescriptors,hp=Object.getOwnPropertySymbols,W2=Object.prototype.hasOwnProperty,V2=Object.prototype.propertyIsEnumerable,up=(s,e,t)=>e in s?q2(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,ga=(s,e)=>{for(var t in e||(e={}))W2.call(e,t)&&up(s,t,e[t]);if(hp)for(var t of hp(e))V2.call(e,t)&&up(s,t,e[t]);return s},K2=(s,e)=>B2(s,H2(e));function hs(s,e,t){var i;const r=yn(s);return((i=e.rpcMap)==null?void 0:i[r.reference])||`${Tw}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function br(s){return s.includes(":")?s.split(":")[1]:s}function Yw(s){return s.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function G2(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 Vc(s={},e={}){const t=dp(s),i=dp(e);return F2(t,i)}function dp(s){var e,t,i,r;const n={};if(!So(s))return n;for(const[o,a]of Object.entries(s)){const c=jh(o)?[o]:a.chains,l=a.methods||[],u=a.events||[],d=a.rpcMap||{},p=no(o);n[p]=K2(ga(ga({},n[p]),a),{chains:Pa(c,(e=n[p])==null?void 0:e.chains),methods:Pa(l,(t=n[p])==null?void 0:t.methods),events:Pa(u,(i=n[p])==null?void 0:i.events),rpcMap:ga(ga({},d),(r=n[p])==null?void 0:r.rpcMap)})}return n}function Y2(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=jh(t)?[t]:i.chains?i.chains:Yw(i.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Kc(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],Gc=(s,e)=>{Qw[s]=e};var Q2=Object.defineProperty,J2=(s,e,t)=>e in s?Q2(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Tr=(s,e,t)=>J2(s,typeof e!="symbol"?e+"":e,t);class Z2{constructor(e){Tr(this,"name","polkadot"),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()}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=br(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 X2=Object.defineProperty,eM=Object.defineProperties,tM=Object.getOwnPropertyDescriptors,gp=Object.getOwnPropertySymbols,sM=Object.prototype.hasOwnProperty,iM=Object.prototype.propertyIsEnumerable,Kl=(s,e,t)=>e in s?X2(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fp=(s,e)=>{for(var t in e||(e={}))sM.call(e,t)&&Kl(s,t,e[t]);if(gp)for(var t of gp(e))iM.call(e,t)&&Kl(s,t,e[t]);return s},wp=(s,e)=>eM(s,tM(e)),Pr=(s,e,t)=>Kl(s,typeof e!="symbol"?e+"":e,t);class rM{constructor(e){Pr(this,"name","eip155"),Pr(this,"client"),Pr(this,"chainId"),Pr(this,"namespace"),Pr(this,"httpProviders"),Pr(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(br(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`${r_}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var nM=Object.defineProperty,oM=(s,e,t)=>e in s?nM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,xr=(s,e,t)=>oM(s,typeof e!="symbol"?e+"":e,t);class aM{constructor(e){xr(this,"name","solana"),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){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=br(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 cM=Object.defineProperty,lM=(s,e,t)=>e in s?cM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Mr=(s,e,t)=>lM(s,typeof e!="symbol"?e+"":e,t);class hM{constructor(e){Mr(this,"name","cosmos"),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=>{var i;const r=br(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 uM=Object.defineProperty,dM=(s,e,t)=>e in s?uM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Or=(s,e,t)=>dM(s,typeof e!="symbol"?e+"":e,t);class pM{constructor(e){Or(this,"name","algorand"),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){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 gM=Object.defineProperty,fM=(s,e,t)=>e in s?gM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Dr=(s,e,t)=>fM(s,typeof e!="symbol"?e+"":e,t);class wM{constructor(e){Dr(this,"name","cip34"),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()}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=br(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 yM=Object.defineProperty,mM=(s,e,t)=>e in s?yM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,kr=(s,e,t)=>mM(s,typeof e!="symbol"?e+"":e,t);class bM{constructor(e){kr(this,"name","elrond"),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()}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=br(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 vM=Object.defineProperty,IM=(s,e,t)=>e in s?vM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,jr=(s,e,t)=>IM(s,typeof e!="symbol"?e+"":e,t);class EM{constructor(e){jr(this,"name","multiversx"),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()}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=br(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 AM=Object.defineProperty,NM=(s,e,t)=>e in s?AM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Rr=(s,e,t)=>NM(s,typeof e!="symbol"?e+"":e,t);class CM{constructor(e){Rr(this,"name","near"),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=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 _M=Object.defineProperty,SM=(s,e,t)=>e in s?_M(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Ur=(s,e,t)=>SM(s,typeof e!="symbol"?e+"":e,t);class $M{constructor(e){Ur(this,"name","tezos"),Ur(this,"client"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"namespace"),Ur(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 TM=Object.defineProperty,PM=(s,e,t)=>e in s?TM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Lr=(s,e,t)=>PM(s,typeof e!="symbol"?e+"":e,t);class xM{constructor(e){Lr(this,"name",rn),Lr(this,"client"),Lr(this,"httpProviders"),Lr(this,"events"),Lr(this,"namespace"),Lr(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=yn(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 MM=Object.defineProperty,OM=Object.defineProperties,DM=Object.getOwnPropertyDescriptors,yp=Object.getOwnPropertySymbols,kM=Object.prototype.hasOwnProperty,jM=Object.prototype.propertyIsEnumerable,Gl=(s,e,t)=>e in s?MM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,fa=(s,e)=>{for(var t in e||(e={}))kM.call(e,t)&&Gl(s,t,e[t]);if(yp)for(var t of yp(e))jM.call(e,t)&&Gl(s,t,e[t]);return s},Yc=(s,e)=>OM(s,DM(e)),Ts=(s,e,t)=>Gl(s,typeof e!="symbol"?e+"":e,t);class Bh{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 Bh(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:fa({},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=Vc(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=Vc(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===rn?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(ur(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 e_.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Hd,relayUrl:this.providerOpts.relayUrl||t_,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=>no(t)))];Gc("client",this.client),Gc("events",this.events),Gc("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=G2(t,this.session),r=Yw(i),n=Vc(this.namespaces,this.optionalNamespaces),o=Yc(fa({},n[t]),{accounts:i,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new rM({namespace:o});break;case"algorand":this.rpcProviders[t]=new pM({namespace:o});break;case"solana":this.rpcProviders[t]=new aM({namespace:o});break;case"cosmos":this.rpcProviders[t]=new hM({namespace:o});break;case"polkadot":this.rpcProviders[t]=new Z2({namespace:o});break;case"cip34":this.rpcProviders[t]=new wM({namespace:o});break;case"elrond":this.rpcProviders[t]=new bM({namespace:o});break;case"multiversx":this.rpcProviders[t]=new EM({namespace:o});break;case"near":this.rpcProviders[t]=new CM({namespace:o});break;case"tezos":this.rpcProviders[t]=new $M({namespace:o});break;default:this.rpcProviders[rn]?this.rpcProviders[rn].updateNamespace(o):this.rpcProviders[rn]=new xM({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&&ur(r)&&this.events.emit("accountsChanged",r.map(Y2))}else if(i.name==="chainChanged"){const r=t.chainId,n=t.event.data,o=no(r),a=Kc(r)!==Kc(n)?`${o}:${Kc(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=Yc(fa({},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",Yc(fa({},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[rn]}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=>no(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=no(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 RM=Bh,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]}},wa={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,""))}},UM=[{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"}]}],LM=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],zM=[{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"}]}],se={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin"},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"},FM={getERC20Abi:s=>se.USDT_CONTRACT_ADDRESSES.includes(s)?zM:UM,getSwapAbi:()=>LM},Ei={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 Qc(s){if(!s)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${s}:connected_connector_id`}const ce={setItem(s,e){ao()&&e!==void 0&&localStorage.setItem(s,e)},getItem(s){if(ao())return localStorage.getItem(s)||void 0},removeItem(s){ao()&&localStorage.removeItem(s)},clear(){ao()&&localStorage.clear()}};function ao(){return typeof window<"u"&&typeof localStorage<"u"}function Mi(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 Jc=(typeof _.process$1<"u"&&typeof _.process$1.env<"u"?_.process$1.env.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Wt={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:Jc,SECURE_SITE_DASHBOARD:`${Jc}/dashboard`,SECURE_SITE_FAVICON:`${Jc}/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=Qc(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=Qc(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=Qc(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()<=Wt.TEN_SEC_MS:!0},isAllowedRetry(s,e=Wt.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()+Wt.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 se.W3M_API_URL},getBlockchainApiUrl(){return se.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return se.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?Wt.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 se.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 Gn(...s){const e=await fetch(...s);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class wc{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 Gn(n,{method:"GET",headers:e,signal:t,cache:i})).json()}async getBlob({headers:e,signal:t,...i}){const r=this.createUrl(i);return(await Gn(r,{method:"GET",headers:e,signal:t})).blob()}async post({body:e,headers:t,signal:i,...r}){const n=this.createUrl(r);return(await Gn(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 Gn(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 Gn(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 qM={handleSolanaDeeplinkRedirect(s){if(I.state.activeChain===se.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}},BM={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00"},Zc=k.proxy({networkImagePromises:{}}),Hh={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||(Zc.networkImagePromises[s]||(Zc.networkImagePromises[s]=ue._fetchNetworkImage(s)),await Zc.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[BM[s]]}},HM={getFeatureValue(s,e){const t=e?.[s];return t===void 0?Wt.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}},re=k.proxy({features:Wt.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Wt.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0}),R={state:re,subscribeKey(s,e){return k.subscribeKey(re,s,e)},setOptions(s){Object.assign(re,s)},setFeatures(s){if(!s)return;re.features||(re.features=Wt.DEFAULT_FEATURES);const e={...re.features,...s};re.features=e,re.features.socials&&(re.features.socials=HM.filterSocialsByPlatform(re.features.socials))},setProjectId(s){re.projectId=s},setCustomRpcUrls(s){re.customRpcUrls=s},setAllWallets(s){re.allWallets=s},setIncludeWalletIds(s){re.includeWalletIds=s},setExcludeWalletIds(s){re.excludeWalletIds=s},setFeaturedWalletIds(s){re.featuredWalletIds=s},setTokens(s){re.tokens=s},setTermsConditionsUrl(s){re.termsConditionsUrl=s},setPrivacyPolicyUrl(s){re.privacyPolicyUrl=s},setCustomWallets(s){re.customWallets=s},setIsSiweEnabled(s){re.isSiweEnabled=s},setIsUniversalProvider(s){re.isUniversalProvider=s},setSdkVersion(s){re.sdkVersion=s},setMetadata(s){re.metadata=s},setDisableAppend(s){re.disableAppend=s},setEIP6963Enabled(s){re.enableEIP6963=s},setDebug(s){re.debug=s},setEnableWalletConnect(s){re.enableWalletConnect=s},setEnableWalletGuide(s){re.enableWalletGuide=s},setEnableAuthLogger(s){re.enableAuthLogger=s},setEnableWallets(s){re.enableWallets=s},setHasMultipleAddresses(s){re.hasMultipleAddresses=s},setSIWX(s){re.siwx=s},setConnectMethodsOrder(s){re.features={...re.features,connectMethodsOrder:s}},setWalletFeaturesOrder(s){re.features={...re.features,walletFeaturesOrder:s}},setSocialsOrder(s){re.features={...re.features,socials:s}},setCollapseWallets(s){re.features={...re.features,collapseWallets:s}},setEnableEmbedded(s){re.enableEmbedded=s},setAllowUnsupportedChain(s){re.allowUnsupportedChain=s},setManualWCControl(s){re.manualWCControl=s},setEnableNetworkSwitch(s){re.enableNetworkSwitch=s},setDefaultAccountTypes(s={}){Object.entries(s).forEach(([e,t])=>{t&&(re.defaultAccountTypes[e]=t)})},setUniversalProviderConfigOverride(s){re.universalProviderConfigOverride=s},getUniversalProviderConfigOverride(){return re.universalProviderConfigOverride},getSnapshot(){return k.snapshot(re)}},Ai=k.proxy({message:"",variant:"info",open:!1}),fo={state:Ai,subscribeKey(s,e){return k.subscribeKey(Ai,s,e)},open(s,e){const{debug:t}=R.state,{shortMessage:i,longMessage:r}=s;t&&(Ai.message=i,Ai.variant=e,Ai.open=!0),r&&console.error(typeof r=="function"?r():r)},close(){Ai.open=!1,Ai.message="",Ai.variant="info"}},WM=he.getAnalyticsUrl(),VM=new wc({baseUrl:WM,clientId:null}),KM=["MODAL_CREATED"],ri=k.proxy({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),Be={state:ri,subscribe(s){return k.subscribe(ri,()=>s(ri))},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=ie.state.address;if(KM.includes(s.data.event)||typeof window>"u")return;await VM.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}}}),ri.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===se.HTTP_STATUS_CODES.FORBIDDEN&&!ri.reportedErrors.FORBIDDEN&&(fo.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${ao()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),ri.reportedErrors.FORBIDDEN=!0)}},sendEvent(s){ri.timestamp=Date.now(),ri.data=s,R.state.features?.analytics&&Be._sendAnalyticsEvent(ri)}},GM=he.getApiUrl(),Ut=new wc({baseUrl:GM,clientId:null}),YM="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=`${Ut.baseUrl}/getWalletImage/${s}`,t=await Ut.getBlob({path:e,params:ue._getSdkProperties()});Is.setWalletImage(s,URL.createObjectURL(t))},async _fetchNetworkImage(s){const e=`${Ut.baseUrl}/public/getAssetImage/${s}`,t=await Ut.getBlob({path:e,params:ue._getSdkProperties()});Is.setNetworkImage(s,URL.createObjectURL(t))},async _fetchConnectorImage(s){const e=`${Ut.baseUrl}/public/getAssetImage/${s}`,t=await Ut.getBlob({path:e,params:ue._getSdkProperties()});Is.setConnectorImage(s,URL.createObjectURL(t))},async _fetchCurrencyImage(s){const e=`${Ut.baseUrl}/public/getCurrencyImage/${s}`,t=await Ut.getBlob({path:e,params:ue._getSdkProperties()});Is.setCurrencyImage(s,URL.createObjectURL(t))},async _fetchTokenImage(s){const e=`${Ut.baseUrl}/public/getTokenImage/${s}`,t=await Ut.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=>!Hh.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 Ut.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 Ut.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 Ut.get({path:"/getWallets",params:{...ue._getSdkProperties(),page:String(s),entries:YM,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 Ut.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 Ut.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 Ut.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):(at.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 at.close();Te.data?.wallet&&(Te.data.wallet=void 0),setTimeout(()=>{if(s){ie.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)}}},ni=k.proxy({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),zt={state:ni,subscribe(s){return k.subscribe(ni,()=>s(ni))},setThemeMode(s){ni.themeMode=s;try{const e=le.getAuthConnector();if(e){const t=zt.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:s,themeVariables:t,w3mThemeVariables:Mi(t,s)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(s){ni.themeVariables={...ni.themeVariables,...s};try{const e=le.getAuthConnector();if(e){const t=zt.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:t,w3mThemeVariables:Mi(ni.themeVariables,ni.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return k.snapshot(ni)}},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===se.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===se.CONNECTOR_ID.AUTH){const e=s,t=k.snapshot(R.state),i=zt.getSnapshot().themeMode,r=zt.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:Mi(r,i)}),this.setConnectors([s])}else this.setConnectors([s])},getAuthConnector(s){const e=s||I.state.activeChain,t=De.connectors.find(i=>i.id===se.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=zt.getSnapshot().themeMode,r=zt.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:Mi(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===se.CHAIN.SOLANA&&qM.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 ya(s,e){return le.getConnectorId(s)===e}function JM(s){const e=Array.from(I.state.chains.keys());let t=[];return s?(t.push([s,I.state.chains.get(s)]),ya(s,se.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(i=>{i!==s&&ya(i,se.CONNECTOR_ID.WALLET_CONNECT)&&t.push([i,I.state.chains.get(i)])}):ya(s,se.CONNECTOR_ID.AUTH)&&e.forEach(i=>{i!==s&&ya(i,se.CONNECTOR_ID.AUTH)&&t.push([i,I.state.chains.get(i)])})):t=Array.from(I.state.chains.entries()),t}var ZM=Object.defineProperty,XM=(s,e,t)=>e in s?ZM(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,bp=(s,e,t)=>XM(s,typeof e!="symbol"?e+"":e,t);class eO extends h.IEvents{constructor(e){super(),this.opts=e,bp(this,"protocol","wc"),bp(this,"version",2)}}var tO=Object.defineProperty,sO=(s,e,t)=>e in s?tO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,iO=(s,e,t)=>sO(s,e+"",t);let rO=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t,iO(this,"records",new Map)}},nO=class{constructor(e,t){this.logger=e,this.core=t}};class oO extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}}let aO=class extends h.IEvents{constructor(e){super()}},cO=class{constructor(e,t,i,r){this.core=e,this.logger=t,this.name=i}},lO=class extends h.IEvents{constructor(e,t){super(),this.relayer=e,this.logger=t}},hO=class extends h.IEvents{constructor(e,t){super(),this.core=e,this.logger=t}},uO=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},dO=class{constructor(e,t){this.projectId=e,this.logger=t}},pO=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};var gO=Object.defineProperty,fO=(s,e,t)=>e in s?gO(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,vp=(s,e,t)=>fO(s,typeof e!="symbol"?e+"":e,t);let wO=class{constructor(e){this.opts=e,vp(this,"protocol","wc"),vp(this,"version",2)}},yO=class{constructor(e){this.client=e}};const mO="https://secure.walletconnect.org/sdk";typeof _.process$1<"u"&&typeof _.process$1.env<"u"&&_.process$1.env.NEXT_PUBLIC_SECURE_SITE_SDK_URL;typeof _.process$1<"u"&&typeof _.process$1.env<"u"&&_.process$1.env.NEXT_PUBLIC_DEFAULT_LOG_LEVEL;typeof _.process$1<"u"&&typeof _.process$1.env<"u"&&_.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"}},Zi=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),dt=k.proxy({...Zi}),It={state:dt,subscribeKey(s,e){return k.subscribeKey(dt,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(){dt.message=Zi.message,dt.variant=Zi.variant,dt.svg=Zi.svg,dt.open=Zi.open,dt.autoClose=Zi.autoClose},_showMessage({message:s,svg:e,variant:t="success",autoClose:i=Zi.autoClose}){dt.open?(dt.open=!1,setTimeout(()=>{dt.message=s,dt.variant=t,dt.svg=e,dt.open=!0,dt.autoClose=i},150)):(dt.message=s,dt.variant=t,dt.svg=e,dt.open=!0,dt.autoClose=i)}},mn={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 at.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"),It.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)===se.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}),at.close(),Be.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){const n=this.getSIWXEventProperties();(!at.state.open||Me.state.view==="ApproveTransaction")&&await at.open({view:"SIWXSignMessage"}),n.isSmartAccount?It.showError("This application might not support Smart Accounts"):It.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():at.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=mn.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(It.showLoading("Authenticating...",{autoClose:!1}),ie.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:mn.getSIWXEventProperties()})}catch(c){throw console.error("SIWX:universalProviderAuth - failed to set sessions",c),Be.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:mn.getSIWXEventProperties()}),await s.disconnect().catch(console.error),c}finally{It.hide()}}return!0},getSIWXEventProperties(){return{network:I.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:ie.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}),bO={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 ne.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:ie.state.preferredAccountType===$i.ACCOUNT_TYPES.SMART_ACCOUNT}}),It.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}},Xe=k.proxy({wcError:!1,buffering:!1,status:"disconnected"});let zr;const qe={state:Xe,subscribeKey(s,e){return k.subscribeKey(Xe,s,e)},_getClient(){return Xe._client},setClient(s){Xe._client=k.ref(s)},async connectWalletConnect(){if(he.isTelegram()||he.isSafari()&&he.isIos()){if(zr){await zr,zr=void 0;return}if(!he.isPairingExpired(Xe?.wcPairingExpiry)){const s=Xe.wcUri;Xe.wcUri=s;return}zr=this._getClient()?.connectWalletConnect?.().catch(()=>{}),this.state.status="connecting",await zr,zr=void 0,Xe.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){at.setLoading(!0,I.state.activeChain);const e=le.getAuthConnector();e&&(await e?.provider.setPreferredAccount(s),await this.reconnectExternal(e),at.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(){Xe.wcUri=void 0,Xe.wcPairingExpiry=void 0,Xe.wcLinking=void 0,Xe.recentWallet=void 0,Xe.status="disconnected",bO.resetTransactions(),X.deleteWalletConnectDeepLink()},resetUri(){Xe.wcUri=void 0,Xe.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){Xe.wcBasic=s},setUri(s){Xe.wcUri=s,Xe.wcPairingExpiry=he.getPairingExpiry()},setWcLinking(s){Xe.wcLinking=s},setWcError(s){Xe.wcError=s,Xe.buffering=!1},setRecentWallet(s){Xe.recentWallet=s},setBuffering(s){Xe.buffering=s},setStatus(s){Xe.status=s},async disconnect(s){try{at.setLoading(!0,s),await mn.clearSessions(),await I.disconnect(s),at.setLoading(!1,s),le.setFilterByNamespace(void 0)}catch{throw new Error("Failed to disconnect")}}},Yn=k.proxy({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),fi={state:Yn,subscribe(s){return k.subscribe(Yn,()=>s(Yn))},set(s){Object.assign(Yn,{...Yn,...s})}},Xc={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 wn.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=ie.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 ne.getBalance(e,t.caipNetworkId,s);return this.filterLowQualityTokens(i.balances)},async getEIP155Balances(s,e){try{const t=Xc.getChainIdHexFromCAIP2ChainId(e.caipNetworkId);if(!(await qe.getCapabilities(s))?.[t]?.assetDiscovery?.supported)return null;const r=await qe.walletGetAssets({account:s,chainFilter:[t]});return Xc.isWalletGetAssetsResponse(r)?(r[t]||[]).map(o=>Xc.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:ie.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:ie.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*Wt.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),It.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?wa.multiply(e.quantity.numeric,e.price).toString():"0")},isInsufficientNetworkTokenForGas(s,e){const t=e||"0";return wa.bigNumber(s).eq(0)?!0:wa.bigNumber(wa.bigNumber(t)).gt(s)},hasInsufficientGasFunds(){let s=!0;return ie.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=ie.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}),It.showSuccess("Transaction started"),Be.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:ie.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:ie.state.preferredAccountType===$i.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token?.symbol||"",amount:s.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),It.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(ie.state.address&&s.sendTokenAmount&&s.receiverAddress&&s.tokenAddress){const t=he.getPlainAddress(s.tokenAddress);await qe.writeContract({fromAddress:ie.state.address,tokenAddress:t,args:[s.receiverAddress,e??BigInt(0)],method:"transfer",abi:FM.getERC20Abi(t),chainNamespace:"eip155"}),It.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:ie.state.preferredAccountType===$i.ACCOUNT_TYPES.SMART_ACCOUNT,token:this.state.token?.symbol||"",amount:s.sendTokenAmount,network:I.state.activeCaipNetwork?.caipNetworkId||""}}),It.showError("Something went wrong")}},sendSolanaToken(){if(!this.state.sendTokenAmount||!this.state.receiverAddress){It.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(),ie.fetchTokenBalance()}).catch(s=>{It.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=[]}},el={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},ma={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&&fi.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({...ma,caipNetwork:u?.[0]}),accountState:k.proxy(el),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:{...ma,caipNetwork:i[0]},accountState:el,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||ma,...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||el,...e};F.chains.set(s,{...i,accountState:r}),(F.chains.size===1||F.activeChain===s)&&(e.caipAddress&&(F.activeCaipAddress=e.caipAddress),ie.replaceState(r))}},setChainNetworkData(s,e){if(!s)return;const t=F.chains.get(s);if(t){const i={...t.networkState||ma,...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),fi.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&&ie.replaceState(e.accountState),Ep.resetSend(),fi.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=Wt.NATIVE_TOKEN_ADDRESS[s];return`${s}:${e}:${t}`},showUnsupportedChainUI(){at.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const s=F.activeCaipNetwork;return!!(s?.chainNamespace&&Wt.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=JM(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=>{se.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:ie.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)}},vO={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 wc({baseUrl:Xw,clientId:null}),supportedChains:{http:[],ws:[]}}),ne={state:ss,async get(s){const{st:e,sv:t}=ne.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 ne.getSupportedNetworks()}catch{return!1}return ss.supportedChains.http.includes(s)},async getSupportedNetworks(){const s=await ne.get({path:"v1/supported-chains"});return ss.supportedChains=s,s},async fetchIdentity({address:s,caipNetworkId:e}){if(!await ne.isNetworkSupported(e))return{avatar:"",name:""};const i=X.getIdentityFromCacheForAddress(s);if(i)return i;const r=await ne.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 ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ne.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 ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ne.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 ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ne.get({path:"/v1/convert/tokens",params:{chainId:s}}):{tokens:[]}},async fetchTokenPrice({addresses:s}){return await ne.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 ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ne.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}=ne.getSdkProperties();if(!await ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return ne.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 ne.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:Wt.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}=ne.getSdkProperties();if(!await ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ne.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}=ne.getSdkProperties();if(!await ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))return It.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${s}`,a=X.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await ne.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 ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ne.get({path:`/v1/profile/account/${s}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:s}){return await ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ne.get({path:`/v1/profile/reverse/${s}`,params:{sender:ie.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(s){return await ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ne.get({path:`/v1/profile/suggestions/${s}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:s,address:e,message:t,signature:i}){return await ne.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 ne.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 ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await ne.get({path:"/v1/onramp/options"})}catch{return vO}},async getOnrampQuote({purchaseCurrency:s,paymentCurrency:e,amount:t,network:i}){try{return await ne.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 ne.isNetworkSupported(I.state.activeCaipNetwork?.caipNetworkId)?ne.get({path:`/v1/sessions/${s}`}):[]},async revokeSmartSession(s,e,t){return await ne.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 wc({baseUrl:Xw,clientId:s})}},Bs=k.proxy({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),ie={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*Wt.ONE_SEC_MS))return Bs.balanceLoading=!1,[];try{if(r&&e&&t){const o=(await ne.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),It.showError("Token Balance Unavailable")}finally{Bs.balanceLoading=!1}return[]},resetAccount(s){I.resetAccount(s)}},Gt=k.proxy({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),at={state:Gt,subscribe(s){return k.subscribe(Gt,()=>s(Gt))},subscribeKey(s,e){return k.subscribeKey(Gt,s,e)},async open(s){const e=ie.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),at.setLoading(!0,s.namespace)):at.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"),Gt.open=!0,fi.set({open:!0}),Be.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!t}})},close(){const s=R.state.enableEmbedded,e=!!I.state.activeCaipAddress;Gt.open&&Be.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),Gt.open=!1,at.clearLoading(),s?e?Me.replace("Account"):Me.push("Connect"):fi.set({open:!1}),qe.resetUri()},setLoading(s,e){e&&Gt.loadingNamespaceMap.set(e,s),Gt.loading=s,fi.set({loading:s})},clearLoading(){Gt.loadingNamespaceMap.clear(),Gt.loading=!1},shake(){Gt.shake||(Gt.shake=!0,setTimeout(()=>{Gt.shake=!1},500))}},Ap=2147483648,IO={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 ne.lookupEnsName(s)}catch(e){const t=e;throw new Error(t?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(s){try{return await ne.lookupEnsName(s),!0}catch{return!1}},async getSuggestions(s){try{fs.loading=!0,fs.suggestions=[];const e=await ne.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 ne.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=ie.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=IO.convertEVMChainIdToCoinType(Number(o));await ne.registerEnsName({coinType:a,address:t,signature:n,message:r}),ie.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 tl={getDocsUrl:({docsBaseUrl:s,docsPath:e="",docsSlug:t})=>e?`${s??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${ty}`};class dr extends Error{constructor(e,t={}){const i=t.cause instanceof dr?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof dr&&t.cause.docsPath||t.docsPath,n=tl.getDocsUrl?.({...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...tl.version?[`Version: ${tl.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 dr{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 xn(s,{dir:e,size:t=32}={}){return typeof s=="string"?EO(s,{dir:e,size:t}):AO(s,{dir:e,size:t})}function EO(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 AO(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 NO extends dr{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 CO extends dr{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Mn(s,{size:e}){if(Np(s)>e)throw new CO({givenSize:Np(s),maxSize:e})}function Yl(s,e={}){const{signed:t}=e;e.size&&Mn(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 _O(s,e={}){return Number(Yl(s,e))}const SO=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Ql(s,e={}){return typeof s=="number"||typeof s=="bigint"?ny(s,e):typeof s=="string"?PO(s,e):typeof s=="boolean"?$O(s,e):ry(s,e)}function $O(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(Mn(t,{size:e.size}),xn(t,{size:e.size})):t}function ry(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=SO[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(Mn(i,{size:e.size}),xn(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 NO({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?xn(a,{size:i}):a}const TO=new TextEncoder;function PO(s,e={}){const t=TO.encode(s);return ry(t,e)}const xO=new TextEncoder;function MO(s,e={}){return typeof s=="number"||typeof s=="bigint"?DO(s,e):typeof s=="boolean"?OO(s,e):$o(s)?oy(s,e):ay(s,e)}function OO(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(Mn(t,{size:e.size}),xn(t,{size:e.size})):t}const oi={zero:48,nine:57,A:65,F:70,a:97,f:102};function Cp(s){if(s>=oi.zero&&s<=oi.nine)return s-oi.zero;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 oy(s,e={}){let t=s;e.size&&(Mn(t,{size:e.size}),t=xn(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 dr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function DO(s,e){const t=ny(s,e);return oy(t)}function ay(s,e={}){const t=xO.encode(s);return typeof e.size=="number"?(Mn(t,{size:e.size}),xn(t,{dir:"right",size:e.size})):t}function Ka(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function kO(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Wo(s,...e){if(!kO(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 jO(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ka(s.outputLen),Ka(s.blockLen)}function Jl(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){Wo(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ba=BigInt(2**32-1),_p=BigInt(32);function RO(s,e=!1){return e?{h:Number(s&ba),l:Number(s>>_p&ba)}:{h:Number(s>>_p&ba)|0,l:Number(s&ba)|0}}function UO(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}=RO(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const LO=(s,e,t)=>s<<t|e>>>32-t,zO=(s,e,t)=>e<<t|s>>>32-t,FO=(s,e,t)=>e<<t-32|s>>>64-t,qO=(s,e,t)=>s<<t-32|e>>>64-t,Fr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function BO(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function HO(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function WO(s,e){return s<<32-e|s>>>e}const Sp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function VO(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]=VO(s[e])}function KO(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Wh(s){return typeof s=="string"&&(s=KO(s)),Wo(s),s}function GO(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Wo(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(Wh(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function YO(s=32){if(Fr&&typeof Fr.getRandomValues=="function")return Fr.getRandomValues(new Uint8Array(s));if(Fr&&typeof Fr.randomBytes=="function")return Fr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const uy=[],dy=[],py=[],QO=BigInt(0),Qn=BigInt(1),JO=BigInt(2),ZO=BigInt(7),XO=BigInt(256),eD=BigInt(113);for(let s=0,e=Qn,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<<Qn^(e>>ZO)*eD)%XO,e&JO&&(r^=Qn<<(Qn<<BigInt(n))-Qn);py.push(r)}const[tD,sD]=UO(py,!0),Tp=(s,e,t)=>t>32?FO(s,e,t):LO(s,e,t),Pp=(s,e,t)=>t>32?qO(s,e,t):zO(s,e,t);function iD(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]^=tD[i],s[1]^=sD[i]}t.fill(0)}class Vh 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,Ka(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=BO(this.state)}keccak(){Sp||$p(this.state32),iD(this.state32,this.rounds),Sp||$p(this.state32),this.posOut=0,this.pos=0}update(e){Jl(this);const{blockLen:t,state:i}=this;e=Wh(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){Jl(this,!1),Wo(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 Ka(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 Vh(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 rD=(s,e,t)=>hy(()=>new Vh(e,s,t)),nD=rD(1,136,256/8);function gy(s,e){const t=e||"hex",i=nD($o(s,{strict:!1})?MO(s):s);return t==="bytes"?i:Ql(i)}class oD 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 sl=new oD(8192);function aD(s,e){if(sl.has(`${s}.${e}`))return sl.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 sl.set(`${s}.${e}`,n),n}function cD(s){const e=gy(`0x${s.substring(4)}`).substring(26);return aD(`0x${e}`)}async function lD({hash:s,signature:e}){const t=$o(s)?s:Ql(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-B2G0zB-5.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(Yl(l),Yl(u)).addRecoveryBit(g)}const o=$o(e)?e:Ql(e),a=_O(`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 hD({hash:s,signature:e}){return cD(await lD({hash:s,signature:e}))}function uD(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 N=g-1;(m!==0||A<d)&&N!==-1;N--,A++)m+=256*w[N]>>>0,w[N]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(u);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,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 N=0;for(let S=f-1;(A!==0||N<p)&&S!==-1;S--,N++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=N,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 dD="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const fy=uD(dD),pD=":";function bn(s){const[e,t]=s.split(pD);return{namespace:e,reference:t}}function wy(s,e){return s.includes(":")?[s]:e.chains||[]}const gD="ReactNative",ls={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},fD="js";function Ga(){return typeof _.process$1<"u"&&typeof _.process$1.versions<"u"&&typeof _.process$1.versions.node<"u"}function Fi(){return!h.cjsExports$2.getDocument()&&!!h.cjsExports$2.getNavigator()&&navigator.product===gD}function wD(){return Fi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="android"}function yD(){return Fi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="ios"}function Vo(){return!Ga()&&!!h.cjsExports$2.getNavigator()&&!!h.cjsExports$2.getDocument()}function Ko(){return Fi()?ls.reactNative:Ga()?ls.node:Vo()?ls.browser:ls.unknown}function Mp(){var s;try{return Fi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Application)<"u"?(s=_.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function mD(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 bD(){if(Ko()===ls.reactNative&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"){const{OS:t,Version:i}=_.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 vD(){var s;const e=Ko();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=bD(),r=vD();return[[s,e].join("-"),[fD,t].join("-"),i,r].join("/")}function ID({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=mD(l[1]||"",d);return l[0]+"?"+p}function or(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Zl(s){return Object.fromEntries(s.entries())}function Xl(s){return new Map(Object.entries(s))}function Xi(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 Oi(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 ED(s){return by("topic",s)}function AD(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 gt(s,e){return h.cjsExports$1.fromMiliseconds(Date.now()+h.cjsExports$1.toMiliseconds(s))}function Ti(s){return Date.now()>=h.cjsExports$1.toMiliseconds(s)}function xe(s,e){return`${s}${e?`:${e}`:""}`}function Da(s=[],e=[]){return[...new Set([...s,...e])]}async function ND({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=CD(n,s,e),a=Ko();if(a===ls.browser){if(!((i=h.cjsExports$2.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}_D(o)}else a===ls.reactNative&&typeof(_.global==null?void 0:_.global.Linking)<"u"&&await _.global.Linking.openURL(o)}catch(r){console.error(r)}}function CD(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}${PD(i,!0)}`}else r=`${r}/wc?${i}`;return r}function _D(s){let e="_self";TD()?e="_top":($D()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function SD(s,e){let t="";try{if(Vo()&&(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 Kh(){return typeof _.process$1<"u"&&_.process$1.env.IS_VITEST==="true"}function $D(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function TD(){try{return window.self!==window.top}catch{return!1}}function PD(s,e=!1){const t=_.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Iy(s){return _.Buffer.from(s,"base64").toString("utf-8")}function xD(s){return new Promise(e=>setTimeout(e,s))}function To(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function MD(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function yc(s,...e){if(!MD(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 Gh(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");To(s.outputLen),To(s.blockLen)}function Nn(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){yc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const va=BigInt(2**32-1),kp=BigInt(32);function OD(s,e=!1){return e?{h:Number(s&va),l:Number(s>>kp&va)}:{h:Number(s>>kp&va)|0,l:Number(s&va)|0}}function DD(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}=OD(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const kD=(s,e,t)=>s<<t|e>>>32-t,jD=(s,e,t)=>e<<t|s>>>32-t,RD=(s,e,t)=>e<<t-32|s>>>64-t,UD=(s,e,t)=>s<<t-32|e>>>64-t,qr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function LD(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function il(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 zD(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]=zD(s[e])}function FD(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Cn(s){return typeof s=="string"&&(s=FD(s)),yc(s),s}let Yh=class{clone(){return this._cloneInto()}};function Ay(s){const e=i=>s().update(Cn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Go(s=32){if(qr&&typeof qr.getRandomValues=="function")return qr.getRandomValues(new Uint8Array(s));if(qr&&typeof qr.randomBytes=="function")return qr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Ny=[],Cy=[],_y=[],qD=BigInt(0),Jn=BigInt(1),BD=BigInt(2),HD=BigInt(7),WD=BigInt(256),VD=BigInt(113);for(let s=0,e=Jn,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=qD;for(let n=0;n<7;n++)e=(e<<Jn^(e>>HD)*VD)%WD,e&BD&&(r^=Jn<<(Jn<<BigInt(n))-Jn);_y.push(r)}const[KD,GD]=DD(_y,!0),Up=(s,e,t)=>t>32?RD(s,e,t):kD(s,e,t),Lp=(s,e,t)=>t>32?UD(s,e,t):jD(s,e,t);function YD(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]^=KD[i],s[1]^=GD[i]}t.fill(0)}let QD=class Sy extends Yh{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,To(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=LD(this.state)}keccak(){jp||Rp(this.state32),YD(this.state32,this.rounds),jp||Rp(this.state32),this.posOut=0,this.pos=0}update(e){Nn(this);const{blockLen:t,state:i}=this;e=Cn(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){Nn(this,!1),yc(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 To(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 JD=(s,e,t)=>Ay(()=>new QD(e,s,t)),ZD=JD(1,136,256/8),XD="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 dr{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 xn(s,{dir:e,size:t=32}={}){return typeof s=="string"?EO(s,{dir:e,size:t}):AO(s,{dir:e,size:t})}function EO(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 AO(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 NO extends dr{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 CO extends dr{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Mn(s,{size:e}){if(Np(s)>e)throw new CO({givenSize:Np(s),maxSize:e})}function Yl(s,e={}){const{signed:t}=e;e.size&&Mn(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 _O(s,e={}){return Number(Yl(s,e))}const SO=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Ql(s,e={}){return typeof s=="number"||typeof s=="bigint"?ny(s,e):typeof s=="string"?PO(s,e):typeof s=="boolean"?$O(s,e):ry(s,e)}function $O(s,e={}){const t=`0x${Number(s)}`;return typeof e.size=="number"?(Mn(t,{size:e.size}),xn(t,{size:e.size})):t}function ry(s,e={}){let t="";for(let r=0;r<s.length;r++)t+=SO[s[r]];const i=`0x${t}`;return typeof e.size=="number"?(Mn(i,{size:e.size}),xn(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 NO({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?xn(a,{size:i}):a}const TO=new TextEncoder;function PO(s,e={}){const t=TO.encode(s);return ry(t,e)}const xO=new TextEncoder;function MO(s,e={}){return typeof s=="number"||typeof s=="bigint"?DO(s,e):typeof s=="boolean"?OO(s,e):$o(s)?oy(s,e):ay(s,e)}function OO(s,e={}){const t=new Uint8Array(1);return t[0]=Number(s),typeof e.size=="number"?(Mn(t,{size:e.size}),xn(t,{size:e.size})):t}const oi={zero:48,nine:57,A:65,F:70,a:97,f:102};function Cp(s){if(s>=oi.zero&&s<=oi.nine)return s-oi.zero;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 oy(s,e={}){let t=s;e.size&&(Mn(t,{size:e.size}),t=xn(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 dr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+l}return n}function DO(s,e){const t=ny(s,e);return oy(t)}function ay(s,e={}){const t=xO.encode(s);return typeof e.size=="number"?(Mn(t,{size:e.size}),xn(t,{dir:"right",size:e.size})):t}function Ka(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function kO(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Wo(s,...e){if(!kO(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 jO(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ka(s.outputLen),Ka(s.blockLen)}function Jl(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){Wo(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ba=BigInt(2**32-1),_p=BigInt(32);function RO(s,e=!1){return e?{h:Number(s&ba),l:Number(s>>_p&ba)}:{h:Number(s>>_p&ba)|0,l:Number(s&ba)|0}}function UO(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}=RO(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const LO=(s,e,t)=>s<<t|e>>>32-t,zO=(s,e,t)=>e<<t|s>>>32-t,FO=(s,e,t)=>e<<t-32|s>>>64-t,qO=(s,e,t)=>s<<t-32|e>>>64-t,Fr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function BO(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function HO(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function WO(s,e){return s<<32-e|s>>>e}const Sp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function VO(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]=VO(s[e])}function KO(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Wh(s){return typeof s=="string"&&(s=KO(s)),Wo(s),s}function GO(...s){let e=0;for(let i=0;i<s.length;i++){const r=s[i];Wo(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(Wh(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function YO(s=32){if(Fr&&typeof Fr.getRandomValues=="function")return Fr.getRandomValues(new Uint8Array(s));if(Fr&&typeof Fr.randomBytes=="function")return Fr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const uy=[],dy=[],py=[],QO=BigInt(0),Qn=BigInt(1),JO=BigInt(2),ZO=BigInt(7),XO=BigInt(256),eD=BigInt(113);for(let s=0,e=Qn,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<<Qn^(e>>ZO)*eD)%XO,e&JO&&(r^=Qn<<(Qn<<BigInt(n))-Qn);py.push(r)}const[tD,sD]=UO(py,!0),Tp=(s,e,t)=>t>32?FO(s,e,t):LO(s,e,t),Pp=(s,e,t)=>t>32?qO(s,e,t):zO(s,e,t);function iD(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]^=tD[i],s[1]^=sD[i]}t.fill(0)}class Vh 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,Ka(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=BO(this.state)}keccak(){Sp||$p(this.state32),iD(this.state32,this.rounds),Sp||$p(this.state32),this.posOut=0,this.pos=0}update(e){Jl(this);const{blockLen:t,state:i}=this;e=Wh(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){Jl(this,!1),Wo(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 Ka(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 Vh(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 rD=(s,e,t)=>hy(()=>new Vh(e,s,t)),nD=rD(1,136,256/8);function gy(s,e){const t=e||"hex",i=nD($o(s,{strict:!1})?MO(s):s);return t==="bytes"?i:Ql(i)}class oD 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 sl=new oD(8192);function aD(s,e){if(sl.has(`${s}.${e}`))return sl.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 sl.set(`${s}.${e}`,n),n}function cD(s){const e=gy(`0x${s.substring(4)}`).substring(26);return aD(`0x${e}`)}async function lD({hash:s,signature:e}){const t=$o(s)?s:Ql(s),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-CeYT4ndf.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(Yl(l),Yl(u)).addRecoveryBit(g)}const o=$o(e)?e:Ql(e),a=_O(`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 hD({hash:s,signature:e}){return cD(await lD({hash:s,signature:e}))}function uD(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 N=g-1;(m!==0||A<d)&&N!==-1;N--,A++)m+=256*w[N]>>>0,w[N]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(u);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,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 N=0;for(let S=f-1;(A!==0||N<p)&&S!==-1;S--,N++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=N,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 dD="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const fy=uD(dD),pD=":";function bn(s){const[e,t]=s.split(pD);return{namespace:e,reference:t}}function wy(s,e){return s.includes(":")?[s]:e.chains||[]}const gD="ReactNative",ls={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},fD="js";function Ga(){return typeof _.process$1<"u"&&typeof _.process$1.versions<"u"&&typeof _.process$1.versions.node<"u"}function Fi(){return!h.cjsExports$2.getDocument()&&!!h.cjsExports$2.getNavigator()&&navigator.product===gD}function wD(){return Fi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="android"}function yD(){return Fi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"&&(_.global==null?void 0:_.global.Platform.OS)==="ios"}function Vo(){return!Ga()&&!!h.cjsExports$2.getNavigator()&&!!h.cjsExports$2.getDocument()}function Ko(){return Fi()?ls.reactNative:Ga()?ls.node:Vo()?ls.browser:ls.unknown}function Mp(){var s;try{return Fi()&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Application)<"u"?(s=_.global.Application)==null?void 0:s.applicationId:void 0}catch{return}}function mD(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 bD(){if(Ko()===ls.reactNative&&typeof _.global<"u"&&typeof(_.global==null?void 0:_.global.Platform)<"u"){const{OS:t,Version:i}=_.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 vD(){var s;const e=Ko();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=bD(),r=vD();return[[s,e].join("-"),[fD,t].join("-"),i,r].join("/")}function ID({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=mD(l[1]||"",d);return l[0]+"?"+p}function or(s,e){return s.filter(t=>e.includes(t)).length===s.length}function Zl(s){return Object.fromEntries(s.entries())}function Xl(s){return new Map(Object.entries(s))}function Xi(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 Oi(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 ED(s){return by("topic",s)}function AD(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 gt(s,e){return h.cjsExports$1.fromMiliseconds(Date.now()+h.cjsExports$1.toMiliseconds(s))}function Ti(s){return Date.now()>=h.cjsExports$1.toMiliseconds(s)}function xe(s,e){return`${s}${e?`:${e}`:""}`}function Da(s=[],e=[]){return[...new Set([...s,...e])]}async function ND({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=CD(n,s,e),a=Ko();if(a===ls.browser){if(!((i=h.cjsExports$2.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}_D(o)}else a===ls.reactNative&&typeof(_.global==null?void 0:_.global.Linking)<"u"&&await _.global.Linking.openURL(o)}catch(r){console.error(r)}}function CD(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}${PD(i,!0)}`}else r=`${r}/wc?${i}`;return r}function _D(s){let e="_self";TD()?e="_top":($D()||s.startsWith("https://")||s.startsWith("http://"))&&(e="_blank"),window.open(s,e,"noreferrer noopener")}async function SD(s,e){let t="";try{if(Vo()&&(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 Kh(){return typeof _.process$1<"u"&&_.process$1.env.IS_VITEST==="true"}function $D(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function TD(){try{return window.self!==window.top}catch{return!1}}function PD(s,e=!1){const t=_.Buffer.from(s).toString("base64");return e?t.replace(/[=]/g,""):t}function Iy(s){return _.Buffer.from(s,"base64").toString("utf-8")}function xD(s){return new Promise(e=>setTimeout(e,s))}function To(s){if(!Number.isSafeInteger(s)||s<0)throw new Error("positive integer expected, got "+s)}function MD(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function yc(s,...e){if(!MD(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 Gh(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");To(s.outputLen),To(s.blockLen)}function Nn(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){yc(s);const t=e.outputLen;if(s.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const va=BigInt(2**32-1),kp=BigInt(32);function OD(s,e=!1){return e?{h:Number(s&va),l:Number(s>>kp&va)}:{h:Number(s>>kp&va)|0,l:Number(s&va)|0}}function DD(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}=OD(s[r],e);[t[r],i[r]]=[n,o]}return[t,i]}const kD=(s,e,t)=>s<<t|e>>>32-t,jD=(s,e,t)=>e<<t|s>>>32-t,RD=(s,e,t)=>e<<t-32|s>>>64-t,UD=(s,e,t)=>s<<t-32|e>>>64-t,qr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function LD(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function il(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 zD(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]=zD(s[e])}function FD(s){if(typeof s!="string")throw new Error("utf8ToBytes expected string, got "+typeof s);return new Uint8Array(new TextEncoder().encode(s))}function Cn(s){return typeof s=="string"&&(s=FD(s)),yc(s),s}let Yh=class{clone(){return this._cloneInto()}};function Ay(s){const e=i=>s().update(Cn(i)).digest(),t=s();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>s(),e}function Go(s=32){if(qr&&typeof qr.getRandomValues=="function")return qr.getRandomValues(new Uint8Array(s));if(qr&&typeof qr.randomBytes=="function")return qr.randomBytes(s);throw new Error("crypto.getRandomValues must be defined")}const Ny=[],Cy=[],_y=[],qD=BigInt(0),Jn=BigInt(1),BD=BigInt(2),HD=BigInt(7),WD=BigInt(256),VD=BigInt(113);for(let s=0,e=Jn,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=qD;for(let n=0;n<7;n++)e=(e<<Jn^(e>>HD)*VD)%WD,e&BD&&(r^=Jn<<(Jn<<BigInt(n))-Jn);_y.push(r)}const[KD,GD]=DD(_y,!0),Up=(s,e,t)=>t>32?RD(s,e,t):kD(s,e,t),Lp=(s,e,t)=>t>32?UD(s,e,t):jD(s,e,t);function YD(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]^=KD[i],s[1]^=GD[i]}t.fill(0)}let QD=class Sy extends Yh{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,To(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=LD(this.state)}keccak(){jp||Rp(this.state32),YD(this.state32,this.rounds),jp||Rp(this.state32),this.posOut=0,this.pos=0}update(e){Nn(this);const{blockLen:t,state:i}=this;e=Cn(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){Nn(this,!1),yc(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 To(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 JD=(s,e,t)=>Ay(()=>new QD(e,s,t)),ZD=JD(1,136,256/8),XD="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"+_.Buffer.from(ZD(t)).toString("hex")}async function ek(s,e,t,i,r,n){switch(t.t){case"eip191":return await tk(s,e,t.s);case"eip1271":return await sk(s,e,t.s,i,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function tk(s,e,t){return(await hD({hash:$y(e),signature:t})).toLowerCase()===s.toLowerCase()}async function sk(s,e,t,i,r,n){const o=bn(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||XD}/?chainId=${i}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:ik(),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 ik(){return Date.now()+Math.floor(Math.random()*1e3)}function rk(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=_.Buffer.from(s,"base64").slice(1,65);return fy.encode(n)}var nk=Object.defineProperty,ok=Object.defineProperties,ak=Object.getOwnPropertyDescriptors,zp=Object.getOwnPropertySymbols,ck=Object.prototype.hasOwnProperty,lk=Object.prototype.propertyIsEnumerable,Fp=(s,e,t)=>e in s?nk(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,hk=(s,e)=>{for(var t in e||(e={}))ck.call(e,t)&&Fp(s,t,e[t]);if(zp)for(var t of zp(e))lk.call(e,t)&&Fp(s,t,e[t]);return s},uk=(s,e)=>ok(s,ak(e));const dk="did:pkh:",Qh=s=>s?.split(":"),pk=s=>{const e=s&&Qh(s);if(e)return s.includes(dk)?e[3]:e[1]},eh=s=>{const e=s&&Qh(s);if(e)return e[2]+":"+e[3]},Ya=s=>{const e=s&&Qh(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=Ya(r.iss);return await ek(o,n,i,eh(r.iss),t)}const Ty=(s,e)=>{const t=`${s.domain} wants you to sign in with your Ethereum account:`,i=Ya(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: ${pk(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=ka(s.resources);if(g){const w=Po(g);r=Ek(r,w)}return[t,i,"",r,"",n,o,a,c,l,u,d,p,f].filter(w=>w!=null).join(`
15
15
  `)};function gk(s){return _.Buffer.from(JSON.stringify(s)).toString("base64")}function fk(s){return JSON.parse(_.Buffer.from(s,"base64").toString("utf-8"))}function pr(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 wk(s,e,t,i={}){return t?.sort((r,n)=>r.localeCompare(n)),{att:{[s]:yk(e,t,i)}}}function yk(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 pr(s),`urn:recap:${gk(s).replace(/=/g,"")}`}function Po(s){const e=fk(s.replace("urn:recap:",""));return pr(e),e}function mk(s,e,t){const i=wk(s,e,t);return Py(i)}function bk(s){return s&&s.includes("urn:recap:")}function vk(s,e){const t=Po(s),i=Po(e),r=Ik(t,i);return Py(r)}function Ik(s,e){pr(s),pr(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]=uk(hk({},i.att[r]),{[a]:((c=s.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),i}function Ek(s="",e){pr(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=Po(s);pr(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=Po(s);pr(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 ka(s){if(!s)return;const e=s?.[s.length-1];return bk(e)?e:void 0}function rl(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 Ak(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 ji=s=>new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)),Nk=s=>new DataView(s.buffer,s.byteOffset,s.byteLength),Ck=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ck)throw new Error("Non little-endian hardware is not supported");function _k(s){if(typeof s!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(s))}function th(s){if(typeof s=="string")s=_k(s);else if(xy(s))s=sh(s);else throw new Error("Uint8Array expected, got "+typeof s);return s}function Sk(s,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(s,e)}function $k(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 Tk=(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&&!Pk(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 Pk(s){return s.byteOffset%4===0}function sh(s){return Uint8Array.from(s)}function _n(...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))),xk=My("expand 16-byte k"),Mk=My("expand 32-byte k"),Ok=ji(xk),Dk=ji(Mk);function Ne(s,e){return s<<e|s>>>32-e}function ih(s){return s.byteOffset%4===0}const Ia=64,kk=16,Oy=2**32-1,Yp=new Uint32Array;function jk(s,e,t,i,r,n,o,a){const c=r.length,l=new Uint8Array(Ia),u=ji(l),d=ih(r)&&ih(n),p=d?ji(r):Yp,f=d?ji(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(Ia,c-g);if(d&&w===Ia){const v=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let b=0,m;b<kk;b++)m=v+b,f[m]=p[m]^u[b];g+=Ia;continue}for(let v=0,b;v<w;v++)b=g+v,n[b]=r[b]^l[v];g+=w}}function Rk(s,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:r,counterRight:n,rounds:o}=Sk({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof s!="function")throw new Error("core must be a function");return rl(r),rl(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),rl(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,v;if(g===32)f.push(w=sh(a)),v=Dk;else if(g===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),v=Ok,f.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);ih(c)||f.push(c=sh(c));const b=ji(w);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(v,b,ji(c.subarray(0,16)),b),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 N=new Uint8Array(12);N.set(c,n?0:12-c.length),c=N,f.push(c)}const A=ji(c);return jk(s,v,b,A,l,u,d,o),_n(...f),u}}const $t=(s,e)=>s[e++]&255|(s[e++]&255)<<8;let Uk=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=th(e),as(e,32);const t=$t(e,0),i=$t(e,2),r=$t(e,4),n=$t(e,6),o=$t(e,8),a=$t(e,10),c=$t(e,12),l=$t(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]=$t(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],v=o[9],b=$t(e,t+0),m=$t(e,t+2),A=$t(e,t+4),N=$t(e,t+6),S=$t(e,t+8),$=$t(e,t+10),O=$t(e,t+12),D=$t(e,t+14);let T=n[0]+(b&8191),q=n[1]+((b>>>13|m<<3)&8191),j=n[2]+((m>>>10|A<<6)&8191),G=n[3]+((A>>>7|N<<9)&8191),B=n[4]+((N>>>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),C=0,z=C+T*a+q*(5*v)+j*(5*w)+G*(5*g)+B*(5*f);C=z>>>13,z&=8191,z+=W*(5*p)+V*(5*d)+H*(5*u)+K*(5*l)+Q*(5*c),C+=z>>>13,z&=8191;let ee=C+T*c+q*a+j*(5*v)+G*(5*w)+B*(5*g);C=ee>>>13,ee&=8191,ee+=W*(5*f)+V*(5*p)+H*(5*d)+K*(5*u)+Q*(5*l),C+=ee>>>13,ee&=8191;let J=C+T*l+q*c+j*a+G*(5*v)+B*(5*w);C=J>>>13,J&=8191,J+=W*(5*g)+V*(5*f)+H*(5*p)+K*(5*d)+Q*(5*u),C+=J>>>13,J&=8191;let ve=C+T*u+q*l+j*c+G*a+B*(5*v);C=ve>>>13,ve&=8191,ve+=W*(5*w)+V*(5*g)+H*(5*f)+K*(5*p)+Q*(5*d),C+=ve>>>13,ve&=8191;let pe=C+T*d+q*u+j*l+G*c+B*a;C=pe>>>13,pe&=8191,pe+=W*(5*v)+V*(5*w)+H*(5*g)+K*(5*f)+Q*(5*p),C+=pe>>>13,pe&=8191;let te=C+T*p+q*d+j*u+G*l+B*c;C=te>>>13,te&=8191,te+=W*a+V*(5*v)+H*(5*w)+K*(5*g)+Q*(5*f),C+=te>>>13,te&=8191;let it=C+T*f+q*p+j*d+G*u+B*l;C=it>>>13,it&=8191,it+=W*c+V*a+H*(5*v)+K*(5*w)+Q*(5*g),C+=it>>>13,it&=8191;let Le=C+T*g+q*f+j*p+G*d+B*u;C=Le>>>13,Le&=8191,Le+=W*l+V*c+H*a+K*(5*v)+Q*(5*w),C+=Le>>>13,Le&=8191;let Ie=C+T*w+q*g+j*f+G*p+B*d;C=Ie>>>13,Ie&=8191,Ie+=W*u+V*l+H*c+K*a+Q*(5*v),C+=Ie>>>13,Ie&=8191;let ke=C+T*v+q*w+j*g+G*f+B*p;C=ke>>>13,ke&=8191,ke+=W*d+V*u+H*l+K*c+Q*a,C+=ke>>>13,ke&=8191,C=(C<<2)+C|0,C=C+z|0,z=C&8191,C=C>>>13,ee+=C,n[0]=z,n[1]=ee,n[2]=J,n[3]=ve,n[4]=pe,n[5]=te,n[6]=it,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;_n(i)}update(e){Wp(this);const{buffer:t,blockLen:i}=this;e=th(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(){_n(this.h,this.r,this.buffer,this.pad)}digestInto(e){Wp(this),Ak(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 Lk(s){const e=(i,r)=>s(r).update(th(i)).digest(),t=s(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>s(i),e}const zk=Lk(s=>new Uk(s));function Fk(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],v=e[6],b=e[7],m=r,A=t[0],N=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=v,K=b,Q=m,C=A,z=N,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,C=Ne(C^O,16),V=V+C|0,j=Ne(j^V,12),O=O+j|0,C=Ne(C^O,8),V=V+C|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,C=Ne(C^D,16),W=W+C|0,B=Ne(B^W,12),D=D+B|0,C=Ne(C^D,8),W=W+C|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++]=v+H|0,i[J++]=b+K|0,i[J++]=m+Q|0,i[J++]=A+C|0,i[J++]=N+z|0,i[J++]=S+ee|0}const qk=Rk(Fk,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Bk=new Uint8Array(16),Qp=(s,e)=>{s.update(e);const t=e.length%16;t&&s.update(Bk.subarray(t))},Hk=new Uint8Array(32);function Jp(s,e,t,i,r){const n=s(e,t,Hk),o=zk.create(n);r&&Qp(o,r),Qp(o,i);const a=new Uint8Array(16),c=Nk(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 _n(n,a),l}const Wk=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),_n(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(!$k(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),s(e,t,n,n,1),_n(c),n}}),Dy=Tk({blockSize:64,nonceLength:12,tagLength:16},Wk(qk));let ky=class extends Yh{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Gh(e);const i=Cn(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 Nn(this),this.iHash.update(e),this}digestInto(e){Nn(this),yc(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 Jh=(s,e,t)=>new ky(s,e).update(t).digest();Jh.create=(s,e)=>new ky(s,e);function Vk(s,e,t){return Gh(s),t===void 0&&(t=new Uint8Array(s.outputLen)),Jh(s,Cn(t),Cn(e))}const nl=new Uint8Array([0]),Zp=new Uint8Array;function Kk(s,e,t,i=32){if(Gh(s),To(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=Jh.create(s,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<r;l++)nl[0]=l+1,a.update(l===0?Zp:c).update(t).update(nl).digestInto(c),n.set(c,s.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),nl.fill(0),n.slice(0,i)}const Gk=(s,e,t,i,r)=>Kk(s,Vk(s,e,t),i,r);function Yk(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 Jk(s,e,t){return s&e^s&t^e&t}class Zk extends Yh{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=il(this.buffer)}update(e){Nn(this);const{view:t,buffer:i,blockLen:r}=this;e=Cn(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=il(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){Nn(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;Yk(i,r-8,BigInt(this.length*8),n),this.process(i,0);const a=il(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 Xk=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]),Ni=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ci=new Uint32Array(64);let e3=class extends Zk{constructor(){super(64,32,8,!1),this.A=Ni[0]|0,this.B=Ni[1]|0,this.C=Ni[2]|0,this.D=Ni[3]|0,this.E=Ni[4]|0,this.F=Ni[5]|0,this.G=Ni[6]|0,this.H=Ni[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)Ci[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const p=Ci[d-15],f=Ci[d-2],g=Hs(p,7)^Hs(p,18)^p>>>3,w=Hs(f,17)^Hs(f,19)^f>>>10;Ci[d]=w+Ci[d-7]+g+Ci[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)+Xk[d]+Ci[d]|0,g=(Hs(i,2)^Hs(i,13)^Hs(i,22))+Jk(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(){Ci.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const mc=Ay(()=>new e3);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const jy=BigInt(0);function Zh(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ry(s){if(!Zh(s))throw new Error("Uint8Array expected")}const t3=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function s3(s){Ry(s);let e="";for(let t=0;t<s.length;t++)e+=t3[s[t]];return e}function i3(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?jy:BigInt("0x"+s)}const ai={_0:48,_9:57,A:65,F:70,a:97,f:102};function Xp(s){if(s>=ai._0&&s<=ai._9)return s-ai._0;if(s>=ai.A&&s<=ai.F)return s-(ai.A-10);if(s>=ai.a&&s<=ai.f)return s-(ai.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),i3(s3(Uint8Array.from(s).reverse()))}function r3(s,e){return Uy(s.toString(16).padStart(e*2,"0"))}function n3(s,e){return r3(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(Zh(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 ol=s=>typeof s=="bigint"&&jy<=s;function o3(s,e,t){return ol(s)&&ol(e)&&ol(t)&&e<=s&&s<t}function sg(s,e,t,i){if(!o3(e,t,i))throw new Error("expected valid "+s+": "+t+" <= n < "+i+", got "+e)}const a3={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"||Zh(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 c3(s,e,t={}){const i=(r,n,o)=>{const a=a3[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 pn=BigInt(0),Ea=BigInt(1);function Ly(s,e){const t=s%e;return t>=pn?t:e+t}function l3(s,e,t){if(e<pn)throw new Error("invalid exponent, negatives unsupported");if(t<=pn)throw new Error("invalid modulus");if(t===Ea)return pn;let i=Ea;for(;e>pn;)e&Ea&&(i=i*s%t),s=s*s%t,e>>=Ea;return i}function Ds(s,e,t){let i=s;for(;e-- >pn;)i*=i,i%=t;return i}BigInt(0),BigInt(1),BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Br=BigInt(0),al=BigInt(1);function h3(s){return c3(s,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...s})}function u3(s){const e=h3(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=>l3(m,t-BigInt(2),t));function l(m,A,N){const S=i(m*(A-N));return A=i(A-S),N=i(N+S),[A,N]}const u=(e.a-BigInt(2))/BigInt(4);function d(m,A){sg("u",m,Br,t),sg("scalar",A,Br,t);const N=A,S=m;let $=al,O=Br,D=m,T=al,q=Br,j;for(let B=BigInt(r-1);B>=Br;B--){const W=N>>B&al;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),C=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(C*(H+i(u*C)))}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 n3(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),N=A.length;if(N!==n&&N!==o){let S=""+n+" or "+o;throw new Error("invalid scalar, expected "+S+" bytes, got "+N)}return eg(a(A))}function w(m,A){const N=f(A),S=g(m),$=d(N,S);if($===Br)throw new Error("invalid private or public key received");return p($)}const v=p(e.Gu);function b(m){return w(m,v)}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(m,A)=>w(m,A),getPublicKey:m=>b(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:v}}const rh=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const d3=BigInt(1),ig=BigInt(2),p3=BigInt(3),g3=BigInt(5);BigInt(8);function f3(s){const e=BigInt(10),t=BigInt(20),i=BigInt(40),r=BigInt(80),n=rh,o=s*s%n*s%n,a=Ds(o,ig,n)*o%n,c=Ds(a,d3,n)*s%n,l=Ds(c,g3,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 w3(s){return s[0]&=248,s[31]&=127,s[31]|=64,s}const nh=u3({P:rh,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:s=>{const e=rh,{pow_p_5_8:t,b2:i}=f3(s);return Ly(Ds(t,p3,e)*i,e)},adjustScalarBytes:w3,randomBytes:Go}),zy="base10",qt="base16",Di="base64pad",Zn="base64url",Yo="utf8",Fy=0,wi=1,Qo=2,y3=0,rg=1,wo=12,Xh=32;function m3(){const s=nh.utils.randomPrivateKey(),e=nh.getPublicKey(s);return{privateKey:h.toString(s,qt),publicKey:h.toString(e,qt)}}function oh(){const s=Go(Xh);return h.toString(s,qt)}function b3(s,e){const t=nh.getSharedSecret(h.fromString(s,qt),h.fromString(e,qt)),i=Gk(mc,t,void 0,void 0,Xh);return h.toString(i,qt)}function ja(s){const e=mc(h.fromString(s,qt));return h.toString(e,qt)}function Ys(s){const e=mc(h.fromString(s,Yo));return h.toString(e,qt)}function qy(s){return h.fromString(`${s}`,zy)}function gr(s){return Number(h.toString(s,zy))}function v3(s){const e=qy(typeof s.type<"u"?s.type:Fy);if(gr(e)===wi&&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,qt):void 0,i=typeof s.iv<"u"?h.fromString(s.iv,qt):Go(wo),r=h.fromString(s.symKey,qt),n=Dy(r,i).encrypt(h.fromString(s.message,Yo));return By({type:e,sealed:n,iv:i,senderPublicKey:t,encoding:s.encoding})}function I3(s){const e=h.fromString(s.symKey,qt),{sealed:t,iv:i}=xo(s),r=Dy(e,i).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return h.toString(r,Yo)}function E3(s,e){const t=qy(Qo),i=Go(wo),r=h.fromString(s,Yo);return By({type:t,sealed:r,iv:i,encoding:e})}function A3(s,e){const{sealed:t}=xo({encoded:s,encoding:e});return h.toString(t,Yo)}function By(s){const{encoding:e=Di}=s;if(gr(s.type)===Qo)return h.toString(h.concat([s.type,s.sealed]),e);if(gr(s.type)===wi){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 xo(s){const{encoded:e,encoding:t=Di}=s,i=h.fromString(e,t),r=i.slice(y3,rg),n=rg;if(gr(r)===wi){const l=n+Xh,u=l+wo,d=i.slice(n,l),p=i.slice(l,u),f=i.slice(u);return{type:r,sealed:f,iv:p,senderPublicKey:d}}if(gr(r)===Qo){const l=i.slice(n),u=Go(wo);return{type:r,sealed:l,iv:u}}const o=n+wo,a=i.slice(n,o),c=i.slice(o);return{type:r,sealed:c,iv:a}}function N3(s,e){const t=xo({encoded:s,encoding:e?.encoding});return Hy({type:gr(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?h.toString(t.senderPublicKey,qt):void 0,receiverPublicKey:e?.receiverPublicKey})}function Hy(s){const e=s?.type||Fy;if(e===wi){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===wi&&typeof s.senderPublicKey=="string"&&typeof s.receiverPublicKey=="string"}function og(s){return s.type===Qo}function C3(s){return new $f.ec("p256").keyFromPublic({x:_.Buffer.from(s.x,"base64").toString("hex"),y:_.Buffer.from(s.y,"base64").toString("hex")},"hex")}function _3(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");const t=e.length%4;return t>0&&(e+="=".repeat(4-t)),e}function S3(s){return _.Buffer.from(_3(s),"base64")}function $3(s,e){const[t,i,r]=s.split("."),n=S3(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=mc(c),u=C3(e),d=h.toString(l,qt);if(!u.verify(d,{r:o,s:a}))throw new Error("Invalid signature");return h.sn(s).payload}const T3="irn";function Qa(s){return s?.relay||{protocol:T3}}function co(s){const e=h.C[s];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${s}`);return e}function P3(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:x3(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:P3(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function x3(s){return s.startsWith("//")?s.substring(2):s}function M3(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=M3(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 Aa(s,e,t){return`${s}?wc_ev=${t}&topic=${e}`}function On(s){const e=[];return s.forEach(t=>{const[i,r]=t.split(":");e.push(`${i}:${r}`)}),e}function O3(s){const e=[];return Object.values(s).forEach(t=>{e.push(...On(t.accounts))}),e}function D3(s,e){const t=[];return Object.values(s).forEach(i=>{On(i.accounts).includes(e)&&t.push(...i.methods)}),t}function k3(s,e){const t=[];return Object.values(s).forEach(i=>{On(i.accounts).includes(e)&&t.push(...i.events)}),t}function eu(s){return s.includes(":")}function lo(s){return eu(s)?s.split(":")[0]:s}function j3(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=j3(e);for(const[i,r]of Object.entries(t))r.methods?r.methods=Da(r.methods,s):r.methods=s,r.events=["chainChanged","accountsChanged"];return t}const R3={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}},U3={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}=U3[s];return{message:e?`${t} ${e}`:t,code:i}}function Ue(s,e){const{message:t,code:i}=R3[s];return{message:e?`${t} ${e}`:t,code:i}}function fr(s,e){return!!Array.isArray(s)}function Mo(s){return Object.getPrototypeOf(s)===Object.prototype&&Object.keys(s).length}function Mt(s){return typeof s>"u"}function ut(s,e){return e&&Mt(s)?!0:typeof s=="string"&&!!s.trim().length}function tu(s,e){return e&&Mt(s)?!0:typeof s=="number"&&!isNaN(s)}function L3(s,e){const{requiredNamespaces:t}=e,i=Object.keys(s.namespaces),r=Object.keys(t);let n=!0;return or(r,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=s.namespaces[o],u=On(a),d=t[o];(!or(wy(o,d),u)||!or(d.methods,c)||!or(d.events,l))&&(n=!1)}),n):!1}function Ja(s){return ut(s,!1)&&s.includes(":")?s.split(":").length===2:!1}function z3(s){if(ut(s,!1)&&s.includes(":")){const e=s.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Ja(t)}}return!1}function F3(s){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ut(s,!1)){if(e(s))return!0;const t=Iy(s);return e(t)}}catch{}return!1}function q3(s){var e;return(e=s?.proposer)==null?void 0:e.publicKey}function B3(s){return s?.topic}function H3(s,e){let t=null;return ut(s?.publicKey,!1)||(t=L("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function hg(s){let e=!0;return fr(s)?s.length&&(e=s.every(t=>ut(t,!1))):e=!1,e}function W3(s,e,t){let i=null;return fr(e)&&e.length?e.forEach(r=>{i||Ja(r)||(i=Ue("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Ja(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 V3(s,e,t){let i=null;return Object.entries(s).forEach(([r,n])=>{if(i)return;const o=W3(r,wy(r,n),`${e} ${t}`);o&&(i=o)}),i}function K3(s,e){let t=null;return fr(s)?s.forEach(i=>{t||z3(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 G3(s,e){let t=null;return Object.values(s).forEach(i=>{if(t)return;const r=K3(i?.accounts,`${e} namespace`);r&&(t=r)}),t}function Y3(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=Y3(i,`${e}, namespace`);r&&(t=r)}),t}function Q3(s,e,t){let i=null;if(s&&Mo(s)){const r=Wy(s,e);r&&(i=r);const n=V3(s,e,t);n&&(i=n)}else i=L("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function cl(s,e){let t=null;if(s&&Mo(s)){const i=Wy(s,e);i&&(t=i);const r=G3(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 ut(s.protocol,!0)}function J3(s,e){let t=!1;return s?s&&fr(s)&&s.length&&s.forEach(i=>{t=Vy(i)}):t=!0,t}function Z3(s){return typeof s=="number"}function Zt(s){return typeof s<"u"&&typeof s!==null}function X3(s){return!(!s||typeof s!="object"||!s.code||!tu(s.code,!1)||!s.message||!ut(s.message,!1))}function ej(s){return!(Mt(s)||!ut(s.method,!1))}function tj(s){return!(Mt(s)||Mt(s.result)&&Mt(s.error)||!tu(s.id,!1)||!ut(s.jsonrpc,!1))}function sj(s){return!(Mt(s)||!ut(s.name,!1))}function ug(s,e){return!(!Ja(e)||!O3(s).includes(e))}function ij(s,e,t){return ut(t,!1)?D3(s,e).includes(t):!1}function rj(s,e,t){return ut(t,!1)?k3(s,e).includes(t):!1}function dg(s,e,t){let i=null;const r=nj(s),n=oj(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,4 +894,4 @@ ${s.length}`,t=new TextEncoder().encode(e+s);return"0x"+_.Buffer.from(ZD(t)).toS
894
894
  .wui-color-fg-350 {
895
895
  background-color: var(--wui-color-fg-350);
896
896
  }
897
- `,Ta={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};function Zo(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}const Eh=Zo({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"}),Ah=Zo({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"}),nz=Zo({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"});Zo({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Zo({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 oz={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 oz[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 Eh.caipNetworkId:u.chains.push(Eh.deprecatedCaipNetworkId);break;case Ah.caipNetworkId:u.chains.push(Ah.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=se.CONNECTOR_ID.WALLET_CONNECT,this.name=Za.ConnectorNamesMap[se.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Za.ConnectorImageIds[se.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 mn.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:az})}}const az=["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 cz{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:se.CONNECTOR_ID.AUTH,type:"AUTH",name:se.CONNECTOR_NAMES.AUTH,provider:e,imageId:Za.ConnectorImageIds[se.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){ie.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 lz extends cz{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&&Wt.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(ie.state.balanceLoading&&e.chainId===I.state.activeCaipNetwork?.id)return{balance:ie.state.balance||"0.00",symbol:ie.state.balanceSymbol||""};const r=(await ie.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===se.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===se.CHAIN.EVM)try{await i.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:wn.toHex(t.id)}]})}catch(r){if(r.code===Ta.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||r.code===Ta.ERROR_INVALID_CHAIN_ID||r.code===Ta.ERROR_CODE_DEFAULT||r?.data?.originalError?.code===Ta.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await i.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:wn.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 hz{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=>{ne.setClientId(t)},this.getProvider=t=>st.getProvider(t),this.getProviderType=t=>st.getProviderId(t),this.getPreferredAccountType=()=>ie.state.preferredAccountType,this.setCaipAddress=(t,i)=>{ie.setCaipAddress(t,i)},this.setBalance=(t,i,r)=>{ie.setBalance(t,i,r)},this.setProfileName=(t,i)=>{ie.setProfileName(t,i)},this.setProfileImage=(t,i)=>{ie.setProfileImage(t,i)},this.setUser=(t,i)=>{ie.setUser(t,i),R.state.enableEmbedded&&at.close()},this.resetAccount=t=>{ie.resetAccount(t)},this.setCaipNetwork=t=>{I.setActiveCaipNetwork(t)},this.setCaipNetworkOfNamespace=(t,i)=>{I.setChainNetworkData(i,{caipNetwork:t})},this.setAllAccounts=(t,i)=>{ie.setAllAccounts(t,i),R.setHasMultipleAddresses(t?.length>1)},this.setStatus=(t,i)=>{ie.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=>ne.fetchIdentity(t),this.getReownName=t=>ey.getNamesForAddress(t),this.getConnectors=()=>le.getConnectors(),this.getConnectorImage=t=>Hh.getConnectorImage(t),this.setConnectedWalletInfo=(t,i)=>{const r=st.getProviderId(i),n=t?{...t,type:r}:void 0;ie.setConnectedWalletInfo(n,i)},this.getIsConnectedState=()=>!!I.state.activeCaipAddress,this.addAddressLabel=(t,i,r)=>{ie.addAddressLabel(t,i,r)},this.removeAddressLabel=(t,i)=>{ie.removeAddressLabel(t,i)},this.getAddress=t=>I.state.activeChain===t||!t?ie.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)=>{ie.setAddressExplorerUrl(t,i)},this.setSmartAccountDeployed=(t,i)=>{ie.setSmartAccountDeployed(t,i)},this.setSmartAccountEnabledNetworks=(t,i)=>{I.setSmartAccountEnabledNetworks(t,i)},this.setPreferredAccountType=(t,i)=>{ie.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(),fi.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&&zt.setThemeMode(e.themeMode),e.themeVariables&&zt.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){fo.open($a.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(r=>r.namespace===se.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=hn.getUnsupportedNetwork(`${t}:${e}`);I.setActiveCaipNetwork(i)}}getDefaultNetwork(){return hn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return hn.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return hn.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?hn.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(_i.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=st.getProvider(t),n=st.getProviderId(t);await i?.disconnect({provider:r,providerType:n}),X.removeConnectedNamespace(t),st.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:ie.state.address,provider:st.getProvider(I.state.activeChain)}))?.signature||"",sendTransaction:async e=>{if(e.chainNamespace===se.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=st.getProvider(I.state.activeChain);return(await t?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}))?.hash||""}return""},estimateGas:async e=>{if(e.chainNamespace===se.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=st.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:ie.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=st.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(st.getProviderId(I.state.activeChain)===_i.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=st.getProvider(t),n=st.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===_i.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}=Ei.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 lz({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=ie.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 se.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case se.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}=Ei.parseCaipAddress(a);return c===n?.toString()})||r[0];if(o){const a=Ei.validateCaipAddress(o),{chainId:c,address:l}=Ei.parseCaipAddress(a);if(st.setProviderId(t,_i.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&I.state.activeCaipNetwork&&i?.namespace!==se.CHAIN.EVM){const u=i?.getWalletConnectProvider({caipNetworks:this.caipNetworks,provider:this.universalProvider,activeCaipNetwork:I.state.activeCaipNetwork});st.setProvider(t,u)}else st.setProvider(t,this.universalProvider);le.setConnectorId(se.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}=Ei.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}){st.setProviderId(r,e),st.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===se.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(b=>Ei.parseCaipNetworkId(b)?.chainId===c.toString()),v=g.find(b=>Ei.parseCaipNetworkId(b)?.chainNamespace===o);d=this.caipNetworks?.find(b=>b.caipNetworkId===w),p=this.caipNetworks?.find(b=>b.caipNetworkId===v||"deprecatedCaipNetworkId"in b&&b.deprecatedCaipNetworkId===v)}const f=d||p;f?.chainNamespace===I.state.activeChain?R.state.enableNetworkSwitch&&!R.state.allowUnsupportedChain&&I.state.activeCaipNetwork?.name===se.UNSUPPORTED_NETWORK_NAME?I.showUnsupportedChainUI():this.setCaipNetwork(f):t||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),Em.isLowerCaseMatch(r,ie.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=st.getProviderId(e);if(i===_i.CONNECTOR_TYPE_ANNOUNCED||i===_i.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===_i.CONNECTOR_TYPE_WALLET_CONNECT){const r=st.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===se.CONNECTOR_ID.COINBASE){const r=this.getConnectors().find(n=>n.id===se.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=JL.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 nu.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(Ei.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&&(fo.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 at.open(e)}async close(){await this.injectModalUi(),at.close()}setLoading(e,t){at.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){fo.open($a.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await I.switchActiveNetwork(t)}getWalletProvider(){return I.state.activeChain?st.state.providers[I.state.activeChain]:null}getWalletProviderType(){return st.getProviderId(I.state.activeChain)}subscribeProviders(e){return st.subscribeProviders(e)}getThemeMode(){return zt.state.themeMode}getThemeVariables(){return zt.state.themeVariables}setThemeMode(e){zt.setThemeMode(e),Nm(zt.state.themeMode)}setTermsConditionsUrl(e){R.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){R.setPrivacyPolicyUrl(e)}setThemeVariables(e){zt.setThemeVariables(e),tz(zt.state.themeVariables)}subscribeTheme(e){return zt.subscribe(e)}getWalletInfo(){return ie.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 ie.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){ie.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){I.subscribeKey("activeCaipNetwork",e)}getState(){return fi.state}subscribeState(e){return fi.subscribe(e)}showErrorMessage(e){It.showError(e)}showSuccessMessage(e){It.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 at.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 ec.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 uz extends hz{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-C6VXQ7m-.js")),await Promise.resolve().then(()=>require("./w3m-modal-B0Lu-6W8.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 dz="1.7.2";function pz(s){return new uz({...s,basic:!0,sdkVersion:`html-core-${dz}`})}function gz(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 N=g-1;(m!==0||A<d)&&N!==-1;N--,A++)m+=256*w[N]>>>0,w[N]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(u);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,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 N=0;for(let S=f-1;(A!==0||N<p)&&S!==-1;S--,N++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=N,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 fz="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const El=gz(fz);class fn extends Error{constructor(){super(),Object.setPrototypeOf(this,fn.prototype)}}class sf extends Error{constructor(e){super(`WalletConnect Adapter - Method ${e} is not supported by the wallet`),this.name="WalletConnectFeatureNotSupportedError"}}function wz(s){let e=[s];return s===ft.Mainnet||s===ft.Deprecated_Mainnet?(e=[ft.Mainnet,ft.Deprecated_Mainnet],s===ft.Deprecated_Mainnet&&console.warn(tc.mainnet)):(s===ft.Deprecated_Devnet||s===ft.Devnet)&&(e=[ft.Devnet,ft.Deprecated_Devnet],console.warn(tc.devnet)),e}const tc={mainnet:`You are using a deprecated chain ID for Solana Mainnet, please use ${ft.Mainnet} instead.`,devnet:`You are using a deprecated chain ID for Solana Devnet, please use ${ft.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===ft.Mainnet)return t?.find(i=>i===ft.Mainnet)?ft.Mainnet:(console.warn(tc.wallet),ft.Deprecated_Mainnet);if(e===ft.Devnet)return t?.find(i=>i===ft.Devnet)?ft.Devnet:(console.warn(tc.wallet),ft.Deprecated_Devnet);throw Error("WalletConnect Solana Adapter: Unable to get a default chain from the session.")}function yz(s){return{optionalNamespaces:{solana:{chains:wz(s),methods:[vs.signTransaction,vs.signMessage],events:[]}}}}class ou extends Error{constructor(){super("QR Code Modal was closed by user"),Object.setPrototypeOf(this,ou.prototype),this.name="QRCodeModalError"}}class mz{_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=yz(this._network);this._modal?.open();const t=new AbortController,i=t.signal;this._modal?.subscribeState(r=>{r.open||t.abort(new ou)});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 rc;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 fn}get client(){if(this._UniversalProvider)return this._UniversalProvider;throw new fn}get session(){if(!this._session)throw new fn;return this._session}get publicKey(){if(this._UniversalProvider?.session&&this._session){const{address:e}=w0(this._session?.namespaces.solana?.accounts[0]??"");return new Ke.PublicKey(e)}throw new fn}async signTransaction(e){this.checkIfWalletSupportsMethod(vs.signTransaction);const t=pi(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,_.Buffer.from(El.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:El.encode(e)}}});return El.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)=>pi(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 RM.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=pz({projectId:this._projectId,universalProvider:this._UniversalProvider,networks:[Eh,Ah,nz],manualWCControl:!0})}}serialize(e){return _.Buffer.from(e.serialize({verifySignatures:!1})).toString("base64")}deserialize(e,t=!1){return t?Ke.VersionedTransaction.deserialize(_.Buffer.from(e,"base64")):Ke.Transaction$1.from(_.Buffer.from(e,"base64"))}checkIfWalletSupportsMethod(e){if(!this.session.namespaces.solana?.methods.includes(e))throw new sf(e)}}const bz="WalletConnect";class vz extends Sh{name=bz;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 Li;this._connecting=!0,this._wallet=new mz({network:this._config.network===Eo.Mainnet?za.Mainnet:za.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 Kb:(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 Oo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signMessage(e)}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAndSendTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAndSendTransaction(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Iz={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"},Ez=[Iz],Az=s=>Ez.find(e=>e.name.toLocaleLowerCase().includes(s.name.toLocaleLowerCase()))||s,Nz=(s,e,t)=>e[s]||t[s],nf=(s,e)=>Nz(s,Az(e),e);class hi extends ti.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 ti.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 ti.WalletState))throw new Error(`Unknown wallet state ${e}`);return ti.WalletState[e]}getFeatures(){const e=[ti.BaseFeatures.SendTransaction,ti.BaseFeatures.SignAndSendTransaction];return this.adapter.signTransaction&&this.adapter.signAllTransactions&&e.push(ti.BaseFeatures.SignTransaction),this.adapter.signMessage&&e.push(ti.BaseFeatures.SignMessage),e}supportsChain(e){return e===ti.CHAIN_ID_SOLANA}}function Cz(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 N=g-1;(m!==0||A<d)&&N!==-1;N--,A++)m+=256*w[N]>>>0,w[N]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(u);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,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 N=0;for(let S=f-1;(A!==0||N<p)&&S!==-1;S--,N++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=N,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 _z="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Sz=Cz(_z);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)},ht=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},xt,Xt,ar,cr,er,uo,sc,_e,ic,Nh,La,Ch,Io,_h,of,af,cf,lf;class $z extends uf{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,ic,"f")}get publicKey(){return Z(this,ar,"f")}get connecting(){return Z(this,cr,"f")}get supportedTransactionVersions(){return Z(this,sc,"f")}get wallet(){return Z(this,_e,"f")}get standard(){return!0}constructor({wallet:e}){super(),xt.add(this),Xt.set(this,void 0),ar.set(this,void 0),cr.set(this,void 0),er.set(this,void 0),uo.set(this,void 0),sc.set(this,void 0),_e.set(this,void 0),ic.set(this,typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.Installed),_h.set(this,t=>{if("accounts"in t){const i=Z(this,_e,"f").accounts[0];Z(this,Xt,"f")&&!Z(this,er,"f")&&i!==Z(this,Xt,"f")&&(i?Z(this,xt,"m",La).call(this,i):(this.emit("error",new hf),Z(this,xt,"m",Ch).call(this)))}"features"in t&&Z(this,xt,"m",Io).call(this)}),ht(this,_e,e,"f"),ht(this,Xt,null,"f"),ht(this,ar,null,"f"),ht(this,cr,!1,"f"),ht(this,er,!1,"f"),ht(this,uo,Z(this,_e,"f").features[oe.StandardEvents].on("change",Z(this,_h,"f")),"f"),Z(this,xt,"m",Io).call(this)}destroy(){ht(this,Xt,null,"f"),ht(this,ar,null,"f"),ht(this,cr,!1,"f"),ht(this,er,!1,"f");const e=Z(this,uo,"f");e&&(ht(this,uo,null,"f"),e())}async autoConnect(){return Z(this,xt,"m",Nh).call(this,{silent:!0})}async connect(){return Z(this,xt,"m",Nh).call(this)}async disconnect(){if(oe.StandardDisconnect in Z(this,_e,"f").features)try{ht(this,er,!0,"f"),await Z(this,_e,"f").features[oe.StandardDisconnect].disconnect()}catch(e){this.emit("error",new Oo(e?.message,e))}finally{ht(this,er,!1,"f")}Z(this,xt,"m",Ch).call(this)}async sendTransaction(e,t,i={}){try{const r=Z(this,Xt,"f");if(!r)throw new Ge;let n;if(oe.SolanaSignAndSendTransaction in Z(this,_e,"f").features)if(r.features.includes(oe.SolanaSignAndSendTransaction))n=oe.SolanaSignAndSendTransaction;else if(oe.SolanaSignTransaction in Z(this,_e,"f").features&&r.features.includes(oe.SolanaSignTransaction))n=oe.SolanaSignTransaction;else throw new Es;else if(oe.SolanaSignTransaction in Z(this,_e,"f").features){if(!r.features.includes(oe.SolanaSignTransaction))throw new Es;n=oe.SolanaSignTransaction}else throw new un;const o=lv(t.rpcEndpoint);if(!r.chains.includes(o))throw new rr;try{const{signers:a,...c}=i;let l;if(pi(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===oe.SolanaSignAndSendTransaction){const[u]=await Z(this,_e,"f").features[oe.SolanaSignAndSendTransaction].signAndSendTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:Tc(c.preflightCommitment||t.commitment),skipPreflight:c.skipPreflight,maxRetries:c.maxRetries,minContextSlot:c.minContextSlot}});return Sz.encode(u.signature)}else{const[u]=await Z(this,_e,"f").features[oe.SolanaSignTransaction].signTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:Tc(c.preflightCommitment||t.commitment),minContextSlot:c.minContextSlot}});return await t.sendRawTransaction(u.signedTransaction,{...c,preflightCommitment:Tc(c.preflightCommitment||t.commitment)})}}catch(a){throw a instanceof Ot?a:new rr(a?.message,a)}}catch(r){throw this.emit("error",r),r}}}Xt=new WeakMap,ar=new WeakMap,cr=new WeakMap,er=new WeakMap,uo=new WeakMap,sc=new WeakMap,_e=new WeakMap,ic=new WeakMap,_h=new WeakMap,xt=new WeakSet,Nh=async function(e){try{if(this.connected||this.connecting)return;if(Z(this,ic,"f")!==ge.Installed)throw new Li;if(ht(this,cr,!0,"f"),!Z(this,_e,"f").accounts.length)try{await Z(this,_e,"f").features[oe.StandardConnect].connect(e)}catch(i){throw new rc(i?.message,i)}const t=Z(this,_e,"f").accounts[0];if(!t)throw new Es;Z(this,xt,"m",La).call(this,t)}catch(t){throw this.emit("error",t),t}finally{ht(this,cr,!1,"f")}},La=function(e){let t;try{t=new Ke.PublicKey(e.address)}catch(i){throw new wr(i?.message,i)}ht(this,Xt,e,"f"),ht(this,ar,t,"f"),Z(this,xt,"m",Io).call(this),this.emit("connect",t)},Ch=function(){ht(this,Xt,null,"f"),ht(this,ar,null,"f"),Z(this,xt,"m",Io).call(this),this.emit("disconnect")},Io=function(){const e=oe.SolanaSignAndSendTransaction in Z(this,_e,"f").features?Z(this,_e,"f").features[oe.SolanaSignAndSendTransaction].supportedTransactionVersions:Z(this,_e,"f").features[oe.SolanaSignTransaction].supportedTransactionVersions;ht(this,sc,zb.arraysEqual(e,["legacy"])?null:new Set(e),"f"),oe.SolanaSignTransaction in Z(this,_e,"f").features&&Z(this,Xt,"f")?.features.includes(oe.SolanaSignTransaction)?(this.signTransaction=Z(this,xt,"m",of),this.signAllTransactions=Z(this,xt,"m",af)):(delete this.signTransaction,delete this.signAllTransactions),oe.SolanaSignMessage in Z(this,_e,"f").features&&Z(this,Xt,"f")?.features.includes(oe.SolanaSignMessage)?this.signMessage=Z(this,xt,"m",cf):delete this.signMessage,oe.SolanaSignIn in Z(this,_e,"f").features?this.signIn=Z(this,xt,"m",lf):delete this.signIn},of=async function(e){try{const t=Z(this,Xt,"f");if(!t)throw new Ge;if(!(oe.SolanaSignTransaction in Z(this,_e,"f").features))throw new un;if(!t.features.includes(oe.SolanaSignTransaction))throw new Es;try{const r=(await Z(this,_e,"f").features[oe.SolanaSignTransaction].signTransaction({account:t,transaction:pi(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return pi(e)?Ke.VersionedTransaction.deserialize(r):Ke.Transaction$1.from(r)}catch(i){throw i instanceof Ot?i:new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}},af=async function(e){try{const t=Z(this,Xt,"f");if(!t)throw new Ge;if(!(oe.SolanaSignTransaction in Z(this,_e,"f").features))throw new un;if(!t.features.includes(oe.SolanaSignTransaction))throw new Es;try{const i=await Z(this,_e,"f").features[oe.SolanaSignTransaction].signTransaction(...e.map(r=>({account:t,transaction:pi(r)?r.serialize():new Uint8Array(r.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((r,n)=>{const o=i[n].signedTransaction;return pi(r)?Ke.VersionedTransaction.deserialize(o):Ke.Transaction$1.from(o)})}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}},cf=async function(e){try{const t=Z(this,Xt,"f");if(!t)throw new Ge;if(!(oe.SolanaSignMessage in Z(this,_e,"f").features))throw new un;if(!t.features.includes(oe.SolanaSignMessage))throw new Es;try{return(await Z(this,_e,"f").features[oe.SolanaSignMessage].signMessage({account:t,message:e}))[0].signature}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}},lf=async function(e={}){try{if(!(oe.SolanaSignIn in Z(this,_e,"f").features))throw new un;let t;try{[t]=await Z(this,_e,"f").features[oe.SolanaSignIn].signIn(e)}catch(i){throw new _u(i?.message,i)}if(!t)throw new _u;return Z(this,xt,"m",La).call(this,t.account),t}catch(t){throw this.emit("error",t),t}};function Sm(s){return Fb.getWallets().get().filter(Gb).map(e=>new hi(new $z({wallet:e}),s))}const Tz=3e3,$m=s=>s.getName().toLowerCase().replaceAll("wallet","").trim();function Pz(s){if(s==="Solana")return Tm();if(s==="Fogo")return Pm();throw new Error(`Unsupported chain: ${s}`)}function Tm(){const s=di.config.isMainnet?Eo.Mainnet:Eo.Devnet,e=new Ke.Connection(di.config.rpcs.Solana||Ke.clusterApiUrl(s)),t=Sm(e).reduce((r,n)=>(r[$m(n)]=n,r),{});let i={};return di.config.ui.walletConnectProjectId&&(i={walletConnect:new hi(new vz({network:s,options:{projectId:di.config.ui.walletConnectProjectId,customStoragePrefix:"wh-connect-solana-adapter"}}),e)}),{...t,bitget:new hi(new Qb,e),clover:new hi(new Zb,e),coin98:new hi(new sv,e),solong:new hi(new nv,e),torus:new hi(new av,e),nightly:new hi(new df,e),...i}}function Pm(){if(!di.config.rpcs.Fogo)throw new Error("Fogo RPC not found");const s=new Ke.Connection(di.config.rpcs.Fogo),e=Sm(s).reduce((t,i)=>($m(i).toLowerCase()==="leap"&&(t.leap=i),t),{});return{nightly:new hi(new df,s),...e}}async function xz(s,e,t){if(!e)throw new Error("Wallet not found");const i=di.config.rpcs[s.chain];if(!i)throw new Error(`${s.chain} RPC not found`);let r=t?.commitment??"confirmed";const n=new Ke.Connection(i);(s.description==="Core.VerifySignature"||s.description==="Core.PostVAA")&&(r="finalized");const{blockhash:o,lastValidBlockHeight:a}=await n.getLatestBlockhash(r),{serializedTransaction:c,sendOptions:l}=await Dz(s,e,n,o,a,r);return await Mz(n,{serializedTransaction:c,sendOptions:l},o,a,r)}async function Mz(s,e,t,i,r){let n=null;const o=await s.sendRawTransaction(e.serializedTransaction,e.sendOptions),a=s.confirmTransaction({signature:o,blockhash:t,lastValidBlockHeight:i},r);try{for(;!n&&(n=await Promise.race([a,new Promise(c=>setTimeout(()=>c(null),Tz))]),!n);)await s.sendRawTransaction(e.serializedTransaction,e.sendOptions)}catch(c){if(c instanceof Error&&c.name==="TransactionExpiredBlockheightExceededError")return await Oz(s,o),o;throw c}if(n?.value.err){const c=kz(n.value.err);throw new Error(`Transaction failed: ${c}`)}return o}async function Oz(s,e,{retries:t=5,delay:i=2e3}={}){Wb(async()=>{await s.getTransaction(e,{commitment:"confirmed",maxSupportedTransactionVersion:0})},{retries:t,delay:i})}async function Dz(s,e,t,i,r,n){const o=await oe.setPriorityFeeInstructions(t,i,r,s);return{serializedTransaction:(await e.signTransaction(o)).serialize(),sendOptions:{skipPreflight:!0,maxRetries:0,preFlightCommitment:n}}}function kz(s){if(!s)return"Unknown error";if(typeof s=="object")try{return di.stringifyWithBigInt(s)}catch{return"Unstringifiable error object"}return String(s)}const jz=Object.freeze(Object.defineProperty({__proto__:null,fetchFogoOptions:Pm,fetchOptions:Pz,fetchSolanaOptions:Tm,signAndSendTransactionWithResends:xz},Symbol.toStringTag,{value:"Module"}));exports.AccountController=ie;exports.AlertController=fo;exports.ApiController=ue;exports.AssetController=Is;exports.AssetUtil=Hh;exports.ChainController=I;exports.ConnectionController=qe;exports.ConnectorController=le;exports.ConnectorUtil=bo;exports.ConstantsUtil=se;exports.ConstantsUtil$1=Wt;exports.ConstantsUtil$2=Am;exports.CoreHelperUtil=he;exports.EventsController=Be;exports.Hash=If;exports.Hash$1=ly;exports.ModalController=at;exports.OptionsController=R;exports.RouterController=Me;exports.SIWXUtil=mn;exports.SnackController=It;exports.StorageUtil=X;exports.ThemeController=zt;exports.WalletUtil=ec;exports.abytes=Ro;exports.abytes$1=Wo;exports.aexists=_l;exports.aexists$1=Jl;exports.ahash=zv;exports.ahash$1=jO;exports.aoutput=vf;exports.aoutput$1=cy;exports.colorStyles=rz;exports.concatBytes=Zv;exports.concatBytes$1=GO;exports.createView=Gv;exports.createView$1=HO;exports.elementStyles=iz;exports.initializeTheming=ez;exports.randomBytes=Xv;exports.randomBytes$1=YO;exports.resetStyles=sz;exports.rotr=Yv;exports.rotr$1=WO;exports.solana=jz;exports.toBytes=$h;exports.toBytes$1=Wh;exports.wrapConstructor=Ef;exports.wrapConstructor$1=hy;
897
+ `,Ta={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};function Zo(s){return{formatters:void 0,fees:void 0,serializers:void 0,...s}}const Eh=Zo({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"}),Ah=Zo({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"}),nz=Zo({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"});Zo({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Zo({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 oz={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 oz[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 Eh.caipNetworkId:u.chains.push(Eh.deprecatedCaipNetworkId);break;case Ah.caipNetworkId:u.chains.push(Ah.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=se.CONNECTOR_ID.WALLET_CONNECT,this.name=Za.ConnectorNamesMap[se.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Za.ConnectorImageIds[se.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 mn.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:az})}}const az=["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 cz{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:se.CONNECTOR_ID.AUTH,type:"AUTH",name:se.CONNECTOR_NAMES.AUTH,provider:e,imageId:Za.ConnectorImageIds[se.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){ie.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 lz extends cz{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&&Wt.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(ie.state.balanceLoading&&e.chainId===I.state.activeCaipNetwork?.id)return{balance:ie.state.balance||"0.00",symbol:ie.state.balanceSymbol||""};const r=(await ie.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===se.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===se.CHAIN.EVM)try{await i.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:wn.toHex(t.id)}]})}catch(r){if(r.code===Ta.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||r.code===Ta.ERROR_INVALID_CHAIN_ID||r.code===Ta.ERROR_CODE_DEFAULT||r?.data?.originalError?.code===Ta.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await i.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:wn.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 hz{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=>{ne.setClientId(t)},this.getProvider=t=>st.getProvider(t),this.getProviderType=t=>st.getProviderId(t),this.getPreferredAccountType=()=>ie.state.preferredAccountType,this.setCaipAddress=(t,i)=>{ie.setCaipAddress(t,i)},this.setBalance=(t,i,r)=>{ie.setBalance(t,i,r)},this.setProfileName=(t,i)=>{ie.setProfileName(t,i)},this.setProfileImage=(t,i)=>{ie.setProfileImage(t,i)},this.setUser=(t,i)=>{ie.setUser(t,i),R.state.enableEmbedded&&at.close()},this.resetAccount=t=>{ie.resetAccount(t)},this.setCaipNetwork=t=>{I.setActiveCaipNetwork(t)},this.setCaipNetworkOfNamespace=(t,i)=>{I.setChainNetworkData(i,{caipNetwork:t})},this.setAllAccounts=(t,i)=>{ie.setAllAccounts(t,i),R.setHasMultipleAddresses(t?.length>1)},this.setStatus=(t,i)=>{ie.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=>ne.fetchIdentity(t),this.getReownName=t=>ey.getNamesForAddress(t),this.getConnectors=()=>le.getConnectors(),this.getConnectorImage=t=>Hh.getConnectorImage(t),this.setConnectedWalletInfo=(t,i)=>{const r=st.getProviderId(i),n=t?{...t,type:r}:void 0;ie.setConnectedWalletInfo(n,i)},this.getIsConnectedState=()=>!!I.state.activeCaipAddress,this.addAddressLabel=(t,i,r)=>{ie.addAddressLabel(t,i,r)},this.removeAddressLabel=(t,i)=>{ie.removeAddressLabel(t,i)},this.getAddress=t=>I.state.activeChain===t||!t?ie.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)=>{ie.setAddressExplorerUrl(t,i)},this.setSmartAccountDeployed=(t,i)=>{ie.setSmartAccountDeployed(t,i)},this.setSmartAccountEnabledNetworks=(t,i)=>{I.setSmartAccountEnabledNetworks(t,i)},this.setPreferredAccountType=(t,i)=>{ie.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(),fi.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&&zt.setThemeMode(e.themeMode),e.themeVariables&&zt.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){fo.open($a.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(r=>r.namespace===se.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=hn.getUnsupportedNetwork(`${t}:${e}`);I.setActiveCaipNetwork(i)}}getDefaultNetwork(){return hn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,t){return hn.extendCaipNetwork(e,{customNetworkImageUrls:t.chainImages,projectId:t.projectId})}extendCaipNetworks(e){return hn.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?hn.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(_i.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=st.getProvider(t),n=st.getProviderId(t);await i?.disconnect({provider:r,providerType:n}),X.removeConnectedNamespace(t),st.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:ie.state.address,provider:st.getProvider(I.state.activeChain)}))?.signature||"",sendTransaction:async e=>{if(e.chainNamespace===se.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=st.getProvider(I.state.activeChain);return(await t?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}))?.hash||""}return""},estimateGas:async e=>{if(e.chainNamespace===se.CHAIN.EVM){const t=this.getAdapter(I.state.activeChain),i=st.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:ie.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=st.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(st.getProviderId(I.state.activeChain)===_i.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=st.getProvider(t),n=st.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===_i.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}=Ei.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 lz({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=ie.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 se.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case se.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}=Ei.parseCaipAddress(a);return c===n?.toString()})||r[0];if(o){const a=Ei.validateCaipAddress(o),{chainId:c,address:l}=Ei.parseCaipAddress(a);if(st.setProviderId(t,_i.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&I.state.activeCaipNetwork&&i?.namespace!==se.CHAIN.EVM){const u=i?.getWalletConnectProvider({caipNetworks:this.caipNetworks,provider:this.universalProvider,activeCaipNetwork:I.state.activeCaipNetwork});st.setProvider(t,u)}else st.setProvider(t,this.universalProvider);le.setConnectorId(se.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}=Ei.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}){st.setProviderId(r,e),st.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===se.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(b=>Ei.parseCaipNetworkId(b)?.chainId===c.toString()),v=g.find(b=>Ei.parseCaipNetworkId(b)?.chainNamespace===o);d=this.caipNetworks?.find(b=>b.caipNetworkId===w),p=this.caipNetworks?.find(b=>b.caipNetworkId===v||"deprecatedCaipNetworkId"in b&&b.deprecatedCaipNetworkId===v)}const f=d||p;f?.chainNamespace===I.state.activeChain?R.state.enableNetworkSwitch&&!R.state.allowUnsupportedChain&&I.state.activeCaipNetwork?.name===se.UNSUPPORTED_NETWORK_NAME?I.showUnsupportedChainUI():this.setCaipNetwork(f):t||i&&this.setCaipNetworkOfNamespace(i,o),this.syncConnectedWalletInfo(o),Em.isLowerCaseMatch(r,ie.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=st.getProviderId(e);if(i===_i.CONNECTOR_TYPE_ANNOUNCED||i===_i.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===_i.CONNECTOR_TYPE_WALLET_CONNECT){const r=st.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===se.CONNECTOR_ID.COINBASE){const r=this.getConnectors().find(n=>n.id===se.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=JL.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 nu.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(Ei.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&&(fo.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 at.open(e)}async close(){await this.injectModalUi(),at.close()}setLoading(e,t){at.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){fo.open($a.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await I.switchActiveNetwork(t)}getWalletProvider(){return I.state.activeChain?st.state.providers[I.state.activeChain]:null}getWalletProviderType(){return st.getProviderId(I.state.activeChain)}subscribeProviders(e){return st.subscribeProviders(e)}getThemeMode(){return zt.state.themeMode}getThemeVariables(){return zt.state.themeVariables}setThemeMode(e){zt.setThemeMode(e),Nm(zt.state.themeMode)}setTermsConditionsUrl(e){R.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){R.setPrivacyPolicyUrl(e)}setThemeVariables(e){zt.setThemeVariables(e),tz(zt.state.themeVariables)}subscribeTheme(e){return zt.subscribe(e)}getWalletInfo(){return ie.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 ie.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){ie.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){I.subscribeKey("activeCaipNetwork",e)}getState(){return fi.state}subscribeState(e){return fi.subscribe(e)}showErrorMessage(e){It.showError(e)}showSuccessMessage(e){It.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 at.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 ec.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 uz extends hz{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-BrW22Cj9.js")),await Promise.resolve().then(()=>require("./w3m-modal-Duc13ei7.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 dz="1.7.2";function pz(s){return new uz({...s,basic:!0,sdkVersion:`html-core-${dz}`})}function gz(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 N=g-1;(m!==0||A<d)&&N!==-1;N--,A++)m+=256*w[N]>>>0,w[N]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(u);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,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 N=0;for(let S=f-1;(A!==0||N<p)&&S!==-1;S--,N++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=N,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 fz="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const El=gz(fz);class fn extends Error{constructor(){super(),Object.setPrototypeOf(this,fn.prototype)}}class sf extends Error{constructor(e){super(`WalletConnect Adapter - Method ${e} is not supported by the wallet`),this.name="WalletConnectFeatureNotSupportedError"}}function wz(s){let e=[s];return s===ft.Mainnet||s===ft.Deprecated_Mainnet?(e=[ft.Mainnet,ft.Deprecated_Mainnet],s===ft.Deprecated_Mainnet&&console.warn(tc.mainnet)):(s===ft.Deprecated_Devnet||s===ft.Devnet)&&(e=[ft.Devnet,ft.Deprecated_Devnet],console.warn(tc.devnet)),e}const tc={mainnet:`You are using a deprecated chain ID for Solana Mainnet, please use ${ft.Mainnet} instead.`,devnet:`You are using a deprecated chain ID for Solana Devnet, please use ${ft.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===ft.Mainnet)return t?.find(i=>i===ft.Mainnet)?ft.Mainnet:(console.warn(tc.wallet),ft.Deprecated_Mainnet);if(e===ft.Devnet)return t?.find(i=>i===ft.Devnet)?ft.Devnet:(console.warn(tc.wallet),ft.Deprecated_Devnet);throw Error("WalletConnect Solana Adapter: Unable to get a default chain from the session.")}function yz(s){return{optionalNamespaces:{solana:{chains:wz(s),methods:[vs.signTransaction,vs.signMessage],events:[]}}}}class ou extends Error{constructor(){super("QR Code Modal was closed by user"),Object.setPrototypeOf(this,ou.prototype),this.name="QRCodeModalError"}}class mz{_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=yz(this._network);this._modal?.open();const t=new AbortController,i=t.signal;this._modal?.subscribeState(r=>{r.open||t.abort(new ou)});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 rc;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 fn}get client(){if(this._UniversalProvider)return this._UniversalProvider;throw new fn}get session(){if(!this._session)throw new fn;return this._session}get publicKey(){if(this._UniversalProvider?.session&&this._session){const{address:e}=w0(this._session?.namespaces.solana?.accounts[0]??"");return new Ke.PublicKey(e)}throw new fn}async signTransaction(e){this.checkIfWalletSupportsMethod(vs.signTransaction);const t=pi(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,_.Buffer.from(El.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:El.encode(e)}}});return El.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)=>pi(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 RM.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=pz({projectId:this._projectId,universalProvider:this._UniversalProvider,networks:[Eh,Ah,nz],manualWCControl:!0})}}serialize(e){return _.Buffer.from(e.serialize({verifySignatures:!1})).toString("base64")}deserialize(e,t=!1){return t?Ke.VersionedTransaction.deserialize(_.Buffer.from(e,"base64")):Ke.Transaction$1.from(_.Buffer.from(e,"base64"))}checkIfWalletSupportsMethod(e){if(!this.session.namespaces.solana?.methods.includes(e))throw new sf(e)}}const bz="WalletConnect";class vz extends Sh{name=bz;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 Li;this._connecting=!0,this._wallet=new mz({network:this._config.network===Eo.Mainnet?za.Mainnet:za.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 Kb:(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 Oo(t?.message,t))}}this.emit("disconnect")}async signTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signTransaction(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signMessage(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signMessage(e)}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAndSendTransaction(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAndSendTransaction(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}async signAllTransactions(e){try{const t=this._wallet;if(!t)throw new Ge;try{return await t.signAllTransactions(e)}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}}}const Iz={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"},Ez=[Iz],Az=s=>Ez.find(e=>e.name.toLocaleLowerCase().includes(s.name.toLocaleLowerCase()))||s,Nz=(s,e,t)=>e[s]||t[s],nf=(s,e)=>Nz(s,Az(e),e);class hi extends ti.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 ti.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 ti.WalletState))throw new Error(`Unknown wallet state ${e}`);return ti.WalletState[e]}getFeatures(){const e=[ti.BaseFeatures.SendTransaction,ti.BaseFeatures.SignAndSendTransaction];return this.adapter.signTransaction&&this.adapter.signAllTransactions&&e.push(ti.BaseFeatures.SignTransaction),this.adapter.signMessage&&e.push(ti.BaseFeatures.SignMessage),e}supportsChain(e){return e===ti.CHAIN_ID_SOLANA}}function Cz(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 N=g-1;(m!==0||A<d)&&N!==-1;N--,A++)m+=256*w[N]>>>0,w[N]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,p++}let v=g-d;for(;v!==g&&w[v]===0;)v++;let b=i.repeat(u);for(;v<g;++v)b+=s.charAt(w[v]);return b}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,d=0,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 N=0;for(let S=f-1;(A!==0||N<p)&&S!==-1;S--,N++)A+=t*g[S]>>>0,g[S]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=N,u++}let w=f-p;for(;w!==f&&g[w]===0;)w++;const v=new Uint8Array(d+(f-w));let b=d;for(;w!==f;)v[b++]=g[w++];return v}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 _z="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Sz=Cz(_z);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)},ht=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},xt,Xt,ar,cr,er,uo,sc,_e,ic,Nh,La,Ch,Io,_h,of,af,cf,lf;class $z extends uf{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,ic,"f")}get publicKey(){return Z(this,ar,"f")}get connecting(){return Z(this,cr,"f")}get supportedTransactionVersions(){return Z(this,sc,"f")}get wallet(){return Z(this,_e,"f")}get standard(){return!0}constructor({wallet:e}){super(),xt.add(this),Xt.set(this,void 0),ar.set(this,void 0),cr.set(this,void 0),er.set(this,void 0),uo.set(this,void 0),sc.set(this,void 0),_e.set(this,void 0),ic.set(this,typeof window>"u"||typeof document>"u"?ge.Unsupported:ge.Installed),_h.set(this,t=>{if("accounts"in t){const i=Z(this,_e,"f").accounts[0];Z(this,Xt,"f")&&!Z(this,er,"f")&&i!==Z(this,Xt,"f")&&(i?Z(this,xt,"m",La).call(this,i):(this.emit("error",new hf),Z(this,xt,"m",Ch).call(this)))}"features"in t&&Z(this,xt,"m",Io).call(this)}),ht(this,_e,e,"f"),ht(this,Xt,null,"f"),ht(this,ar,null,"f"),ht(this,cr,!1,"f"),ht(this,er,!1,"f"),ht(this,uo,Z(this,_e,"f").features[oe.StandardEvents].on("change",Z(this,_h,"f")),"f"),Z(this,xt,"m",Io).call(this)}destroy(){ht(this,Xt,null,"f"),ht(this,ar,null,"f"),ht(this,cr,!1,"f"),ht(this,er,!1,"f");const e=Z(this,uo,"f");e&&(ht(this,uo,null,"f"),e())}async autoConnect(){return Z(this,xt,"m",Nh).call(this,{silent:!0})}async connect(){return Z(this,xt,"m",Nh).call(this)}async disconnect(){if(oe.StandardDisconnect in Z(this,_e,"f").features)try{ht(this,er,!0,"f"),await Z(this,_e,"f").features[oe.StandardDisconnect].disconnect()}catch(e){this.emit("error",new Oo(e?.message,e))}finally{ht(this,er,!1,"f")}Z(this,xt,"m",Ch).call(this)}async sendTransaction(e,t,i={}){try{const r=Z(this,Xt,"f");if(!r)throw new Ge;let n;if(oe.SolanaSignAndSendTransaction in Z(this,_e,"f").features)if(r.features.includes(oe.SolanaSignAndSendTransaction))n=oe.SolanaSignAndSendTransaction;else if(oe.SolanaSignTransaction in Z(this,_e,"f").features&&r.features.includes(oe.SolanaSignTransaction))n=oe.SolanaSignTransaction;else throw new Es;else if(oe.SolanaSignTransaction in Z(this,_e,"f").features){if(!r.features.includes(oe.SolanaSignTransaction))throw new Es;n=oe.SolanaSignTransaction}else throw new un;const o=lv(t.rpcEndpoint);if(!r.chains.includes(o))throw new rr;try{const{signers:a,...c}=i;let l;if(pi(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===oe.SolanaSignAndSendTransaction){const[u]=await Z(this,_e,"f").features[oe.SolanaSignAndSendTransaction].signAndSendTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:Tc(c.preflightCommitment||t.commitment),skipPreflight:c.skipPreflight,maxRetries:c.maxRetries,minContextSlot:c.minContextSlot}});return Sz.encode(u.signature)}else{const[u]=await Z(this,_e,"f").features[oe.SolanaSignTransaction].signTransaction({account:r,chain:o,transaction:l,options:{preflightCommitment:Tc(c.preflightCommitment||t.commitment),minContextSlot:c.minContextSlot}});return await t.sendRawTransaction(u.signedTransaction,{...c,preflightCommitment:Tc(c.preflightCommitment||t.commitment)})}}catch(a){throw a instanceof Ot?a:new rr(a?.message,a)}}catch(r){throw this.emit("error",r),r}}}Xt=new WeakMap,ar=new WeakMap,cr=new WeakMap,er=new WeakMap,uo=new WeakMap,sc=new WeakMap,_e=new WeakMap,ic=new WeakMap,_h=new WeakMap,xt=new WeakSet,Nh=async function(e){try{if(this.connected||this.connecting)return;if(Z(this,ic,"f")!==ge.Installed)throw new Li;if(ht(this,cr,!0,"f"),!Z(this,_e,"f").accounts.length)try{await Z(this,_e,"f").features[oe.StandardConnect].connect(e)}catch(i){throw new rc(i?.message,i)}const t=Z(this,_e,"f").accounts[0];if(!t)throw new Es;Z(this,xt,"m",La).call(this,t)}catch(t){throw this.emit("error",t),t}finally{ht(this,cr,!1,"f")}},La=function(e){let t;try{t=new Ke.PublicKey(e.address)}catch(i){throw new wr(i?.message,i)}ht(this,Xt,e,"f"),ht(this,ar,t,"f"),Z(this,xt,"m",Io).call(this),this.emit("connect",t)},Ch=function(){ht(this,Xt,null,"f"),ht(this,ar,null,"f"),Z(this,xt,"m",Io).call(this),this.emit("disconnect")},Io=function(){const e=oe.SolanaSignAndSendTransaction in Z(this,_e,"f").features?Z(this,_e,"f").features[oe.SolanaSignAndSendTransaction].supportedTransactionVersions:Z(this,_e,"f").features[oe.SolanaSignTransaction].supportedTransactionVersions;ht(this,sc,zb.arraysEqual(e,["legacy"])?null:new Set(e),"f"),oe.SolanaSignTransaction in Z(this,_e,"f").features&&Z(this,Xt,"f")?.features.includes(oe.SolanaSignTransaction)?(this.signTransaction=Z(this,xt,"m",of),this.signAllTransactions=Z(this,xt,"m",af)):(delete this.signTransaction,delete this.signAllTransactions),oe.SolanaSignMessage in Z(this,_e,"f").features&&Z(this,Xt,"f")?.features.includes(oe.SolanaSignMessage)?this.signMessage=Z(this,xt,"m",cf):delete this.signMessage,oe.SolanaSignIn in Z(this,_e,"f").features?this.signIn=Z(this,xt,"m",lf):delete this.signIn},of=async function(e){try{const t=Z(this,Xt,"f");if(!t)throw new Ge;if(!(oe.SolanaSignTransaction in Z(this,_e,"f").features))throw new un;if(!t.features.includes(oe.SolanaSignTransaction))throw new Es;try{const r=(await Z(this,_e,"f").features[oe.SolanaSignTransaction].signTransaction({account:t,transaction:pi(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return pi(e)?Ke.VersionedTransaction.deserialize(r):Ke.Transaction$1.from(r)}catch(i){throw i instanceof Ot?i:new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}},af=async function(e){try{const t=Z(this,Xt,"f");if(!t)throw new Ge;if(!(oe.SolanaSignTransaction in Z(this,_e,"f").features))throw new un;if(!t.features.includes(oe.SolanaSignTransaction))throw new Es;try{const i=await Z(this,_e,"f").features[oe.SolanaSignTransaction].signTransaction(...e.map(r=>({account:t,transaction:pi(r)?r.serialize():new Uint8Array(r.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((r,n)=>{const o=i[n].signedTransaction;return pi(r)?Ke.VersionedTransaction.deserialize(o):Ke.Transaction$1.from(o)})}catch(i){throw new nt(i?.message,i)}}catch(t){throw this.emit("error",t),t}},cf=async function(e){try{const t=Z(this,Xt,"f");if(!t)throw new Ge;if(!(oe.SolanaSignMessage in Z(this,_e,"f").features))throw new un;if(!t.features.includes(oe.SolanaSignMessage))throw new Es;try{return(await Z(this,_e,"f").features[oe.SolanaSignMessage].signMessage({account:t,message:e}))[0].signature}catch(i){throw new Do(i?.message,i)}}catch(t){throw this.emit("error",t),t}},lf=async function(e={}){try{if(!(oe.SolanaSignIn in Z(this,_e,"f").features))throw new un;let t;try{[t]=await Z(this,_e,"f").features[oe.SolanaSignIn].signIn(e)}catch(i){throw new _u(i?.message,i)}if(!t)throw new _u;return Z(this,xt,"m",La).call(this,t.account),t}catch(t){throw this.emit("error",t),t}};function Sm(s){return Fb.getWallets().get().filter(Gb).map(e=>new hi(new $z({wallet:e}),s))}const Tz=3e3,$m=s=>s.getName().toLowerCase().replaceAll("wallet","").trim();function Pz(s){if(s==="Solana")return Tm();if(s==="Fogo")return Pm();throw new Error(`Unsupported chain: ${s}`)}function Tm(){const s=di.config.isMainnet?Eo.Mainnet:Eo.Devnet,e=new Ke.Connection(di.config.rpcs.Solana||Ke.clusterApiUrl(s)),t=Sm(e).reduce((r,n)=>(r[$m(n)]=n,r),{});let i={};return di.config.ui.walletConnectProjectId&&(i={walletConnect:new hi(new vz({network:s,options:{projectId:di.config.ui.walletConnectProjectId,customStoragePrefix:"wh-connect-solana-adapter"}}),e)}),{...t,bitget:new hi(new Qb,e),clover:new hi(new Zb,e),coin98:new hi(new sv,e),solong:new hi(new nv,e),torus:new hi(new av,e),nightly:new hi(new df,e),...i}}function Pm(){if(!di.config.rpcs.Fogo)throw new Error("Fogo RPC not found");const s=new Ke.Connection(di.config.rpcs.Fogo),e=Sm(s).reduce((t,i)=>($m(i).toLowerCase()==="leap"&&(t.leap=i),t),{});return{nightly:new hi(new df,s),...e}}async function xz(s,e,t){if(!e)throw new Error("Wallet not found");const i=di.config.rpcs[s.chain];if(!i)throw new Error(`${s.chain} RPC not found`);let r=t?.commitment??"confirmed";const n=new Ke.Connection(i);(s.description==="Core.VerifySignature"||s.description==="Core.PostVAA")&&(r="finalized");const{blockhash:o,lastValidBlockHeight:a}=await n.getLatestBlockhash(r),{serializedTransaction:c,sendOptions:l}=await Dz(s,e,n,o,a,r);return await Mz(n,{serializedTransaction:c,sendOptions:l},o,a,r)}async function Mz(s,e,t,i,r){let n=null;const o=await s.sendRawTransaction(e.serializedTransaction,e.sendOptions),a=s.confirmTransaction({signature:o,blockhash:t,lastValidBlockHeight:i},r);try{for(;!n&&(n=await Promise.race([a,new Promise(c=>setTimeout(()=>c(null),Tz))]),!n);)await s.sendRawTransaction(e.serializedTransaction,e.sendOptions)}catch(c){if(c instanceof Error&&c.name==="TransactionExpiredBlockheightExceededError")return await Oz(s,o),o;throw c}if(n?.value.err){const c=kz(n.value.err);throw new Error(`Transaction failed: ${c}`)}return o}async function Oz(s,e,{retries:t=5,delay:i=2e3}={}){Wb(async()=>{await s.getTransaction(e,{commitment:"confirmed",maxSupportedTransactionVersion:0})},{retries:t,delay:i})}async function Dz(s,e,t,i,r,n){const o=await oe.setPriorityFeeInstructions(t,i,r,s);return{serializedTransaction:(await e.signTransaction(o)).serialize(),sendOptions:{skipPreflight:!0,maxRetries:0,preFlightCommitment:n}}}function kz(s){if(!s)return"Unknown error";if(typeof s=="object")try{return di.stringifyWithBigInt(s)}catch{return"Unstringifiable error object"}return String(s)}const jz=Object.freeze(Object.defineProperty({__proto__:null,fetchFogoOptions:Pm,fetchOptions:Pz,fetchSolanaOptions:Tm,signAndSendTransactionWithResends:xz},Symbol.toStringTag,{value:"Module"}));exports.AccountController=ie;exports.AlertController=fo;exports.ApiController=ue;exports.AssetController=Is;exports.AssetUtil=Hh;exports.ChainController=I;exports.ConnectionController=qe;exports.ConnectorController=le;exports.ConnectorUtil=bo;exports.ConstantsUtil=se;exports.ConstantsUtil$1=Wt;exports.ConstantsUtil$2=Am;exports.CoreHelperUtil=he;exports.EventsController=Be;exports.Hash=If;exports.Hash$1=ly;exports.ModalController=at;exports.OptionsController=R;exports.RouterController=Me;exports.SIWXUtil=mn;exports.SnackController=It;exports.StorageUtil=X;exports.ThemeController=zt;exports.WalletUtil=ec;exports.abytes=Ro;exports.abytes$1=Wo;exports.aexists=_l;exports.aexists$1=Jl;exports.ahash=zv;exports.ahash$1=jO;exports.aoutput=vf;exports.aoutput$1=cy;exports.colorStyles=rz;exports.concatBytes=Zv;exports.concatBytes$1=GO;exports.createView=Gv;exports.createView$1=HO;exports.elementStyles=iz;exports.initializeTheming=ez;exports.randomBytes=Xv;exports.randomBytes$1=YO;exports.resetStyles=sz;exports.rotr=Yv;exports.rotr$1=WO;exports.solana=jz;exports.toBytes=$h;exports.toBytes$1=Wh;exports.wrapConstructor=Ef;exports.wrapConstructor$1=hy;