@dcl/explorer-website 2.6.1-25865517797.commit-b7a7cba → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/{ConstantsUtil-ByjAYmvC.js → ConstantsUtil-BYRHWuZV.js} +1 -1
- package/assets/{ExchangeController-Bp8ztJrX.js → ExchangeController-N42lbf3C.js} +1 -1
- package/assets/{HelpersUtil-Dp4e1zvd.js → HelpersUtil-DFmhrbIH.js} +1 -1
- package/assets/{NetworkUtil-DqGcuBfF.js → NetworkUtil-DM5H1DOt.js} +1 -1
- package/assets/{SwapController-DUCq2f7d.js → SwapController-SgAc8zJM.js} +1 -1
- package/assets/{W3MFrameProviderSingleton-9eitOT0j.js → W3MFrameProviderSingleton-dGwr0u32.js} +3 -3
- package/assets/{basic-C7tUDecp.js → basic-CDUVa7W3.js} +1 -1
- package/assets/{biconomy-plHCR2Qq.js → biconomy-Dj37CYYZ.js} +1 -1
- package/assets/{browser-VYI7gorG.js → browser-h4rN6CV4.js} +1 -1
- package/assets/browser-ponyfill-LG9Rjmfj.js +1 -0
- package/assets/{ccip-Bldffu31.js → ccip-Cv_5kGJ0.js} +1 -1
- package/assets/{ccip-CrAifiNa.js → ccip-TlIoUAte.js} +1 -1
- package/assets/{chains-DTVDhUwv.js → chains-CsuV2rnE.js} +1 -1
- package/assets/{common-BEf2T7Hi.js → common-C9wbti_7.js} +1 -1
- package/assets/{controller-B8Iy-6V9.js → controller-DpEeOSLx.js} +2 -2
- package/assets/{core-XFvzSI58.js → core-BGvtiIgG.js} +4 -4
- package/assets/{custom-cPmISGcH.js → custom-BbQhcg55.js} +1 -1
- package/assets/{data-capture-DnvAEYWK.js → data-capture-C5UoNnMk.js} +1 -1
- package/assets/decimals-DA8L6Gte.js +1 -0
- package/assets/{decimals-8g2-fBFa.js → decimals-mBEEumco.js} +1 -1
- package/assets/{detectExtension-yvI5WWZb.js → detectExtension-oDT7CrDk.js} +1 -1
- package/assets/{email-C8DRQjTT.js → email-CUatRSQC.js} +1 -1
- package/assets/{embedded-wallet-BxgtT1uV.js → embedded-wallet-DZAeJhJN.js} +1 -1
- package/assets/{engine-BERe87yT.js → engine-AXDB-0h6.js} +1 -1
- package/assets/{estimate-l1-fee-BTeKvFv5.js → estimate-l1-fee-Bxwscz8f.js} +1 -1
- package/assets/eth_estimateGas-DFXalA2X.js +1 -0
- package/assets/{eth_getStorageAt-SbVMAQY-.js → eth_getStorageAt-Dr4zmiJF.js} +1 -1
- package/assets/{eth_getTransactionCount-qv0oO1Md.js → eth_getTransactionCount-cZacEETx.js} +1 -1
- package/assets/{ethereum-BP59xYBe.js → ethereum-CIBzGnJl.js} +1 -1
- package/assets/{extractIPFS-BOFlZk7U.js → extractIPFS-Czsz8-sO.js} +1 -1
- package/assets/{features-DVWd8_kC.js → features-fx-atM_l.js} +1 -1
- package/assets/{fetchTokenMetadata-BaJXN6RH.js → fetchTokenMetadata-uG4nb_Kh.js} +2 -2
- package/assets/{fortmatic-DARkeYTE.js → fortmatic-boxtmFta.js} +1 -1
- package/assets/get-ecosystem-wallet-info-BI2Fd0Vd.js +1 -0
- package/assets/{getBalance-D6wpo61w.js → getBalance-CC2S0qtL.js} +2 -2
- package/assets/{getInstalledModules-Dkj379ys.js → getInstalledModules-53n5UYt2.js} +1 -1
- package/assets/{getNFT-HMkoXD7L.js → getNFT-C3FPakLN.js} +2 -2
- package/assets/{getNFT-Drn4rxrk.js → getNFT-CnaK4j2q.js} +1 -1
- package/assets/{hashTypedData-CMDSWYgs.js → hashTypedData-C4JiqOxU.js} +1 -1
- package/assets/{hashTypedData-B5shS-rs.js → hashTypedData-D1Ievn97.js} +1 -1
- package/assets/{in-app-wallet-calls-l9-2W_Em.js → in-app-wallet-calls-khLeeKNu.js} +1 -1
- package/assets/{index-BIPd_vR5.js → index-0P32tQWj.js} +1 -1
- package/assets/{index-DIlwNfpB.js → index-1quVm3wk.js} +1 -1
- package/assets/{index-DbAu4Peg.js → index-B2PoGJRP.js} +3 -3
- package/assets/{index-BaGjqMte.js → index-B5w_jZpc.js} +2 -2
- package/assets/{index-CE5G6IEJ.js → index-B6j-Tckn.js} +1 -1
- package/assets/{index-CjiwjbqL.js → index-BCiKer83.js} +1 -1
- package/assets/{index-C8NSq3HK.js → index-BCqrDgyR.js} +1 -1
- package/assets/{index-BXAxcybX.js → index-BE5nQY53.js} +1 -1
- package/assets/{index-C51HwlD0.js → index-BF9Yx_yV.js} +1 -1
- package/assets/{index-CWGeCZBJ.js → index-BJCYEGPg.js} +1 -1
- package/assets/{index-Cy1X3n_C.js → index-BT0xQ-Xd.js} +1 -1
- package/assets/{index-0ShVRzxt.js → index-BVi4iI8y.js} +1 -1
- package/assets/{index-BDgZ3gDE.js → index-BVvMg9ZB.js} +1 -1
- package/assets/{index-DFE6t65x.js → index-BpxeqYFx.js} +1 -1
- package/assets/{index-B5ECjSS9.js → index-Bv6LvzLS.js} +1 -1
- package/assets/{index-i4VBSYqA.js → index-BvCGPTHO.js} +1 -1
- package/assets/index-Bzi38pjx.css +1 -0
- package/assets/{index-CH0zI801.js → index-C5oPclal.js} +1 -1
- package/assets/{index-D2ZBQG8w.js → index-C6-AvlPm.js} +1 -1
- package/assets/{index-CWnFK_-0.js → index-C9EMW8qD.js} +1 -1
- package/assets/{index-C-uqursN.js → index-C9vcJp9T.js} +1 -1
- package/assets/{index-DK-ZMNLh.js → index-CO3lXLzl.js} +1 -1
- package/assets/{index-DS2Lm9tG.js → index-CYBDya_s.js} +1 -1
- package/assets/{index-okvlQSs2.js → index-Coj3uG35.js} +1 -1
- package/assets/{index-Cu4ZjLNb.js → index-CqbvjyBi.js} +5 -5
- package/assets/{index-wds8TuUm.js → index-CwfOYq8B.js} +1 -1
- package/assets/{index-aoxVkzFE.js → index-Cz0JdeQb.js} +1 -1
- package/assets/{index-C5ciuua_.js → index-D-YuFp2i.js} +1 -1
- package/assets/{index-I68folnJ.js → index-D4NLrlUn.js} +1 -1
- package/assets/{index-B7Jt3b4d.js → index-D8PaxcsI.js} +1 -1
- package/assets/{index-r_1z0VI_.js → index-D9ey6cqT.js} +1 -1
- package/assets/{index-B-vyBZw9.js → index-DRYOQXZX.js} +1 -1
- package/assets/{index-DOnRCLNP.js → index-DT1PkdGa.js} +2 -2
- package/assets/{index-DWRq2SN_.js → index-DXCSroqX.js} +1 -1
- package/assets/{index-mZa0UiRt.js → index-DXs78xw9.js} +1 -1
- package/assets/{index-kXKMGszW.js → index-DZ0punK7.js} +1 -1
- package/assets/{index-B9U0GcYk.js → index-D_m5AL3D.js} +1 -1
- package/assets/{index-BxdNwV86.js → index-Dc148hav.js} +1 -1
- package/assets/{index-DP1DuCnR.js → index-DgDxBH9m.js} +1 -1
- package/assets/{index-DfWsAOhN.js → index-Dm7tCcMc.js} +3 -3
- package/assets/{index-D0LvjNIX.js → index-DmIGOG39.js} +1 -1
- package/assets/{index-JfVynEph.js → index-DmK5ktNw.js} +1 -1
- package/assets/{index-Cp7mdTuR.js → index-Eyans5--.js} +1 -1
- package/assets/{index-DPxCDCvr.js → index-KK8ZylE4.js} +1 -1
- package/assets/{index-DvJmANzU.js → index-TUD0QlWP.js} +1 -1
- package/assets/{index-TBthDmkl.js → index-ak5cSl-l.js} +1 -1
- package/assets/{index-8M7OkBFm.js → index-bVr8-SEv.js} +1 -1
- package/assets/{index-BlykZ8Gp.js → index-prLj8b2x.js} +1 -1
- package/assets/{index-BKL7nv1p.js → index-vajj2FBo.js} +1 -1
- package/assets/{index.es-YpI01v2I.js → index.es-C85F8NOj.js} +1 -1
- package/assets/{index.es-CkxUaFYS.js → index.es-DYgSAVrd.js} +1 -1
- package/assets/{index.es-cEGj7JU0.js → index.es-XXBqJXMm.js} +4 -4
- package/assets/{localBatchGatewayRequest-CNIOIq-Z.js → localBatchGatewayRequest-DbQn1s0J.js} +1 -1
- package/assets/{networks-DJ72puSk.js → networks-DMqekeph.js} +1 -1
- package/assets/{onramp--l5ZLxWE.js → onramp-qvbxoSMm.js} +1 -1
- package/assets/{openzeppelin-CqtRqxtF.js → openzeppelin-B6Und3LJ.js} +1 -1
- package/assets/{ownerOf-cWkgEtd8.js → ownerOf-CUoSe2c5.js} +1 -1
- package/assets/{parseEventLogs-D1xiFnCH.js → parseEventLogs-BxtEI7tW.js} +3 -3
- package/assets/{parseNft-DH5KlHPI.js → parseNft-DB_pGzOu.js} +2 -2
- package/assets/{parseSignature-HAlgOHnm.js → parseSignature-Csyua1uA.js} +3 -3
- package/assets/{parseSignature-BYhcrVdX.js → parseSignature-O0fAqZoB.js} +1 -1
- package/assets/{pay-with-exchange-CiXPJJ6-.js → pay-with-exchange-1MlV9x6H.js} +1 -1
- package/assets/{qr-overlay-CmFgwJBd.js → qr-overlay-DA6htUdY.js} +3 -3
- package/assets/{receive-t2TxUItI.js → receive-JnpfZY7d.js} +1 -1
- package/assets/{resolveImplementation-iG9WRRnW.js → resolveImplementation-B8d2Q-Ro.js} +1 -1
- package/assets/{rpc-sIdV4wiJ.js → rpc-DkFFCBh9.js} +1 -1
- package/assets/{secp256k1-Rk5k9i7o.js → secp256k1-BCPsQ5nJ.js} +1 -1
- package/assets/{secp256k1-Co_Jve4c.js → secp256k1-BZmrY8e3.js} +1 -1
- package/assets/{secp256k1-Bg2aUJRs.js → secp256k1-TIizaas9.js} +1 -1
- package/assets/{send-ByB5fOtm.js → send-DsnDja5n.js} +1 -1
- package/assets/{send-batch-transaction-D79MC_wr.js → send-batch-transaction-jNcvidMH.js} +1 -1
- package/assets/{send-eip712-transaction-CB6qLgks.js → send-eip712-transaction-DDJVOUpU.js} +2 -2
- package/assets/{send-gasless-transaction-Dt1qtUR8.js → send-gasless-transaction-DXjarWmh.js} +2 -2
- package/assets/{session-proposal-CY0k9Jnm.js → session-proposal-xJguSOgr.js} +1 -1
- package/assets/{session-request-B_2glC9e.js → session-request-BhD4eDPG.js} +2 -2
- package/assets/{sha256-Dy8KQE_5.js → sha256-CbjS9vFa.js} +1 -1
- package/assets/{signing-gNn6SJWz.js → signing-tKzVzr3v.js} +5 -5
- package/assets/{socials-Dx84-PrV.js → socials-CER945jA.js} +1 -1
- package/assets/{swaps-CK9Sfcew.js → swaps-Dy4hNTFm.js} +1 -1
- package/assets/{thirdweb-Bx5V_C1s.js → thirdweb-CNCkvOQU.js} +3 -3
- package/assets/{totalSupply-O-VFDoRO.js → totalSupply-BQvZy7Uc.js} +1 -1
- package/assets/{transactionReceipt-BqEjx5q-.js → transactionReceipt-DA1xo-2g.js} +1 -1
- package/assets/{transactions-BLOC2qYE.js → transactions-CwEfhngY.js} +1 -1
- package/assets/{utils-h8VUSGPW.js → utils-BUWGRgBa.js} +1 -1
- package/assets/{verifyHash-CNJ6t8Wp.js → verifyHash-CX9Livyx.js} +1 -1
- package/assets/{w3m-modal-nzPxg0Fr.js → w3m-modal-B1spewtI.js} +1 -1
- package/assets/{w3m-modal-CCQuGDus.js → w3m-modal-B6M729n4.js} +1 -1
- package/assets/{wait-for-tx-receipt-5pSBMNe2.js → wait-for-tx-receipt-BLruoSfj.js} +1 -1
- package/assets/{wallets-Bz03-Btm.js → wallets-vCTTbbau.js} +6 -6
- package/assets/{web-connector-CAOe_uvv.js → web-connector-h9SB5qXs.js} +3 -3
- package/assets/{writeContract-CCar3Ocq.js → writeContract-C9KDDivM.js} +1 -1
- package/assets/{zora-sepolia-D6mjhB5j.js → zora-sepolia-pCyxGzqm.js} +1 -1
- package/assets/{zoraTestnet-WLSFziQl.js → zoraTestnet-ChmlUfs6.js} +1 -1
- package/index.html +4 -4
- package/package.json +3 -3
- package/assets/browser-ponyfill-BmgQyNz0.js +0 -1
- package/assets/decimals-DR6jraOc.js +0 -1
- package/assets/eth_estimateGas-DKKwG-Ue.js +0 -1
- package/assets/get-ecosystem-wallet-info-Cvjz8DFX.js +0 -1
- package/assets/index-829Uxa3Y.css +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-
|
|
2
|
-
import{_ as Pa,b as Ui,h as ch,B as Ie,g as hh,e as St,N as tn}from"./index-
|
|
3
|
-
`);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=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Sa}walk(e){return Oa(this,e)}}function Oa(i,e){return e?.(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?Oa(i.cause,e):e?null:i}class xa extends Mt{constructor({size:e,targetSize:t,type:s}){super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Pi(i,{dir:e,size:t=32}={}){return typeof i=="string"?_h(i,{dir:e,size:t}):Ph(i,{dir:e,size:t})}function _h(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new xa({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function Ph(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new xa({size:i.length,targetSize:t,type:"bytes"});const s=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";s[n?r:t-r-1]=i[n?r:i.length-r-1]}return s}class $h extends Mt{constructor({max:e,min:t,signed:s,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${s?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class Sh extends Mt{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function $i(i,{size:e}){if(En(i)>e)throw new Sh({givenSize:En(i),maxSize:e})}function Pr(i,e={}){const{signed:t}=e;e.size&&$i(i,{size:e.size});const s=BigInt(i);if(!t)return s;const r=(i.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return s<=n?s:s-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function Oh(i,e={}){return Number(Pr(i,e))}const xh=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function $r(i,e={}){return typeof i=="number"||typeof i=="bigint"?Ta(i,e):typeof i=="string"?Ch(i,e):typeof i=="boolean"?Ah(i,e):Aa(i,e)}function Ah(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?($i(t,{size:e.size}),Pi(t,{size:e.size})):t}function Aa(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=xh[i[r]];const s=`0x${t}`;return typeof e.size=="number"?($i(s,{size:e.size}),Pi(s,{dir:"right",size:e.size})):s}function Ta(i,e={}){const{signed:t,size:s}=e,r=BigInt(i);let n;s?t?n=(1n<<BigInt(s)*8n-1n)-1n:n=2n**(BigInt(s)*8n)-1n:typeof i=="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 i=="bigint"?"n":"";throw new $h({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:s,value:`${i}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(s*8))+BigInt(r):r).toString(16)}`;return s?Pi(a,{size:s}):a}const Th=new TextEncoder;function Ch(i,e={}){const t=Th.encode(i);return Aa(t,e)}const Nh=new TextEncoder;function Rh(i,e={}){return typeof i=="number"||typeof i=="bigint"?qh(i,e):typeof i=="boolean"?jh(i,e):Fi(i)?Ca(i,e):Na(i,e)}function jh(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?($i(t,{size:e.size}),Pi(t,{size:e.size})):t}const ht={zero:48,nine:57,A:65,F:70,a:97,f:102};function In(i){if(i>=ht.zero&&i<=ht.nine)return i-ht.zero;if(i>=ht.A&&i<=ht.F)return i-(ht.A-10);if(i>=ht.a&&i<=ht.f)return i-(ht.a-10)}function Ca(i,e={}){let t=i;e.size&&($i(t,{size:e.size}),t=Pi(t,{dir:"right",size:e.size}));let s=t.slice(2);s.length%2&&(s=`0${s}`);const r=s.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=In(s.charCodeAt(a++)),h=In(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new Mt(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function qh(i,e){const t=Ta(i,e);return Ca(t)}function Na(i,e={}){const t=Nh.encode(i);return typeof e.size=="number"?($i(t,{size:e.size}),Pi(t,{dir:"right",size:e.size})):t}function xs(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function kh(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ms(i,...e){if(!kh(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function yE(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");xs(i.outputLen),xs(i.blockLen)}function _n(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Dh(i,e){Ms(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const hs=BigInt(2**32-1),Pn=BigInt(32);function Lh(i,e=!1){return e?{h:Number(i&hs),l:Number(i>>Pn&hs)}:{h:Number(i>>Pn&hs)|0,l:Number(i&hs)|0}}function Mh(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Lh(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Uh=(i,e,t)=>i<<t|e>>>32-t,zh=(i,e,t)=>e<<t|i>>>32-t,Bh=(i,e,t)=>e<<t-32|i>>>64-t,Kh=(i,e,t)=>i<<t-32|e>>>64-t,Ft=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Vh(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function wE(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function bE(i,e){return i<<32-e|i>>>e}const $n=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Hh(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Sn(i){for(let e=0;e<i.length;e++)i[e]=Hh(i[e])}function Fh(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Ra(i){return typeof i=="string"&&(i=Fh(i)),Ms(i),i}function vE(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Ms(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}class Gh{clone(){return this._cloneInto()}}function Wh(i){const e=s=>i().update(Ra(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function EE(i=32){if(Ft&&typeof Ft.getRandomValues=="function")return Ft.getRandomValues(new Uint8Array(i));if(Ft&&typeof Ft.randomBytes=="function")return Ft.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const ja=[],qa=[],ka=[],Jh=BigInt(0),Ti=BigInt(1),Qh=BigInt(2),Yh=BigInt(7),Zh=BigInt(256),Xh=BigInt(113);for(let i=0,e=Ti,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],ja.push(2*(5*s+t)),qa.push((i+1)*(i+2)/2%64);let r=Jh;for(let n=0;n<7;n++)e=(e<<Ti^(e>>Yh)*Xh)%Zh,e&Qh&&(r^=Ti<<(Ti<<BigInt(n))-Ti);ka.push(r)}const[el,tl]=Mh(ka,!0),On=(i,e,t)=>t>32?Bh(i,e,t):Uh(i,e,t),xn=(i,e,t)=>t>32?Kh(i,e,t):zh(i,e,t);function il(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=On(h,l,1)^t[a],p=xn(h,l,1)^t[a+1];for(let d=0;d<50;d+=10)i[o+d]^=u,i[o+d+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=qa[o],c=On(r,n,a),h=xn(r,n,a),l=ja[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=el[s],i[1]^=tl[s]}t.fill(0)}class nn extends Gh{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,xs(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Vh(this.state)}keccak(){$n||Sn(this.state32),il(this.state32,this.rounds),$n||Sn(this.state32),this.posOut=0,this.pos=0}update(e){_n(this);const{blockLen:t,state:s}=this;e=Ra(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){_n(this,!1),Ms(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 xs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Dh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new nn(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const sl=(i,e,t)=>Wh(()=>new nn(e,i,t)),rl=sl(1,136,256/8);function Da(i,e){const t=e||"hex",s=rl(Fi(i,{strict:!1})?Rh(i):i);return t==="bytes"?s:$r(s)}class nl 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 s=this.keys().next().value;s&&this.delete(s)}return this}}const Ys=new nl(8192);function ol(i,e){if(Ys.has(`${i}.${e}`))return Ys.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),s=Da(Na(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)s[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(s[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Ys.set(`${i}.${e}`,n),n}function al(i){const e=Da(`0x${i.substring(4)}`).substring(26);return ol(`0x${e}`)}async function cl({hash:i,signature:e}){const t=Fi(i)?i:$r(i),{secp256k1:s}=await Pa(async()=>{const{secp256k1:o}=await import("./secp256k1-Co_Jve4c.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:u,yParity:p}=e,d=Number(p??u),g=An(d);return new s.Signature(Pr(h),Pr(l)).addRecoveryBit(g)}const o=Fi(e)?e:$r(e),a=Oh(`0x${o.slice(130)}`),c=An(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function An(i){if(i===0||i===1)return i;if(i===27)return 0;if(i===28)return 1;throw new Error("Invalid yParityOrV value")}async function hl({hash:i,signature:e}){return al(await cl({hash:i,signature:e}))}function La(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function zi(i,e){e||(e=i.reduce((r,n)=>r+n.length,0));const t=La(e);let s=0;for(const r of i)t.set(r,s),s+=r.length;return t}function Ma(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Tn=Ma("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Zs=Ma("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=La(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),Ua={utf8:Tn,"utf-8":Tn,hex:wn.base16,latin1:Zs,ascii:Zs,binary:Zs,...wn};function Be(i,e="utf8"){const t=Ua[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(i,"utf8"):t.decoder.decode(`${t.prefix}${i}`)}function Te(i,e="utf8"){const t=Ua[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(i.buffer,i.byteOffset,i.byteLength).toString("utf8"):t.encoder.encode(i).substring(1)}var ll={};const ul=":";function gi(i){const[e,t]=i.split(ul);return{namespace:e,reference:t}}function Cn(i,e=[]){const t=[];return Object.keys(i).forEach(s=>{if(e.length&&!e.includes(s))return;const r=i[s];t.push(...r.accounts)}),t}function za(i,e){return i.includes(":")?[i]:e.chains||[]}var pl=Object.defineProperty,dl=Object.defineProperties,gl=Object.getOwnPropertyDescriptors,Nn=Object.getOwnPropertySymbols,fl=Object.prototype.hasOwnProperty,ml=Object.prototype.propertyIsEnumerable,Rn=(i,e,t)=>e in i?pl(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,jn=(i,e)=>{for(var t in e||(e={}))fl.call(e,t)&&Rn(i,t,e[t]);if(Nn)for(var t of Nn(e))ml.call(e,t)&&Rn(i,t,e[t]);return i},yl=(i,e)=>dl(i,gl(e));const wl="ReactNative",De={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},bl="js";function As(){return typeof Ui<"u"&&typeof Ui.versions<"u"&&typeof Ui.versions.node<"u"}function Ot(){return!yt.getDocument()&&!!yt.getNavigator()&&navigator.product===wl}function vl(){return Ot()&&typeof globalThis<"u"&&typeof globalThis?.Platform<"u"&&globalThis?.Platform.OS==="android"}function El(){return Ot()&&typeof globalThis<"u"&&typeof globalThis?.Platform<"u"&&globalThis?.Platform.OS==="ios"}function Si(){return!As()&&!!yt.getNavigator()&&!!yt.getDocument()}function Zi(){return Ot()?De.reactNative:As()?De.node:Si()?De.browser:De.unknown}function qn(){var i;try{return Ot()&&typeof globalThis<"u"&&typeof globalThis?.Application<"u"?(i=globalThis.Application)==null?void 0:i.applicationId:void 0}catch{return}}function Il(i,e){const t=new URLSearchParams(i);for(const s of Object.keys(e).sort())if(e.hasOwnProperty(s)){const r=e[s];r!==void 0&&t.set(s,r)}return t.toString()}function _l(i){var e,t;const s=Ba();try{return i!=null&&i.url&&s.url&&new URL(i.url).host!==new URL(s.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${i.url} differs from the actual page url:${s.url}. This is probably unintended and can lead to issues.`),i.url=s.url),(e=i?.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(r=>r!=="")),yl(jn(jn({},s),i),{url:i?.url||s.url,name:i?.name||s.name,description:i?.description||s.description,icons:(t=i?.icons)!=null&&t.length&&i.icons.length>0?i.icons:s.icons})}catch(r){return console.warn("Error populating app metadata",r),i||s}}function Ba(){return lh.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Pl(){if(Zi()===De.reactNative&&typeof globalThis<"u"&&typeof globalThis?.Platform<"u"){const{OS:t,Version:s}=globalThis.Platform;return[t,s].join("-")}const i=ch();if(i===null)return"unknown";const e=i.os?i.os.replace(" ","").toLowerCase():"unknown";return i.type==="browser"?[e,i.name,i.version].join("-"):[e,i.version].join("-")}function $l(){var i;const e=Zi();return e===De.browser?[e,((i=yt.getLocation())==null?void 0:i.host)||"unknown"].join(":"):e}function Ka(i,e,t){const s=Pl(),r=$l();return[[i,e].join("-"),[bl,t].join("-"),s,r].join("/")}function Sl({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Ka(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=Il(h[1]||"",u);return h[0]+"?"+p}function Dt(i,e){return i.filter(t=>e.includes(t)).length===i.length}function Sr(i){return Object.fromEntries(i.entries())}function Or(i){return new Map(Object.entries(i))}function Ct(i=j.FIVE_MINUTES,e){const t=j.toMiliseconds(i||j.FIVE_MINUTES);let s,r,n,o;return{resolve:a=>{n&&s&&(clearTimeout(n),s(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 h=new Error(e);o=Promise.reject(h),c(h)},t),s=a,r=c})}}function _t(i,e,t){return new Promise(async(s,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await i;s(o)}catch(o){r(o)}clearTimeout(n)})}function Va(i,e){if(typeof e=="string"&&e.startsWith(`${i}:`))return e;if(i.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(i.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: ${i}`)}function Ol(i){return Va("topic",i)}function xl(i){return Va("id",i)}function Ha(i){const[e,t]=i.split(":"),s={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")s.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))s.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return s}function ce(i,e){return j.fromMiliseconds(Date.now()+j.toMiliseconds(i))}function Et(i){return Date.now()>=j.toMiliseconds(i)}function J(i,e){return`${i}${e?`:${e}`:""}`}function nt(i=[],e=[]){return[...new Set([...i,...e])]}async function Al({id:i,topic:e,wcDeepLink:t}){var s;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r?.href;if(typeof n!="string")return;const o=Tl(n,i,e),a=Zi();if(a===De.browser){if(!((s=yt.getDocument())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Cl(o)}else a===De.reactNative&&typeof globalThis?.Linking<"u"&&await globalThis.Linking.openURL(o)}catch(r){console.error(r)}}function Tl(i,e,t){const s=`requestId=${e}&sessionTopic=${t}`;i.endsWith("/")&&(i=i.slice(0,-1));let r=`${i}`;if(i.startsWith("https://t.me")){const n=i.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${ql(s,!0)}`}else r=`${r}/wc?${s}`;return r}function Cl(i){let e="_self";jl()?e="_top":(Rl()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Nl(i,e){let t="";try{if(Si()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function kn(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function Dn(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function on(){return typeof Ui<"u"&&ll.IS_VITEST==="true"}function Rl(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function jl(){try{return window.self!==window.top}catch{return!1}}function ql(i,e=!1){const t=Ie.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Fa(i){return Ie.from(i,"base64").toString("utf-8")}function kl(i){return new Promise(e=>setTimeout(e,i))}function Gi(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Dl(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Xi(i,...e){if(!Dl(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function an(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Gi(i.outputLen),Gi(i.blockLen)}function fi(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Ga(i,e){Xi(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ls=BigInt(2**32-1),Ln=BigInt(32);function Ll(i,e=!1){return e?{h:Number(i&ls),l:Number(i>>Ln&ls)}:{h:Number(i>>Ln&ls)|0,l:Number(i&ls)|0}}function Ml(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Ll(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Ul=(i,e,t)=>i<<t|e>>>32-t,zl=(i,e,t)=>e<<t|i>>>32-t,Bl=(i,e,t)=>e<<t-32|i>>>64-t,Kl=(i,e,t)=>i<<t-32|e>>>64-t,Gt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Vl(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Xs(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Xe(i,e){return i<<32-e|i>>>e}const Mn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Hl(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Un(i){for(let e=0;e<i.length;e++)i[e]=Hl(i[e])}function Fl(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function mi(i){return typeof i=="string"&&(i=Fl(i)),Xi(i),i}function Gl(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Xi(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}let cn=class{clone(){return this._cloneInto()}};function Wa(i){const e=s=>i().update(mi(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Oi(i=32){if(Gt&&typeof Gt.getRandomValues=="function")return Gt.getRandomValues(new Uint8Array(i));if(Gt&&typeof Gt.randomBytes=="function")return Gt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Ja=[],Qa=[],Ya=[],Wl=BigInt(0),Ci=BigInt(1),Jl=BigInt(2),Ql=BigInt(7),Yl=BigInt(256),Zl=BigInt(113);for(let i=0,e=Ci,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Ja.push(2*(5*s+t)),Qa.push((i+1)*(i+2)/2%64);let r=Wl;for(let n=0;n<7;n++)e=(e<<Ci^(e>>Ql)*Zl)%Yl,e&Jl&&(r^=Ci<<(Ci<<BigInt(n))-Ci);Ya.push(r)}const[Xl,eu]=Ml(Ya,!0),zn=(i,e,t)=>t>32?Bl(i,e,t):Ul(i,e,t),Bn=(i,e,t)=>t>32?Kl(i,e,t):zl(i,e,t);function tu(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=zn(h,l,1)^t[a],p=Bn(h,l,1)^t[a+1];for(let d=0;d<50;d+=10)i[o+d]^=u,i[o+d+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Qa[o],c=zn(r,n,a),h=Bn(r,n,a),l=Ja[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=Xl[s],i[1]^=eu[s]}t.fill(0)}let iu=class Za extends cn{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Gi(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Vl(this.state)}keccak(){Mn||Un(this.state32),tu(this.state32,this.rounds),Mn||Un(this.state32),this.posOut=0,this.pos=0}update(e){fi(this);const{blockLen:t,state:s}=this;e=mi(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){fi(this,!1),Xi(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 Gi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ga(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Za(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const su=(i,e,t)=>Wa(()=>new iu(e,i,t)),ru=su(1,136,256/8),nu="https://rpc.walletconnect.org/v1";function Xa(i){const e=`Ethereum Signed Message:
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-BZmrY8e3.js","assets/index-CqbvjyBi.js","assets/index-Bzi38pjx.css","assets/index-DRYOQXZX.js","assets/index-CYBDya_s.js","assets/index-nibyPLVP.js","assets/index-CJdot1dH.js","assets/index.es-DYgSAVrd.js","assets/browser-ponyfill-LG9Rjmfj.js","assets/core-BGvtiIgG.js","assets/NetworkUtil-DM5H1DOt.js","assets/sha2-D3ryOfi3.js","assets/W3MFrameProviderSingleton-dGwr0u32.js","assets/lit-element-Cn7T8F1W.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as Pa,b as Ui,h as ch,B as Ie,g as hh,e as St,N as tn}from"./index-CqbvjyBi.js";import{d as wn,e as lh,g as j,h as yt,C as uh,j as _r,k as ph,l as cs,a as Os,s as Hi,I as Ii,m as dh,c as kt,r as _i,o as Ke,n as gh,q as sn,t as rn,b as Ls,P as bn,Q as fh,u as mh,v as li,f as $a,w as ut,x as st,y as wt}from"./index-DRYOQXZX.js";import{c as yh,a as wh,k as bh,d as vh,s as Eh,g as vn}from"./index-nibyPLVP.js";import{r as Ih}from"./index-CJdot1dH.js";import"./index-CYBDya_s.js";import{f as Ye}from"./index.es-DYgSAVrd.js";function Fi(i,{strict:e=!0}={}){return!i||typeof i!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(i):i.startsWith("0x")}function En(i){return Fi(i,{strict:!1})?Math.ceil((i.length-2)/2):i.length}const Sa="2.23.2";let Qs={getDocsUrl:({docsBaseUrl:i,docsPath:e="",docsSlug:t})=>e?`${i??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${Sa}`};class Mt extends Error{constructor(e,t={}){const s=t.cause instanceof Mt?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof Mt&&t.cause.docsPath||t.docsPath,n=Qs.getDocsUrl?.({...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...s?[`Details: ${s}`]:[],...Qs.version?[`Version: ${Qs.version}`]:[]].join(`
|
|
3
|
+
`);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=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Sa}walk(e){return Oa(this,e)}}function Oa(i,e){return e?.(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?Oa(i.cause,e):e?null:i}class xa extends Mt{constructor({size:e,targetSize:t,type:s}){super(`${s.charAt(0).toUpperCase()}${s.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Pi(i,{dir:e,size:t=32}={}){return typeof i=="string"?_h(i,{dir:e,size:t}):Ph(i,{dir:e,size:t})}function _h(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new xa({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function Ph(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new xa({size:i.length,targetSize:t,type:"bytes"});const s=new Uint8Array(t);for(let r=0;r<t;r++){const n=e==="right";s[n?r:t-r-1]=i[n?r:i.length-r-1]}return s}class $h extends Mt{constructor({max:e,min:t,signed:s,size:r,value:n}){super(`Number "${n}" is not in safe ${r?`${r*8}-bit ${s?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class Sh extends Mt{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function $i(i,{size:e}){if(En(i)>e)throw new Sh({givenSize:En(i),maxSize:e})}function Pr(i,e={}){const{signed:t}=e;e.size&&$i(i,{size:e.size});const s=BigInt(i);if(!t)return s;const r=(i.length-2)/2,n=(1n<<BigInt(r)*8n-1n)-1n;return s<=n?s:s-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function Oh(i,e={}){return Number(Pr(i,e))}const xh=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function $r(i,e={}){return typeof i=="number"||typeof i=="bigint"?Ta(i,e):typeof i=="string"?Ch(i,e):typeof i=="boolean"?Ah(i,e):Aa(i,e)}function Ah(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?($i(t,{size:e.size}),Pi(t,{size:e.size})):t}function Aa(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=xh[i[r]];const s=`0x${t}`;return typeof e.size=="number"?($i(s,{size:e.size}),Pi(s,{dir:"right",size:e.size})):s}function Ta(i,e={}){const{signed:t,size:s}=e,r=BigInt(i);let n;s?t?n=(1n<<BigInt(s)*8n-1n)-1n:n=2n**(BigInt(s)*8n)-1n:typeof i=="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 i=="bigint"?"n":"";throw new $h({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:s,value:`${i}${c}`})}const a=`0x${(t&&r<0?(1n<<BigInt(s*8))+BigInt(r):r).toString(16)}`;return s?Pi(a,{size:s}):a}const Th=new TextEncoder;function Ch(i,e={}){const t=Th.encode(i);return Aa(t,e)}const Nh=new TextEncoder;function Rh(i,e={}){return typeof i=="number"||typeof i=="bigint"?qh(i,e):typeof i=="boolean"?jh(i,e):Fi(i)?Ca(i,e):Na(i,e)}function jh(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?($i(t,{size:e.size}),Pi(t,{size:e.size})):t}const ht={zero:48,nine:57,A:65,F:70,a:97,f:102};function In(i){if(i>=ht.zero&&i<=ht.nine)return i-ht.zero;if(i>=ht.A&&i<=ht.F)return i-(ht.A-10);if(i>=ht.a&&i<=ht.f)return i-(ht.a-10)}function Ca(i,e={}){let t=i;e.size&&($i(t,{size:e.size}),t=Pi(t,{dir:"right",size:e.size}));let s=t.slice(2);s.length%2&&(s=`0${s}`);const r=s.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=In(s.charCodeAt(a++)),h=In(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new Mt(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function qh(i,e){const t=Ta(i,e);return Ca(t)}function Na(i,e={}){const t=Nh.encode(i);return typeof e.size=="number"?($i(t,{size:e.size}),Pi(t,{dir:"right",size:e.size})):t}function xs(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function kh(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ms(i,...e){if(!kh(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function yE(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");xs(i.outputLen),xs(i.blockLen)}function _n(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Dh(i,e){Ms(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const hs=BigInt(2**32-1),Pn=BigInt(32);function Lh(i,e=!1){return e?{h:Number(i&hs),l:Number(i>>Pn&hs)}:{h:Number(i>>Pn&hs)|0,l:Number(i&hs)|0}}function Mh(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Lh(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Uh=(i,e,t)=>i<<t|e>>>32-t,zh=(i,e,t)=>e<<t|i>>>32-t,Bh=(i,e,t)=>e<<t-32|i>>>64-t,Kh=(i,e,t)=>i<<t-32|e>>>64-t,Ft=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Vh(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function wE(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function bE(i,e){return i<<32-e|i>>>e}const $n=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Hh(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Sn(i){for(let e=0;e<i.length;e++)i[e]=Hh(i[e])}function Fh(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Ra(i){return typeof i=="string"&&(i=Fh(i)),Ms(i),i}function vE(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Ms(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}class Gh{clone(){return this._cloneInto()}}function Wh(i){const e=s=>i().update(Ra(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function EE(i=32){if(Ft&&typeof Ft.getRandomValues=="function")return Ft.getRandomValues(new Uint8Array(i));if(Ft&&typeof Ft.randomBytes=="function")return Ft.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const ja=[],qa=[],ka=[],Jh=BigInt(0),Ti=BigInt(1),Qh=BigInt(2),Yh=BigInt(7),Zh=BigInt(256),Xh=BigInt(113);for(let i=0,e=Ti,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],ja.push(2*(5*s+t)),qa.push((i+1)*(i+2)/2%64);let r=Jh;for(let n=0;n<7;n++)e=(e<<Ti^(e>>Yh)*Xh)%Zh,e&Qh&&(r^=Ti<<(Ti<<BigInt(n))-Ti);ka.push(r)}const[el,tl]=Mh(ka,!0),On=(i,e,t)=>t>32?Bh(i,e,t):Uh(i,e,t),xn=(i,e,t)=>t>32?Kh(i,e,t):zh(i,e,t);function il(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=On(h,l,1)^t[a],p=xn(h,l,1)^t[a+1];for(let d=0;d<50;d+=10)i[o+d]^=u,i[o+d+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=qa[o],c=On(r,n,a),h=xn(r,n,a),l=ja[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=el[s],i[1]^=tl[s]}t.fill(0)}class nn extends Gh{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,xs(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Vh(this.state)}keccak(){$n||Sn(this.state32),il(this.state32,this.rounds),$n||Sn(this.state32),this.posOut=0,this.pos=0}update(e){_n(this);const{blockLen:t,state:s}=this;e=Ra(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){_n(this,!1),Ms(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 xs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Dh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new nn(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const sl=(i,e,t)=>Wh(()=>new nn(e,i,t)),rl=sl(1,136,256/8);function Da(i,e){const t=e||"hex",s=rl(Fi(i,{strict:!1})?Rh(i):i);return t==="bytes"?s:$r(s)}class nl 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 s=this.keys().next().value;s&&this.delete(s)}return this}}const Ys=new nl(8192);function ol(i,e){if(Ys.has(`${i}.${e}`))return Ys.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),s=Da(Na(t),"bytes"),r=t.split("");for(let o=0;o<40;o+=2)s[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(s[o>>1]&15)>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const n=`0x${r.join("")}`;return Ys.set(`${i}.${e}`,n),n}function al(i){const e=Da(`0x${i.substring(4)}`).substring(26);return ol(`0x${e}`)}async function cl({hash:i,signature:e}){const t=Fi(i)?i:$r(i),{secp256k1:s}=await Pa(async()=>{const{secp256k1:o}=await import("./secp256k1-BZmrY8e3.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:u,yParity:p}=e,d=Number(p??u),g=An(d);return new s.Signature(Pr(h),Pr(l)).addRecoveryBit(g)}const o=Fi(e)?e:$r(e),a=Oh(`0x${o.slice(130)}`),c=An(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function An(i){if(i===0||i===1)return i;if(i===27)return 0;if(i===28)return 1;throw new Error("Invalid yParityOrV value")}async function hl({hash:i,signature:e}){return al(await cl({hash:i,signature:e}))}function La(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function zi(i,e){e||(e=i.reduce((r,n)=>r+n.length,0));const t=La(e);let s=0;for(const r of i)t.set(r,s),s+=r.length;return t}function Ma(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Tn=Ma("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Zs=Ma("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=La(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),Ua={utf8:Tn,"utf-8":Tn,hex:wn.base16,latin1:Zs,ascii:Zs,binary:Zs,...wn};function Be(i,e="utf8"){const t=Ua[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(i,"utf8"):t.decoder.decode(`${t.prefix}${i}`)}function Te(i,e="utf8"){const t=Ua[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(i.buffer,i.byteOffset,i.byteLength).toString("utf8"):t.encoder.encode(i).substring(1)}var ll={};const ul=":";function gi(i){const[e,t]=i.split(ul);return{namespace:e,reference:t}}function Cn(i,e=[]){const t=[];return Object.keys(i).forEach(s=>{if(e.length&&!e.includes(s))return;const r=i[s];t.push(...r.accounts)}),t}function za(i,e){return i.includes(":")?[i]:e.chains||[]}var pl=Object.defineProperty,dl=Object.defineProperties,gl=Object.getOwnPropertyDescriptors,Nn=Object.getOwnPropertySymbols,fl=Object.prototype.hasOwnProperty,ml=Object.prototype.propertyIsEnumerable,Rn=(i,e,t)=>e in i?pl(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,jn=(i,e)=>{for(var t in e||(e={}))fl.call(e,t)&&Rn(i,t,e[t]);if(Nn)for(var t of Nn(e))ml.call(e,t)&&Rn(i,t,e[t]);return i},yl=(i,e)=>dl(i,gl(e));const wl="ReactNative",De={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},bl="js";function As(){return typeof Ui<"u"&&typeof Ui.versions<"u"&&typeof Ui.versions.node<"u"}function Ot(){return!yt.getDocument()&&!!yt.getNavigator()&&navigator.product===wl}function vl(){return Ot()&&typeof globalThis<"u"&&typeof globalThis?.Platform<"u"&&globalThis?.Platform.OS==="android"}function El(){return Ot()&&typeof globalThis<"u"&&typeof globalThis?.Platform<"u"&&globalThis?.Platform.OS==="ios"}function Si(){return!As()&&!!yt.getNavigator()&&!!yt.getDocument()}function Zi(){return Ot()?De.reactNative:As()?De.node:Si()?De.browser:De.unknown}function qn(){var i;try{return Ot()&&typeof globalThis<"u"&&typeof globalThis?.Application<"u"?(i=globalThis.Application)==null?void 0:i.applicationId:void 0}catch{return}}function Il(i,e){const t=new URLSearchParams(i);for(const s of Object.keys(e).sort())if(e.hasOwnProperty(s)){const r=e[s];r!==void 0&&t.set(s,r)}return t.toString()}function _l(i){var e,t;const s=Ba();try{return i!=null&&i.url&&s.url&&new URL(i.url).host!==new URL(s.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${i.url} differs from the actual page url:${s.url}. This is probably unintended and can lead to issues.`),i.url=s.url),(e=i?.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(r=>r!=="")),yl(jn(jn({},s),i),{url:i?.url||s.url,name:i?.name||s.name,description:i?.description||s.description,icons:(t=i?.icons)!=null&&t.length&&i.icons.length>0?i.icons:s.icons})}catch(r){return console.warn("Error populating app metadata",r),i||s}}function Ba(){return lh.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Pl(){if(Zi()===De.reactNative&&typeof globalThis<"u"&&typeof globalThis?.Platform<"u"){const{OS:t,Version:s}=globalThis.Platform;return[t,s].join("-")}const i=ch();if(i===null)return"unknown";const e=i.os?i.os.replace(" ","").toLowerCase():"unknown";return i.type==="browser"?[e,i.name,i.version].join("-"):[e,i.version].join("-")}function $l(){var i;const e=Zi();return e===De.browser?[e,((i=yt.getLocation())==null?void 0:i.host)||"unknown"].join(":"):e}function Ka(i,e,t){const s=Pl(),r=$l();return[[i,e].join("-"),[bl,t].join("-"),s,r].join("/")}function Sl({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Ka(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=Il(h[1]||"",u);return h[0]+"?"+p}function Dt(i,e){return i.filter(t=>e.includes(t)).length===i.length}function Sr(i){return Object.fromEntries(i.entries())}function Or(i){return new Map(Object.entries(i))}function Ct(i=j.FIVE_MINUTES,e){const t=j.toMiliseconds(i||j.FIVE_MINUTES);let s,r,n,o;return{resolve:a=>{n&&s&&(clearTimeout(n),s(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 h=new Error(e);o=Promise.reject(h),c(h)},t),s=a,r=c})}}function _t(i,e,t){return new Promise(async(s,r)=>{const n=setTimeout(()=>r(new Error(t)),e);try{const o=await i;s(o)}catch(o){r(o)}clearTimeout(n)})}function Va(i,e){if(typeof e=="string"&&e.startsWith(`${i}:`))return e;if(i.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(i.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: ${i}`)}function Ol(i){return Va("topic",i)}function xl(i){return Va("id",i)}function Ha(i){const[e,t]=i.split(":"),s={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")s.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))s.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return s}function ce(i,e){return j.fromMiliseconds(Date.now()+j.toMiliseconds(i))}function Et(i){return Date.now()>=j.toMiliseconds(i)}function J(i,e){return`${i}${e?`:${e}`:""}`}function nt(i=[],e=[]){return[...new Set([...i,...e])]}async function Al({id:i,topic:e,wcDeepLink:t}){var s;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r?.href;if(typeof n!="string")return;const o=Tl(n,i,e),a=Zi();if(a===De.browser){if(!((s=yt.getDocument())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Cl(o)}else a===De.reactNative&&typeof globalThis?.Linking<"u"&&await globalThis.Linking.openURL(o)}catch(r){console.error(r)}}function Tl(i,e,t){const s=`requestId=${e}&sessionTopic=${t}`;i.endsWith("/")&&(i=i.slice(0,-1));let r=`${i}`;if(i.startsWith("https://t.me")){const n=i.includes("?")?"&startapp=":"?startapp=";r=`${r}${n}${ql(s,!0)}`}else r=`${r}/wc?${s}`;return r}function Cl(i){let e="_self";jl()?e="_top":(Rl()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Nl(i,e){let t="";try{if(Si()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function kn(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function Dn(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function on(){return typeof Ui<"u"&&ll.IS_VITEST==="true"}function Rl(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function jl(){try{return window.self!==window.top}catch{return!1}}function ql(i,e=!1){const t=Ie.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Fa(i){return Ie.from(i,"base64").toString("utf-8")}function kl(i){return new Promise(e=>setTimeout(e,i))}function Gi(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Dl(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Xi(i,...e){if(!Dl(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function an(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Gi(i.outputLen),Gi(i.blockLen)}function fi(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Ga(i,e){Xi(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ls=BigInt(2**32-1),Ln=BigInt(32);function Ll(i,e=!1){return e?{h:Number(i&ls),l:Number(i>>Ln&ls)}:{h:Number(i>>Ln&ls)|0,l:Number(i&ls)|0}}function Ml(i,e=!1){let t=new Uint32Array(i.length),s=new Uint32Array(i.length);for(let r=0;r<i.length;r++){const{h:n,l:o}=Ll(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Ul=(i,e,t)=>i<<t|e>>>32-t,zl=(i,e,t)=>e<<t|i>>>32-t,Bl=(i,e,t)=>e<<t-32|i>>>64-t,Kl=(i,e,t)=>i<<t-32|e>>>64-t,Gt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Vl(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Xs(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Xe(i,e){return i<<32-e|i>>>e}const Mn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Hl(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Un(i){for(let e=0;e<i.length;e++)i[e]=Hl(i[e])}function Fl(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function mi(i){return typeof i=="string"&&(i=Fl(i)),Xi(i),i}function Gl(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Xi(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}let cn=class{clone(){return this._cloneInto()}};function Wa(i){const e=s=>i().update(mi(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Oi(i=32){if(Gt&&typeof Gt.getRandomValues=="function")return Gt.getRandomValues(new Uint8Array(i));if(Gt&&typeof Gt.randomBytes=="function")return Gt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Ja=[],Qa=[],Ya=[],Wl=BigInt(0),Ci=BigInt(1),Jl=BigInt(2),Ql=BigInt(7),Yl=BigInt(256),Zl=BigInt(113);for(let i=0,e=Ci,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Ja.push(2*(5*s+t)),Qa.push((i+1)*(i+2)/2%64);let r=Wl;for(let n=0;n<7;n++)e=(e<<Ci^(e>>Ql)*Zl)%Yl,e&Jl&&(r^=Ci<<(Ci<<BigInt(n))-Ci);Ya.push(r)}const[Xl,eu]=Ml(Ya,!0),zn=(i,e,t)=>t>32?Bl(i,e,t):Ul(i,e,t),Bn=(i,e,t)=>t>32?Kl(i,e,t):zl(i,e,t);function tu(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=zn(h,l,1)^t[a],p=Bn(h,l,1)^t[a+1];for(let d=0;d<50;d+=10)i[o+d]^=u,i[o+d+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Qa[o],c=zn(r,n,a),h=Bn(r,n,a),l=Ja[o];r=i[l],n=i[l+1],i[l]=c,i[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=Xl[s],i[1]^=eu[s]}t.fill(0)}let iu=class Za extends cn{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Gi(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Vl(this.state)}keccak(){Mn||Un(this.state32),tu(this.state32,this.rounds),Mn||Un(this.state32),this.posOut=0,this.pos=0}update(e){fi(this);const{blockLen:t,state:s}=this;e=mi(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++)s[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:s,blockLen:r}=this;e[s]^=t,(t&128)!==0&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){fi(this,!1),Xi(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-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 Gi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ga(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new Za(t,s,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=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const su=(i,e,t)=>Wa(()=>new iu(e,i,t)),ru=su(1,136,256/8),nu="https://rpc.walletconnect.org/v1";function Xa(i){const e=`Ethereum Signed Message:
|
|
4
4
|
${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+Ie.from(ru(t)).toString("hex")}async function ou(i,e,t,s,r,n){switch(t.t){case"eip191":return await au(i,e,t.s);case"eip1271":return await cu(i,e,t.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function au(i,e,t){return(await hl({hash:Xa(e),signature:t})).toLowerCase()===i.toLowerCase()}async function cu(i,e,t,s,r,n){const o=gi(s);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${s}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",h="0000000000000000000000000000000000000000000000000000000000000041",l=t.substring(2),u=Xa(e).substring(2),p=a+u+c+h+l,d=await fetch(`${n||nu}/?chainId=${s}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:hu(),jsonrpc:"2.0",method:"eth_call",params:[{to:i,data:p},"latest"]})}),{result:g}=await d.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function hu(){return Date.now()+Math.floor(Math.random()*1e3)}function lu(i){const e=atob(i),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const s=t[0];if(s===0)throw new Error("No signatures found");const r=1+s*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=Ie.from(i,"base64").slice(1,65);return ph.encode(n)}var uu=Object.defineProperty,pu=Object.defineProperties,du=Object.getOwnPropertyDescriptors,Kn=Object.getOwnPropertySymbols,gu=Object.prototype.hasOwnProperty,fu=Object.prototype.propertyIsEnumerable,Vn=(i,e,t)=>e in i?uu(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,mu=(i,e)=>{for(var t in e||(e={}))gu.call(e,t)&&Vn(i,t,e[t]);if(Kn)for(var t of Kn(e))fu.call(e,t)&&Vn(i,t,e[t]);return i},yu=(i,e)=>pu(i,du(e));const wu="did:pkh:",hn=i=>i?.split(":"),bu=i=>{const e=i&&hn(i);if(e)return i.includes(wu)?e[3]:e[1]},xr=i=>{const e=i&&hn(i);if(e)return e[2]+":"+e[3]},Ts=i=>{const e=i&&hn(i);if(e)return e.pop()};async function Hn(i){const{cacao:e,projectId:t}=i,{s,p:r}=e,n=ec(r,r.iss),o=Ts(r.iss);return await ou(o,n,s,xr(r.iss),t)}const ec=(i,e)=>{const t=`${i.domain} wants you to sign in with your Ethereum account:`,s=Ts(e);if(!i.aud&&!i.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=i.statement||void 0;const n=`URI: ${i.aud||i.uri}`,o=`Version: ${i.version}`,a=`Chain ID: ${bu(e)}`,c=`Nonce: ${i.nonce}`,h=`Issued At: ${i.iat}`,l=i.exp?`Expiration Time: ${i.exp}`:void 0,u=i.nbf?`Not Before: ${i.nbf}`:void 0,p=i.requestId?`Request ID: ${i.requestId}`:void 0,d=i.resources?`Resources:${i.resources.map(y=>`
|
|
5
5
|
- ${y}`).join("")}`:void 0,g=Es(i.resources);if(g){const y=Wi(g);r=xu(r,y)}return[t,s,"",r,"",n,o,a,c,h,l,u,p,d].filter(y=>y!=null).join(`
|
|
6
6
|
`)};function vu(i){return Ie.from(JSON.stringify(i)).toString("base64")}function Eu(i){return JSON.parse(Ie.from(i,"base64").toString("utf-8"))}function Ut(i){if(!i)throw new Error("No recap provided, value is undefined");if(!i.att)throw new Error("No `att` property found");const e=Object.keys(i.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const s=i.att[t];if(Array.isArray(s))throw new Error(`Resource must be an object: ${t}`);if(typeof s!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(s).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(s).forEach(r=>{const n=s[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 Iu(i,e,t,s={}){return t?.sort((r,n)=>r.localeCompare(n)),{att:{[i]:_u(e,t,s)}}}function _u(i,e,t={}){e=e?.sort((r,n)=>r.localeCompare(n));const s=e.map(r=>({[`${i}/${r}`]:[t]}));return Object.assign({},...s)}function tc(i){return Ut(i),`urn:recap:${vu(i).replace(/=/g,"")}`}function Wi(i){const e=Eu(i.replace("urn:recap:",""));return Ut(e),e}function Pu(i,e,t){const s=Iu(i,e,t);return tc(s)}function $u(i){return i&&i.includes("urn:recap:")}function Su(i,e){const t=Wi(i),s=Wi(e),r=Ou(t,s);return tc(r)}function Ou(i,e){Ut(i),Ut(e);const t=Object.keys(i.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),s={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=i.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,h;s.att[r]=yu(mu({},s.att[r]),{[a]:((c=i.att[r])==null?void 0:c[a])||((h=e.att[r])==null?void 0:h[a])})})}),s}function xu(i="",e){Ut(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(i.includes(t))return i;const s=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,p)=>u.action.localeCompare(p.action));const h={};c.forEach(u=>{h[u.ability]||(h[u.ability]=[]),h[u.ability].push(u.action)});const l=Object.keys(h).map(u=>(r++,`(${r}) '${u}': '${h[u].join("', '")}' for '${a}'.`));s.push(l.join(", ").replace(".,","."))});const n=s.join(" "),o=`${t}${n}`;return`${i?i+" ":""}${o}`}function Fn(i){var e;const t=Wi(i);Ut(t);const s=(e=t.att)==null?void 0:e.eip155;return s?Object.keys(s).map(r=>r.split("/")[1]):[]}function Gn(i){const e=Wi(i);Ut(e);const t=[];return Object.values(e.att).forEach(s=>{Object.values(s).forEach(r=>{var n;(n=r?.[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function Es(i){if(!i)return;const e=i?.[i.length-1];return $u(e)?e:void 0}function er(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function ic(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ke(i,...e){if(!ic(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Wn(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Au(i,e){ke(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Jn(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const Pt=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),Tu=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Cu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Cu)throw new Error("Non little-endian hardware is not supported");function Nu(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function Ar(i){if(typeof i=="string")i=Nu(i);else if(ic(i))i=Tr(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function Ru(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function ju(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}const qu=(i,e)=>{function t(s,...r){if(ke(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?ke(h):ke(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&ke(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");ke(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ke(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(ke(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(h,l)}}}return Object.assign(t,i),t};function Qn(i,e,t=!0){if(e===void 0)return new Uint8Array(i);if(e.length!==i)throw new Error("invalid output length, expected "+i+", got: "+e.length);if(t&&!ku(e))throw new Error("invalid output, must be aligned");return e}function Yn(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n);i.setUint32(e+4,o,s),i.setUint32(e+0,a,s)}function ku(i){return i.byteOffset%4===0}function Tr(i){return Uint8Array.from(i)}function yi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const sc=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),Du=sc("expand 16-byte k"),Lu=sc("expand 32-byte k"),Mu=Pt(Du),Uu=Pt(Lu);function H(i,e){return i<<e|i>>>32-e}function Cr(i){return i.byteOffset%4===0}const us=64,zu=16,rc=2**32-1,Zn=new Uint32Array;function Bu(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(us),l=Pt(h),u=Cr(r)&&Cr(n),p=u?Pt(r):Zn,d=u?Pt(n):Zn;for(let g=0;g<c;o++){if(i(e,t,s,l,o,a),o>=rc)throw new Error("arx: counter overflow");const y=Math.min(us,c-g);if(u&&y===us){const f=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let b=0,w;b<zu;b++)w=f+b,d[w]=p[w]^l[b];g+=us;continue}for(let f=0,b;f<y;f++)b=g+f,n[b]=r[b]^h[f];g+=y}}function Ku(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=Ru({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return er(r),er(o),Jn(n),Jn(t),(a,c,h,l,u=0)=>{ke(a),ke(c),ke(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),ke(l),er(u),u<0||u>=rc)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const d=[];let g=a.length,y,f;if(g===32)d.push(y=Tr(a)),f=Uu;else if(g===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),f=Mu,d.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Cr(c)||d.push(c=Tr(c));const b=Pt(y);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(f,b,Pt(c.subarray(0,16)),b),c=c.subarray(16)}const w=16-r;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){const A=new Uint8Array(12);A.set(c,n?0:12-c.length),c=A,d.push(c)}const P=Pt(c);return Bu(i,f,b,P,h,l,u,o),yi(...d),l}}const fe=(i,e)=>i[e++]&255|(i[e++]&255)<<8;class Vu{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=Ar(e),ke(e,32);const t=fe(e,0),s=fe(e,2),r=fe(e,4),n=fe(e,6),o=fe(e,8),a=fe(e,10),c=fe(e,12),h=fe(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>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|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=fe(e,16+2*l)}process(e,t,s=!1){const r=s?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],u=o[4],p=o[5],d=o[6],g=o[7],y=o[8],f=o[9],b=fe(e,t+0),w=fe(e,t+2),P=fe(e,t+4),A=fe(e,t+6),R=fe(e,t+8),m=fe(e,t+10),E=fe(e,t+12),_=fe(e,t+14);let I=n[0]+(b&8191),C=n[1]+((b>>>13|w<<3)&8191),T=n[2]+((w>>>10|P<<6)&8191),q=n[3]+((P>>>7|A<<9)&8191),M=n[4]+((A>>>4|R<<12)&8191),v=n[5]+(R>>>1&8191),$=n[6]+((R>>>14|m<<2)&8191),x=n[7]+((m>>>11|E<<5)&8191),k=n[8]+((E>>>8|_<<8)&8191),L=n[9]+(_>>>5|r),O=0,D=O+I*a+C*(5*f)+T*(5*y)+q*(5*g)+M*(5*d);O=D>>>13,D&=8191,D+=v*(5*p)+$*(5*u)+x*(5*l)+k*(5*h)+L*(5*c),O+=D>>>13,D&=8191;let U=O+I*c+C*a+T*(5*f)+q*(5*y)+M*(5*g);O=U>>>13,U&=8191,U+=v*(5*d)+$*(5*p)+x*(5*u)+k*(5*l)+L*(5*h),O+=U>>>13,U&=8191;let z=O+I*h+C*c+T*a+q*(5*f)+M*(5*y);O=z>>>13,z&=8191,z+=v*(5*g)+$*(5*d)+x*(5*p)+k*(5*u)+L*(5*l),O+=z>>>13,z&=8191;let W=O+I*l+C*h+T*c+q*a+M*(5*f);O=W>>>13,W&=8191,W+=v*(5*y)+$*(5*g)+x*(5*d)+k*(5*p)+L*(5*u),O+=W>>>13,W&=8191;let V=O+I*u+C*l+T*h+q*c+M*a;O=V>>>13,V&=8191,V+=v*(5*f)+$*(5*y)+x*(5*g)+k*(5*d)+L*(5*p),O+=V>>>13,V&=8191;let ie=O+I*p+C*u+T*l+q*h+M*c;O=ie>>>13,ie&=8191,ie+=v*a+$*(5*f)+x*(5*y)+k*(5*g)+L*(5*d),O+=ie>>>13,ie&=8191;let Y=O+I*d+C*p+T*u+q*l+M*h;O=Y>>>13,Y&=8191,Y+=v*c+$*a+x*(5*f)+k*(5*y)+L*(5*g),O+=Y>>>13,Y&=8191;let ve=O+I*g+C*d+T*p+q*u+M*l;O=ve>>>13,ve&=8191,ve+=v*h+$*c+x*a+k*(5*f)+L*(5*y),O+=ve>>>13,ve&=8191;let oe=O+I*y+C*g+T*d+q*p+M*u;O=oe>>>13,oe&=8191,oe+=v*l+$*h+x*c+k*a+L*(5*f),O+=oe>>>13,oe&=8191;let ae=O+I*f+C*y+T*g+q*d+M*p;O=ae>>>13,ae&=8191,ae+=v*u+$*l+x*h+k*c+L*a,O+=ae>>>13,ae&=8191,O=(O<<2)+O|0,O=O+D|0,D=O&8191,O=O>>>13,U+=O,n[0]=D,n[1]=U,n[2]=z,n[3]=W,n[4]=V,n[5]=ie,n[6]=Y,n[7]=ve,n[8]=oe,n[9]=ae}finalize(){const{h:e,pad:t}=this,s=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,s[0]=e[0]+5,r=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+r,r=s[a]>>>13,s[a]&=8191;s[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)s[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|s[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;yi(s)}update(e){Wn(this);const{buffer:t,blockLen:s}=this;e=Ar(e);const r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o===s){for(;s<=r-n;n+=s)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){yi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Wn(this),Au(e,this),this.finished=!0;const{buffer:t,h:s}=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++]=s[o]>>>0,e[n++]=s[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}}function Hu(i){const e=(s,r)=>i(r).update(Ar(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const Fu=Hu(i=>new Vu(i));function Gu(i,e,t,s,r,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],l=e[0],u=e[1],p=e[2],d=e[3],g=e[4],y=e[5],f=e[6],b=e[7],w=r,P=t[0],A=t[1],R=t[2],m=o,E=a,_=c,I=h,C=l,T=u,q=p,M=d,v=g,$=y,x=f,k=b,L=w,O=P,D=A,U=R;for(let W=0;W<n;W+=2)m=m+C|0,L=H(L^m,16),v=v+L|0,C=H(C^v,12),m=m+C|0,L=H(L^m,8),v=v+L|0,C=H(C^v,7),E=E+T|0,O=H(O^E,16),$=$+O|0,T=H(T^$,12),E=E+T|0,O=H(O^E,8),$=$+O|0,T=H(T^$,7),_=_+q|0,D=H(D^_,16),x=x+D|0,q=H(q^x,12),_=_+q|0,D=H(D^_,8),x=x+D|0,q=H(q^x,7),I=I+M|0,U=H(U^I,16),k=k+U|0,M=H(M^k,12),I=I+M|0,U=H(U^I,8),k=k+U|0,M=H(M^k,7),m=m+T|0,U=H(U^m,16),x=x+U|0,T=H(T^x,12),m=m+T|0,U=H(U^m,8),x=x+U|0,T=H(T^x,7),E=E+q|0,L=H(L^E,16),k=k+L|0,q=H(q^k,12),E=E+q|0,L=H(L^E,8),k=k+L|0,q=H(q^k,7),_=_+M|0,O=H(O^_,16),v=v+O|0,M=H(M^v,12),_=_+M|0,O=H(O^_,8),v=v+O|0,M=H(M^v,7),I=I+C|0,D=H(D^I,16),$=$+D|0,C=H(C^$,12),I=I+C|0,D=H(D^I,8),$=$+D|0,C=H(C^$,7);let z=0;s[z++]=o+m|0,s[z++]=a+E|0,s[z++]=c+_|0,s[z++]=h+I|0,s[z++]=l+C|0,s[z++]=u+T|0,s[z++]=p+q|0,s[z++]=d+M|0,s[z++]=g+v|0,s[z++]=y+$|0,s[z++]=f+x|0,s[z++]=b+k|0,s[z++]=w+L|0,s[z++]=P+O|0,s[z++]=A+D|0,s[z++]=R+U|0}const Wu=Ku(Gu,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Ju=new Uint8Array(16),Xn=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(Ju.subarray(t))},Qu=new Uint8Array(32);function eo(i,e,t,s,r){const n=i(e,t,Qu),o=Fu.create(n);r&&Xn(o,r),Xn(o,s);const a=new Uint8Array(16),c=Tu(a);Yn(c,0,BigInt(r?r.length:0),!0),Yn(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return yi(n,a),h}const Yu=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=Qn(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=eo(i,e,t,a,s);return n.set(c,o),yi(c),n},decrypt(r,n){n=Qn(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=eo(i,e,t,o,s);if(!ju(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),yi(c),n}}),nc=qu({blockSize:64,nonceLength:12,tagLength:16},Yu(Wu));let oc=class extends cn{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,an(e);const s=mi(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(s.length>r?e.create().update(s).digest():s);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 fi(this),this.iHash.update(e),this}digestInto(e){fi(this),Xi(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:s,finished: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=s._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Us=(i,e,t)=>new oc(i,e).update(t).digest();Us.create=(i,e)=>new oc(i,e);function Zu(i,e,t){return an(i),t===void 0&&(t=new Uint8Array(i.outputLen)),Us(i,mi(t),mi(e))}const tr=new Uint8Array([0]),to=new Uint8Array;function Xu(i,e,t,s=32){if(an(i),Gi(s),s>255*i.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(s/i.outputLen);t===void 0&&(t=to);const n=new Uint8Array(r*i.outputLen),o=Us.create(i,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<r;h++)tr[0]=h+1,a.update(h===0?to:c).update(t).update(tr).digestInto(c),n.set(c,i.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),tr.fill(0),n.slice(0,s)}const ep=(i,e,t,s,r)=>Xu(i,Zu(i,e,t),s,r);function tp(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=s?4:0,h=s?0:4;i.setUint32(e+c,o,s),i.setUint32(e+h,a,s)}function ip(i,e,t){return i&e^~i&t}function sp(i,e,t){return i&e^i&t^e&t}let rp=class extends cn{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Xs(this.buffer)}update(e){fi(this);const{view:t,buffer:s,blockLen:r}=this;e=mi(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=Xs(e);for(;r<=n-o;o+=r)this.process(c,o);continue}s.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){fi(this),Ga(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:r,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>r-o&&(this.process(s,0),o=0);for(let u=o;u<r;u++)t[u]=0;tp(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=Xs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:s,length: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(s),e}};const np=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]),bt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),vt=new Uint32Array(64);class op extends rp{constructor(){super(64,32,8,!1),this.A=bt[0]|0,this.B=bt[1]|0,this.C=bt[2]|0,this.D=bt[3]|0,this.E=bt[4]|0,this.F=bt[5]|0,this.G=bt[6]|0,this.H=bt[7]|0}get(){const{A:e,B:t,C:s,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,s,r,n,o,a,c]}set(e,t,s,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=s|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 u=0;u<16;u++,t+=4)vt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=vt[u-15],d=vt[u-2],g=Xe(p,7)^Xe(p,18)^p>>>3,y=Xe(d,17)^Xe(d,19)^d>>>10;vt[u]=y+vt[u-7]+g+vt[u-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const p=Xe(a,6)^Xe(a,11)^Xe(a,25),d=l+p+ip(a,c,h)+np[u]+vt[u]|0,g=(Xe(s,2)^Xe(s,13)^Xe(s,22))+sp(s,r,n)|0;l=h,h=c,c=a,a=o+d|0,o=n,n=r,r=s,s=d+g|0}s=s+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,h=h+this.G|0,l=l+this.H|0,this.set(s,r,n,o,a,c,h,l)}roundClean(){vt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const es=Wa(()=>new op);const zs=BigInt(0),Bs=BigInt(1),ap=BigInt(2);function zt(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ts(i){if(!zt(i))throw new Error("Uint8Array expected")}function wi(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const cp=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function bi(i){ts(i);let e="";for(let t=0;t<i.length;t++)e+=cp[i[t]];return e}function ui(i){const e=i.toString(16);return e.length&1?"0"+e:e}function ln(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?zs:BigInt("0x"+i)}const lt={_0:48,_9:57,A:65,F:70,a:97,f:102};function io(i){if(i>=lt._0&&i<=lt._9)return i-lt._0;if(i>=lt.A&&i<=lt.F)return i-(lt.A-10);if(i>=lt.a&&i<=lt.f)return i-(lt.a-10)}function vi(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const s=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=io(i.charCodeAt(n)),a=io(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}s[r]=o*16+a}return s}function Lt(i){return ln(bi(i))}function Ji(i){return ts(i),ln(bi(Uint8Array.from(i).reverse()))}function Ei(i,e){return vi(i.toString(16).padStart(e*2,"0"))}function Ks(i,e){return Ei(i,e).reverse()}function hp(i){return vi(ui(i))}function qe(i,e,t){let s;if(typeof e=="string")try{s=vi(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(zt(e))s=Uint8Array.from(e);else throw new Error(i+" must be hex string or Uint8Array");const r=s.length;if(typeof t=="number"&&r!==t)throw new Error(i+" of length "+t+" expected, got "+r);return s}function Qi(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];ts(r),e+=r.length}const t=new Uint8Array(e);for(let s=0,r=0;s<i.length;s++){const n=i[s];t.set(n,r),r+=n.length}return t}function lp(i,e){if(i.length!==e.length)return!1;let t=0;for(let s=0;s<i.length;s++)t|=i[s]^e[s];return t===0}function up(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const ir=i=>typeof i=="bigint"&&zs<=i;function Vs(i,e,t){return ir(i)&&ir(e)&&ir(t)&&e<=i&&i<t}function ft(i,e,t,s){if(!Vs(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function ac(i){let e;for(e=0;i>zs;i>>=Bs,e+=1);return e}function pp(i,e){return i>>BigInt(e)&Bs}function dp(i,e,t){return i|(t?Bs:zs)<<BigInt(e)}const un=i=>(ap<<BigInt(i-1))-Bs,sr=i=>new Uint8Array(i),so=i=>Uint8Array.from(i);function cc(i,e,t){if(typeof i!="number"||i<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let s=sr(i),r=sr(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=sr())=>{r=a(so([0]),l),s=a(),l.length!==0&&(r=a(so([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const u=[];for(;l<e;){s=a();const p=s.slice();u.push(p),l+=s.length}return Qi(...u)};return(l,u)=>{o(),c(l);let p;for(;!(p=u(h()));)c();return o(),p}}const gp={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||zt(i),isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function xi(i,e,t={}){const s=(r,n,o)=>{const a=gp[n];if(typeof a!="function")throw new Error("invalid validator function");const c=i[r];if(!(o&&c===void 0)&&!a(c,i))throw new Error("param "+String(r)+" is invalid. Expected "+n+", got "+c)};for(const[r,n]of Object.entries(e))s(r,n,!1);for(const[r,n]of Object.entries(t))s(r,n,!0);return i}const fp=()=>{throw new Error("not implemented")};function Nr(i){const e=new WeakMap;return(t,...s)=>{const r=e.get(t);if(r!==void 0)return r;const n=i(t,...s);return e.set(t,n),n}}var mp=Object.freeze({__proto__:null,isBytes:zt,abytes:ts,abool:wi,bytesToHex:bi,numberToHexUnpadded:ui,hexToNumber:ln,hexToBytes:vi,bytesToNumberBE:Lt,bytesToNumberLE:Ji,numberToBytesBE:Ei,numberToBytesLE:Ks,numberToVarBytesBE:hp,ensureBytes:qe,concatBytes:Qi,equalBytes:lp,utf8ToBytes:up,inRange:Vs,aInRange:ft,bitLen:ac,bitGet:pp,bitSet:dp,bitMask:un,createHmacDrbg:cc,validateObject:xi,notImplemented:fp,memoized:Nr});const ge=BigInt(0),se=BigInt(1),Rt=BigInt(2),yp=BigInt(3),Rr=BigInt(4),ro=BigInt(5),no=BigInt(8);function Ae(i,e){const t=i%e;return t>=ge?t:e+t}function hc(i,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===se)return ge;let s=se;for(;e>ge;)e&se&&(s=s*i%t),i=i*i%t,e>>=se;return s}function We(i,e,t){let s=i;for(;e-- >ge;)s*=s,s%=t;return s}function jr(i,e){if(i===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let t=Ae(i,e),s=e,r=ge,n=se;for(;t!==ge;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==se)throw new Error("invert: does not exist");return Ae(r,e)}function wp(i){const e=(i-se)/Rt;let t,s,r;for(t=i-se,s=0;t%Rt===ge;t/=Rt,s++);for(r=Rt;r<i&&hc(r,e,i)!==i-se;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+se)/Rr;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(t+se)/Rt;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=s,h=o.pow(o.mul(o.ONE,r),t),l=o.pow(a,n),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let p=1;for(let g=o.sqr(u);p<c&&!o.eql(g,o.ONE);p++)g=o.sqr(g);const d=o.pow(h,se<<BigInt(c-p-1));h=o.sqr(d),l=o.mul(l,d),u=o.mul(u,h),c=p}return l}}function bp(i){if(i%Rr===yp){const e=(i+se)/Rr;return function(t,s){const r=t.pow(s,e);if(!t.eql(t.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%no===ro){const e=(i-ro)/no;return function(t,s){const r=t.mul(s,Rt),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Rt),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),s))throw new Error("Cannot find square root");return c}}return wp(i)}const vp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ep(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=vp.reduce((s,r)=>(s[r]="function",s),e);return xi(i,t)}function Ip(i,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return i.ONE;if(t===se)return e;let s=i.ONE,r=e;for(;t>ge;)t&se&&(s=i.mul(s,r)),r=i.sqr(r),t>>=se;return s}function _p(i,e){const t=new Array(e.length),s=e.reduce((n,o,a)=>i.is0(o)?n:(t[a]=n,i.mul(n,o)),i.ONE),r=i.inv(s);return e.reduceRight((n,o,a)=>i.is0(o)?n:(t[a]=i.mul(n,t[a]),i.mul(n,o)),r),t}function lc(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function uc(i,e,t=!1,s={}){if(i<=ge)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=lc(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:r,BYTES:n,MASK:un(r),ZERO:ge,ONE:se,create:c=>Ae(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ge<=c&&c<i},is0:c=>c===ge,isOdd:c=>(c&se)===se,neg:c=>Ae(-c,i),eql:(c,h)=>c===h,sqr:c=>Ae(c*c,i),add:(c,h)=>Ae(c+h,i),sub:(c,h)=>Ae(c-h,i),mul:(c,h)=>Ae(c*h,i),pow:(c,h)=>Ip(a,c,h),div:(c,h)=>Ae(c*jr(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>jr(c,i),sqrt:s.sqrt||(c=>(o||(o=bp(i)),o(a,c))),invertBatch:c=>_p(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?Ks(c,n):Ei(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Ji(c):Lt(c)}});return Object.freeze(a)}function pc(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function dc(i){const e=pc(i);return e+Math.ceil(e/2)}function Pp(i,e,t=!1){const s=i.length,r=pc(e),n=dc(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?Ji(i):Lt(i),a=Ae(o,e-se)+se;return t?Ks(a,r):Ei(a,r)}const oo=BigInt(0),ps=BigInt(1);function rr(i,e){const t=e.negate();return i?t:e}function gc(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function nr(i,e){gc(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function $p(i,e){if(!Array.isArray(i))throw new Error("array expected");i.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function Sp(i,e){if(!Array.isArray(i))throw new Error("array of scalars expected");i.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}const or=new WeakMap,fc=new WeakMap;function ar(i){return fc.get(i)||1}function Op(i,e){return{constTimeNegate:rr,hasPrecomputes(t){return ar(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>oo;)s&ps&&(r=r.add(n)),n=n.double(),s>>=ps;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=nr(s,e),o=[];let a=t,c=a;for(let h=0;h<r;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,s,r){const{windows:n,windowSize:o}=nr(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let p=0;p<n;p++){const d=p*o;let g=Number(r&h);r>>=u,g>o&&(g-=l,r+=ps);const y=d,f=d+Math.abs(g)-1,b=p%2!==0,w=g<0;g===0?c=c.add(rr(b,s[y])):a=a.add(rr(w,s[f]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=nr(t,e),c=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let u=0;u<o;u++){const p=u*a;if(r===oo)break;let d=Number(r&c);if(r>>=l,d>a&&(d-=h,r+=ps),d===0)continue;let g=s[p+Math.abs(d)-1];d<0&&(g=g.negate()),n=n.add(g)}return n},getPrecomputes(t,s,r){let n=or.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&or.set(s,r(n))),n},wNAFCached(t,s,r){const n=ar(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=ar(t);return o===1?this.unsafeLadder(t,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),s,n)},setWindowSize(t,s){gc(s,e),fc.set(t,s),or.delete(t)}}}function xp(i,e,t,s){if($p(t,i),Sp(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=ac(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r),h=Math.floor((e.BITS-1)/o)*o;let l=r;for(let u=h;u>=0;u-=o){c.fill(r);for(let d=0;d<s.length;d++){const g=s[d],y=Number(g>>BigInt(u)&BigInt(a));c[y]=c[y].add(t[d])}let p=r;for(let d=c.length-1,g=r;d>0;d--)g=g.add(c[d]),p=p.add(g);if(l=l.add(p),u!==0)for(let d=0;d<o;d++)l=l.double()}return l}function mc(i){return Ep(i.Fp),xi(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...lc(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Wt=BigInt(0),cr=BigInt(1);function Ap(i){return xi(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function Tp(i){const e=Ap(i),{P:t}=e,s=w=>Ae(w,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(w=>w),c=e.powPminus2||(w=>hc(w,t-BigInt(2),t));function h(w,P,A){const R=s(w*(P-A));return P=s(P-R),A=s(A+R),[P,A]}const l=(e.a-BigInt(2))/BigInt(4);function u(w,P){ft("u",w,Wt,t),ft("scalar",P,Wt,t);const A=P,R=w;let m=cr,E=Wt,_=w,I=cr,C=Wt,T;for(let M=BigInt(r-1);M>=Wt;M--){const v=A>>M&cr;C^=v,T=h(C,m,_),m=T[0],_=T[1],T=h(C,E,I),E=T[0],I=T[1],C=v;const $=m+E,x=s($*$),k=m-E,L=s(k*k),O=x-L,D=_+I,U=_-I,z=s(U*$),W=s(D*k),V=z+W,ie=z-W;_=s(V*V),I=s(R*s(ie*ie)),m=s(x*L),E=s(O*(x+s(l*O)))}T=h(C,m,_),m=T[0],_=T[1],T=h(C,E,I),E=T[0],I=T[1];const q=c(E);return s(m*q)}function p(w){return Ks(s(w),n)}function d(w){const P=qe("u coordinate",w,n);return o===32&&(P[31]&=127),Ji(P)}function g(w){const P=qe("scalar",w),A=P.length;if(A!==n&&A!==o){let R=""+n+" or "+o;throw new Error("invalid scalar, expected "+R+" bytes, got "+A)}return Ji(a(P))}function y(w,P){const A=d(P),R=g(w),m=u(A,R);if(m===Wt)throw new Error("invalid private or public key received");return p(m)}const f=p(e.Gu);function b(w){return y(w,f)}return{scalarMult:y,scalarMultBase:b,getSharedSecret:(w,P)=>y(w,P),getPublicKey:w=>b(w),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:f}}const qr=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Cp=BigInt(1),ao=BigInt(2),Np=BigInt(3),Rp=BigInt(5);BigInt(8);function jp(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=qr,o=i*i%n*i%n,a=We(o,ao,n)*o%n,c=We(a,Cp,n)*i%n,h=We(c,Rp,n)*c%n,l=We(h,e,n)*h%n,u=We(l,t,n)*l%n,p=We(u,s,n)*u%n,d=We(p,r,n)*p%n,g=We(d,r,n)*p%n,y=We(g,e,n)*h%n;return{pow_p_5_8:We(y,ao,n)*i%n,b2:o}}function qp(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const kr=Tp({P:qr,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=qr,{pow_p_5_8:t,b2:s}=jp(i);return Ae(We(t,Np,e)*s,e)},adjustScalarBytes:qp,randomBytes:Oi});function co(i){i.lowS!==void 0&&wi("lowS",i.lowS),i.prehash!==void 0&&wi("prehash",i.prehash)}function kp(i){const e=mc(i);xi(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:s,a:r}=e;if(t){if(!s.eql(r,s.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:Dp,hexToBytes:Lp}=mp;class Mp extends Error{constructor(e=""){super(e)}}const dt={Err:Mp,_tlv:{encode:(i,e)=>{const{Err:t}=dt;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const s=e.length/2,r=ui(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?ui(r.length/2|128):"";return ui(i)+n+r+e},decode(i,e){const{Err:t}=dt;let s=0;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==i)throw new t("tlv.decode: wrong tlv");const r=e[s++],n=!!(r&128);let o=0;if(!n)o=r;else{const c=r&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(s,s+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(s+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(s,s+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+o)}}},_int:{encode(i){const{Err:e}=dt;if(i<gt)throw new e("integer: negative integers are not allowed");let t=ui(i);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(i){const{Err:e}=dt;if(i[0]&128)throw new e("invalid signature integer: negative");if(i[0]===0&&!(i[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Dp(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=dt,r=typeof i=="string"?Lp(i):i;ts(r);const{v:n,l:o}=s.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l}=s.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(i){const{_tlv:e,_int:t}=dt,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},gt=BigInt(0),pe=BigInt(1);BigInt(2);const ho=BigInt(3);BigInt(4);function Up(i){const e=kp(i),{Fp:t}=e,s=uc(e.n,e.nBitLength),r=e.toBytes||((y,f,b)=>{const w=f.toAffine();return Qi(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),n=e.fromBytes||(y=>{const f=y.subarray(1),b=t.fromBytes(f.subarray(0,t.BYTES)),w=t.fromBytes(f.subarray(t.BYTES,2*t.BYTES));return{x:b,y:w}});function o(y){const{a:f,b}=e,w=t.sqr(y),P=t.mul(w,y);return t.add(t.add(P,t.mul(y,f)),b)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Vs(y,pe,e.n)}function c(y){const{allowedPrivateKeyLengths:f,nByteLength:b,wrapPrivateKey:w,n:P}=e;if(f&&typeof y!="bigint"){if(zt(y)&&(y=bi(y)),typeof y!="string"||!f.includes(y.length))throw new Error("invalid private key");y=y.padStart(b*2,"0")}let A;try{A=typeof y=="bigint"?y:Lt(qe("private key",y,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof y)}return w&&(A=Ae(A,P)),ft("private key",A,pe,P),A}function h(y){if(!(y instanceof p))throw new Error("ProjectivePoint expected")}const l=Nr((y,f)=>{const{px:b,py:w,pz:P}=y;if(t.eql(P,t.ONE))return{x:b,y:w};const A=y.is0();f==null&&(f=A?t.ONE:t.inv(P));const R=t.mul(b,f),m=t.mul(w,f),E=t.mul(P,f);if(A)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:R,y:m}}),u=Nr(y=>{if(y.is0()){if(e.allowInfinityPoint&&!t.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:f,y:b}=y.toAffine();if(!t.isValid(f)||!t.isValid(b))throw new Error("bad point: x or y not FE");const w=t.sqr(b),P=o(f);if(!t.eql(w,P))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(f,b,w){if(this.px=f,this.py=b,this.pz=w,f==null||!t.isValid(f))throw new Error("x required");if(b==null||!t.isValid(b))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required");Object.freeze(this)}static fromAffine(f){const{x:b,y:w}=f||{};if(!f||!t.isValid(b)||!t.isValid(w))throw new Error("invalid affine point");if(f instanceof p)throw new Error("projective point not allowed");const P=A=>t.eql(A,t.ZERO);return P(b)&&P(w)?p.ZERO:new p(b,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const b=t.invertBatch(f.map(w=>w.pz));return f.map((w,P)=>w.toAffine(b[P])).map(p.fromAffine)}static fromHex(f){const b=p.fromAffine(n(qe("pointHex",f)));return b.assertValidity(),b}static fromPrivateKey(f){return p.BASE.multiply(c(f))}static msm(f,b){return xp(p,s,f,b)}_setWindowSize(f){g.setWindowSize(this,f)}assertValidity(){u(this)}hasEvenY(){const{y:f}=this.toAffine();if(t.isOdd)return!t.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){h(f);const{px:b,py:w,pz:P}=this,{px:A,py:R,pz:m}=f,E=t.eql(t.mul(b,m),t.mul(A,P)),_=t.eql(t.mul(w,m),t.mul(R,P));return E&&_}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:f,b}=e,w=t.mul(b,ho),{px:P,py:A,pz:R}=this;let m=t.ZERO,E=t.ZERO,_=t.ZERO,I=t.mul(P,P),C=t.mul(A,A),T=t.mul(R,R),q=t.mul(P,A);return q=t.add(q,q),_=t.mul(P,R),_=t.add(_,_),m=t.mul(f,_),E=t.mul(w,T),E=t.add(m,E),m=t.sub(C,E),E=t.add(C,E),E=t.mul(m,E),m=t.mul(q,m),_=t.mul(w,_),T=t.mul(f,T),q=t.sub(I,T),q=t.mul(f,q),q=t.add(q,_),_=t.add(I,I),I=t.add(_,I),I=t.add(I,T),I=t.mul(I,q),E=t.add(E,I),T=t.mul(A,R),T=t.add(T,T),I=t.mul(T,q),m=t.sub(m,I),_=t.mul(T,C),_=t.add(_,_),_=t.add(_,_),new p(m,E,_)}add(f){h(f);const{px:b,py:w,pz:P}=this,{px:A,py:R,pz:m}=f;let E=t.ZERO,_=t.ZERO,I=t.ZERO;const C=e.a,T=t.mul(e.b,ho);let q=t.mul(b,A),M=t.mul(w,R),v=t.mul(P,m),$=t.add(b,w),x=t.add(A,R);$=t.mul($,x),x=t.add(q,M),$=t.sub($,x),x=t.add(b,P);let k=t.add(A,m);return x=t.mul(x,k),k=t.add(q,v),x=t.sub(x,k),k=t.add(w,P),E=t.add(R,m),k=t.mul(k,E),E=t.add(M,v),k=t.sub(k,E),I=t.mul(C,x),E=t.mul(T,v),I=t.add(E,I),E=t.sub(M,I),I=t.add(M,I),_=t.mul(E,I),M=t.add(q,q),M=t.add(M,q),v=t.mul(C,v),x=t.mul(T,x),M=t.add(M,v),v=t.sub(q,v),v=t.mul(C,v),x=t.add(x,v),q=t.mul(M,x),_=t.add(_,q),q=t.mul(k,x),E=t.mul($,E),E=t.sub(E,q),q=t.mul($,M),I=t.mul(k,I),I=t.add(I,q),new p(E,_,I)}subtract(f){return this.add(f.negate())}is0(){return this.equals(p.ZERO)}wNAF(f){return g.wNAFCached(this,f,p.normalizeZ)}multiplyUnsafe(f){const{endo:b,n:w}=e;ft("scalar",f,gt,w);const P=p.ZERO;if(f===gt)return P;if(this.is0()||f===pe)return this;if(!b||g.hasPrecomputes(this))return g.wNAFCachedUnsafe(this,f,p.normalizeZ);let{k1neg:A,k1:R,k2neg:m,k2:E}=b.splitScalar(f),_=P,I=P,C=this;for(;R>gt||E>gt;)R&pe&&(_=_.add(C)),E&pe&&(I=I.add(C)),C=C.double(),R>>=pe,E>>=pe;return A&&(_=_.negate()),m&&(I=I.negate()),I=new p(t.mul(I.px,b.beta),I.py,I.pz),_.add(I)}multiply(f){const{endo:b,n:w}=e;ft("scalar",f,pe,w);let P,A;if(b){const{k1neg:R,k1:m,k2neg:E,k2:_}=b.splitScalar(f);let{p:I,f:C}=this.wNAF(m),{p:T,f:q}=this.wNAF(_);I=g.constTimeNegate(R,I),T=g.constTimeNegate(E,T),T=new p(t.mul(T.px,b.beta),T.py,T.pz),P=I.add(T),A=C.add(q)}else{const{p:R,f:m}=this.wNAF(f);P=R,A=m}return p.normalizeZ([P,A])[0]}multiplyAndAddUnsafe(f,b,w){const P=p.BASE,A=(m,E)=>E===gt||E===pe||!m.equals(P)?m.multiplyUnsafe(E):m.multiply(E),R=A(this,b).add(A(f,w));return R.is0()?void 0:R}toAffine(f){return l(this,f)}isTorsionFree(){const{h:f,isTorsionFree:b}=e;if(f===pe)return!0;if(b)return b(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:b}=e;return f===pe?this:b?b(p,this):this.multiplyUnsafe(e.h)}toRawBytes(f=!0){return wi("isCompressed",f),this.assertValidity(),r(p,this,f)}toHex(f=!0){return wi("isCompressed",f),bi(this.toRawBytes(f))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const d=e.nBitLength,g=Op(p,e.endo?Math.ceil(d/2):d);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function zp(i){const e=mc(i);return xi(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Bp(i){const e=zp(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(v){return Ae(v,s)}function a(v){return jr(v,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=Up({...e,toBytes(v,$,x){const k=$.toAffine(),L=t.toBytes(k.x),O=Qi;return wi("isCompressed",x),x?O(Uint8Array.from([$.hasEvenY()?2:3]),L):O(Uint8Array.from([4]),L,t.toBytes(k.y))},fromBytes(v){const $=v.length,x=v[0],k=v.subarray(1);if($===r&&(x===2||x===3)){const L=Lt(k);if(!Vs(L,pe,t.ORDER))throw new Error("Point is not on curve");const O=l(L);let D;try{D=t.sqrt(O)}catch(z){const W=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+W)}const U=(D&pe)===pe;return(x&1)===1!==U&&(D=t.neg(D)),{x:L,y:D}}else if($===n&&x===4){const L=t.fromBytes(k.subarray(0,t.BYTES)),O=t.fromBytes(k.subarray(t.BYTES,2*t.BYTES));return{x:L,y:O}}else{const L=r,O=n;throw new Error("invalid Point, expected length of "+L+", or uncompressed "+O+", got "+$)}}}),p=v=>bi(Ei(v,e.nByteLength));function d(v){const $=s>>pe;return v>$}function g(v){return d(v)?o(-v):v}const y=(v,$,x)=>Lt(v.slice($,x));class f{constructor($,x,k){this.r=$,this.s=x,this.recovery=k,this.assertValidity()}static fromCompact($){const x=e.nByteLength;return $=qe("compactSignature",$,x*2),new f(y($,0,x),y($,x,2*x))}static fromDER($){const{r:x,s:k}=dt.toSig(qe("DER",$));return new f(x,k)}assertValidity(){ft("r",this.r,pe,s),ft("s",this.s,pe,s)}addRecoveryBit($){return new f(this.r,this.s,$)}recoverPublicKey($){const{r:x,s:k,recovery:L}=this,O=m(qe("msgHash",$));if(L==null||![0,1,2,3].includes(L))throw new Error("recovery id invalid");const D=L===2||L===3?x+e.n:x;if(D>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const U=(L&1)===0?"02":"03",z=c.fromHex(U+p(D)),W=a(D),V=o(-O*W),ie=o(k*W),Y=c.BASE.multiplyAndAddUnsafe(z,V,ie);if(!Y)throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return vi(this.toDERHex())}toDERHex(){return dt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return vi(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const b={isValidPrivateKey(v){try{return h(v),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const v=dc(e.n);return Pp(e.randomBytes(v),e.n)},precompute(v=8,$=c.BASE){return $._setWindowSize(v),$.multiply(BigInt(3)),$}};function w(v,$=!0){return c.fromPrivateKey(v).toRawBytes($)}function P(v){const $=zt(v),x=typeof v=="string",k=($||x)&&v.length;return $?k===r||k===n:x?k===2*r||k===2*n:v instanceof c}function A(v,$,x=!0){if(P(v))throw new Error("first arg must be private key");if(!P($))throw new Error("second arg must be public key");return c.fromHex($).multiply(h(v)).toRawBytes(x)}const R=e.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");const $=Lt(v),x=v.length*8-e.nBitLength;return x>0?$>>BigInt(x):$},m=e.bits2int_modN||function(v){return o(R(v))},E=un(e.nBitLength);function _(v){return ft("num < 2^"+e.nBitLength,v,gt,E),Ei(v,e.nByteLength)}function I(v,$,x=C){if(["recovered","canonical"].some(oe=>oe in x))throw new Error("sign() legacy options not supported");const{hash:k,randomBytes:L}=e;let{lowS:O,prehash:D,extraEntropy:U}=x;O==null&&(O=!0),v=qe("msgHash",v),co(x),D&&(v=qe("prehashed msgHash",k(v)));const z=m(v),W=h($),V=[_(W),_(z)];if(U!=null&&U!==!1){const oe=U===!0?L(t.BYTES):U;V.push(qe("extraEntropy",oe))}const ie=Qi(...V),Y=z;function ve(oe){const ae=R(oe);if(!u(ae))return;const xt=a(ae),at=c.BASE.multiply(ae).toAffine(),Ze=o(at.x);if(Ze===gt)return;const ct=o(xt*o(Y+Ze*W));if(ct===gt)return;let Ht=(at.x===Ze?0:2)|Number(at.y&pe),as=ct;return O&&d(ct)&&(as=g(ct),Ht^=1),new f(Ze,as,Ht)}return{seed:ie,k2sig:ve}}const C={lowS:e.lowS,prehash:!1},T={lowS:e.lowS,prehash:!1};function q(v,$,x=C){const{seed:k,k2sig:L}=I(v,$,x),O=e;return cc(O.hash.outputLen,O.nByteLength,O.hmac)(k,L)}c.BASE._setWindowSize(8);function M(v,$,x,k=T){const L=v;$=qe("msgHash",$),x=qe("publicKey",x);const{lowS:O,prehash:D,format:U}=k;if(co(k),"strict"in k)throw new Error("options.strict was renamed to lowS");if(U!==void 0&&U!=="compact"&&U!=="der")throw new Error("format must be compact or der");const z=typeof L=="string"||zt(L),W=!z&&!U&&typeof L=="object"&&L!==null&&typeof L.r=="bigint"&&typeof L.s=="bigint";if(!z&&!W)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let V,ie;try{if(W&&(V=new f(L.r,L.s)),z){try{U!=="compact"&&(V=f.fromDER(L))}catch(ct){if(!(ct instanceof dt.Err))throw ct}!V&&U!=="der"&&(V=f.fromCompact(L))}ie=c.fromHex(x)}catch{return!1}if(!V||O&&V.hasHighS())return!1;D&&($=e.hash($));const{r:Y,s:ve}=V,oe=m($),ae=a(ve),xt=o(oe*ae),at=o(Y*ae),Ze=c.BASE.multiplyAndAddUnsafe(ie,xt,at)?.toAffine();return Ze?o(Ze.x)===Y:!1}return{CURVE:e,getPublicKey:w,getSharedSecret:A,sign:q,verify:M,ProjectivePoint:c,Signature:f,utils:b}}function Kp(i){return{hash:i,hmac:(e,...t)=>Us(i,e,Gl(...t)),randomBytes:Oi}}function Vp(i,e){const t=s=>Bp({...i,...Kp(s)});return{...t(e),create:t}}const yc=uc(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Hp=yc.create(BigInt("-3")),Fp=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gp=Vp({a:Hp,b:Fp,Fp:yc,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},es),wc="base10",Pe="base16",Je="base64pad",It="base64url",is="utf8",bc=0,mt=1,ss=2,Wp=0,lo=1,Bi=12,pn=32;function Jp(){const i=kr.utils.randomPrivateKey(),e=kr.getPublicKey(i);return{privateKey:Te(i,Pe),publicKey:Te(e,Pe)}}function Dr(){const i=Oi(pn);return Te(i,Pe)}function Qp(i,e){const t=kr.getSharedSecret(Be(i,Pe),Be(e,Pe)),s=ep(es,t,void 0,void 0,pn);return Te(s,Pe)}function Is(i){const e=es(Be(i,Pe));return Te(e,Pe)}function rt(i){const e=es(Be(i,is));return Te(e,Pe)}function vc(i){return Be(`${i}`,wc)}function Bt(i){return Number(Te(i,wc))}function Ec(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ic(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Yp(i){const e=vc(typeof i.type<"u"?i.type:bc);if(Bt(e)===mt&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?Be(i.senderPublicKey,Pe):void 0,s=typeof i.iv<"u"?Be(i.iv,Pe):Oi(Bi),r=Be(i.symKey,Pe),n=nc(r,s).encrypt(Be(i.message,is)),o=_c({type:e,sealed:n,iv:s,senderPublicKey:t});return i.encoding===It?Ec(o):o}function Zp(i){const e=Be(i.symKey,Pe),{sealed:t,iv:s}=Yi({encoded:i.encoded,encoding:i.encoding}),r=nc(e,s).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return Te(r,is)}function Xp(i,e){const t=vc(ss),s=Oi(Bi),r=Be(i,is),n=_c({type:t,sealed:r,iv:s});return e===It?Ec(n):n}function ed(i,e){const{sealed:t}=Yi({encoded:i,encoding:e});return Te(t,is)}function _c(i){if(Bt(i.type)===ss)return Te(zi([i.type,i.sealed]),Je);if(Bt(i.type)===mt){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Te(zi([i.type,i.senderPublicKey,i.iv,i.sealed]),Je)}return Te(zi([i.type,i.iv,i.sealed]),Je)}function Yi(i){const e=(i.encoding||Je)===It?Ic(i.encoded):i.encoded,t=Be(e,Je),s=t.slice(Wp,lo),r=lo;if(Bt(s)===mt){const c=r+pn,h=c+Bi,l=t.slice(r,c),u=t.slice(c,h),p=t.slice(h);return{type:s,sealed:p,iv:u,senderPublicKey:l}}if(Bt(s)===ss){const c=t.slice(r),h=Oi(Bi);return{type:s,sealed:c,iv:h}}const n=r+Bi,o=t.slice(r,n),a=t.slice(n);return{type:s,sealed:a,iv:o}}function td(i,e){const t=Yi({encoded:i,encoding:e?.encoding});return Pc({type:Bt(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Te(t.senderPublicKey,Pe):void 0,receiverPublicKey:e?.receiverPublicKey})}function Pc(i){const e=i?.type||bc;if(e===mt){if(typeof i?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof i?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:i?.senderPublicKey,receiverPublicKey:i?.receiverPublicKey}}function uo(i){return i.type===mt&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function po(i){return i.type===ss}function id(i){const e=Ie.from(i.x,"base64"),t=Ie.from(i.y,"base64");return zi([new Uint8Array([4]),e,t])}function sd(i,e){const[t,s,r]=i.split("."),n=Ie.from(Ic(r),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${t}.${s}`,h=es(c),l=id(e);if(!Gp.verify(zi([o,a]),h,l))throw new Error("Invalid signature");return _r(i).payload}const rd="irn";function Cs(i){return i?.relay||{protocol:rd}}function Li(i){const e=uh[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function nd(i,e="-"){const t={},s="relay"+e;return Object.keys(i).forEach(r=>{if(r.startsWith(s)){const n=r.replace(s,""),o=i[r];t[n]=o}}),t}function go(i){if(!i.includes("wc:")){const h=Fa(i);h!=null&&h.includes("wc:")&&(i=h)}i=i.includes("wc://")?i.replace("wc://",""):i,i=i.includes("wc:")?i.replace("wc:",""):i;const e=i.indexOf(":"),t=i.indexOf("?")!==-1?i.indexOf("?"):void 0,s=i.substring(0,e),r=i.substring(e+1,t).split("@"),n=typeof t<"u"?i.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((h,l)=>{a[l]=h});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:s,topic:od(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:nd(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function od(i){return i.startsWith("//")?i.substring(2):i}function ad(i,e="-"){const t="relay",s={};return Object.keys(i).forEach(r=>{const n=r,o=t+e+n;i[n]&&(s[o]=i[n])}),s}function fo(i){const e=new URLSearchParams,t=ad(i.relay);Object.keys(t).sort().forEach(r=>{e.set(r,t[r])}),e.set("symKey",i.symKey),i.expiryTimestamp&&e.set("expiryTimestamp",i.expiryTimestamp.toString()),i.methods&&e.set("methods",i.methods.join(","));const s=e.toString();return`${i.protocol}:${i.topic}@${i.version}?${s}`}function ds(i,e,t){return`${i}?wc_ev=${t}&topic=${e}`}var cd=Object.defineProperty,hd=Object.defineProperties,ld=Object.getOwnPropertyDescriptors,mo=Object.getOwnPropertySymbols,ud=Object.prototype.hasOwnProperty,pd=Object.prototype.propertyIsEnumerable,yo=(i,e,t)=>e in i?cd(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,dd=(i,e)=>{for(var t in e||(e={}))ud.call(e,t)&&yo(i,t,e[t]);if(mo)for(var t of mo(e))pd.call(e,t)&&yo(i,t,e[t]);return i},gd=(i,e)=>hd(i,ld(e));function Ai(i){const e=[];return i.forEach(t=>{const[s,r]=t.split(":");e.push(`${s}:${r}`)}),e}function fd(i){const e=[];return Object.values(i).forEach(t=>{e.push(...Ai(t.accounts))}),e}function md(i,e){const t=[];return Object.values(i).forEach(s=>{Ai(s.accounts).includes(e)&&t.push(...s.methods)}),t}function yd(i,e){const t=[];return Object.values(i).forEach(s=>{Ai(s.accounts).includes(e)&&t.push(...s.events)}),t}function Hs(i){return i.includes(":")}function pi(i){return Hs(i)?i.split(":")[0]:i}function wo(i){var e,t,s;const r={};if(!$t(i))return r;for(const[n,o]of Object.entries(i)){const a=Hs(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],l=pi(n);r[l]=gd(dd({},r[l]),{chains:nt(a,(e=r[l])==null?void 0:e.chains),methods:nt(c,(t=r[l])==null?void 0:t.methods),events:nt(h,(s=r[l])==null?void 0:s.events)})}return r}function wd(i){const e={};return i?.forEach(t=>{var s;const[r,n]=t.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(t),(s=e[r].chains)==null||s.push(`${r}:${n}`)}),e}function bo(i,e){e=e.map(s=>s.replace("did:pkh:",""));const t=wd(e);for(const[s,r]of Object.entries(t))r.methods?r.methods=nt(r.methods,i):r.methods=i,r.events=["chainChanged","accountsChanged"];return t}function bd(i,e){var t,s,r,n,o,a;const c=wo(i),h=wo(e),l={},u=Object.keys(c).concat(Object.keys(h));for(const p of u)l[p]={chains:nt((t=c[p])==null?void 0:t.chains,(s=h[p])==null?void 0:s.chains),methods:nt((r=c[p])==null?void 0:r.methods,(n=h[p])==null?void 0:n.methods),events:nt((o=c[p])==null?void 0:o.events,(a=h[p])==null?void 0:a.events)};return l}const vd={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}},Ed={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 N(i,e){const{message:t,code:s}=Ed[i];return{message:e?`${t} ${e}`:t,code:s}}function Q(i,e){const{message:t,code:s}=vd[i];return{message:e?`${t} ${e}`:t,code:s}}function Qe(i,e){return!!Array.isArray(i)}function $t(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}function we(i){return typeof i>"u"}function ne(i,e){return e&&we(i)?!0:typeof i=="string"&&!!i.trim().length}function dn(i,e){return e&&we(i)?!0:typeof i=="number"&&!isNaN(i)}function Id(i,e){const{requiredNamespaces:t}=e,s=Object.keys(i.namespaces),r=Object.keys(t);let n=!0;return Dt(r,s)?(s.forEach(o=>{const{accounts:a,methods:c,events:h}=i.namespaces[o],l=Ai(a),u=t[o];(!Dt(za(o,u),l)||!Dt(u.methods,c)||!Dt(u.events,h))&&(n=!1)}),n):!1}function Ns(i){return ne(i,!1)&&i.includes(":")?i.split(":").length===2:!1}function _d(i){if(ne(i,!1)&&i.includes(":")){const e=i.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Ns(t)}}return!1}function Pd(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ne(i,!1)){if(e(i))return!0;const t=Fa(i);return e(t)}}catch{}return!1}function $d(i){var e;return(e=i?.proposer)==null?void 0:e.publicKey}function Sd(i){return i?.topic}function Od(i,e){let t=null;return ne(i?.publicKey,!1)||(t=N("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function vo(i){let e=!0;return Qe(i)?i.length&&(e=i.every(t=>ne(t,!1))):e=!1,e}function xd(i,e,t){let s=null;return Qe(e)&&e.length?e.forEach(r=>{s||Ns(r)||(s=Q("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Ns(i)||(s=Q("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"] }`)),s}function Ad(i,e,t){let s=null;return Object.entries(i).forEach(([r,n])=>{if(s)return;const o=xd(r,za(r,n),`${e} ${t}`);o&&(s=o)}),s}function Td(i,e){let t=null;return Qe(i)?i.forEach(s=>{t||_d(s)||(t=Q("UNSUPPORTED_ACCOUNTS",`${e}, account ${s} should be a string and conform to "namespace:chainId:address" format`))}):t=Q("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function Cd(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=Td(s?.accounts,`${e} namespace`);r&&(t=r)}),t}function Nd(i,e){let t=null;return vo(i?.methods)?vo(i?.events)||(t=Q("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Q("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function $c(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=Nd(s,`${e}, namespace`);r&&(t=r)}),t}function Rd(i,e,t){let s=null;if(i&&$t(i)){const r=$c(i,e);r&&(s=r);const n=Ad(i,e,t);n&&(s=n)}else s=N("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return s}function hr(i,e){let t=null;if(i&&$t(i)){const s=$c(i,e);s&&(t=s);const r=Cd(i,e);r&&(t=r)}else t=N("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Sc(i){return ne(i.protocol,!0)}function jd(i,e){let t=!1;return i?i&&Qe(i)&&i.length&&i.forEach(s=>{t=Sc(s)}):t=!0,t}function qd(i){return typeof i=="number"}function xe(i){return typeof i<"u"&&typeof i!==null}function kd(i){return!(!i||typeof i!="object"||!i.code||!dn(i.code,!1)||!i.message||!ne(i.message,!1))}function Dd(i){return!(we(i)||!ne(i.method,!1))}function Ld(i){return!(we(i)||we(i.result)&&we(i.error)||!dn(i.id,!1)||!ne(i.jsonrpc,!1))}function Md(i){return!(we(i)||!ne(i.name,!1))}function Eo(i,e){return!(!Ns(e)||!fd(i).includes(e))}function Ud(i,e,t){return ne(t,!1)?md(i,e).includes(t):!1}function zd(i,e,t){return ne(t,!1)?yd(i,e).includes(t):!1}function Io(i,e,t){let s=null;const r=Bd(i),n=Kd(e),o=Object.keys(r),a=Object.keys(n),c=_o(Object.keys(i)),h=_o(Object.keys(e)),l=c.filter(u=>!h.includes(u));return l.length&&(s=N("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
|
|
@@ -9,4 +9,4 @@ ${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+Ie.from(ru(t)).toString(
|
|
|
9
9
|
Required: ${o.toString()}
|
|
10
10
|
Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||s)return;const p=Ai(e[u].accounts);p.includes(u)||(s=N("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${u}
|
|
11
11
|
Required: ${u}
|
|
12
|
-
Approved: ${p.toString()}`))}),o.forEach(u=>{s||(Dt(r[u].methods,n[u].methods)?Dt(r[u].events,n[u].events)||(s=N("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=N("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function Bd(i){const e={};return Object.keys(i).forEach(t=>{var s;t.includes(":")?e[t]=i[t]:(s=i[t].chains)==null||s.forEach(r=>{e[r]={methods:i[t].methods,events:i[t].events}})}),e}function _o(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Kd(i){const e={};return Object.keys(i).forEach(t=>{t.includes(":")?e[t]=i[t]:Ai(i[t].accounts)?.forEach(r=>{e[r]={accounts:i[t].accounts.filter(n=>n.includes(`${r}:`)),methods:i[t].methods,events:i[t].events}})}),e}function Vd(i,e){return dn(i,!1)&&i<=e.max&&i>=e.min}function Po(){const i=Zi();return new Promise(e=>{switch(i){case De.browser:e(Hd());break;case De.reactNative:e(Fd());break;case De.node:e(Gd());break;default:e(!0)}})}function Hd(){return Si()&&navigator?.onLine}async function Fd(){return Ot()&&typeof globalThis<"u"&&globalThis!=null&&globalThis.NetInfo?(await globalThis?.NetInfo.fetch())?.isConnected:!0}function Gd(){return!0}function Wd(i){switch(Zi()){case De.browser:Jd(i);break;case De.reactNative:Qd(i);break}}function Jd(i){!Ot()&&Si()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function Qd(i){Ot()&&typeof globalThis<"u"&&globalThis!=null&&globalThis.NetInfo&&globalThis?.NetInfo.addEventListener(e=>i(e?.isConnected))}function Yd(){var i;return Si()&&yt.getDocument()?((i=yt.getDocument())==null?void 0:i.visibilityState)==="visible":!0}const lr={};class Ni{static get(e){return lr[e]}static set(e,t){lr[e]=t}static delete(e){delete lr[e]}}function Zd(i){return!i||typeof i.then!="function"?Promise.resolve(i):i}function ue(i,...e){try{return Zd(i(...e))}catch(t){return Promise.reject(t)}}function Xd(i){const e=typeof i;return i===null||e!=="object"&&e!=="function"}function eg(i){const e=Object.getPrototypeOf(i);return!e||e.isPrototypeOf(Object)}function _s(i){if(Xd(i))return String(i);if(eg(i)||Array.isArray(i))return JSON.stringify(i);if(typeof i.toJSON=="function")return _s(i.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Lr="base64:";function tg(i){return typeof i=="string"?i:Lr+rg(i)}function ig(i){return typeof i!="string"||!i.startsWith(Lr)?i:sg(i.slice(Lr.length))}function sg(i){return globalThis.Buffer?Buffer.from(i,"base64"):Uint8Array.from(globalThis.atob(i),e=>e.codePointAt(0))}function rg(i){return globalThis.Buffer?Buffer.from(i).toString("base64"):globalThis.btoa(String.fromCodePoint(...i))}function Oe(i){return i&&i.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function ng(...i){return Oe(i.join(":"))}function gs(i){return i=Oe(i),i?i+":":""}function og(i,e){if(e===void 0)return!0;let t=0,s=i.indexOf(":");for(;s>-1;)t++,s=i.indexOf(":",s+1);return t<=e}function ag(i,e){return e?i.startsWith(e)&&i[i.length-1]!=="$":i[i.length-1]!=="$"}const cg="memory",hg=()=>{const i=new Map;return{name:cg,getInstance:()=>i,hasItem(e){return i.has(e)},getItem(e){return i.get(e)??null},getItemRaw(e){return i.get(e)??null},setItem(e,t){i.set(e,t)},setItemRaw(e,t){i.set(e,t)},removeItem(e){i.delete(e)},getKeys(){return[...i.keys()]},clear(){i.clear()},dispose(){i.clear()}}};function lg(i={}){const e={mounts:{"":i.driver||hg()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=h=>{for(const l of e.mountpoints)if(h.startsWith(l))return{base:l,relativeKey:h.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:h,driver:e.mounts[""]}},s=(h,l)=>e.mountpoints.filter(u=>u.startsWith(h)||l&&h.startsWith(u)).map(u=>({relativeBase:h.length>u.length?h.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(h,l)=>{if(e.watching){l=Oe(l);for(const u of e.watchListeners)u(h,l)}},n=async()=>{if(!e.watching){e.watching=!0;for(const h in e.mounts)e.unwatch[h]=await $o(e.mounts[h],r,h)}},o=async()=>{if(e.watching){for(const h in e.unwatch)await e.unwatch[h]();e.unwatch={},e.watching=!1}},a=(h,l,u)=>{const p=new Map,d=g=>{let y=p.get(g.base);return y||(y={driver:g.driver,base:g.base,items:[]},p.set(g.base,y)),y};for(const g of h){const y=typeof g=="string",f=Oe(y?g:g.key),b=y?void 0:g.value,w=y||!g.options?l:{...l,...g.options},P=t(f);d(P).items.push({key:f,value:b,relativeKey:P.relativeKey,options:w})}return Promise.all([...p.values()].map(g=>u(g))).then(g=>g.flat())},c={hasItem(h,l={}){h=Oe(h);const{relativeKey:u,driver:p}=t(h);return ue(p.hasItem,u,l)},getItem(h,l={}){h=Oe(h);const{relativeKey:u,driver:p}=t(h);return ue(p.getItem,u,l).then(d=>cs(d))},getItems(h,l={}){return a(h,l,u=>u.driver.getItems?ue(u.driver.getItems,u.items.map(p=>({key:p.relativeKey,options:p.options})),l).then(p=>p.map(d=>({key:ng(u.base,d.key),value:cs(d.value)}))):Promise.all(u.items.map(p=>ue(u.driver.getItem,p.relativeKey,p.options).then(d=>({key:p.key,value:cs(d)})))))},getItemRaw(h,l={}){h=Oe(h);const{relativeKey:u,driver:p}=t(h);return p.getItemRaw?ue(p.getItemRaw,u,l):ue(p.getItem,u,l).then(d=>ig(d))},async setItem(h,l,u={}){if(l===void 0)return c.removeItem(h);h=Oe(h);const{relativeKey:p,driver:d}=t(h);d.setItem&&(await ue(d.setItem,p,_s(l),u),d.watch||r("update",h))},async setItems(h,l){await a(h,l,async u=>{if(u.driver.setItems)return ue(u.driver.setItems,u.items.map(p=>({key:p.relativeKey,value:_s(p.value),options:p.options})),l);u.driver.setItem&&await Promise.all(u.items.map(p=>ue(u.driver.setItem,p.relativeKey,_s(p.value),p.options)))})},async setItemRaw(h,l,u={}){if(l===void 0)return c.removeItem(h,u);h=Oe(h);const{relativeKey:p,driver:d}=t(h);if(d.setItemRaw)await ue(d.setItemRaw,p,l,u);else if(d.setItem)await ue(d.setItem,p,tg(l),u);else return;d.watch||r("update",h)},async removeItem(h,l={}){typeof l=="boolean"&&(l={removeMeta:l}),h=Oe(h);const{relativeKey:u,driver:p}=t(h);p.removeItem&&(await ue(p.removeItem,u,l),(l.removeMeta||l.removeMata)&&await ue(p.removeItem,u+"$",l),p.watch||r("remove",h))},async getMeta(h,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),h=Oe(h);const{relativeKey:u,driver:p}=t(h),d=Object.create(null);if(p.getMeta&&Object.assign(d,await ue(p.getMeta,u,l)),!l.nativeOnly){const g=await ue(p.getItem,u+"$",l).then(y=>cs(y));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(d,g))}return d},setMeta(h,l,u={}){return this.setItem(h+"$",l,u)},removeMeta(h,l={}){return this.removeItem(h+"$",l)},async getKeys(h,l={}){h=gs(h);const u=s(h,!0);let p=[];const d=[];let g=!0;for(const f of u){f.driver.flags?.maxDepth||(g=!1);const b=await ue(f.driver.getKeys,f.relativeBase,l);for(const w of b){const P=f.mountpoint+Oe(w);p.some(A=>P.startsWith(A))||d.push(P)}p=[f.mountpoint,...p.filter(w=>!w.startsWith(f.mountpoint))]}const y=l.maxDepth!==void 0&&!g;return d.filter(f=>(!y||og(f,l.maxDepth))&&ag(f,h))},async clear(h,l={}){h=gs(h),await Promise.all(s(h,!1).map(async u=>{if(u.driver.clear)return ue(u.driver.clear,u.relativeBase,l);if(u.driver.removeItem){const p=await u.driver.getKeys(u.relativeBase||"",l);return Promise.all(p.map(d=>u.driver.removeItem(d,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(h=>So(h)))},async watch(h){return await n(),e.watchListeners.push(h),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==h),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(h,l){if(h=gs(h),h&&e.mounts[h])throw new Error(`already mounted at ${h}`);return h&&(e.mountpoints.push(h),e.mountpoints.sort((u,p)=>p.length-u.length)),e.mounts[h]=l,e.watching&&Promise.resolve($o(l,r,h)).then(u=>{e.unwatch[h]=u}).catch(console.error),c},async unmount(h,l=!0){h=gs(h),!(!h||!e.mounts[h])&&(e.watching&&h in e.unwatch&&(e.unwatch[h]?.(),delete e.unwatch[h]),l&&await So(e.mounts[h]),e.mountpoints=e.mountpoints.filter(u=>u!==h),delete e.mounts[h])},getMount(h=""){h=Oe(h)+":";const l=t(h);return{driver:l.driver,base:l.base}},getMounts(h="",l={}){return h=Oe(h),s(h,l.parents).map(p=>({driver:p.driver,base:p.mountpoint}))},keys:(h,l={})=>c.getKeys(h,l),get:(h,l={})=>c.getItem(h,l),set:(h,l,u={})=>c.setItem(h,l,u),has:(h,l={})=>c.hasItem(h,l),del:(h,l={})=>c.removeItem(h,l),remove:(h,l={})=>c.removeItem(h,l)};return c}function $o(i,e,t){return i.watch?i.watch((s,r)=>e(s,t+r)):()=>{}}async function So(i){typeof i.dispose=="function"&&await ue(i.dispose)}const ug="idb-keyval";var pg=(i={})=>{const e=i.base&&i.base.length>0?`${i.base}:`:"",t=r=>e+r;let s;return i.dbName&&i.storeName&&(s=yh(i.dbName,i.storeName)),{name:ug,options:i,async hasItem(r){return!(typeof await vn(t(r),s)>"u")},async getItem(r){return await vn(t(r),s)??null},setItem(r,n){return Eh(t(r),n,s)},removeItem(r){return vh(t(r),s)},getKeys(){return bh(s)},clear(){return wh(s)}}};const dg="WALLET_CONNECT_V2_INDEXED_DB",gg="keyvaluestorage";let fg=class{constructor(){this.indexedDb=lg({driver:pg({dbName:dg,storeName:gg})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,Hi(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ur=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},Ps={exports:{}};(function(){let i;function e(){}i=e,i.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},i.prototype.setItem=function(t,s){this[t]=String(s)},i.prototype.removeItem=function(t){delete this[t]},i.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(s){t[s]=void 0,delete t[s]})},i.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},i.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ur<"u"&&ur.localStorage?Ps.exports=ur.localStorage:typeof window<"u"&&window.localStorage?Ps.exports=window.localStorage:Ps.exports=new e})();function mg(i){var e;return[i[0],Os((e=i[1])!=null?e:"")]}let yg=class{constructor(){this.localStorage=Ps.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(mg)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return Os(t)}async setItem(e,t){this.localStorage.setItem(e,Hi(t))}async removeItem(e){this.localStorage.removeItem(e)}};const wg="wc_storage_version",Oo=1,bg=async(i,e,t)=>{const s=wg,r=await e.getItem(s);if(r&&r>=Oo){t(e);return}const n=await i.getKeys();if(!n.length){t(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const h=await i.getItem(a);await e.setItem(a,h),o.push(a)}}await e.setItem(s,Oo),t(e),vg(i,o)},vg=async(i,e)=>{e.length&&e.forEach(async t=>{await i.removeItem(t)})};let Eg=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new yg;this.storage=e;try{const t=new fg;bg(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};var pr,xo;function Ig(){if(xo)return pr;xo=1;const i=Ih();pr=r;const e=R().console||{},t={mapHttpRequest:g,mapHttpResponse:g,wrapRequestSerializer:y,wrapResponseSerializer:y,wrapErrorSerializer:y,req:g,res:g,err:p};function s(m,E){return Array.isArray(m)?m.filter(function(I){return I!=="!stdSerializers.err"}):m===!0?Object.keys(E):!1}function r(m){m=m||{},m.browser=m.browser||{};const E=m.browser.transmit;if(E&&typeof E.send!="function")throw Error("pino: transmit option must have a send function");const _=m.browser.write||e;m.browser.write&&(m.browser.asObject=!0);const I=m.serializers||{},C=s(m.browser.serialize,I);let T=m.browser.serialize;Array.isArray(m.browser.serialize)&&m.browser.serialize.indexOf("!stdSerializers.err")>-1&&(T=!1);const q=["error","fatal","warn","info","debug","trace"];typeof _=="function"&&(_.error=_.fatal=_.warn=_.info=_.debug=_.trace=_),m.enabled===!1&&(m.level="silent");const M=m.level||"info",v=Object.create(_);v.log||(v.log=f),Object.defineProperty(v,"levelVal",{get:x}),Object.defineProperty(v,"level",{get:k,set:L});const $={transmit:E,serialize:C,asObject:m.browser.asObject,levels:q,timestamp:d(m)};v.levels=r.levels,v.level=M,v.setMaxListeners=v.getMaxListeners=v.emit=v.addListener=v.on=v.prependListener=v.once=v.prependOnceListener=v.removeListener=v.removeAllListeners=v.listeners=v.listenerCount=v.eventNames=v.write=v.flush=f,v.serializers=I,v._serialize=C,v._stdErrSerialize=T,v.child=O,E&&(v._logEvent=u());function x(){return this.level==="silent"?1/0:this.levels.values[this.level]}function k(){return this._level}function L(D){if(D!=="silent"&&!this.levels.values[D])throw Error("unknown level "+D);this._level=D,n($,v,"error","log"),n($,v,"fatal","error"),n($,v,"warn","error"),n($,v,"info","log"),n($,v,"debug","log"),n($,v,"trace","log")}function O(D,U){if(!D)throw new Error("missing bindings for child Pino");U=U||{},C&&D.serializers&&(U.serializers=D.serializers);const z=U.serializers;if(C&&z){var W=Object.assign({},I,z),V=m.browser.serialize===!0?Object.keys(W):C;delete D.serializers,c([D],V,W,this._stdErrSerialize)}function ie(Y){this._childLevel=(Y._childLevel|0)+1,this.error=h(Y,D,"error"),this.fatal=h(Y,D,"fatal"),this.warn=h(Y,D,"warn"),this.info=h(Y,D,"info"),this.debug=h(Y,D,"debug"),this.trace=h(Y,D,"trace"),W&&(this.serializers=W,this._serialize=V),E&&(this._logEvent=u([].concat(Y._logEvent.bindings,D)))}return ie.prototype=this,new ie(this)}return v}r.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},r.stdSerializers=t,r.stdTimeFunctions=Object.assign({},{nullTime:b,epochTime:w,unixTime:P,isoTime:A});function n(m,E,_,I){const C=Object.getPrototypeOf(E);E[_]=E.levelVal>E.levels.values[_]?f:C[_]?C[_]:e[_]||e[I]||f,o(m,E,_)}function o(m,E,_){!m.transmit&&E[_]===f||(E[_]=(function(I){return function(){const T=m.timestamp(),q=new Array(arguments.length),M=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var v=0;v<q.length;v++)q[v]=arguments[v];if(m.serialize&&!m.asObject&&c(q,this._serialize,this.serializers,this._stdErrSerialize),m.asObject?I.call(M,a(this,_,q,T)):I.apply(M,q),m.transmit){const $=m.transmit.level||E.level,x=r.levels.values[$],k=r.levels.values[_];if(k<x)return;l(this,{ts:T,methodLevel:_,methodValue:k,transmitValue:r.levels.values[m.transmit.level||E.level],send:m.transmit.send,val:E.levelVal},q)}}})(E[_]))}function a(m,E,_,I){m._serialize&&c(_,m._serialize,m.serializers,m._stdErrSerialize);const C=_.slice();let T=C[0];const q={};I&&(q.time=I),q.level=r.levels.values[E];let M=(m._childLevel|0)+1;if(M<1&&(M=1),T!==null&&typeof T=="object"){for(;M--&&typeof C[0]=="object";)Object.assign(q,C.shift());T=C.length?i(C.shift(),C):void 0}else typeof T=="string"&&(T=i(C.shift(),C));return T!==void 0&&(q.msg=T),q}function c(m,E,_,I){for(const C in m)if(I&&m[C]instanceof Error)m[C]=r.stdSerializers.err(m[C]);else if(typeof m[C]=="object"&&!Array.isArray(m[C]))for(const T in m[C])E&&E.indexOf(T)>-1&&T in _&&(m[C][T]=_[T](m[C][T]))}function h(m,E,_){return function(){const I=new Array(1+arguments.length);I[0]=E;for(var C=1;C<I.length;C++)I[C]=arguments[C-1];return m[_].apply(this,I)}}function l(m,E,_){const I=E.send,C=E.ts,T=E.methodLevel,q=E.methodValue,M=E.val,v=m._logEvent.bindings;c(_,m._serialize||Object.keys(m.serializers),m.serializers,m._stdErrSerialize===void 0?!0:m._stdErrSerialize),m._logEvent.ts=C,m._logEvent.messages=_.filter(function($){return v.indexOf($)===-1}),m._logEvent.level.label=T,m._logEvent.level.value=q,I(T,m._logEvent,M),m._logEvent=u(v)}function u(m){return{ts:0,messages:[],bindings:m||[],level:{label:"",value:0}}}function p(m){const E={type:m.constructor.name,msg:m.message,stack:m.stack};for(const _ in m)E[_]===void 0&&(E[_]=m[_]);return E}function d(m){return typeof m.timestamp=="function"?m.timestamp:m.timestamp===!1?b:w}function g(){return{}}function y(m){return m}function f(){}function b(){return!1}function w(){return Date.now()}function P(){return Math.round(Date.now()/1e3)}function A(){return new Date(Date.now()).toISOString()}function R(){function m(E){return typeof E<"u"&&E}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return m(self)||m(window)||m(this)||{}}}return pr}var ci=Ig();const rs=hh(ci),_g={level:"info"},ns="custom_context",gn=1e3*1024;let Pg=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Ao=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new Pg(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;t!==null;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}},Oc=class{constructor(e,t=gn){this.level=e??"error",this.levelValue=ci.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new Ao(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===ci.levels.values.error?console.error(e):t===ci.levels.values.warn?console.warn(e):t===ci.levels.values.debug?console.debug(e):t===ci.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Hi({timestamp:new Date().toISOString(),log:e}));const t=typeof e=="string"?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new Ao(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(Hi({extraMetadata:e})),new Blob(t,{type:"application/json"})}},$g=class{constructor(e,t=gn){this.baseChunkLogger=new Oc(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),s=document.createElement("a");s.href=t,s.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)}},Sg=class{constructor(e,t=gn){this.baseChunkLogger=new Oc(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var Og=Object.defineProperty,xg=Object.defineProperties,Ag=Object.getOwnPropertyDescriptors,To=Object.getOwnPropertySymbols,Tg=Object.prototype.hasOwnProperty,Cg=Object.prototype.propertyIsEnumerable,Co=(i,e,t)=>e in i?Og(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Rs=(i,e)=>{for(var t in e||(e={}))Tg.call(e,t)&&Co(i,t,e[t]);if(To)for(var t of To(e))Cg.call(e,t)&&Co(i,t,e[t]);return i},js=(i,e)=>xg(i,Ag(e));function Fs(i){return js(Rs({},i),{level:i?.level||_g.level})}function Ng(i,e=ns){return i[e]||""}function Rg(i,e,t=ns){return i[t]=e,i}function Ce(i,e=ns){let t="";return typeof i.bindings>"u"?t=Ng(i,e):t=i.bindings().context||"",t}function jg(i,e,t=ns){const s=Ce(i,t);return s.trim()?`${s}/${e}`:e}function $e(i,e,t=ns){const s=jg(i,e,t),r=i.child({context:s});return Rg(r,s,t)}function qg(i){var e,t;const s=new $g((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:rs(js(Rs({},i.opts),{level:"trace",browser:js(Rs({},(t=i.opts)==null?void 0:t.browser),{write:r=>s.write(r)})})),chunkLoggerController:s}}function kg(i){var e;const t=new Sg((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:rs(js(Rs({},i.opts),{level:"trace"}),t),chunkLoggerController:t}}function Dg(i){return typeof i.loggerOverride<"u"&&typeof i.loggerOverride!="string"?{logger:i.loggerOverride,chunkLoggerController:null}:typeof window<"u"?qg(i):kg(i)}var Lg=Object.defineProperty,Mg=(i,e,t)=>e in i?Lg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,No=(i,e,t)=>Mg(i,typeof e!="symbol"?e+"":e,t);let Ug=class extends Ii{constructor(e){super(),this.opts=e,No(this,"protocol","wc"),No(this,"version",2)}};var zg=Object.defineProperty,Bg=(i,e,t)=>e in i?zg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Kg=(i,e,t)=>Bg(i,e+"",t);let Vg=class extends Ii{constructor(e,t){super(),this.core=e,this.logger=t,Kg(this,"records",new Map)}},Hg=class{constructor(e,t){this.logger=e,this.core=t}};class Fg extends Ii{constructor(e,t){super(),this.relayer=e,this.logger=t}}let Gg=class extends Ii{constructor(e){super()}},Wg=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},Jg=class extends Ii{constructor(e,t){super(),this.relayer=e,this.logger=t}},Qg=class extends Ii{constructor(e,t){super(),this.core=e,this.logger=t}},Yg=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},Zg=class{constructor(e,t){this.projectId=e,this.logger=t}},Xg=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var ef=Object.defineProperty,tf=(i,e,t)=>e in i?ef(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ro=(i,e,t)=>tf(i,typeof e!="symbol"?e+"":e,t);let sf=class{constructor(e){this.opts=e,Ro(this,"protocol","wc"),Ro(this,"version",2)}},rf=class{constructor(e){this.client=e}};var nf={};const xc="wc",Ac=2,Mr="core",ot=`${xc}@2:${Mr}:`,of={logger:"error"},af={database:":memory:"},cf="crypto",jo="client_ed25519_seed",hf=j.ONE_DAY,lf="keychain",uf="0.3",pf="messages",df="0.3",qo=j.SIX_HOURS,gf="publisher",Tc="irn",ff="error",Cc="wss://relay.walletconnect.org",mf="relayer",de={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"},yf="_subscription",Me={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},wf=.1,Ur="2.21.1",te={link_mode:"link_mode",relay:"relay"},$s={inbound:"inbound",outbound:"outbound"},bf="0.3",vf="WALLETCONNECT_CLIENT_ID",ko="WALLETCONNECT_LINK_MODE_APPS",je={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Ef="subscription",If="0.3",_f="pairing",Pf="0.3",Ri={wc_pairingDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:j.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:j.ONE_DAY,prompt:!1,tag:0},res:{ttl:j.ONE_DAY,prompt:!1,tag:0}}},jt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},He={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},$f="history",Sf="0.3",Of="expirer",ze={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},xf="0.3",Af="verify-api",Tf="https://verify.walletconnect.com",Nc="https://verify.walletconnect.org",Ki=Nc,Cf=`${Ki}/v3`,Nf=[Tf,Nc],Rf="echo",jf="https://echo.walletconnect.com",it={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"},pt={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"},Fe={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"},At={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"},Tt={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"},ji={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"},qf=.1,kf="event-client",Df=86400,Lf="https://pulse.walletconnect.org/batch";function Mf(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var r=0;r<i.length;r++){var n=i.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,f=0,b=0,w=g.length;b!==w&&g[b]===0;)b++,y++;for(var P=(w-b)*l+1>>>0,A=new Uint8Array(P);b!==w;){for(var R=g[b],m=0,E=P-1;(R!==0||m<f)&&E!==-1;E--,m++)R+=256*A[E]>>>0,A[E]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");f=m,b++}for(var _=P-f;_!==P&&A[_]===0;)_++;for(var I=c.repeat(y);_<P;++_)I+=i.charAt(A[_]);return I}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var f=0,b=0;g[y]===c;)f++,y++;for(var w=(g.length-y)*h+1>>>0,P=new Uint8Array(w);g[y];){var A=t[g.charCodeAt(y)];if(A===255)return;for(var R=0,m=w-1;(A!==0||R<b)&&m!==-1;m--,R++)A+=a*P[m]>>>0,P[m]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");b=R,y++}if(g[y]!==" "){for(var E=w-b;E!==w&&P[E]===0;)E++;for(var _=new Uint8Array(f+(w-E)),I=f;E!==w;)_[I++]=P[E++];return _}}}function d(g){var y=p(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:d}}var Uf=Mf,zf=Uf;const Rc=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},Bf=i=>new TextEncoder().encode(i),Kf=i=>new TextDecoder().decode(i);class Vf{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Hf{constructor(e,t,s){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=s}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 jc(this,e)}}class Ff{constructor(e){this.decoders=e}or(e){return jc(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const jc=(i,e)=>new Ff({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Gf{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Vf(e,t,s),this.decoder=new Hf(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Gs=({name:i,prefix:e,encode:t,decode:s})=>new Gf(i,e,t,s),os=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=zf(t,e);return Gs({prefix:i,name:e,encode:s,decode:n=>Rc(r(n))})},Wf=(i,e,t,s)=>{const r={};for(let l=0;l<e.length;++l)r[e[l]]=l;let n=i.length;for(;i[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const u=r[i[l]];if(u===void 0)throw new SyntaxError(`Non-${s} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Jf=(i,e,t)=>{const s=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),s)for(;n.length*t&7;)n+="=";return n},be=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>Gs({prefix:e,name:i,encode(r){return Jf(r,s,t)},decode(r){return Wf(r,s,t,i)}}),Qf=Gs({prefix:"\0",name:"identity",encode:i=>Kf(i),decode:i=>Bf(i)});var Yf=Object.freeze({__proto__:null,identity:Qf});const Zf=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Xf=Object.freeze({__proto__:null,base2:Zf});const em=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var tm=Object.freeze({__proto__:null,base8:em});const im=os({prefix:"9",name:"base10",alphabet:"0123456789"});var sm=Object.freeze({__proto__:null,base10:im});const rm=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),nm=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var om=Object.freeze({__proto__:null,base16:rm,base16upper:nm});const am=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),cm=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hm=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lm=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),um=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pm=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dm=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gm=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fm=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mm=Object.freeze({__proto__:null,base32:am,base32upper:cm,base32pad:hm,base32padupper:lm,base32hex:um,base32hexupper:pm,base32hexpad:dm,base32hexpadupper:gm,base32z:fm});const ym=os({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wm=os({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var bm=Object.freeze({__proto__:null,base36:ym,base36upper:wm});const vm=os({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Em=os({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Im=Object.freeze({__proto__:null,base58btc:vm,base58flickr:Em});const _m=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Pm=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$m=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Sm=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Om=Object.freeze({__proto__:null,base64:_m,base64pad:Pm,base64url:$m,base64urlpad:Sm});const qc=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),xm=qc.reduce((i,e,t)=>(i[t]=e,i),[]),Am=qc.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Tm(i){return i.reduce((e,t)=>(e+=xm[t],e),"")}function Cm(i){const e=[];for(const t of i){const s=Am[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Nm=Gs({prefix:"🚀",name:"base256emoji",encode:Tm,decode:Cm});var Rm=Object.freeze({__proto__:null,base256emoji:Nm}),jm=kc,Do=128,qm=-128,km=Math.pow(2,31);function kc(i,e,t){e=e||[],t=t||0;for(var s=t;i>=km;)e[t++]=i&255|Do,i/=128;for(;i&qm;)e[t++]=i&255|Do,i>>>=7;return e[t]=i|0,kc.bytes=t-s+1,e}var Dm=zr,Lm=128,Lo=127;function zr(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw zr.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&Lo)<<r:(o&Lo)*Math.pow(2,r),r+=7}while(o>=Lm);return zr.bytes=n-s,t}var Mm=Math.pow(2,7),Um=Math.pow(2,14),zm=Math.pow(2,21),Bm=Math.pow(2,28),Km=Math.pow(2,35),Vm=Math.pow(2,42),Hm=Math.pow(2,49),Fm=Math.pow(2,56),Gm=Math.pow(2,63),Wm=function(i){return i<Mm?1:i<Um?2:i<zm?3:i<Bm?4:i<Km?5:i<Vm?6:i<Hm?7:i<Fm?8:i<Gm?9:10},Jm={encode:jm,decode:Dm,encodingLength:Wm},Dc=Jm;const Mo=(i,e,t=0)=>(Dc.encode(i,e,t),e),Uo=i=>Dc.encodingLength(i),Br=(i,e)=>{const t=e.byteLength,s=Uo(i),r=s+Uo(t),n=new Uint8Array(r+t);return Mo(i,n,0),Mo(t,n,s),n.set(e,r),new Qm(i,t,e,n)};class Qm{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Lc=({name:i,code:e,encode:t})=>new Ym(i,e,t);class Ym{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Br(this.code,t):t.then(s=>Br(this.code,s))}else throw Error("Unknown type, must be binary type")}}const Mc=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Zm=Lc({name:"sha2-256",code:18,encode:Mc("SHA-256")}),Xm=Lc({name:"sha2-512",code:19,encode:Mc("SHA-512")});var ey=Object.freeze({__proto__:null,sha256:Zm,sha512:Xm});const Uc=0,ty="identity",zc=Rc,iy=i=>Br(Uc,zc(i)),sy={code:Uc,name:ty,encode:zc,digest:iy};var ry=Object.freeze({__proto__:null,identity:sy});new TextEncoder,new TextDecoder;const zo={...Yf,...Xf,...tm,...sm,...om,...mm,...bm,...Im,...Om,...Rm};({...ey,...ry});function ny(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Bc(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Bo=Bc("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),dr=Bc("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=ny(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),oy={utf8:Bo,"utf-8":Bo,hex:zo.base16,latin1:dr,ascii:dr,binary:dr,...zo};function ay(i,e="utf8"){const t=oy[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(i,"utf8"):t.decoder.decode(`${t.prefix}${i}`)}var cy=Object.defineProperty,hy=(i,e,t)=>e in i?cy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,et=(i,e,t)=>hy(i,typeof e!="symbol"?e+"":e,t);class ly{constructor(e,t){this.core=e,this.logger=t,et(this,"keychain",new Map),et(this,"name",lf),et(this,"version",uf),et(this,"initialized",!1),et(this,"storagePrefix",ot),et(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),et(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),et(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),et(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),et(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Sr(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Or(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var uy=Object.defineProperty,py=(i,e,t)=>e in i?uy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,me=(i,e,t)=>py(i,typeof e!="symbol"?e+"":e,t);class dy{constructor(e,t,s){this.core=e,this.logger=t,me(this,"name",cf),me(this,"keychain"),me(this,"randomSessionIdentifier",Dr()),me(this,"initialized",!1),me(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),me(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),me(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=bn(r);return fh(n.publicKey)}),me(this,"generateKeyPair",()=>{this.isInitialized();const r=Jp();return this.setPrivateKey(r.publicKey,r.privateKey)}),me(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=bn(n),a=this.randomSessionIdentifier;return await mh(a,r,hf,o)}),me(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Qp(a,n);return this.setSymKey(c,o)}),me(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||Is(r);return await this.keychain.set(o,r),o}),me(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),me(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),me(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Pc(o),c=Hi(n);if(po(a))return Xp(c,o?.encoding);if(uo(a)){const p=a.senderPublicKey,d=a.receiverPublicKey;r=await this.generateSharedKey(p,d)}const h=this.getSymKey(r),{type:l,senderPublicKey:u}=a;return Yp({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o?.encoding})}),me(this,"decode",async(r,n,o)=>{this.isInitialized();const a=td(n,o);if(po(a)){const c=ed(n,o?.encoding);return Os(c)}if(uo(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Zp({symKey:c,encoded:n,encoding:o?.encoding});return Os(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),me(this,"getPayloadType",(r,n=Je)=>{const o=Yi({encoded:r,encoding:n});return Bt(o.type)}),me(this,"getPayloadSenderPublicKey",(r,n=Je)=>{const o=Yi({encoded:r,encoding:n});return o.senderPublicKey?Te(o.senderPublicKey,Pe):void 0}),this.core=e,this.logger=$e(t,this.name),this.keychain=s||new ly(this.core,this.logger)}get context(){return Ce(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(jo)}catch{e=Dr(),await this.keychain.set(jo,e)}return ay(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var gy=Object.defineProperty,fy=Object.defineProperties,my=Object.getOwnPropertyDescriptors,Ko=Object.getOwnPropertySymbols,yy=Object.prototype.hasOwnProperty,wy=Object.prototype.propertyIsEnumerable,Kr=(i,e,t)=>e in i?gy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,by=(i,e)=>{for(var t in e||(e={}))yy.call(e,t)&&Kr(i,t,e[t]);if(Ko)for(var t of Ko(e))wy.call(e,t)&&Kr(i,t,e[t]);return i},vy=(i,e)=>fy(i,my(e)),Ne=(i,e,t)=>Kr(i,typeof e!="symbol"?e+"":e,t);class Ey extends Hg{constructor(e,t){super(e,t),this.logger=e,this.core=t,Ne(this,"messages",new Map),Ne(this,"messagesWithoutClientAck",new Map),Ne(this,"name",pf),Ne(this,"version",df),Ne(this,"initialized",!1),Ne(this,"storagePrefix",ot),Ne(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const s=await this.getRelayerMessages();typeof s<"u"&&(this.messages=s);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(s){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(s)}finally{this.initialized=!0}}}),Ne(this,"set",async(s,r,n)=>{this.isInitialized();const o=rt(r);let a=this.messages.get(s);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(s,a),n===$s.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,vy(by({},c),{[o]:r}))}return await this.persist(),o}),Ne(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Ne(this,"getWithoutAck",s=>{this.isInitialized();const r={};for(const n of s){const o=this.messagesWithoutClientAck.get(n)||{};r[n]=Object.values(o)}return r}),Ne(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=rt(r);return typeof n[o]<"u"}),Ne(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=rt(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Ne(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=$e(e,this.name),this.core=t}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Sr(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Sr(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Or(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Or(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Iy=Object.defineProperty,_y=Object.defineProperties,Py=Object.getOwnPropertyDescriptors,Vo=Object.getOwnPropertySymbols,$y=Object.prototype.hasOwnProperty,Sy=Object.prototype.propertyIsEnumerable,Vr=(i,e,t)=>e in i?Iy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,fs=(i,e)=>{for(var t in e||(e={}))$y.call(e,t)&&Vr(i,t,e[t]);if(Vo)for(var t of Vo(e))Sy.call(e,t)&&Vr(i,t,e[t]);return i},gr=(i,e)=>_y(i,Py(e)),Ge=(i,e,t)=>Vr(i,typeof e!="symbol"?e+"":e,t);class Oy extends Fg{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Ge(this,"events",new St.EventEmitter),Ge(this,"name",gf),Ge(this,"queue",new Map),Ge(this,"publishTimeout",j.toMiliseconds(j.ONE_MINUTE)),Ge(this,"initialPublishTimeout",j.toMiliseconds(j.ONE_SECOND*15)),Ge(this,"needsTransportRestart",!1),Ge(this,"publish",async(s,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:s,message:r,opts:n}});const a=n?.ttl||qo,c=Cs(n),h=n?.prompt||!1,l=n?.tag||0,u=n?.id||li().toString(),p={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}},d=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const g=new Promise(async y=>{const f=({id:w})=>{p.opts.id===w&&(this.removeRequestFromQueue(w),this.relayer.events.removeListener(de.publish,f),y(p))};this.relayer.events.on(de.publish,f);const b=_t(new Promise((w,P)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}).then(w).catch(A=>{this.logger.warn(A,A?.message),P(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await b,this.events.removeListener(de.publish,f)}catch(w){this.queue.set(u,gr(fs({},p),{attempt:1})),this.logger.warn(w,w?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await _t(g,this.publishTimeout,d)}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(u)}}),Ge(this,"on",(s,r)=>{this.events.on(s,r)}),Ge(this,"once",(s,r)=>{this.events.once(s,r)}),Ge(this,"off",(s,r)=>{this.events.off(s,r)}),Ge(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=$e(t,this.name),this.registerEventListeners()}get context(){return Ce(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=qo,prompt:h,tag:l,id:u,attestation:p,tvf:d}=e,g={method:Li(Cs().protocol).publish,params:fs({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},d),id:u};we((t=g.params)==null?void 0:t.prompt)&&((s=g.params)==null||delete s.prompt),we((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 y=await this.relayer.request(g);return this.relayer.events.emit(de.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,gr(fs({},e),{attempt:s}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${s}`),await this.rpcPublish(gr(fs({},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(_i.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(de.connection_stalled);return}this.checkQueue()}),this.relayer.on(de.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var xy=Object.defineProperty,Ay=(i,e,t)=>e in i?xy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Jt=(i,e,t)=>Ay(i,typeof e!="symbol"?e+"":e,t);class Ty{constructor(){Jt(this,"map",new Map),Jt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),Jt(this,"get",e=>this.map.get(e)||[]),Jt(this,"exists",(e,t)=>this.get(e).includes(t)),Jt(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const r=s.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),Jt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Cy=Object.defineProperty,Ny=Object.defineProperties,Ry=Object.getOwnPropertyDescriptors,Ho=Object.getOwnPropertySymbols,jy=Object.prototype.hasOwnProperty,qy=Object.prototype.propertyIsEnumerable,Hr=(i,e,t)=>e in i?Cy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qi=(i,e)=>{for(var t in e||(e={}))jy.call(e,t)&&Hr(i,t,e[t]);if(Ho)for(var t of Ho(e))qy.call(e,t)&&Hr(i,t,e[t]);return i},fr=(i,e)=>Ny(i,Ry(e)),Z=(i,e,t)=>Hr(i,typeof e!="symbol"?e+"":e,t);class ky extends Jg{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Z(this,"subscriptions",new Map),Z(this,"topicMap",new Ty),Z(this,"events",new St.EventEmitter),Z(this,"name",Ef),Z(this,"version",If),Z(this,"pending",new Map),Z(this,"cached",[]),Z(this,"initialized",!1),Z(this,"storagePrefix",ot),Z(this,"subscribeTimeout",j.toMiliseconds(j.ONE_MINUTE)),Z(this,"initialSubscribeTimeout",j.toMiliseconds(j.ONE_SECOND*15)),Z(this,"clientId"),Z(this,"batchSubscribeTopicsLimit",500),Z(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Z(this,"subscribe",async(s,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:r}});try{const n=Cs(r),o={topic:s,relay:n,transportType:r?.transportType};this.pending.set(s,o);const a=await this.rpcSubscribe(s,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:s,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),Z(this,"unsubscribe",async(s,r)=>{this.isInitialized(),typeof r?.id<"u"?await this.unsubscribeById(s,r.id,r):await this.unsubscribeByTopic(s,r)}),Z(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),Z(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),Z(this,"on",(s,r)=>{this.events.on(s,r)}),Z(this,"once",(s,r)=>{this.events.once(s,r)}),Z(this,"off",(s,r)=>{this.events.off(s,r)}),Z(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),Z(this,"start",async()=>{await this.onConnect()}),Z(this,"stop",async()=>{await this.onDisconnect()}),Z(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Z(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const s=[];this.pending.forEach(r=>{s.push(r)}),await this.batchSubscribe(s)}),Z(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(_i.pulse,async()=>{await this.checkPending()}),this.events.on(je.created,async s=>{const r=je.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(je.deleted,async s=>{const r=je.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=$e(t,this.name),this.clientId=""}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const r=Cs(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Q("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:s}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,s){var r;(!s||s?.transportType===te.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Li(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=s?.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(s?.transportType===te.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},j.toMiliseconds(j.ONE_SECOND)),a;const c=new Promise(async l=>{const u=p=>{p.topic===e&&(this.events.removeListener(je.created,u),l(p.id))};this.events.on(je.created,u);try{const p=await _t(new Promise((d,g)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(je.created,u),l(p)}catch{}}),h=await _t(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(de.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Li(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await _t(new Promise(r=>{this.relayer.request(s).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Li(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let r;try{r=await await _t(new Promise((n,o)=>{this.relayer.request(s).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Li(s.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,fr(qi({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,qi({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,qi({},t)),this.topicMap.set(t.topic,e),this.events.emit(je.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:s}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(je.deleted,fr(qi({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(je.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s<t;s++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(je.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=N("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=>fr(qi({},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 kl(j.toMiliseconds(j.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}=N("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 rt(e+await this.getClientId())}}var Dy=Object.defineProperty,Fo=Object.getOwnPropertySymbols,Ly=Object.prototype.hasOwnProperty,My=Object.prototype.propertyIsEnumerable,Fr=(i,e,t)=>e in i?Dy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Go=(i,e)=>{for(var t in e||(e={}))Ly.call(e,t)&&Fr(i,t,e[t]);if(Fo)for(var t of Fo(e))My.call(e,t)&&Fr(i,t,e[t]);return i},F=(i,e,t)=>Fr(i,typeof e!="symbol"?e+"":e,t);class Uy extends Gg{constructor(e){super(e),F(this,"protocol","wc"),F(this,"version",2),F(this,"core"),F(this,"logger"),F(this,"events",new St.EventEmitter),F(this,"provider"),F(this,"messages"),F(this,"subscriber"),F(this,"publisher"),F(this,"name",mf),F(this,"transportExplicitlyClosed",!1),F(this,"initialized",!1),F(this,"connectionAttemptInProgress",!1),F(this,"relayUrl"),F(this,"projectId"),F(this,"packageName"),F(this,"bundleId"),F(this,"hasExperiencedNetworkDisruption",!1),F(this,"pingTimeout"),F(this,"heartBeatTimeout",j.toMiliseconds(j.THIRTY_SECONDS+j.FIVE_SECONDS)),F(this,"reconnectTimeout"),F(this,"connectPromise"),F(this,"reconnectInProgress",!1),F(this,"requestsInFlight",[]),F(this,"connectTimeout",j.toMiliseconds(j.ONE_SECOND*15)),F(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||li().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(s=t.params)==null?void 0:s.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}}),F(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,s,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(s=(t=this.provider)==null?void 0:t.connection)==null?void 0:s.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),F(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),F(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(de.connect)}),F(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),F(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(de.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),F(this,"registerProviderListeners",()=>{this.provider.on(Me.payload,this.onPayloadHandler),this.provider.on(Me.connect,this.onConnectHandler),this.provider.on(Me.disconnect,this.onDisconnectHandler),this.provider.on(Me.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?$e(e.logger,this.name):rs(Fs({level:e.logger||ff})),this.messages=new Ey(this.logger,e.core),this.subscriber=new ky(this,this.logger),this.publisher=new Oy(this,this.logger),this.relayUrl=e?.relayUrl||Cc,this.projectId=e.projectId,vl()?this.packageName=qn():El()&&(this.bundleId=qn()),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 Ce(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1||!1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:te.relay},$s.outbound)}async subscribe(e,t){var s,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((s=t?.internal)==null?void 0:s.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 h=l=>{l.topic===e&&(this.subscriber.off(je.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(je.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,Go({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&u(p)})||a,l()})]),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 _t(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,s)=>{await this.connect(e).then(t).catch(s).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}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 Po())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((s,r)=>s.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const s of t)try{await this.onMessageEvent(s)}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:s}=e;if(!t.sessionExists){const r=ce(j.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(de.message,e),await this.recordMessageEvent(e,$s.inbound)}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(s,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Me.disconnect,n),await _t(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(Me.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(Me.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Me.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,s()})}catch(s){await this.subscriber.stop();const r=s;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(s=>setTimeout(s,j.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(As())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(s=this.provider)==null?void 0:s.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 Ke(new gh(Sl({sdkVersion:Ur,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:s,message:r}=e;await this.messages.set(s,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||s.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,s);return r&&this.logger.warn(`Ignoring duplicate message: ${s}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),sn(e)){if(!e.method.endsWith(yf))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:te.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Go({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else rn(e)&&this.events.emit(de.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,$s.inbound),this.events.emit(de.message,e))}async acknowledgePayload(e){const t=Ls(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Me.payload,this.onPayloadHandler),this.provider.off(Me.connect,this.onConnectHandler),this.provider.off(Me.disconnect,this.onDisconnectHandler),this.provider.off(Me.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Po();Wd(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(_i.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Yd())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(de.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},j.toMiliseconds(wf)))))}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function zy(){}function Wo(i){if(!i||typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(i)==="[object Object]":!1}function Jo(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Qo(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const By="[object RegExp]",Ky="[object String]",Vy="[object Number]",Hy="[object Boolean]",Yo="[object Arguments]",Fy="[object Symbol]",Gy="[object Date]",Wy="[object Map]",Jy="[object Set]",Qy="[object Array]",Yy="[object Function]",Zy="[object ArrayBuffer]",mr="[object Object]",Xy="[object Error]",ew="[object DataView]",tw="[object Uint8Array]",iw="[object Uint8ClampedArray]",sw="[object Uint16Array]",rw="[object Uint32Array]",nw="[object BigUint64Array]",ow="[object Int8Array]",aw="[object Int16Array]",cw="[object Int32Array]",hw="[object BigInt64Array]",lw="[object Float32Array]",uw="[object Float64Array]";function pw(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function dw(i,e,t){return Mi(i,e,void 0,void 0,void 0,void 0,t)}function Mi(i,e,t,s,r,n,o){const a=o(i,e,t,s,r,n);if(a!==void 0)return a;if(typeof i==typeof e)switch(typeof i){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return i===e;case"number":return i===e||Object.is(i,e);case"function":return i===e;case"object":return Vi(i,e,n,o)}return Vi(i,e,n,o)}function Vi(i,e,t,s){if(Object.is(i,e))return!0;let r=Qo(i),n=Qo(e);if(r===Yo&&(r=mr),n===Yo&&(n=mr),r!==n)return!1;switch(r){case Ky:return i.toString()===e.toString();case Vy:{const c=i.valueOf(),h=e.valueOf();return pw(c,h)}case Hy:case Gy:case Fy:return Object.is(i.valueOf(),e.valueOf());case By:return i.source===e.source&&i.flags===e.flags;case Yy:return i===e}t=t??new Map;const o=t.get(i),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(i,e),t.set(e,i);try{switch(r){case Wy:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!Mi(h,e.get(c),c,i,e,t,s))return!1;return!0}case Jy:{if(i.size!==e.size)return!1;const c=Array.from(i.values()),h=Array.from(e.values());for(let l=0;l<c.length;l++){const u=c[l],p=h.findIndex(d=>Mi(u,d,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case Qy:case tw:case iw:case sw:case rw:case nw:case ow:case aw:case cw:case hw:case lw:case uw:{if(typeof Ie<"u"&&Ie.isBuffer(i)!==Ie.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!Mi(i[c],e[c],c,i,e,t,s))return!1;return!0}case Zy:return i.byteLength!==e.byteLength?!1:Vi(new Uint8Array(i),new Uint8Array(e),t,s);case ew:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:Vi(new Uint8Array(i),new Uint8Array(e),t,s);case Xy:return i.name===e.name&&i.message===e.message;case mr:{if(!(Vi(i.constructor,e.constructor,t,s)||Wo(i)&&Wo(e)))return!1;const c=[...Object.keys(i),...Jo(i)],h=[...Object.keys(e),...Jo(e)];if(c.length!==h.length)return!1;for(let l=0;l<c.length;l++){const u=c[l],p=i[u];if(!Object.hasOwn(e,u))return!1;const d=e[u];if(!Mi(p,d,u,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function gw(i,e){return dw(i,e,zy)}var fw=Object.defineProperty,Zo=Object.getOwnPropertySymbols,mw=Object.prototype.hasOwnProperty,yw=Object.prototype.propertyIsEnumerable,Gr=(i,e,t)=>e in i?fw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xo=(i,e)=>{for(var t in e||(e={}))mw.call(e,t)&&Gr(i,t,e[t]);if(Zo)for(var t of Zo(e))yw.call(e,t)&&Gr(i,t,e[t]);return i},Se=(i,e,t)=>Gr(i,typeof e!="symbol"?e+"":e,t);class Kt extends Wg{constructor(e,t,s,r=ot,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,Se(this,"map",new Map),Se(this,"version",bf),Se(this,"cached",[]),Se(this,"initialized",!1),Se(this,"getKey"),Se(this,"storagePrefix",ot),Se(this,"recentlyDeleted",[]),Se(this,"recentlyDeletedLimit",200),Se(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!we(o)?this.map.set(this.getKey(o),o):$d(o)?this.map.set(o.id,o):Sd(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Se(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())}),Se(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Se(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>gw(a[c],o[c]))):this.values)),Se(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=Xo(Xo({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Se(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=$e(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return Ce(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}=N("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}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}=N("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}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ww=Object.defineProperty,bw=(i,e,t)=>e in i?ww(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,B=(i,e,t)=>bw(i,typeof e!="symbol"?e+"":e,t);class vw{constructor(e,t){this.core=e,this.logger=t,B(this,"name",_f),B(this,"version",Pf),B(this,"events",new tn),B(this,"pairings"),B(this,"initialized",!1),B(this,"storagePrefix",ot),B(this,"ignoredPayloadTypes",[mt]),B(this,"registeredMethods",[]),B(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),B(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),B(this,"create",async s=>{this.isInitialized();const r=Dr(),n=await this.core.crypto.setSymKey(r),o=ce(j.FIVE_MINUTES),a={protocol:Tc},c={topic:n,expiry:o,relay:a,active:!1,methods:s?.methods},h=fo({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:s?.methods});return this.events.emit(jt.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:s?.transportType}),{topic:n,uri:h}}),B(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s?.uri,trace:[it.pairing_started]}});this.isValidPair(s,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=go(s.uri);r.props.properties.topic=n,r.addTrace(it.pairing_uri_validation_success),r.addTrace(it.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(it.existing_pairing),l.active)throw r.setError(pt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(it.pairing_not_expired)}const u=c||ce(j.FIVE_MINUTES),p={topic:n,relay:a,expiry:u,active:!1,methods:h};this.core.expirer.set(n,u),await this.pairings.set(n,p),r.addTrace(it.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(jt.create,p),r.addTrace(it.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(it.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(pt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(d){throw r.setError(pt.subscribe_pairing_topic_failure),d}return r.addTrace(it.subscribe_pairing_topic_success),p}),B(this,"activate",async({topic:s})=>{this.isInitialized();const r=ce(j.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),B(this,"ping",async s=>{this.isInitialized(),await this.isValidPing(s),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=s;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ct();this.events.once(J("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),B(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),B(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),B(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),B(this,"disconnect",async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:r}=s;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Q("USER_DISCONNECTED")),await this.deletePairing(r))}),B(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return fo({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),B(this,"sendRequest",async(s,r,n)=>{const o=kt(r,n),a=await this.core.crypto.encode(s,o),c=Ri[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),B(this,"sendResult",async(s,r,n)=>{const o=Ls(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=Ri[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),B(this,"sendError",async(s,r,n)=>{const o=$a(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=Ri[c]?Ri[c].res:Ri.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),B(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,Q("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),B(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>Et(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),B(this,"onRelayEventRequest",async s=>{const{topic:r,payload:n}=s;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,n);default:return await this.onUnknownRpcMethodRequest(r,n)}}),B(this,"onRelayEventResponse",async s=>{const{topic:r,payload:n}=s,o=(await this.core.history.get(r,n.id)).request.method;return o==="wc_pairingPing"?this.onPairingPingResponse(r,n):this.onUnknownRpcMethodResponse(o)}),B(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(jt.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),B(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{ut(r)?this.events.emit(J("pairing_ping",n),{}):st(r)&&this.events.emit(J("pairing_ping",n),{error:r.error})},500)}),B(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(jt.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),B(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Q("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,s,a),this.logger.error(a)}catch(a){await this.sendError(n,s,a),this.logger.error(a)}}),B(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(Q("WC_METHOD_UNSUPPORTED",s))}),B(this,"isValidPair",(s,r)=>{var n;if(!xe(s)){const{message:a}=N("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(pt.malformed_pairing_uri),new Error(a)}if(!Pd(s.uri)){const{message:a}=N("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(pt.malformed_pairing_uri),new Error(a)}const o=go(s?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=N("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(pt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=N("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(pt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&j.toMiliseconds(o?.expiryTimestamp)<Date.now()){r.setError(pt.pairing_expired);const{message:a}=N("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),B(this,"isValidPing",async s=>{if(!xe(s)){const{message:n}=N("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),B(this,"isValidDisconnect",async s=>{if(!xe(s)){const{message:n}=N("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),B(this,"isValidPairingTopic",async s=>{if(!ne(s,!1)){const{message:r}=N("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=N("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(Et(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=N("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=$e(t,this.name),this.pairings=new Kt(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ce(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(de.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==te.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);sn(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):rn(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,s)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(ze.expired,async e=>{const{topic:t}=Ha(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(jt.expire,{topic:t}))})}}var Ew=Object.defineProperty,Iw=(i,e,t)=>e in i?Ew(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>Iw(i,typeof e!="symbol"?e+"":e,t);class _w extends Vg{constructor(e,t){super(e,t),this.core=e,this.logger=t,ye(this,"records",new Map),ye(this,"events",new St.EventEmitter),ye(this,"name",$f),ye(this,"version",Sf),ye(this,"cached",[]),ye(this,"initialized",!1),ye(this,"storagePrefix",ot),ye(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.records.set(s.id,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ye(this,"set",(s,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:s,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:s,request:{method:r.method,params:r.params||null},chainId:n,expiry:ce(j.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(He.created,o)}),ye(this,"resolve",async s=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:s}),!this.records.has(s.id))return;const r=await this.getRecord(s.id);typeof r.response>"u"&&(r.response=st(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(He.updated,r))}),ye(this,"get",async(s,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:s,id:r}),await this.getRecord(r))),ye(this,"delete",(s,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===s){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(He.deleted,n)}}),this.persist()}),ye(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),ye(this,"on",(s,r)=>{this.events.on(s,r)}),ye(this,"once",(s,r)=>{this.events.once(s,r)}),ye(this,"off",(s,r)=>{this.events.off(s,r)}),ye(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:kt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:s}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(He.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=N("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(He.created,e=>{const t=He.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(He.updated,e=>{const t=He.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(He.deleted,e=>{const t=He.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(_i.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{j.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(He.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Pw=Object.defineProperty,$w=(i,e,t)=>e in i?Pw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ee=(i,e,t)=>$w(i,typeof e!="symbol"?e+"":e,t);class Sw extends Qg{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ee(this,"expirations",new Map),Ee(this,"events",new St.EventEmitter),Ee(this,"name",Of),Ee(this,"version",xf),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",ot),Ee(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ee(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ee(this,"set",(s,r)=>{this.isInitialized();const n=this.formatTarget(s),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(ze.created,{target:n,expiration:o})}),Ee(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),Ee(this,"del",s=>{if(this.isInitialized(),this.has(s)){const r=this.formatTarget(s),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(ze.deleted,{target:r,expiration:n})}}),Ee(this,"on",(s,r)=>{this.events.on(s,r)}),Ee(this,"once",(s,r)=>{this.events.once(s,r)}),Ee(this,"off",(s,r)=>{this.events.off(s,r)}),Ee(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=$e(t,this.name)}get context(){return Ce(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 Ol(e);if(typeof e=="number")return xl(e);const{message:t}=N("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(ze.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=N("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:s}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;j.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(ze.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(_i.pulse,()=>this.checkExpirations()),this.events.on(ze.created,e=>{const t=ze.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ze.expired,e=>{const t=ze.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ze.deleted,e=>{const t=ze.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ow=Object.defineProperty,xw=(i,e,t)=>e in i?Ow(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,re=(i,e,t)=>xw(i,typeof e!="symbol"?e+"":e,t);class Aw extends Yg{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,re(this,"name",Af),re(this,"abortController"),re(this,"isDevEnv"),re(this,"verifyUrlV3",Cf),re(this,"storagePrefix",ot),re(this,"version",Ac),re(this,"publicKey"),re(this,"fetchPromise"),re(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&j.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),re(this,"register",async r=>{if(!Si()||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 h=yt.getDocument(),l=this.startAbortTimer(j.ONE_SECOND*5),u=await new Promise((p,d)=>{const g=()=>{window.removeEventListener("message",f),h.body.removeChild(y),d("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const y=h.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",g,{signal:this.abortController.signal});const f=b=>{if(b.data&&typeof b.data=="string")try{const w=JSON.parse(b.data);if(w.type==="verify_attestation"){if(_r(w.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(y),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",f),p(w.attestation===null?"":w.attestation)}}catch(w){this.logger.warn(w)}};h.body.appendChild(y),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),re(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(_r(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(r?.verifyUrl);return this.fetchAttestation(o,c)}),re(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(j.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}),re(this,"getVerifyUrl",r=>{let n=r||Ki;return Nf.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ki}`),n=Ki),n}),re(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(j.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)}}),re(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),re(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),re(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")}}),re(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),re(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}),re(this,"validateAttestation",(r,n)=>{const o=sd(r,n.publicKey),a={hasExpired:j.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=$e(t,this.name),this.abortController=new AbortController,this.isDevEnv=on(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ce(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),j.toMiliseconds(e))}}var Tw=Object.defineProperty,Cw=(i,e,t)=>e in i?Tw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ea=(i,e,t)=>Cw(i,typeof e!="symbol"?e+"":e,t);class Nw extends Zg{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,ea(this,"context",Rf),ea(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${jf}/${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=$e(t,this.context)}}var Rw=Object.defineProperty,ta=Object.getOwnPropertySymbols,jw=Object.prototype.hasOwnProperty,qw=Object.prototype.propertyIsEnumerable,Wr=(i,e,t)=>e in i?Rw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ki=(i,e)=>{for(var t in e||(e={}))jw.call(e,t)&&Wr(i,t,e[t]);if(ta)for(var t of ta(e))qw.call(e,t)&&Wr(i,t,e[t]);return i},he=(i,e,t)=>Wr(i,typeof e!="symbol"?e+"":e,t);class kw extends Xg{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,he(this,"context",kf),he(this,"storagePrefix",ot),he(this,"storageVersion",qf),he(this,"events",new Map),he(this,"shouldPersist",!1),he(this,"init",async()=>{if(!on())try{const r={eventId:Dn(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ka(this.core.relayer.protocol,this.core.relayer.version,Ur)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),he(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=Dn(),l=this.core.projectId||"",u=Date.now(),p=ki({eventId:h,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(h));return this.telemetryEnabled&&(this.events.set(h,p),this.shouldPersist=!0),p}),he(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 ki(ki({},a),this.setMethods(a.eventId))}),he(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),he(this,"setEventListeners",()=>{this.core.heartbeat.on(_i.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{j.fromMiliseconds(Date.now())-j.fromMiliseconds(r.timestamp)>Df&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),he(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),he(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)}),he(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)}),he(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),he(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,ki(ki({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),he(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)}}),he(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Lf}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ur}${n}`,{method:"POST",body:JSON.stringify(r)})}),he(this,"getAppDomain",()=>Ba().url),this.logger=$e(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var Dw=Object.defineProperty,ia=Object.getOwnPropertySymbols,Lw=Object.prototype.hasOwnProperty,Mw=Object.prototype.propertyIsEnumerable,Jr=(i,e,t)=>e in i?Dw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,sa=(i,e)=>{for(var t in e||(e={}))Lw.call(e,t)&&Jr(i,t,e[t]);if(ia)for(var t of ia(e))Mw.call(e,t)&&Jr(i,t,e[t]);return i},ee=(i,e,t)=>Jr(i,typeof e!="symbol"?e+"":e,t);let Uw=class Kc extends Ug{constructor(e){var t;super(e),ee(this,"protocol",xc),ee(this,"version",Ac),ee(this,"name",Mr),ee(this,"relayUrl"),ee(this,"projectId"),ee(this,"customStoragePrefix"),ee(this,"events",new St.EventEmitter),ee(this,"logger"),ee(this,"heartbeat"),ee(this,"relayer"),ee(this,"crypto"),ee(this,"storage"),ee(this,"history"),ee(this,"expirer"),ee(this,"pairing"),ee(this,"verify"),ee(this,"echoClient"),ee(this,"linkModeSupportedApps"),ee(this,"eventClient"),ee(this,"initialized",!1),ee(this,"logChunkController"),ee(this,"on",(a,c)=>this.events.on(a,c)),ee(this,"once",(a,c)=>this.events.once(a,c)),ee(this,"off",(a,c)=>this.events.off(a,c)),ee(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ee(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:te.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e?.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Cc,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Fs({level:typeof e?.logger=="string"&&e.logger?e.logger:of.logger,name:Mr}),{logger:n,chunkLoggerController:o}=Dg({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=$e(n,this.name),this.heartbeat=new dh,this.crypto=new dy(this,this.logger,e?.keychain),this.history=new _w(this,this.logger),this.expirer=new Sw(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Eg(sa(sa({},af),e?.storageOptions)),this.relayer=new Uy({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new vw(this,this.logger),this.verify=new Aw(this,this.logger,this.storage),this.echoClient=new Nw(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new kw(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Kc(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(vf,s),t}get context(){return Ce(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(ko,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(ko)||[],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}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,s=`${t}_count`;return globalThis[s]=(globalThis[s]||0)+1,globalThis[s]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[s]} times.`),globalThis[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[s]=e}catch(s){console.warn("Failed to set global WalletConnect core",s)}}isGlobalCoreDisabled(){try{return typeof Ui<"u"&&nf.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const zw=Uw,Vc="wc",Hc=2,Fc="client",fn=`${Vc}@${Hc}:${Fc}:`,yr={name:Fc,logger:"error"},ra="WALLETCONNECT_DEEPLINK_CHOICE",Bw="proposal",na="Proposal expired",Kw="session",Qt=j.SEVEN_DAYS,Vw="engine",le={wc_sessionPropose:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1104},res:{ttl:j.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1106},res:{ttl:j.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1112},res:{ttl:j.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1114},res:{ttl:j.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:j.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:j.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1119}}},wr={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},tt={idle:"IDLE",active:"ACTIVE"},oa={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Hw="request",Fw=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Gw="wc",Ww="auth",Jw="authKeys",Qw="pairingTopics",Yw="requests",Ws=`${Gw}@${1.5}:${Ww}:`,Ss=`${Ws}:PUB_KEY`;var Zw=Object.defineProperty,Xw=Object.defineProperties,eb=Object.getOwnPropertyDescriptors,aa=Object.getOwnPropertySymbols,tb=Object.prototype.hasOwnProperty,ib=Object.prototype.propertyIsEnumerable,Qr=(i,e,t)=>e in i?Zw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,X=(i,e)=>{for(var t in e||(e={}))tb.call(e,t)&&Qr(i,t,e[t]);if(aa)for(var t of aa(e))ib.call(e,t)&&Qr(i,t,e[t]);return i},_e=(i,e)=>Xw(i,eb(e)),S=(i,e,t)=>Qr(i,typeof e!="symbol"?e+"":e,t);class sb extends rf{constructor(e){super(e),S(this,"name",Vw),S(this,"events",new tn),S(this,"initialized",!1),S(this,"requestQueue",{state:tt.idle,queue:[]}),S(this,"sessionRequestQueue",{state:tt.idle,queue:[]}),S(this,"requestQueueDelay",j.ONE_SECOND),S(this,"expectedPairingMethodMap",new Map),S(this,"recentlyDeletedMap",new Map),S(this,"recentlyDeletedLimit",200),S(this,"relayMessageCache",[]),S(this,"pendingSessions",new Map),S(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(le)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay)))}),S(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=_e(X({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=bd(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=s;let l=r,u,p=!1;try{if(l){const m=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."),p=m.active}}catch(m){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),m}if(!l||!p){const{topic:m,uri:E}=await this.client.core.pairing.create();l=m,u=E}if(!l){const{message:m}=N("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(m)}const d=await this.client.core.crypto.generateKeyPair(),g=le.wc_sessionPropose.req.ttl||j.FIVE_MINUTES,y=ce(g),f=_e(X(X({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:Tc}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:wt()}),b=J("session_connect",f.id),{reject:w,resolve:P,done:A}=Ct(g,na),R=({id:m})=>{m===f.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(f.id),this.events.emit(b,{error:{message:na,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(b,({error:m,session:E})=>{this.client.events.off("proposal_expire",R),m?w(m):E&&P(E)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:u,approval:A}}),S(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(s){throw this.client.logger.error("pair() failed"),s}}),S(this,"approve",async t=>{var s,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(s=t?.id)==null?void 0:s.toString(),trace:[Fe.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(I){throw o.setError(At.no_internet_connection),I}try{await this.isValidProposalId(t?.id)}catch(I){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),o.setError(At.proposal_not_found),I}try{await this.isValidApprove(t)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(At.session_approve_namespace_validation_failure),I}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=t,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:y,requiredNamespaces:f,optionalNamespaces:b}=d;let w=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});w||(w=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Fe.session_approve_started,properties:{topic:g,trace:[Fe.session_approve_started,Fe.session_namespaces_validation_success]}}));const P=await this.client.core.crypto.generateKeyPair(),A=y.publicKey,R=await this.client.core.crypto.generateSharedKey(P,A),m=X(X(X({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:P,metadata:this.client.metadata},expiry:ce(Qt)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),E=te.relay;w.addTrace(Fe.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:E})}catch(I){throw w.setError(At.subscribe_session_topic_failure),I}w.addTrace(Fe.subscribe_session_topic_success);const _=_e(X({},m),{topic:R,requiredNamespaces:f,optionalNamespaces:b,pairingTopic:g,acknowledged:!1,self:m.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:P,transportType:te.relay});await this.client.session.set(R,_),w.addTrace(Fe.store_session);try{w.addTrace(Fe.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:m,throwOnFailedPublish:!0}).catch(I=>{throw w?.setError(At.session_settle_publish_failure),I}),w.addTrace(Fe.session_settle_publish_success),w.addTrace(Fe.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:P},throwOnFailedPublish:!0}).catch(I=>{throw w?.setError(At.session_approve_publish_failure),I}),w.addTrace(Fe.session_approve_publish_success)}catch(I){throw this.client.logger.error(I),this.client.session.delete(R,Q("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),I}return this.client.core.eventClient.deleteEvent({eventId:w.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:y.metadata}),await this.client.proposal.delete(a,Q("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(R,ce(Qt)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}}),S(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:s,reason:r}=t;let n;try{n=this.client.proposal.get(s).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${s}) failed`),o}n&&(await this.sendError({id:s,topic:n,error:r,rpcOpts:le.wc_sessionPropose.reject}),await this.client.proposal.delete(s,Q("USER_DISCONNECTED")))}),S(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:s,namespaces:r}=t,{done:n,resolve:o,reject:a}=Ct(),c=wt(),h=li().toString(),l=this.client.session.get(s).namespaces;return this.events.once(J("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(s,{namespaces:r}),await this.sendRequest({topic:s,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(u=>{this.client.logger.error(u),this.client.session.update(s,{namespaces:l}),a(u)}),{acknowledged:n}}),S(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:s}=t,r=wt(),{done:n,resolve:o,reject:a}=Ct();return this.events.once(J("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ce(Qt)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),S(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:s,request:r,topic:n,expiry:o=le.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);a?.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const c=wt(),h=li().toString(),{done:l,resolve:u,reject:p}=Ct(o,"Request expired. Please try again.");this.events.once(J("session_request",c),({error:b,result:w})=>{b?p(b):u(w)});const d="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:{request:_e(X({},r),{expiryTimestamp:ce(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(b=>p(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const y={request:_e(X({},r),{expiryTimestamp:ce(o)}),chainId:s},f=this.shouldSetTVF(d,y);return await Promise.all([new Promise(async b=>{await this.sendRequest(X({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:y,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,y)})).catch(w=>p(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),b()}),new Promise(async b=>{var w;if(!((w=a.sessionConfig)!=null&&w.disableDeepLink)){const P=await Nl(this.client.core.storage,ra);await Al({id:c,topic:n,wcDeepLink:P})}b()}),l()]).then(b=>b[2])}),S(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:s,response:r}=t,{id:n}=r,o=this.client.session.get(s);o.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);ut(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):st(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),S(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:s}=t;if(this.client.session.keys.includes(s)){const r=wt(),n=li().toString(),{done:o,resolve:a,reject:c}=Ct();this.events.once(J("session_ping",r),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:s,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(s)&&(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:s}))}),S(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:s,event:r,chainId:n}=t,o=li().toString(),a=wt();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),S(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:s}=t;if(this.client.session.keys.includes(s))await this.sendRequest({topic:s,method:"wc_sessionDelete",params:Q("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:s,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(s))await this.client.core.pairing.disconnect({topic:s});else{const{message:r}=N("MISMATCHED_TOPIC",`Session or pairing topic not found: ${s}`);throw new Error(r)}}),S(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>Id(s,t)))),S(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),S(this,"authenticate",async(t,s)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=s&&this.client.core.linkModeSupportedApps.includes(s)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?te.link_mode:te.relay;o===te.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:d,nbf:g,methods:y=[],expiry:f}=t,b=[...t.resources||[]],{topic:w,uri:P}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:w,uri:P}});const A=await this.client.core.crypto.generateKeyPair(),R=Is(A);if(await Promise.all([this.client.auth.authKeys.set(Ss,{responseTopic:R,publicKey:A}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:w})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${w}`),y.length>0){const{namespace:O}=gi(a[0]);let D=Pu(O,"request",y);Es(b)&&(D=Su(D,b.pop())),b.push(D)}const m=f&&f>le.wc_sessionAuthenticate.req.ttl?f:le.wc_sessionAuthenticate.req.ttl,E={authPayload:{type:p??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:d,nbf:g,resources:b},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:ce(m)},_={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},I={requiredNamespaces:{},optionalNamespaces:_,relays:[{protocol:"irn"}],pairingTopic:w,proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:ce(le.wc_sessionPropose.req.ttl),id:wt()},{done:C,resolve:T,reject:q}=Ct(m,"Request expired"),M=wt(),v=J("session_connect",I.id),$=J("session_request",M),x=async({error:O,session:D})=>{this.events.off($,k),O?q(O):D&&T({session:D})},k=async O=>{var D,U,z;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),O.error){const ae=Q("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===ae.code?void 0:(this.events.off(v,x),q(O.error.message))}await this.deleteProposal(I.id),this.events.off(v,x);const{cacaos:W,responder:V}=O.result,ie=[],Y=[];for(const ae of W){await Hn({cacao:ae,projectId:this.client.core.projectId})||(this.client.logger.error(ae,"Signature verification failed"),q(Q("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:xt}=ae,at=Es(xt.resources),Ze=[xr(xt.iss)],ct=Ts(xt.iss);if(at){const Ht=Fn(at),as=Gn(at);ie.push(...Ht),Ze.push(...as)}for(const Ht of Ze)Y.push(`${Ht}:${ct}`)}const ve=await this.client.core.crypto.generateSharedKey(A,V.publicKey);let oe;ie.length>0&&(oe={topic:ve,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:V,controller:V.publicKey,expiry:ce(Qt),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:w,namespaces:bo([...new Set(ie)],[...new Set(Y)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,oe),w&&await this.client.core.pairing.updateMetadata({topic:w,metadata:V.metadata}),oe=this.client.session.get(ve)),(D=this.client.metadata.redirect)!=null&&D.linkMode&&(U=V.metadata.redirect)!=null&&U.linkMode&&(z=V.metadata.redirect)!=null&&z.universal&&s&&(this.client.core.addLinkModeSupportedApp(V.metadata.redirect.universal),this.client.session.update(ve,{transportType:te.link_mode})),T({auths:W,session:oe})};this.events.once(v,x),this.events.once($,k);let L;try{if(n){const O=kt("wc_sessionAuthenticate",E,M);this.client.core.history.set(w,O);const D=await this.client.core.crypto.encode("",O,{type:ss,encoding:It});L=ds(s,w,D)}else await Promise.all([this.sendRequest({topic:w,method:"wc_sessionAuthenticate",params:E,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:w,method:"wc_sessionPropose",params:I,expiry:le.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:I.id})])}catch(O){throw this.events.off(v,x),this.events.off($,k),O}return await this.setProposal(I.id,I),await this.setAuthRequest(M,{request:_e(X({},E),{verifyContext:{}}),pairingTopic:w,transportType:o}),{uri:L??P,response:C}}),S(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[Tt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(ji.no_internet_connection),f}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(ji.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||te.relay;a===te.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=Is(c),u={type:mt,receiverPublicKey:c,senderPublicKey:h},p=[],d=[];for(const f of r){if(!await Hn({cacao:f,projectId:this.client.core.projectId})){n.setError(ji.invalid_cacao);const R=Q("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:R,encodeOpts:u}),new Error(R.message)}n.addTrace(Tt.cacaos_verified);const{p:b}=f,w=Es(b.resources),P=[xr(b.iss)],A=Ts(b.iss);if(w){const R=Fn(w),m=Gn(w);p.push(...R),P.push(...m)}for(const R of P)d.push(`${R}:${A}`)}const g=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Tt.create_authenticated_session_topic);let y;if(p?.length>0){y={topic:g,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ce(Qt),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:bo([...new Set(p)],[...new Set(d)]),transportType:a},n.addTrace(Tt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(f){throw n.setError(ji.subscribe_authenticated_session_topic_failure),f}n.addTrace(Tt.subscribe_authenticated_session_topic_success),await this.client.session.set(g,y),n.addTrace(Tt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Tt.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:s,result:{cacaos:r,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(f){throw n.setError(ji.authenticated_session_approve_publish_failure),f}return await this.client.auth.requests.delete(s,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:y}}),S(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:s,reason:r}=t,n=this.getPendingAuthRequest(s);if(!n)throw new Error(`Could not find pending auth request with id ${s}`);n.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Is(o),h={type:mt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:le.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(s,{message:"rejected",code:0}),await this.client.proposal.delete(s,Q("USER_DISCONNECTED"))}),S(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return ec(s,r)}),S(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)}),S(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const s=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!==s.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(s){this.client.logger.error(s)}}),S(this,"deleteSession",async t=>{var s;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,Q("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(ra).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,Q("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=tt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),S(this,"deleteProposal",async(t,s)=>{if(s)try{const r=this.client.proposal.get(t);this.client.core.eventClient.getEvent({topic:r.pairingTopic})?.setError(At.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Q("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),S(this,"deletePendingSessionRequest",async(t,s,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,s),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=tt.idle,this.client.events.emit("session_request_expire",{id:t}))}),S(this,"deletePendingAuthRequest",async(t,s,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,s),r?Promise.resolve():this.client.core.expirer.del(t)])}),S(this,"setExpiry",async(t,s)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,s),await this.client.session.update(t,{expiry:s}))}),S(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ce(le.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),S(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=te.relay}=s;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})}),S(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ce(le.wc_sessionRequest.req.ttl);this.client.core.expirer.set(s,a),await this.client.pendingRequest.set(s,{id:s,topic:r,params:n,verifyContext:o})}),S(this,"sendRequest",async t=>{const{topic:s,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:u}=t,p=kt(r,n,c);let d;const g=!!l;try{const b=g?It:Je;d=await this.client.core.crypto.encode(s,p,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),b}let y;if(Fw.includes(r)){const b=rt(JSON.stringify(p)),w=rt(d);y=await this.client.core.verify.register({id:w,decryptedId:b})}const f=le[r].req;if(f.attestation=y,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(s,p),g){const b=ds(l,s,d);await globalThis.Linking.openURL(b,this.client.name)}else{const b=le[r].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=_e(X({},u),{correlationId:p.id}),h?(b.internal=_e(X({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,d,b)):this.client.core.relayer.publish(s,d,b).catch(w=>this.client.logger.error(w))}return p.id}),S(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=Ls(s,n);let l;const u=c&&typeof globalThis?.Linking<"u";try{const g=u?It:Je;l=await this.client.core.crypto.encode(r,h,_e(X({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let p,d;try{p=await this.client.core.history.get(r,s);const g=p.request;try{this.shouldSetTVF(g.method,g.params)&&(d=this.getTVFParams(s,g.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),g}if(u){const g=ds(c,r,l);await globalThis.Linking.openURL(g,this.client.name)}else{const g=p.request.method,y=le[g].res;y.tvf=_e(X({},d),{correlationId:s}),o?(y.internal=_e(X({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,y)):this.client.core.relayer.publish(r,l,y).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(h)}),S(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=$a(s,n);let l;const u=c&&typeof globalThis?.Linking<"u";try{const d=u?It:Je;l=await this.client.core.crypto.encode(r,h,_e(X({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),d}let p;try{p=await this.client.core.history.get(r,s)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),d}if(u){const d=ds(c,r,l);await globalThis.Linking.openURL(d,this.client.name)}else{const d=p.request.method,g=a||le[d].res;this.client.core.relayer.publish(r,l,g)}await this.client.core.history.resolve(h)}),S(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;Et(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=>{Et(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),S(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),S(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),S(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===tt.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=tt.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=tt.idle}),S(this,"processRequest",async t=>{const{topic:s,payload:r,attestation:n,transportType:o,encryptedId:a}=t,c=r.method;if(!this.shouldIgnorePairingRequest({topic:s,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:s,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(s,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(s,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(s,r);case"wc_sessionPing":return await this.onSessionPingRequest(s,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(s,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(s,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),S(this,"onRelayEventResponse",async t=>{const{topic:s,payload:r,transportType:n}=t,o=(await this.client.core.history.get(s,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(s,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(s,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(s,r);case"wc_sessionExtend":return this.onSessionExtendResponse(s,r);case"wc_sessionPing":return this.onSessionPingResponse(s,r);case"wc_sessionRequest":return this.onSessionRequestResponse(s,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(s,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),S(this,"onRelayEventUnknownPayload",t=>{const{topic:s}=t,{message:r}=N("MISSING_OR_INVALID",`Decoded payload on topic ${s} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),S(this,"shouldIgnorePairingRequest",t=>{const{topic:s,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(s);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),S(this,"onSessionProposeRequest",async t=>{const{topic:s,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:c}=r;try{const h=this.client.core.eventClient.getEvent({topic:s});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),h?.setError(pt.proposal_listener_not_found)),this.isValidConnect(X({},r.params));const l=a.expiryTimestamp||ce(le.wc_sessionPropose.req.ttl),u=X({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:rt(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h?.addTrace(it.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:p})}catch(h){await this.sendError({id:c,topic:s,error:h,rpcOpts:le.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),S(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(ut(s)){const{result:o}=s;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 h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(n,{sessionTopic:l,pairingTopic:t,proposalId:n,publicKey:c});const u=await this.client.core.relayer.subscribe(l,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(st(s)){await this.client.proposal.delete(n,Q("USER_DISCONNECTED"));const o=J("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:s.error})}}),S(this,"onSessionSettleRequest",async(t,s)=>{const{id:r,params:n}=s;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=s.params,d=[...this.pendingSessions.values()].find(f=>f.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const g=this.client.proposal.get(d.proposalId),y=_e(X(X(X({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),{transportType:te.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(J("session_connect",d.proposalId),{session:y}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:s.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),S(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;ut(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(J("session_approve",r),{})):st(s)&&(await this.client.session.delete(t,Q("USER_DISCONNECTED")),this.events.emit(J("session_approve",r),{error:s.error}))}),S(this,"onSessionUpdateRequest",async(t,s)=>{const{params:r,id:n}=s;try{const o=`${t}_session_update`,a=Ni.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:Q("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(X({topic:t},r));try{Ni.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 Ni.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)}}),S(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),S(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=J("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ut(s)?this.events.emit(J("session_update",r),{}):st(s)&&this.events.emit(J("session_update",r),{error:s.error})}),S(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ce(Qt)),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)}}),S(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=J("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ut(s)?this.events.emit(J("session_extend",r),{}):st(s)&&this.events.emit(J("session_extend",r),{error:s.error})}),S(this,"onSessionPingRequest",async(t,s)=>{const{id:r}=s;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)}}),S(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=J("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);ut(s)?this.events.emit(J("session_ping",r),{}):st(s)&&this.events.emit(J("session_ping",r),{error:s.error})},500)}),S(this,"onSessionDeleteRequest",async(t,s)=>{const{id:r}=s;try{this.isValidDisconnect({topic:t,reason:s.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(de.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:Q("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),S(this,"onSessionRequest",async t=>{var s,r,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:l}=t,{id:u,params:p}=a;try{await this.isValidRequest(X({topic:o},p));const d=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:rt(JSON.stringify(kt("wc_sessionRequest",p,u))),encryptedId:h,metadata:d.peer.metadata,transportType:l}),y={id:u,topic:o,params:p,verifyContext:g};await this.setPendingSessionRequest(y),l===te.link_mode&&(s=d.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=d.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(d){await this.sendError({id:u,topic:o,error:d}),this.client.logger.error(d)}}),S(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=J("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ut(s)?this.events.emit(J("session_request",r),{result:s.result}):st(s)&&this.events.emit(J("session_request",r),{error:s.error})}),S(this,"onSessionEventRequest",async(t,s)=>{const{id:r,params:n}=s;try{const o=`${t}_session_event_${n.event.name}`,a=Ni.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(X({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),Ni.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),S(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),ut(s)?this.events.emit(J("session_request",r),{result:s.result}):st(s)&&this.events.emit(J("session_request",r),{error:s.error})}),S(this,"onSessionAuthenticateRequest",async t=>{var s;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:h,authPayload:l,expiryTimestamp:u}=n.params,p=await this.getVerifyContext({attestationId:o,hash:rt(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),d={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:p,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:d,pairingTopic:r,transportType:c}),c===te.link_mode&&(s=h.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:p})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),d={type:mt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:d,rpcOpts:le.wc_sessionAuthenticate.autoReject,appLink:p})}}),S(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),S(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=tt.idle,this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay))}),S(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:s})=>{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=J("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(J("session_request",n.request.id),{error:s})})}),S(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===tt.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=tt.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),S(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),S(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const s=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);s&&this.onSessionProposeRequest({topic:t.topic,payload:kt("wc_sessionPropose",_e(X({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),S(this,"isValidConnect",async t=>{if(!xe(t)){const{message:h}=N("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:s,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(we(s)||await this.isValidPairingTopic(s),!jd(c)){const{message:h}=N("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!we(r)&&$t(r)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(r,"requiredNamespaces")}if(!we(n)&&$t(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>h.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}}),S(this,"validateNamespaces",(t,s)=>{const r=Rd(t,"connect()",s);if(r)throw new Error(r.message)}),S(this,"isValidApprove",async t=>{if(!xe(t))throw new Error(N("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:s,namespaces:r,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(s),await this.isValidProposalId(s);const c=this.client.proposal.get(s),h=hr(r,"approve()");if(h)throw new Error(h.message);const l=Io(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!ne(n,!0)){const{message:u}=N("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(p=>u.has(p)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),S(this,"isValidReject",async t=>{if(!xe(t)){const{message:n}=N("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!kd(r)){const{message:n}=N("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),S(this,"isValidSessionSettleRequest",t=>{if(!xe(t)){const{message:h}=N("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!Sc(s)){const{message:h}=N("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=Od(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=hr(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Et(o)){const{message:h}=N("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),S(this,"isValidUpdate",async t=>{if(!xe(t)){const{message:c}=N("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:s,namespaces:r}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const n=this.client.session.get(s),o=hr(r,"update()");if(o)throw new Error(o.message);const a=Io(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),S(this,"isValidExtend",async t=>{if(!xe(t)){const{message:r}=N("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:s}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s)}),S(this,"isValidRequest",async t=>{if(!xe(t)){const{message:c}=N("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:s,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const{namespaces:a}=this.client.session.get(s);if(!Eo(a,n)){const{message:c}=N("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Dd(r)){const{message:c}=N("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!Ud(a,n,r.method)){const{message:c}=N("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Vd(o,wr)){const{message:c}=N("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${wr.min} and ${wr.max}`);throw new Error(c)}}),S(this,"isValidRespond",async t=>{var s;if(!xe(t)){const{message:o}=N("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(s=t?.response)!=null&&s.id&&this.cleanupAfterResponse(t),o}if(!Ld(n)){const{message:o}=N("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),S(this,"isValidPing",async t=>{if(!xe(t)){const{message:r}=N("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),S(this,"isValidEmit",async t=>{if(!xe(t)){const{message:a}=N("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:s,event:r,chainId:n}=t;await this.isValidSessionTopic(s);const{namespaces:o}=this.client.session.get(s);if(!Eo(o,n)){const{message:a}=N("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Md(r)){const{message:a}=N("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!zd(o,n,r.name)){const{message:a}=N("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),S(this,"isValidDisconnect",async t=>{if(!xe(t)){const{message:r}=N("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),S(this,"isValidAuthenticate",t=>{const{chains:s,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(s)||s.length===0)throw new Error("chains is required and must be a non-empty array");if(!ne(r,!1))throw new Error("uri is required parameter");if(!ne(n,!1))throw new Error("domain is required parameter");if(!ne(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>gi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=gi(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),S(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||Ki,validation:"UNKNOWN",origin:o.url||""}};try{if(a===te.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:s,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),S(this,"validateSessionProps",(t,s)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=N("MISSING_OR_INVALID",`${s} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),S(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),S(this,"addToRecentlyDeleted",(t,s)=>{if(this.recentlyDeletedMap.set(t,s),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)}}}),S(this,"checkRecentlyDeleted",t=>{const s=this.recentlyDeletedMap.get(t);if(s){const{message:r}=N("MISSING_OR_INVALID",`Record was recently deleted - ${s}: ${t}`);throw new Error(r)}}),S(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,u,p;return!t||s!==te.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&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((l=t?.redirect)==null?void 0:l.universal)!==void 0&&((u=t?.redirect)==null?void 0:u.universal)!==""&&((p=t?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof globalThis?.Linking<"u"}),S(this,"getAppLinkIfEnabled",(t,s)=>{var r;return this.isLinkModeEnabled(t,s)?(r=t?.redirect)==null?void 0:r.universal:void 0}),S(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=kn(t,"topic")||"",r=decodeURIComponent(kn(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:te.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),S(this,"registerLinkModeListeners",async()=>{var t;if(on()||Ot()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=globalThis?.Linking;if(typeof s<"u"){s.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await s.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),S(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(oa).includes(r.method)}),S(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return _e(X({correlationId:t,rpcMethods:[a],chainId:s.chainId},this.isValidContractData(s.request.params)&&{contractAddresses:[(o=(n=s.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{}}),S(this,"isValidContractData",t=>{var s;if(!t)return!1;try{const r=t?.data||((s=t?.[0])==null?void 0:s.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}),S(this,"extractTxHashesFromResult",(t,s)=>{try{const r=oa[t];if(typeof s=="string")return[s];const n=s[r.key];if(Qe(n))return t==="solana_signAllTransactions"?n.map(o=>lu(o)):n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[s,r]of Object.entries(t))for(const n of r)try{await this.onProviderMessageEvent({topic:s,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${s}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(de.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Ss)?this.client.auth.authKeys.get(Ss):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===te.link_mode?It:Je});sn(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:rt(s)})):rn(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)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,s)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ze.expired,async e=>{const{topic:t,id:s}=Ha(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,N("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,N("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s}))})}registerPairingEvents(){this.client.core.pairing.events.on(jt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(jt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ne(e,!1)){const{message:t}=N("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}=N("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=N("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ne(e,!1)){const{message:t}=N("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}=N("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=N("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=N("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(ne(e,!1)){const{message:t}=N("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=N("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!qd(e)){const{message:t}=N("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=N("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=N("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class rb extends Kt{constructor(e,t){super(e,t,Bw,fn),this.core=e,this.logger=t}}let nb=class extends Kt{constructor(e,t){super(e,t,Kw,fn),this.core=e,this.logger=t}};class ob extends Kt{constructor(e,t){super(e,t,Hw,fn,s=>s.id),this.core=e,this.logger=t}}class ab extends Kt{constructor(e,t){super(e,t,Jw,Ws,()=>Ss),this.core=e,this.logger=t}}class cb extends Kt{constructor(e,t){super(e,t,Qw,Ws),this.core=e,this.logger=t}}class hb extends Kt{constructor(e,t){super(e,t,Yw,Ws,s=>s.id),this.core=e,this.logger=t}}var lb=Object.defineProperty,ub=(i,e,t)=>e in i?lb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,br=(i,e,t)=>ub(i,typeof e!="symbol"?e+"":e,t);class pb{constructor(e,t){this.core=e,this.logger=t,br(this,"authKeys"),br(this,"pairingTopics"),br(this,"requests"),this.authKeys=new ab(this.core,this.logger),this.pairingTopics=new cb(this.core,this.logger),this.requests=new hb(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var db=Object.defineProperty,gb=(i,e,t)=>e in i?db(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,K=(i,e,t)=>gb(i,typeof e!="symbol"?e+"":e,t);let fb=class Gc extends sf{constructor(e){super(e),K(this,"protocol",Vc),K(this,"version",Hc),K(this,"name",yr.name),K(this,"metadata"),K(this,"core"),K(this,"logger"),K(this,"events",new St.EventEmitter),K(this,"engine"),K(this,"session"),K(this,"proposal"),K(this,"pendingRequest"),K(this,"auth"),K(this,"signConfig"),K(this,"on",(s,r)=>this.events.on(s,r)),K(this,"once",(s,r)=>this.events.once(s,r)),K(this,"off",(s,r)=>this.events.off(s,r)),K(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),K(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),K(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),K(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),K(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"rejectSessionAuthenticate",async s=>{try{return await this.engine.rejectSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),this.name=e?.name||yr.name,this.metadata=_l(e?.metadata),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:rs(Fs({level:e?.logger||yr.logger}));this.core=e?.core||new zw(e),this.logger=$e(t,this.name),this.session=new nb(this.core,this.logger),this.proposal=new rb(this.core,this.logger),this.pendingRequest=new ob(this.core,this.logger),this.engine=new sb(this),this.auth=new pb(this.core,this.logger)}static async init(e){const t=new Gc(e);return await t.initialize(),t}get context(){return Ce(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()},j.toMiliseconds(j.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const ca="error",mb="wss://relay.walletconnect.org",yb="wc",wb="universal_provider",ms=`${yb}@2:${wb}:`,Wc="https://rpc.walletconnect.org/v1/",hi="generic",bb=`${Wc}bundler`,Ve={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function vb(){}function mn(i){return i==null||typeof i!="object"&&typeof i!="function"}function yn(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Eb(i){if(mn(i))return i;if(Array.isArray(i)||yn(i)||i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);const e=Object.getPrototypeOf(i),t=e.constructor;if(i instanceof Date||i instanceof Map||i instanceof Set)return new t(i);if(i instanceof RegExp){const s=new t(i);return s.lastIndex=i.lastIndex,s}if(i instanceof DataView)return new t(i.buffer.slice(0));if(i instanceof Error){const s=new t(i.message);return s.stack=i.stack,s.name=i.name,s.cause=i.cause,s}if(typeof File<"u"&&i instanceof File)return new t([i],i.name,{type:i.type,lastModified:i.lastModified});if(typeof i=="object"){const s=Object.create(e);return Object.assign(s,i)}return i}function ha(i){return typeof i=="object"&&i!==null}function Jc(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Qc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Ib="[object RegExp]",Yc="[object String]",Zc="[object Number]",Xc="[object Boolean]",eh="[object Arguments]",_b="[object Symbol]",Pb="[object Date]",$b="[object Map]",Sb="[object Set]",Ob="[object Array]",xb="[object ArrayBuffer]",Ab="[object Object]",Tb="[object DataView]",Cb="[object Uint8Array]",Nb="[object Uint8ClampedArray]",Rb="[object Uint16Array]",jb="[object Uint32Array]",qb="[object Int8Array]",kb="[object Int16Array]",Db="[object Int32Array]",Lb="[object Float32Array]",Mb="[object Float64Array]";function Ub(i,e){return di(i,void 0,i,new Map,e)}function di(i,e,t,s=new Map,r=void 0){const n=r?.(i,e,t,s);if(n!=null)return n;if(mn(i))return i;if(s.has(i))return s.get(i);if(Array.isArray(i)){const o=new Array(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=di(i[a],a,t,s,r);return Object.hasOwn(i,"index")&&(o.index=i.index),Object.hasOwn(i,"input")&&(o.input=i.input),o}if(i instanceof Date)return new Date(i.getTime());if(i instanceof RegExp){const o=new RegExp(i.source,i.flags);return o.lastIndex=i.lastIndex,o}if(i instanceof Map){const o=new Map;s.set(i,o);for(const[a,c]of i)o.set(a,di(c,a,t,s,r));return o}if(i instanceof Set){const o=new Set;s.set(i,o);for(const a of i)o.add(di(a,void 0,t,s,r));return o}if(typeof Ie<"u"&&Ie.isBuffer(i))return i.subarray();if(yn(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=di(i[a],a,t,s,r);return o}if(i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);if(i instanceof DataView){const o=new DataView(i.buffer.slice(0),i.byteOffset,i.byteLength);return s.set(i,o),qt(o,i,t,s,r),o}if(typeof File<"u"&&i instanceof File){const o=new File([i],i.name,{type:i.type});return s.set(i,o),qt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),qt(o,i,t,s,r),o}if(i instanceof Error){const o=new i.constructor;return s.set(i,o),o.message=i.message,o.name=i.name,o.stack=i.stack,o.cause=i.cause,qt(o,i,t,s,r),o}if(typeof i=="object"&&zb(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),qt(o,i,t,s,r),o}return i}function qt(i,e,t=i,s,r){const n=[...Object.keys(e),...Jc(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=di(e[a],a,t,s,r))}}function zb(i){switch(Qc(i)){case eh:case Ob:case xb:case Tb:case Xc:case Pb:case Lb:case Mb:case qb:case kb:case Db:case $b:case Zc:case Ab:case Ib:case Sb:case Yc:case _b:case Cb:case Nb:case Rb:case jb:return!0;default:return!1}}function Bb(i,e){return Ub(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case Zc:case Yc:case Xc:{const o=new i.constructor(i?.valueOf());return qt(o,i),o}case eh:{const o={};return qt(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function la(i){return Bb(i)}function ua(i){return i!==null&&typeof i=="object"&&Qc(i)==="[object Arguments]"}function Kb(i){return yn(i)}function Vb(i){if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const t=i[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(i,Symbol.toStringTag)?.writable?!1:i.toString()===`[object ${t}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function Hb(i,...e){const t=e.slice(0,-1),s=e[e.length-1];let r=i;for(let n=0;n<t.length;n++){const o=t[n];r=Yr(r,o,s,new Map)}return r}function Yr(i,e,t,s){if(mn(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return Eb(s.get(e));if(s.set(e,i),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const r=[...Object.keys(e),...Jc(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(ua(a)&&(a={...a}),ua(c)&&(c={...c}),typeof Ie<"u"&&Ie.isBuffer(a)&&(a=la(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],u=Reflect.ownKeys(c);for(let p=0;p<u.length;p++){const d=u[p];l[d]=c[d]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||ha(c)&&ha(a)?i[o]=Yr(c,a,t,s):c==null&&Vb(a)?i[o]=Yr({},a,t,s):c==null&&Kb(a)?i[o]=la(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Fb(i,...e){return Hb(i,...e,vb)}var Gb=Object.defineProperty,Wb=Object.defineProperties,Jb=Object.getOwnPropertyDescriptors,pa=Object.getOwnPropertySymbols,Qb=Object.prototype.hasOwnProperty,Yb=Object.prototype.propertyIsEnumerable,da=(i,e,t)=>e in i?Gb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ys=(i,e)=>{for(var t in e||(e={}))Qb.call(e,t)&&da(i,t,e[t]);if(pa)for(var t of pa(e))Yb.call(e,t)&&da(i,t,e[t]);return i},Zb=(i,e)=>Wb(i,Jb(e));function Le(i,e,t){var s;const r=gi(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Wc}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Vt(i){return i.includes(":")?i.split(":")[1]:i}function th(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function Xb(i,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(i));if(!t.length)return[];const s=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;s.push(...n)}),s}function ws(i={},e={}){const t=ga(i),s=ga(e);return Fb(t,s)}function ga(i){var e,t,s,r,n;const o={};if(!$t(i))return o;for(const[a,c]of Object.entries(i)){const h=Hs(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},d=pi(a);o[d]=Zb(ys(ys({},o[d]),c),{chains:nt(h,(e=o[d])==null?void 0:e.chains),methods:nt(l,(t=o[d])==null?void 0:t.methods),events:nt(u,(s=o[d])==null?void 0:s.events)}),($t(p)||$t(((r=o[d])==null?void 0:r.rpcMap)||{}))&&(o[d].rpcMap=ys(ys({},p),(n=o[d])==null?void 0:n.rpcMap))}return o}function fa(i){return i.includes(":")?i.split(":")[2]:i}function ma(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Hs(t)?[t]:s.chains?s.chains:th(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function vr(i){return typeof i=="number"?i:i.includes("0x")?parseInt(i,16):(i=i.includes(":")?i.split(":")[1]:i,isNaN(Number(i))?i:Number(i))}const ih={},G=i=>ih[i],Er=(i,e)=>{ih[i]=e};var ev=Object.defineProperty,tv=(i,e,t)=>e in i?ev(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Yt=(i,e,t)=>tv(i,typeof e!="symbol"?e+"":e,t);class iv{constructor(e){Yt(this,"name","polkadot"),Yt(this,"client"),Yt(this,"httpProviders"),Yt(this,"events"),Yt(this,"namespace"),Yt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var sv=Object.defineProperty,rv=Object.defineProperties,nv=Object.getOwnPropertyDescriptors,ya=Object.getOwnPropertySymbols,ov=Object.prototype.hasOwnProperty,av=Object.prototype.propertyIsEnumerable,Zr=(i,e,t)=>e in i?sv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,wa=(i,e)=>{for(var t in e||(e={}))ov.call(e,t)&&Zr(i,t,e[t]);if(ya)for(var t of ya(e))av.call(e,t)&&Zr(i,t,e[t]);return i},ba=(i,e)=>rv(i,nv(e)),Zt=(i,e,t)=>Zr(i,typeof e!="symbol"?e+"":e,t);class cv{constructor(e){Zt(this,"name","eip155"),Zt(this,"client"),Zt(this,"chainId"),Zt(this,"namespace"),Zt(this,"httpProviders"),Zt(this,"events"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s=t||Le(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=parseInt(Vt(t));e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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,s;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:(s=this.namespace.chains)==null?void 0:s[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,s,r,n,o;const a=(s=(t=e.request)==null?void 0:t.params)==null?void 0:s[0],c=((n=(r=e.request)==null?void 0:r.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u?.[h];const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ba(wa({},l.sessionProperties||{}),{capabilities:ba(wa({},u||{}),{[h]:p})})})}catch(d){console.warn("Failed to update session with capabilities",d)}return p}async getCallStatus(e){var t,s;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=(s=r.sessionProperties)==null?void 0:s.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 s;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(kt("eth_getUserOperationReceipt",[(s=t.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${bb}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var hv=Object.defineProperty,lv=(i,e,t)=>e in i?hv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xt=(i,e,t)=>lv(i,typeof e!="symbol"?e+"":e,t);class uv{constructor(e){Xt(this,"name","solana"),Xt(this,"client"),Xt(this,"httpProviders"),Xt(this,"events"),Xt(this,"namespace"),Xt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var pv=Object.defineProperty,dv=(i,e,t)=>e in i?pv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ei=(i,e,t)=>dv(i,typeof e!="symbol"?e+"":e,t);class gv{constructor(e){ei(this,"name","cosmos"),ei(this,"client"),ei(this,"httpProviders"),ei(this,"events"),ei(this,"namespace"),ei(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var fv=Object.defineProperty,mv=(i,e,t)=>e in i?fv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ti=(i,e,t)=>mv(i,typeof e!="symbol"?e+"":e,t);class yv{constructor(e){ti(this,"name","algorand"),ti(this,"client"),ti(this,"httpProviders"),ti(this,"events"),ti(this,"namespace"),ti(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const s=t||Le(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.chainId=e,this.events.emit(Ve.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 s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new Ke(new Ye(s,G("disableProviderPing")))}}var wv=Object.defineProperty,bv=(i,e,t)=>e in i?wv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ii=(i,e,t)=>bv(i,typeof e!="symbol"?e+"":e,t);class vv{constructor(e){ii(this,"name","cip34"),ii(this,"client"),ii(this,"httpProviders"),ii(this,"events"),ii(this,"namespace"),ii(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s=this.getCardanoRPCUrl(t),r=Vt(t);e[r]=this.createHttpProvider(r,s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var Ev=Object.defineProperty,Iv=(i,e,t)=>e in i?Ev(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,si=(i,e,t)=>Iv(i,typeof e!="symbol"?e+"":e,t);class _v{constructor(e){si(this,"name","elrond"),si(this,"client"),si(this,"httpProviders"),si(this,"events"),si(this,"namespace"),si(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var Pv=Object.defineProperty,$v=(i,e,t)=>e in i?Pv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ri=(i,e,t)=>$v(i,typeof e!="symbol"?e+"":e,t);class Sv{constructor(e){ri(this,"name","multiversx"),ri(this,"client"),ri(this,"httpProviders"),ri(this,"events"),ri(this,"namespace"),ri(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var Ov=Object.defineProperty,xv=(i,e,t)=>e in i?Ov(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ni=(i,e,t)=>xv(i,typeof e!="symbol"?e+"":e,t);class Av{constructor(e){ni(this,"name","near"),ni(this,"client"),ni(this,"httpProviders"),ni(this,"events"),ni(this,"namespace"),ni(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||Le(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(Ve.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 s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace);return typeof s>"u"?void 0:new Ke(new Ye(s,G("disableProviderPing")))}}var Tv=Object.defineProperty,Cv=(i,e,t)=>e in i?Tv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oi=(i,e,t)=>Cv(i,typeof e!="symbol"?e+"":e,t);class Nv{constructor(e){oi(this,"name","tezos"),oi(this,"client"),oi(this,"httpProviders"),oi(this,"events"),oi(this,"namespace"),oi(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||Le(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(Ve.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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace);return typeof s>"u"?void 0:new Ke(new Ye(s))}}var Rv=Object.defineProperty,jv=(i,e,t)=>e in i?Rv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ai=(i,e,t)=>jv(i,typeof e!="symbol"?e+"":e,t);class qv{constructor(e){ai(this,"name",hi),ai(this,"client"),ai(this,"httpProviders"),ai(this,"events"),ai(this,"namespace"),ai(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=gi(r);s[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),s}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var kv=Object.defineProperty,Dv=Object.defineProperties,Lv=Object.getOwnPropertyDescriptors,va=Object.getOwnPropertySymbols,Mv=Object.prototype.hasOwnProperty,Uv=Object.prototype.propertyIsEnumerable,Xr=(i,e,t)=>e in i?kv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bs=(i,e)=>{for(var t in e||(e={}))Mv.call(e,t)&&Xr(i,t,e[t]);if(va)for(var t of va(e))Uv.call(e,t)&&Xr(i,t,e[t]);return i},Ir=(i,e)=>Dv(i,Lv(e)),Ue=(i,e,t)=>Xr(i,typeof e!="symbol"?e+"":e,t);let zv=class sh{constructor(e){Ue(this,"client"),Ue(this,"namespaces"),Ue(this,"optionalNamespaces"),Ue(this,"sessionProperties"),Ue(this,"scopedProperties"),Ue(this,"events",new tn),Ue(this,"rpcProviders",{}),Ue(this,"session"),Ue(this,"providerOpts"),Ue(this,"logger"),Ue(this,"uri"),Ue(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:rs(Fs({level:e?.logger||ca})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new sh(e);return await t.initialize(),t}async request(e,t,s){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:bs({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:s})}sendAsync(e,t,s,r){const n=new Date().getTime();this.request(e,s,r).then(o=>t(null,Ls(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,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Q("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:s,response:r}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const n=await r();if(this.session=n.session,this.session){const o=ma(this.session.namespaces);this.namespaces=ws(this.namespaces,o),await 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:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await s();this.session=r;const n=ma(r.namespaces);return this.namespaces=ws(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[s,r]=this.validateChain(e),n=this.getProvider(s);n.name===hi?n.setDefaultChain(`${s}:${r}`,t):n.setDefaultChain(r,t)}catch(s){if(!/Please call connect/.test(s.message))throw s}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(Qe(t)){for(const s of t)e.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await fb.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ca,relayUrl:this.providerOpts.relayUrl||mb,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(s){throw this.logger.error("Failed to get session",s),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const s=this.client.session.getAll();this.session=s[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>pi(t)))];Er("client",this.client),Er("events",this.events),Er("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=Xb(t,this.session),r=th(s),n=ws(this.namespaces,this.optionalNamespaces),o=Ir(bs({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new cv({namespace:o});break;case"algorand":this.rpcProviders[t]=new yv({namespace:o});break;case"solana":this.rpcProviders[t]=new uv({namespace:o});break;case"cosmos":this.rpcProviders[t]=new gv({namespace:o});break;case"polkadot":this.rpcProviders[t]=new iv({namespace:o});break;case"cip34":this.rpcProviders[t]=new vv({namespace:o});break;case"elrond":this.rpcProviders[t]=new _v({namespace:o});break;case"multiversx":this.rpcProviders[t]=new Sv({namespace:o});break;case"near":this.rpcProviders[t]=new Av({namespace:o});break;case"tezos":this.rpcProviders[t]=new Nv({namespace:o});break;default:this.rpcProviders[hi]?this.rpcProviders[hi].updateNamespace(o):this.rpcProviders[hi]=new qv({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:s}=e;s===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:s,topic:r}=e;if(r!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=s;if(n.name==="accountsChanged"){const o=n.data;o&&Qe(o)&&this.events.emit("accountsChanged",o.map(fa))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=pi(o),h=vr(o)!==vr(a)?`${c}:${vr(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,r;if(e!==((s=this.session)==null?void 0:s.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Ir(bs({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ir(bs({},Q("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Ve.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[hi]}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:s={},sessionProperties:r,scopedProperties:n}=e;this.optionalNamespaces=ws(t,s),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,s]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(o=>pi(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&s)return[t,s];const r=pi(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()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[s,r]=this.validateChain(e);if(!r)return;this.updateNamespaceChain(s,r),this.events.emit("chainChanged",r);const n=this.getProvider(s).getDefaultChain();t||this.getProvider(s).setDefaultChain(r),this.emitAccountsChangedOnChainChange({namespace:s,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:s}){var r,n;try{if(t===s)return;const o=(n=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(fa);if(!Qe(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const s=this.namespaces[e]?e:`${e}:${t}`,r={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[s]?this.namespaces[s]&&(this.namespaces[s].defaultChain=t):this.namespaces[s]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.setItem(`${ms}/${e}${r}`,t)}async getFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${ms}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${ms}/${e}${s}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const s of t)s.startsWith(ms)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const Bv=zv,Kv="wc",Vv="ethereum_provider",Hv=`${Kv}@2:${Vv}:`,Fv="https://rpc.walletconnect.org/v1/",qs=["eth_sendTransaction","personal_sign"],rh=["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_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],ks=["chainChanged","accountsChanged"],nh=["chainChanged","accountsChanged","message","disconnect","connect"],Gv=async()=>{const{createAppKit:i}=await Pa(()=>import("./core-XFvzSI58.js").then(e=>e.u),__vite__mapDeps([9,1,2,3,4,7,8,10,11,12,13]));return i};var Wv=Object.defineProperty,Jv=Object.defineProperties,Qv=Object.getOwnPropertyDescriptors,Ea=Object.getOwnPropertySymbols,Yv=Object.prototype.hasOwnProperty,Zv=Object.prototype.propertyIsEnumerable,en=(i,e,t)=>e in i?Wv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Nt=(i,e)=>{for(var t in e||(e={}))Yv.call(e,t)&&en(i,t,e[t]);if(Ea)for(var t of Ea(e))Zv.call(e,t)&&en(i,t,e[t]);return i},Di=(i,e)=>Jv(i,Qv(e)),Re=(i,e,t)=>en(i,typeof e!="symbol"?e+"":e,t);function Ds(i){return Number(i[0].split(":")[1])}function vs(i){return`0x${i.toString(16)}`}function Xv(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Qe(e))throw new Error("Invalid chains");const c={chains:e,methods:s||qs,events:n||ks,rpcMap:Nt({},e.length?{[Ds(e)]:a[Ds(e)]}:{})},h=n?.filter(d=>!ks.includes(d)),l=s?.filter(d=>!qs.includes(d));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=h?.length&&l?.length||!t,p={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:rh))],events:[...new Set(c.events.concat(o!=null&&o.length?o:nh))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class Js{constructor(){Re(this,"events",new St.EventEmitter),Re(this,"namespace","eip155"),Re(this,"accounts",[]),Re(this,"signer"),Re(this,"chainId",1),Re(this,"modal"),Re(this,"rpc"),Re(this,"STORAGE_KEY",Hv),Re(this,"on",(e,t)=>(this.events.on(e,t),this)),Re(this,"once",(e,t)=>(this.events.once(e,t),this)),Re(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),Re(this,"off",(e,t)=>(this.events.off(e,t),this)),Re(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new Js;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,s){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),s)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:s,optional:r}=Xv(this.rpc);try{const n=await new Promise(async(a,c)=>{var h,l;this.rpc.showQrModal&&((h=this.modal)==null||h.open(),(l=this.modal)==null||l.subscribeState(p=>{!p.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Di(Nt({namespaces:Nt({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e?.pairingTopic,scopedProperties:u})).then(p=>{a(p)}).catch(p=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(p.message))})});if(!n)return;const o=Cn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:vs(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){var s;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const r=await new Promise(async(o,a)=>{var c,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Di(Nt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=r.session;if(n){const o=Cn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:vs(this.chainId)})}return r}catch(r){throw this.signer.logger.error(r),r}finally{(s=this.modal)==null||s.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:s}=t;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",vs(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",Di(Nt({},Q("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",vs(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,s,r]=e.split(":");return{chainId:`${t}:${s}`,address:r}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,s;const r=(t=e?.chains)!=null?t:[],n=(s=e?.optionalChains)!=null?s:[],o=r.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=r.length?e?.methods||qs:[],c=r.length?e?.events||ks:[],h=e?.optionalMethods||[],l=e?.optionalEvents||[],u=e?.rpcMap||this.buildRpcMap(o,e.projectId),p=e?.qrModalOptions||void 0;return{chains:r?.map(d=>this.formatChainId(d)),optionalChains:n.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:h,optionalEvents:l,rpcMap:u,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:p,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const s={};return e.forEach(r=>{s[r]=this.getRpcUrl(r,t)}),s}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ds(this.rpc.chains):Ds(this.rpc.optionalChains),this.signer=await Bv.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const s=await Gv(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return lE}),n=r(Di(Nt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=s(Di(Nt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:s,rpcMap:r}=e;t&&Qe(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)})),s&&Qe(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)}))}getRpcUrl(e,t){var s;return((s=this.rpc.rpcMap)==null?void 0:s[e])||`${Fv}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const eE=Js;var tE=Object.defineProperty,iE=Object.defineProperties,sE=Object.getOwnPropertyDescriptors,Ia=Object.getOwnPropertySymbols,rE=Object.prototype.hasOwnProperty,nE=Object.prototype.propertyIsEnumerable,_a=(i,e,t)=>e in i?tE(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oh=(i,e)=>{for(var t in e||(e={}))rE.call(e,t)&&_a(i,t,e[t]);if(Ia)for(var t of Ia(e))nE.call(e,t)&&_a(i,t,e[t]);return i},oE=(i,e)=>iE(i,sE(e));function aE(i){if(i)return{"--w3m-font-family":i["--wcm-font-family"],"--w3m-accent":i["--wcm-accent-color"],"--w3m-color-mix":i["--wcm-background-color"],"--w3m-z-index":i["--wcm-z-index"]?Number(i["--wcm-z-index"]):void 0,"--w3m-qr-color":i["--wcm-accent-color"],"--w3m-font-size-master":i["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":i["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const cE=i=>{const[e,t]=i.split(":");return ah({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function hE(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(cE).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(u=>{var p;return u.id===((p=i.defaultChain)==null?void 0:p.id)}),l={projectId:i.projectId,networks:c,themeMode:i.themeMode,themeVariables:aE(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:oE(oh({},i.metadata),{name:((t=i.metadata)==null?void 0:t.name)||"WalletConnect",description:((s=i.metadata)==null?void 0:s.description)||"Connect to WalletConnect-compatible wallets",url:((r=i.metadata)==null?void 0:r.url)||"https://walletconnect.org",icons:((n=i.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:i.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(i.explorerRecommendedWalletIds)?i.explorerRecommendedWalletIds:[],excludeWalletIds:i.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(i.explorerExcludedWalletIds)?i.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=i.mobileWallets)!=null&&o.length||(a=i.desktopWallets)!=null&&a.length){const u=[...(i.mobileWallets||[]).map(g=>({id:g.id,name:g.name,links:g.links})),...(i.desktopWallets||[]).map(g=>({id:g.id,name:g.name,links:{native:g.links.native,universal:g.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],d=u.filter(g=>!p.includes(g.id));d.length&&(l.customWallets=d)}return l}function ah(i){return oh({formatters:void 0,fees:void 0,serializers:void 0},i)}var lE=Object.freeze({__proto__:null,convertWCMToAppKitOptions:hE,defineChain:ah});const FE=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:eE,OPTIONAL_EVENTS:nh,OPTIONAL_METHODS:rh,REQUIRED_EVENTS:ks,REQUIRED_METHODS:qs,default:Js},Symbol.toStringTag,{value:"Module"}));export{Dg as A,$e as E,Gh as H,rs as O,_n as a,Dh as b,wE as c,yE as d,Ms as e,EE as f,vE as g,Be as h,Te as i,zi as j,rl as k,Fs as l,Eg as m,FE as n,bE as r,Ra as t,Wh as w,Ce as y};
|
|
12
|
+
Approved: ${p.toString()}`))}),o.forEach(u=>{s||(Dt(r[u].methods,n[u].methods)?Dt(r[u].events,n[u].events)||(s=N("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=N("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function Bd(i){const e={};return Object.keys(i).forEach(t=>{var s;t.includes(":")?e[t]=i[t]:(s=i[t].chains)==null||s.forEach(r=>{e[r]={methods:i[t].methods,events:i[t].events}})}),e}function _o(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Kd(i){const e={};return Object.keys(i).forEach(t=>{t.includes(":")?e[t]=i[t]:Ai(i[t].accounts)?.forEach(r=>{e[r]={accounts:i[t].accounts.filter(n=>n.includes(`${r}:`)),methods:i[t].methods,events:i[t].events}})}),e}function Vd(i,e){return dn(i,!1)&&i<=e.max&&i>=e.min}function Po(){const i=Zi();return new Promise(e=>{switch(i){case De.browser:e(Hd());break;case De.reactNative:e(Fd());break;case De.node:e(Gd());break;default:e(!0)}})}function Hd(){return Si()&&navigator?.onLine}async function Fd(){return Ot()&&typeof globalThis<"u"&&globalThis!=null&&globalThis.NetInfo?(await globalThis?.NetInfo.fetch())?.isConnected:!0}function Gd(){return!0}function Wd(i){switch(Zi()){case De.browser:Jd(i);break;case De.reactNative:Qd(i);break}}function Jd(i){!Ot()&&Si()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function Qd(i){Ot()&&typeof globalThis<"u"&&globalThis!=null&&globalThis.NetInfo&&globalThis?.NetInfo.addEventListener(e=>i(e?.isConnected))}function Yd(){var i;return Si()&&yt.getDocument()?((i=yt.getDocument())==null?void 0:i.visibilityState)==="visible":!0}const lr={};class Ni{static get(e){return lr[e]}static set(e,t){lr[e]=t}static delete(e){delete lr[e]}}function Zd(i){return!i||typeof i.then!="function"?Promise.resolve(i):i}function ue(i,...e){try{return Zd(i(...e))}catch(t){return Promise.reject(t)}}function Xd(i){const e=typeof i;return i===null||e!=="object"&&e!=="function"}function eg(i){const e=Object.getPrototypeOf(i);return!e||e.isPrototypeOf(Object)}function _s(i){if(Xd(i))return String(i);if(eg(i)||Array.isArray(i))return JSON.stringify(i);if(typeof i.toJSON=="function")return _s(i.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Lr="base64:";function tg(i){return typeof i=="string"?i:Lr+rg(i)}function ig(i){return typeof i!="string"||!i.startsWith(Lr)?i:sg(i.slice(Lr.length))}function sg(i){return globalThis.Buffer?Buffer.from(i,"base64"):Uint8Array.from(globalThis.atob(i),e=>e.codePointAt(0))}function rg(i){return globalThis.Buffer?Buffer.from(i).toString("base64"):globalThis.btoa(String.fromCodePoint(...i))}function Oe(i){return i&&i.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function ng(...i){return Oe(i.join(":"))}function gs(i){return i=Oe(i),i?i+":":""}function og(i,e){if(e===void 0)return!0;let t=0,s=i.indexOf(":");for(;s>-1;)t++,s=i.indexOf(":",s+1);return t<=e}function ag(i,e){return e?i.startsWith(e)&&i[i.length-1]!=="$":i[i.length-1]!=="$"}const cg="memory",hg=()=>{const i=new Map;return{name:cg,getInstance:()=>i,hasItem(e){return i.has(e)},getItem(e){return i.get(e)??null},getItemRaw(e){return i.get(e)??null},setItem(e,t){i.set(e,t)},setItemRaw(e,t){i.set(e,t)},removeItem(e){i.delete(e)},getKeys(){return[...i.keys()]},clear(){i.clear()},dispose(){i.clear()}}};function lg(i={}){const e={mounts:{"":i.driver||hg()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=h=>{for(const l of e.mountpoints)if(h.startsWith(l))return{base:l,relativeKey:h.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:h,driver:e.mounts[""]}},s=(h,l)=>e.mountpoints.filter(u=>u.startsWith(h)||l&&h.startsWith(u)).map(u=>({relativeBase:h.length>u.length?h.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(h,l)=>{if(e.watching){l=Oe(l);for(const u of e.watchListeners)u(h,l)}},n=async()=>{if(!e.watching){e.watching=!0;for(const h in e.mounts)e.unwatch[h]=await $o(e.mounts[h],r,h)}},o=async()=>{if(e.watching){for(const h in e.unwatch)await e.unwatch[h]();e.unwatch={},e.watching=!1}},a=(h,l,u)=>{const p=new Map,d=g=>{let y=p.get(g.base);return y||(y={driver:g.driver,base:g.base,items:[]},p.set(g.base,y)),y};for(const g of h){const y=typeof g=="string",f=Oe(y?g:g.key),b=y?void 0:g.value,w=y||!g.options?l:{...l,...g.options},P=t(f);d(P).items.push({key:f,value:b,relativeKey:P.relativeKey,options:w})}return Promise.all([...p.values()].map(g=>u(g))).then(g=>g.flat())},c={hasItem(h,l={}){h=Oe(h);const{relativeKey:u,driver:p}=t(h);return ue(p.hasItem,u,l)},getItem(h,l={}){h=Oe(h);const{relativeKey:u,driver:p}=t(h);return ue(p.getItem,u,l).then(d=>cs(d))},getItems(h,l={}){return a(h,l,u=>u.driver.getItems?ue(u.driver.getItems,u.items.map(p=>({key:p.relativeKey,options:p.options})),l).then(p=>p.map(d=>({key:ng(u.base,d.key),value:cs(d.value)}))):Promise.all(u.items.map(p=>ue(u.driver.getItem,p.relativeKey,p.options).then(d=>({key:p.key,value:cs(d)})))))},getItemRaw(h,l={}){h=Oe(h);const{relativeKey:u,driver:p}=t(h);return p.getItemRaw?ue(p.getItemRaw,u,l):ue(p.getItem,u,l).then(d=>ig(d))},async setItem(h,l,u={}){if(l===void 0)return c.removeItem(h);h=Oe(h);const{relativeKey:p,driver:d}=t(h);d.setItem&&(await ue(d.setItem,p,_s(l),u),d.watch||r("update",h))},async setItems(h,l){await a(h,l,async u=>{if(u.driver.setItems)return ue(u.driver.setItems,u.items.map(p=>({key:p.relativeKey,value:_s(p.value),options:p.options})),l);u.driver.setItem&&await Promise.all(u.items.map(p=>ue(u.driver.setItem,p.relativeKey,_s(p.value),p.options)))})},async setItemRaw(h,l,u={}){if(l===void 0)return c.removeItem(h,u);h=Oe(h);const{relativeKey:p,driver:d}=t(h);if(d.setItemRaw)await ue(d.setItemRaw,p,l,u);else if(d.setItem)await ue(d.setItem,p,tg(l),u);else return;d.watch||r("update",h)},async removeItem(h,l={}){typeof l=="boolean"&&(l={removeMeta:l}),h=Oe(h);const{relativeKey:u,driver:p}=t(h);p.removeItem&&(await ue(p.removeItem,u,l),(l.removeMeta||l.removeMata)&&await ue(p.removeItem,u+"$",l),p.watch||r("remove",h))},async getMeta(h,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),h=Oe(h);const{relativeKey:u,driver:p}=t(h),d=Object.create(null);if(p.getMeta&&Object.assign(d,await ue(p.getMeta,u,l)),!l.nativeOnly){const g=await ue(p.getItem,u+"$",l).then(y=>cs(y));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(d,g))}return d},setMeta(h,l,u={}){return this.setItem(h+"$",l,u)},removeMeta(h,l={}){return this.removeItem(h+"$",l)},async getKeys(h,l={}){h=gs(h);const u=s(h,!0);let p=[];const d=[];let g=!0;for(const f of u){f.driver.flags?.maxDepth||(g=!1);const b=await ue(f.driver.getKeys,f.relativeBase,l);for(const w of b){const P=f.mountpoint+Oe(w);p.some(A=>P.startsWith(A))||d.push(P)}p=[f.mountpoint,...p.filter(w=>!w.startsWith(f.mountpoint))]}const y=l.maxDepth!==void 0&&!g;return d.filter(f=>(!y||og(f,l.maxDepth))&&ag(f,h))},async clear(h,l={}){h=gs(h),await Promise.all(s(h,!1).map(async u=>{if(u.driver.clear)return ue(u.driver.clear,u.relativeBase,l);if(u.driver.removeItem){const p=await u.driver.getKeys(u.relativeBase||"",l);return Promise.all(p.map(d=>u.driver.removeItem(d,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(h=>So(h)))},async watch(h){return await n(),e.watchListeners.push(h),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==h),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(h,l){if(h=gs(h),h&&e.mounts[h])throw new Error(`already mounted at ${h}`);return h&&(e.mountpoints.push(h),e.mountpoints.sort((u,p)=>p.length-u.length)),e.mounts[h]=l,e.watching&&Promise.resolve($o(l,r,h)).then(u=>{e.unwatch[h]=u}).catch(console.error),c},async unmount(h,l=!0){h=gs(h),!(!h||!e.mounts[h])&&(e.watching&&h in e.unwatch&&(e.unwatch[h]?.(),delete e.unwatch[h]),l&&await So(e.mounts[h]),e.mountpoints=e.mountpoints.filter(u=>u!==h),delete e.mounts[h])},getMount(h=""){h=Oe(h)+":";const l=t(h);return{driver:l.driver,base:l.base}},getMounts(h="",l={}){return h=Oe(h),s(h,l.parents).map(p=>({driver:p.driver,base:p.mountpoint}))},keys:(h,l={})=>c.getKeys(h,l),get:(h,l={})=>c.getItem(h,l),set:(h,l,u={})=>c.setItem(h,l,u),has:(h,l={})=>c.hasItem(h,l),del:(h,l={})=>c.removeItem(h,l),remove:(h,l={})=>c.removeItem(h,l)};return c}function $o(i,e,t){return i.watch?i.watch((s,r)=>e(s,t+r)):()=>{}}async function So(i){typeof i.dispose=="function"&&await ue(i.dispose)}const ug="idb-keyval";var pg=(i={})=>{const e=i.base&&i.base.length>0?`${i.base}:`:"",t=r=>e+r;let s;return i.dbName&&i.storeName&&(s=yh(i.dbName,i.storeName)),{name:ug,options:i,async hasItem(r){return!(typeof await vn(t(r),s)>"u")},async getItem(r){return await vn(t(r),s)??null},setItem(r,n){return Eh(t(r),n,s)},removeItem(r){return vh(t(r),s)},getKeys(){return bh(s)},clear(){return wh(s)}}};const dg="WALLET_CONNECT_V2_INDEXED_DB",gg="keyvaluestorage";let fg=class{constructor(){this.indexedDb=lg({driver:pg({dbName:dg,storeName:gg})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,Hi(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ur=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},Ps={exports:{}};(function(){let i;function e(){}i=e,i.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},i.prototype.setItem=function(t,s){this[t]=String(s)},i.prototype.removeItem=function(t){delete this[t]},i.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(s){t[s]=void 0,delete t[s]})},i.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},i.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ur<"u"&&ur.localStorage?Ps.exports=ur.localStorage:typeof window<"u"&&window.localStorage?Ps.exports=window.localStorage:Ps.exports=new e})();function mg(i){var e;return[i[0],Os((e=i[1])!=null?e:"")]}let yg=class{constructor(){this.localStorage=Ps.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(mg)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return Os(t)}async setItem(e,t){this.localStorage.setItem(e,Hi(t))}async removeItem(e){this.localStorage.removeItem(e)}};const wg="wc_storage_version",Oo=1,bg=async(i,e,t)=>{const s=wg,r=await e.getItem(s);if(r&&r>=Oo){t(e);return}const n=await i.getKeys();if(!n.length){t(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const h=await i.getItem(a);await e.setItem(a,h),o.push(a)}}await e.setItem(s,Oo),t(e),vg(i,o)},vg=async(i,e)=>{e.length&&e.forEach(async t=>{await i.removeItem(t)})};let Eg=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new yg;this.storage=e;try{const t=new fg;bg(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};var pr,xo;function Ig(){if(xo)return pr;xo=1;const i=Ih();pr=r;const e=R().console||{},t={mapHttpRequest:g,mapHttpResponse:g,wrapRequestSerializer:y,wrapResponseSerializer:y,wrapErrorSerializer:y,req:g,res:g,err:p};function s(m,E){return Array.isArray(m)?m.filter(function(I){return I!=="!stdSerializers.err"}):m===!0?Object.keys(E):!1}function r(m){m=m||{},m.browser=m.browser||{};const E=m.browser.transmit;if(E&&typeof E.send!="function")throw Error("pino: transmit option must have a send function");const _=m.browser.write||e;m.browser.write&&(m.browser.asObject=!0);const I=m.serializers||{},C=s(m.browser.serialize,I);let T=m.browser.serialize;Array.isArray(m.browser.serialize)&&m.browser.serialize.indexOf("!stdSerializers.err")>-1&&(T=!1);const q=["error","fatal","warn","info","debug","trace"];typeof _=="function"&&(_.error=_.fatal=_.warn=_.info=_.debug=_.trace=_),m.enabled===!1&&(m.level="silent");const M=m.level||"info",v=Object.create(_);v.log||(v.log=f),Object.defineProperty(v,"levelVal",{get:x}),Object.defineProperty(v,"level",{get:k,set:L});const $={transmit:E,serialize:C,asObject:m.browser.asObject,levels:q,timestamp:d(m)};v.levels=r.levels,v.level=M,v.setMaxListeners=v.getMaxListeners=v.emit=v.addListener=v.on=v.prependListener=v.once=v.prependOnceListener=v.removeListener=v.removeAllListeners=v.listeners=v.listenerCount=v.eventNames=v.write=v.flush=f,v.serializers=I,v._serialize=C,v._stdErrSerialize=T,v.child=O,E&&(v._logEvent=u());function x(){return this.level==="silent"?1/0:this.levels.values[this.level]}function k(){return this._level}function L(D){if(D!=="silent"&&!this.levels.values[D])throw Error("unknown level "+D);this._level=D,n($,v,"error","log"),n($,v,"fatal","error"),n($,v,"warn","error"),n($,v,"info","log"),n($,v,"debug","log"),n($,v,"trace","log")}function O(D,U){if(!D)throw new Error("missing bindings for child Pino");U=U||{},C&&D.serializers&&(U.serializers=D.serializers);const z=U.serializers;if(C&&z){var W=Object.assign({},I,z),V=m.browser.serialize===!0?Object.keys(W):C;delete D.serializers,c([D],V,W,this._stdErrSerialize)}function ie(Y){this._childLevel=(Y._childLevel|0)+1,this.error=h(Y,D,"error"),this.fatal=h(Y,D,"fatal"),this.warn=h(Y,D,"warn"),this.info=h(Y,D,"info"),this.debug=h(Y,D,"debug"),this.trace=h(Y,D,"trace"),W&&(this.serializers=W,this._serialize=V),E&&(this._logEvent=u([].concat(Y._logEvent.bindings,D)))}return ie.prototype=this,new ie(this)}return v}r.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},r.stdSerializers=t,r.stdTimeFunctions=Object.assign({},{nullTime:b,epochTime:w,unixTime:P,isoTime:A});function n(m,E,_,I){const C=Object.getPrototypeOf(E);E[_]=E.levelVal>E.levels.values[_]?f:C[_]?C[_]:e[_]||e[I]||f,o(m,E,_)}function o(m,E,_){!m.transmit&&E[_]===f||(E[_]=(function(I){return function(){const T=m.timestamp(),q=new Array(arguments.length),M=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var v=0;v<q.length;v++)q[v]=arguments[v];if(m.serialize&&!m.asObject&&c(q,this._serialize,this.serializers,this._stdErrSerialize),m.asObject?I.call(M,a(this,_,q,T)):I.apply(M,q),m.transmit){const $=m.transmit.level||E.level,x=r.levels.values[$],k=r.levels.values[_];if(k<x)return;l(this,{ts:T,methodLevel:_,methodValue:k,transmitValue:r.levels.values[m.transmit.level||E.level],send:m.transmit.send,val:E.levelVal},q)}}})(E[_]))}function a(m,E,_,I){m._serialize&&c(_,m._serialize,m.serializers,m._stdErrSerialize);const C=_.slice();let T=C[0];const q={};I&&(q.time=I),q.level=r.levels.values[E];let M=(m._childLevel|0)+1;if(M<1&&(M=1),T!==null&&typeof T=="object"){for(;M--&&typeof C[0]=="object";)Object.assign(q,C.shift());T=C.length?i(C.shift(),C):void 0}else typeof T=="string"&&(T=i(C.shift(),C));return T!==void 0&&(q.msg=T),q}function c(m,E,_,I){for(const C in m)if(I&&m[C]instanceof Error)m[C]=r.stdSerializers.err(m[C]);else if(typeof m[C]=="object"&&!Array.isArray(m[C]))for(const T in m[C])E&&E.indexOf(T)>-1&&T in _&&(m[C][T]=_[T](m[C][T]))}function h(m,E,_){return function(){const I=new Array(1+arguments.length);I[0]=E;for(var C=1;C<I.length;C++)I[C]=arguments[C-1];return m[_].apply(this,I)}}function l(m,E,_){const I=E.send,C=E.ts,T=E.methodLevel,q=E.methodValue,M=E.val,v=m._logEvent.bindings;c(_,m._serialize||Object.keys(m.serializers),m.serializers,m._stdErrSerialize===void 0?!0:m._stdErrSerialize),m._logEvent.ts=C,m._logEvent.messages=_.filter(function($){return v.indexOf($)===-1}),m._logEvent.level.label=T,m._logEvent.level.value=q,I(T,m._logEvent,M),m._logEvent=u(v)}function u(m){return{ts:0,messages:[],bindings:m||[],level:{label:"",value:0}}}function p(m){const E={type:m.constructor.name,msg:m.message,stack:m.stack};for(const _ in m)E[_]===void 0&&(E[_]=m[_]);return E}function d(m){return typeof m.timestamp=="function"?m.timestamp:m.timestamp===!1?b:w}function g(){return{}}function y(m){return m}function f(){}function b(){return!1}function w(){return Date.now()}function P(){return Math.round(Date.now()/1e3)}function A(){return new Date(Date.now()).toISOString()}function R(){function m(E){return typeof E<"u"&&E}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return m(self)||m(window)||m(this)||{}}}return pr}var ci=Ig();const rs=hh(ci),_g={level:"info"},ns="custom_context",gn=1e3*1024;let Pg=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Ao=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new Pg(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;t!==null;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}},Oc=class{constructor(e,t=gn){this.level=e??"error",this.levelValue=ci.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new Ao(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===ci.levels.values.error?console.error(e):t===ci.levels.values.warn?console.warn(e):t===ci.levels.values.debug?console.debug(e):t===ci.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Hi({timestamp:new Date().toISOString(),log:e}));const t=typeof e=="string"?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new Ao(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(Hi({extraMetadata:e})),new Blob(t,{type:"application/json"})}},$g=class{constructor(e,t=gn){this.baseChunkLogger=new Oc(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),s=document.createElement("a");s.href=t,s.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)}},Sg=class{constructor(e,t=gn){this.baseChunkLogger=new Oc(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var Og=Object.defineProperty,xg=Object.defineProperties,Ag=Object.getOwnPropertyDescriptors,To=Object.getOwnPropertySymbols,Tg=Object.prototype.hasOwnProperty,Cg=Object.prototype.propertyIsEnumerable,Co=(i,e,t)=>e in i?Og(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Rs=(i,e)=>{for(var t in e||(e={}))Tg.call(e,t)&&Co(i,t,e[t]);if(To)for(var t of To(e))Cg.call(e,t)&&Co(i,t,e[t]);return i},js=(i,e)=>xg(i,Ag(e));function Fs(i){return js(Rs({},i),{level:i?.level||_g.level})}function Ng(i,e=ns){return i[e]||""}function Rg(i,e,t=ns){return i[t]=e,i}function Ce(i,e=ns){let t="";return typeof i.bindings>"u"?t=Ng(i,e):t=i.bindings().context||"",t}function jg(i,e,t=ns){const s=Ce(i,t);return s.trim()?`${s}/${e}`:e}function $e(i,e,t=ns){const s=jg(i,e,t),r=i.child({context:s});return Rg(r,s,t)}function qg(i){var e,t;const s=new $g((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:rs(js(Rs({},i.opts),{level:"trace",browser:js(Rs({},(t=i.opts)==null?void 0:t.browser),{write:r=>s.write(r)})})),chunkLoggerController:s}}function kg(i){var e;const t=new Sg((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:rs(js(Rs({},i.opts),{level:"trace"}),t),chunkLoggerController:t}}function Dg(i){return typeof i.loggerOverride<"u"&&typeof i.loggerOverride!="string"?{logger:i.loggerOverride,chunkLoggerController:null}:typeof window<"u"?qg(i):kg(i)}var Lg=Object.defineProperty,Mg=(i,e,t)=>e in i?Lg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,No=(i,e,t)=>Mg(i,typeof e!="symbol"?e+"":e,t);let Ug=class extends Ii{constructor(e){super(),this.opts=e,No(this,"protocol","wc"),No(this,"version",2)}};var zg=Object.defineProperty,Bg=(i,e,t)=>e in i?zg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Kg=(i,e,t)=>Bg(i,e+"",t);let Vg=class extends Ii{constructor(e,t){super(),this.core=e,this.logger=t,Kg(this,"records",new Map)}},Hg=class{constructor(e,t){this.logger=e,this.core=t}};class Fg extends Ii{constructor(e,t){super(),this.relayer=e,this.logger=t}}let Gg=class extends Ii{constructor(e){super()}},Wg=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},Jg=class extends Ii{constructor(e,t){super(),this.relayer=e,this.logger=t}},Qg=class extends Ii{constructor(e,t){super(),this.core=e,this.logger=t}},Yg=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},Zg=class{constructor(e,t){this.projectId=e,this.logger=t}},Xg=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var ef=Object.defineProperty,tf=(i,e,t)=>e in i?ef(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ro=(i,e,t)=>tf(i,typeof e!="symbol"?e+"":e,t);let sf=class{constructor(e){this.opts=e,Ro(this,"protocol","wc"),Ro(this,"version",2)}},rf=class{constructor(e){this.client=e}};var nf={};const xc="wc",Ac=2,Mr="core",ot=`${xc}@2:${Mr}:`,of={logger:"error"},af={database:":memory:"},cf="crypto",jo="client_ed25519_seed",hf=j.ONE_DAY,lf="keychain",uf="0.3",pf="messages",df="0.3",qo=j.SIX_HOURS,gf="publisher",Tc="irn",ff="error",Cc="wss://relay.walletconnect.org",mf="relayer",de={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"},yf="_subscription",Me={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},wf=.1,Ur="2.21.1",te={link_mode:"link_mode",relay:"relay"},$s={inbound:"inbound",outbound:"outbound"},bf="0.3",vf="WALLETCONNECT_CLIENT_ID",ko="WALLETCONNECT_LINK_MODE_APPS",je={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Ef="subscription",If="0.3",_f="pairing",Pf="0.3",Ri={wc_pairingDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:j.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:j.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:j.ONE_DAY,prompt:!1,tag:0},res:{ttl:j.ONE_DAY,prompt:!1,tag:0}}},jt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},He={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},$f="history",Sf="0.3",Of="expirer",ze={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},xf="0.3",Af="verify-api",Tf="https://verify.walletconnect.com",Nc="https://verify.walletconnect.org",Ki=Nc,Cf=`${Ki}/v3`,Nf=[Tf,Nc],Rf="echo",jf="https://echo.walletconnect.com",it={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"},pt={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"},Fe={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"},At={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"},Tt={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"},ji={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"},qf=.1,kf="event-client",Df=86400,Lf="https://pulse.walletconnect.org/batch";function Mf(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var r=0;r<i.length;r++){var n=i.charAt(r),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=r}var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,f=0,b=0,w=g.length;b!==w&&g[b]===0;)b++,y++;for(var P=(w-b)*l+1>>>0,A=new Uint8Array(P);b!==w;){for(var R=g[b],m=0,E=P-1;(R!==0||m<f)&&E!==-1;E--,m++)R+=256*A[E]>>>0,A[E]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");f=m,b++}for(var _=P-f;_!==P&&A[_]===0;)_++;for(var I=c.repeat(y);_<P;++_)I+=i.charAt(A[_]);return I}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var f=0,b=0;g[y]===c;)f++,y++;for(var w=(g.length-y)*h+1>>>0,P=new Uint8Array(w);g[y];){var A=t[g.charCodeAt(y)];if(A===255)return;for(var R=0,m=w-1;(A!==0||R<b)&&m!==-1;m--,R++)A+=a*P[m]>>>0,P[m]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");b=R,y++}if(g[y]!==" "){for(var E=w-b;E!==w&&P[E]===0;)E++;for(var _=new Uint8Array(f+(w-E)),I=f;E!==w;)_[I++]=P[E++];return _}}}function d(g){var y=p(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:d}}var Uf=Mf,zf=Uf;const Rc=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},Bf=i=>new TextEncoder().encode(i),Kf=i=>new TextDecoder().decode(i);class Vf{constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Hf{constructor(e,t,s){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=s}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 jc(this,e)}}class Ff{constructor(e){this.decoders=e}or(e){return jc(this,e)}decode(e){const t=e[0],s=this.decoders[t];if(s)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const jc=(i,e)=>new Ff({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Gf{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Vf(e,t,s),this.decoder=new Hf(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Gs=({name:i,prefix:e,encode:t,decode:s})=>new Gf(i,e,t,s),os=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=zf(t,e);return Gs({prefix:i,name:e,encode:s,decode:n=>Rc(r(n))})},Wf=(i,e,t,s)=>{const r={};for(let l=0;l<e.length;++l)r[e[l]]=l;let n=i.length;for(;i[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const u=r[i[l]];if(u===void 0)throw new SyntaxError(`Non-${s} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Jf=(i,e,t)=>{const s=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),s)for(;n.length*t&7;)n+="=";return n},be=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>Gs({prefix:e,name:i,encode(r){return Jf(r,s,t)},decode(r){return Wf(r,s,t,i)}}),Qf=Gs({prefix:"\0",name:"identity",encode:i=>Kf(i),decode:i=>Bf(i)});var Yf=Object.freeze({__proto__:null,identity:Qf});const Zf=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Xf=Object.freeze({__proto__:null,base2:Zf});const em=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var tm=Object.freeze({__proto__:null,base8:em});const im=os({prefix:"9",name:"base10",alphabet:"0123456789"});var sm=Object.freeze({__proto__:null,base10:im});const rm=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),nm=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var om=Object.freeze({__proto__:null,base16:rm,base16upper:nm});const am=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),cm=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hm=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lm=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),um=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pm=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dm=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gm=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fm=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mm=Object.freeze({__proto__:null,base32:am,base32upper:cm,base32pad:hm,base32padupper:lm,base32hex:um,base32hexupper:pm,base32hexpad:dm,base32hexpadupper:gm,base32z:fm});const ym=os({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wm=os({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var bm=Object.freeze({__proto__:null,base36:ym,base36upper:wm});const vm=os({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Em=os({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Im=Object.freeze({__proto__:null,base58btc:vm,base58flickr:Em});const _m=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Pm=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$m=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Sm=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Om=Object.freeze({__proto__:null,base64:_m,base64pad:Pm,base64url:$m,base64urlpad:Sm});const qc=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),xm=qc.reduce((i,e,t)=>(i[t]=e,i),[]),Am=qc.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Tm(i){return i.reduce((e,t)=>(e+=xm[t],e),"")}function Cm(i){const e=[];for(const t of i){const s=Am[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Nm=Gs({prefix:"🚀",name:"base256emoji",encode:Tm,decode:Cm});var Rm=Object.freeze({__proto__:null,base256emoji:Nm}),jm=kc,Do=128,qm=-128,km=Math.pow(2,31);function kc(i,e,t){e=e||[],t=t||0;for(var s=t;i>=km;)e[t++]=i&255|Do,i/=128;for(;i&qm;)e[t++]=i&255|Do,i>>>=7;return e[t]=i|0,kc.bytes=t-s+1,e}var Dm=zr,Lm=128,Lo=127;function zr(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw zr.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&Lo)<<r:(o&Lo)*Math.pow(2,r),r+=7}while(o>=Lm);return zr.bytes=n-s,t}var Mm=Math.pow(2,7),Um=Math.pow(2,14),zm=Math.pow(2,21),Bm=Math.pow(2,28),Km=Math.pow(2,35),Vm=Math.pow(2,42),Hm=Math.pow(2,49),Fm=Math.pow(2,56),Gm=Math.pow(2,63),Wm=function(i){return i<Mm?1:i<Um?2:i<zm?3:i<Bm?4:i<Km?5:i<Vm?6:i<Hm?7:i<Fm?8:i<Gm?9:10},Jm={encode:jm,decode:Dm,encodingLength:Wm},Dc=Jm;const Mo=(i,e,t=0)=>(Dc.encode(i,e,t),e),Uo=i=>Dc.encodingLength(i),Br=(i,e)=>{const t=e.byteLength,s=Uo(i),r=s+Uo(t),n=new Uint8Array(r+t);return Mo(i,n,0),Mo(t,n,s),n.set(e,r),new Qm(i,t,e,n)};class Qm{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Lc=({name:i,code:e,encode:t})=>new Ym(i,e,t);class Ym{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Br(this.code,t):t.then(s=>Br(this.code,s))}else throw Error("Unknown type, must be binary type")}}const Mc=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Zm=Lc({name:"sha2-256",code:18,encode:Mc("SHA-256")}),Xm=Lc({name:"sha2-512",code:19,encode:Mc("SHA-512")});var ey=Object.freeze({__proto__:null,sha256:Zm,sha512:Xm});const Uc=0,ty="identity",zc=Rc,iy=i=>Br(Uc,zc(i)),sy={code:Uc,name:ty,encode:zc,digest:iy};var ry=Object.freeze({__proto__:null,identity:sy});new TextEncoder,new TextDecoder;const zo={...Yf,...Xf,...tm,...sm,...om,...mm,...bm,...Im,...Om,...Rm};({...ey,...ry});function ny(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Bc(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Bo=Bc("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),dr=Bc("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=ny(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),oy={utf8:Bo,"utf-8":Bo,hex:zo.base16,latin1:dr,ascii:dr,binary:dr,...zo};function ay(i,e="utf8"){const t=oy[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(i,"utf8"):t.decoder.decode(`${t.prefix}${i}`)}var cy=Object.defineProperty,hy=(i,e,t)=>e in i?cy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,et=(i,e,t)=>hy(i,typeof e!="symbol"?e+"":e,t);class ly{constructor(e,t){this.core=e,this.logger=t,et(this,"keychain",new Map),et(this,"name",lf),et(this,"version",uf),et(this,"initialized",!1),et(this,"storagePrefix",ot),et(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),et(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),et(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),et(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=N("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),et(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Sr(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Or(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var uy=Object.defineProperty,py=(i,e,t)=>e in i?uy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,me=(i,e,t)=>py(i,typeof e!="symbol"?e+"":e,t);class dy{constructor(e,t,s){this.core=e,this.logger=t,me(this,"name",cf),me(this,"keychain"),me(this,"randomSessionIdentifier",Dr()),me(this,"initialized",!1),me(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),me(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),me(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=bn(r);return fh(n.publicKey)}),me(this,"generateKeyPair",()=>{this.isInitialized();const r=Jp();return this.setPrivateKey(r.publicKey,r.privateKey)}),me(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=bn(n),a=this.randomSessionIdentifier;return await mh(a,r,hf,o)}),me(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Qp(a,n);return this.setSymKey(c,o)}),me(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||Is(r);return await this.keychain.set(o,r),o}),me(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),me(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),me(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Pc(o),c=Hi(n);if(po(a))return Xp(c,o?.encoding);if(uo(a)){const p=a.senderPublicKey,d=a.receiverPublicKey;r=await this.generateSharedKey(p,d)}const h=this.getSymKey(r),{type:l,senderPublicKey:u}=a;return Yp({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o?.encoding})}),me(this,"decode",async(r,n,o)=>{this.isInitialized();const a=td(n,o);if(po(a)){const c=ed(n,o?.encoding);return Os(c)}if(uo(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Zp({symKey:c,encoded:n,encoding:o?.encoding});return Os(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),me(this,"getPayloadType",(r,n=Je)=>{const o=Yi({encoded:r,encoding:n});return Bt(o.type)}),me(this,"getPayloadSenderPublicKey",(r,n=Je)=>{const o=Yi({encoded:r,encoding:n});return o.senderPublicKey?Te(o.senderPublicKey,Pe):void 0}),this.core=e,this.logger=$e(t,this.name),this.keychain=s||new ly(this.core,this.logger)}get context(){return Ce(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(jo)}catch{e=Dr(),await this.keychain.set(jo,e)}return ay(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var gy=Object.defineProperty,fy=Object.defineProperties,my=Object.getOwnPropertyDescriptors,Ko=Object.getOwnPropertySymbols,yy=Object.prototype.hasOwnProperty,wy=Object.prototype.propertyIsEnumerable,Kr=(i,e,t)=>e in i?gy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,by=(i,e)=>{for(var t in e||(e={}))yy.call(e,t)&&Kr(i,t,e[t]);if(Ko)for(var t of Ko(e))wy.call(e,t)&&Kr(i,t,e[t]);return i},vy=(i,e)=>fy(i,my(e)),Ne=(i,e,t)=>Kr(i,typeof e!="symbol"?e+"":e,t);class Ey extends Hg{constructor(e,t){super(e,t),this.logger=e,this.core=t,Ne(this,"messages",new Map),Ne(this,"messagesWithoutClientAck",new Map),Ne(this,"name",pf),Ne(this,"version",df),Ne(this,"initialized",!1),Ne(this,"storagePrefix",ot),Ne(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const s=await this.getRelayerMessages();typeof s<"u"&&(this.messages=s);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(s){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(s)}finally{this.initialized=!0}}}),Ne(this,"set",async(s,r,n)=>{this.isInitialized();const o=rt(r);let a=this.messages.get(s);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(s,a),n===$s.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,vy(by({},c),{[o]:r}))}return await this.persist(),o}),Ne(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Ne(this,"getWithoutAck",s=>{this.isInitialized();const r={};for(const n of s){const o=this.messagesWithoutClientAck.get(n)||{};r[n]=Object.values(o)}return r}),Ne(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=rt(r);return typeof n[o]<"u"}),Ne(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=rt(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Ne(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=$e(e,this.name),this.core=t}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Sr(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Sr(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Or(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Or(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Iy=Object.defineProperty,_y=Object.defineProperties,Py=Object.getOwnPropertyDescriptors,Vo=Object.getOwnPropertySymbols,$y=Object.prototype.hasOwnProperty,Sy=Object.prototype.propertyIsEnumerable,Vr=(i,e,t)=>e in i?Iy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,fs=(i,e)=>{for(var t in e||(e={}))$y.call(e,t)&&Vr(i,t,e[t]);if(Vo)for(var t of Vo(e))Sy.call(e,t)&&Vr(i,t,e[t]);return i},gr=(i,e)=>_y(i,Py(e)),Ge=(i,e,t)=>Vr(i,typeof e!="symbol"?e+"":e,t);class Oy extends Fg{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Ge(this,"events",new St.EventEmitter),Ge(this,"name",gf),Ge(this,"queue",new Map),Ge(this,"publishTimeout",j.toMiliseconds(j.ONE_MINUTE)),Ge(this,"initialPublishTimeout",j.toMiliseconds(j.ONE_SECOND*15)),Ge(this,"needsTransportRestart",!1),Ge(this,"publish",async(s,r,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:s,message:r,opts:n}});const a=n?.ttl||qo,c=Cs(n),h=n?.prompt||!1,l=n?.tag||0,u=n?.id||li().toString(),p={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}},d=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const g=new Promise(async y=>{const f=({id:w})=>{p.opts.id===w&&(this.removeRequestFromQueue(w),this.relayer.events.removeListener(de.publish,f),y(p))};this.relayer.events.on(de.publish,f);const b=_t(new Promise((w,P)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:u,attestation:n?.attestation,tvf:n?.tvf}).then(w).catch(A=>{this.logger.warn(A,A?.message),P(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await b,this.events.removeListener(de.publish,f)}catch(w){this.queue.set(u,gr(fs({},p),{attempt:1})),this.logger.warn(w,w?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await _t(g,this.publishTimeout,d)}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(u)}}),Ge(this,"on",(s,r)=>{this.events.on(s,r)}),Ge(this,"once",(s,r)=>{this.events.once(s,r)}),Ge(this,"off",(s,r)=>{this.events.off(s,r)}),Ge(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=$e(t,this.name),this.registerEventListeners()}get context(){return Ce(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=qo,prompt:h,tag:l,id:u,attestation:p,tvf:d}=e,g={method:Li(Cs().protocol).publish,params:fs({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},d),id:u};we((t=g.params)==null?void 0:t.prompt)&&((s=g.params)==null||delete s.prompt),we((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 y=await this.relayer.request(g);return this.relayer.events.emit(de.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,gr(fs({},e),{attempt:s}));const{topic:r,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${s}`),await this.rpcPublish(gr(fs({},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(_i.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(de.connection_stalled);return}this.checkQueue()}),this.relayer.on(de.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var xy=Object.defineProperty,Ay=(i,e,t)=>e in i?xy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Jt=(i,e,t)=>Ay(i,typeof e!="symbol"?e+"":e,t);class Ty{constructor(){Jt(this,"map",new Map),Jt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),Jt(this,"get",e=>this.map.get(e)||[]),Jt(this,"exists",(e,t)=>this.get(e).includes(t)),Jt(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const s=this.get(e);if(!this.exists(e,t))return;const r=s.filter(n=>n!==t);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),Jt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Cy=Object.defineProperty,Ny=Object.defineProperties,Ry=Object.getOwnPropertyDescriptors,Ho=Object.getOwnPropertySymbols,jy=Object.prototype.hasOwnProperty,qy=Object.prototype.propertyIsEnumerable,Hr=(i,e,t)=>e in i?Cy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qi=(i,e)=>{for(var t in e||(e={}))jy.call(e,t)&&Hr(i,t,e[t]);if(Ho)for(var t of Ho(e))qy.call(e,t)&&Hr(i,t,e[t]);return i},fr=(i,e)=>Ny(i,Ry(e)),Z=(i,e,t)=>Hr(i,typeof e!="symbol"?e+"":e,t);class ky extends Jg{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Z(this,"subscriptions",new Map),Z(this,"topicMap",new Ty),Z(this,"events",new St.EventEmitter),Z(this,"name",Ef),Z(this,"version",If),Z(this,"pending",new Map),Z(this,"cached",[]),Z(this,"initialized",!1),Z(this,"storagePrefix",ot),Z(this,"subscribeTimeout",j.toMiliseconds(j.ONE_MINUTE)),Z(this,"initialSubscribeTimeout",j.toMiliseconds(j.ONE_SECOND*15)),Z(this,"clientId"),Z(this,"batchSubscribeTopicsLimit",500),Z(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Z(this,"subscribe",async(s,r)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:s,opts:r}});try{const n=Cs(r),o={topic:s,relay:n,transportType:r?.transportType};this.pending.set(s,o);const a=await this.rpcSubscribe(s,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:s,opts:r}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),Z(this,"unsubscribe",async(s,r)=>{this.isInitialized(),typeof r?.id<"u"?await this.unsubscribeById(s,r.id,r):await this.unsubscribeByTopic(s,r)}),Z(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),Z(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),Z(this,"on",(s,r)=>{this.events.on(s,r)}),Z(this,"once",(s,r)=>{this.events.once(s,r)}),Z(this,"off",(s,r)=>{this.events.off(s,r)}),Z(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),Z(this,"start",async()=>{await this.onConnect()}),Z(this,"stop",async()=>{await this.onDisconnect()}),Z(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Z(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const s=[];this.pending.forEach(r=>{s.push(r)}),await this.batchSubscribe(s)}),Z(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(_i.pulse,async()=>{await this.checkPending()}),this.events.on(je.created,async s=>{const r=je.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(je.deleted,async s=>{const r=je.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=$e(t,this.name),this.clientId=""}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const r=Cs(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Q("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:s}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,s){var r;(!s||s?.transportType===te.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Li(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(r=s?.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(s?.transportType===te.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},j.toMiliseconds(j.ONE_SECOND)),a;const c=new Promise(async l=>{const u=p=>{p.topic===e&&(this.events.removeListener(je.created,u),l(p.id))};this.events.on(je.created,u);try{const p=await _t(new Promise((d,g)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(je.created,u),l(p)}catch{}}),h=await _t(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(de.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Li(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await _t(new Promise(r=>{this.relayer.request(s).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Li(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let r;try{r=await await _t(new Promise((n,o)=>{this.relayer.request(s).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Li(s.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,fr(qi({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,qi({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,s){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,s),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,qi({},t)),this.topicMap.set(t.topic,e),this.events.emit(je.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:s}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const s=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(s.topic,e),this.events.emit(je.deleted,fr(qi({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(je.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let s=0;s<t;s++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(je.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=N("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=>fr(qi({},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 kl(j.toMiliseconds(j.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}=N("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 rt(e+await this.getClientId())}}var Dy=Object.defineProperty,Fo=Object.getOwnPropertySymbols,Ly=Object.prototype.hasOwnProperty,My=Object.prototype.propertyIsEnumerable,Fr=(i,e,t)=>e in i?Dy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Go=(i,e)=>{for(var t in e||(e={}))Ly.call(e,t)&&Fr(i,t,e[t]);if(Fo)for(var t of Fo(e))My.call(e,t)&&Fr(i,t,e[t]);return i},F=(i,e,t)=>Fr(i,typeof e!="symbol"?e+"":e,t);class Uy extends Gg{constructor(e){super(e),F(this,"protocol","wc"),F(this,"version",2),F(this,"core"),F(this,"logger"),F(this,"events",new St.EventEmitter),F(this,"provider"),F(this,"messages"),F(this,"subscriber"),F(this,"publisher"),F(this,"name",mf),F(this,"transportExplicitlyClosed",!1),F(this,"initialized",!1),F(this,"connectionAttemptInProgress",!1),F(this,"relayUrl"),F(this,"projectId"),F(this,"packageName"),F(this,"bundleId"),F(this,"hasExperiencedNetworkDisruption",!1),F(this,"pingTimeout"),F(this,"heartBeatTimeout",j.toMiliseconds(j.THIRTY_SECONDS+j.FIVE_SECONDS)),F(this,"reconnectTimeout"),F(this,"connectPromise"),F(this,"reconnectInProgress",!1),F(this,"requestsInFlight",[]),F(this,"connectTimeout",j.toMiliseconds(j.ONE_SECOND*15)),F(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||li().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(s=t.params)==null?void 0:s.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}}),F(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,s,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(s=(t=this.provider)==null?void 0:t.connection)==null?void 0:s.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),F(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),F(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(de.connect)}),F(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),F(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(de.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),F(this,"registerProviderListeners",()=>{this.provider.on(Me.payload,this.onPayloadHandler),this.provider.on(Me.connect,this.onConnectHandler),this.provider.on(Me.disconnect,this.onDisconnectHandler),this.provider.on(Me.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?$e(e.logger,this.name):rs(Fs({level:e.logger||ff})),this.messages=new Ey(this.logger,e.core),this.subscriber=new ky(this,this.logger),this.publisher=new Oy(this,this.logger),this.relayUrl=e?.relayUrl||Cc,this.projectId=e.projectId,vl()?this.packageName=qn():El()&&(this.bundleId=qn()),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 Ce(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1||!1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:te.relay},$s.outbound)}async subscribe(e,t){var s,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((s=t?.internal)==null?void 0:s.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 h=l=>{l.topic===e&&(this.subscriber.off(je.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(je.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,Go({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&u(p)})||a,l()})]),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 _t(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,s)=>{await this.connect(e).then(t).catch(s).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}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 Po())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((s,r)=>s.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const s of t)try{await this.onMessageEvent(s)}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:s}=e;if(!t.sessionExists){const r=ce(j.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(de.message,e),await this.recordMessageEvent(e,$s.inbound)}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(s,r)=>{const n=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Me.disconnect,n),await _t(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(Me.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(Me.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Me.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,s()})}catch(s){await this.subscriber.stop();const r=s;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(s=>setTimeout(s,j.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(As())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(s=this.provider)==null?void 0:s.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 Ke(new gh(Sl({sdkVersion:Ur,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:s,message:r}=e;await this.messages.set(s,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||s.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,s);return r&&this.logger.warn(`Ignoring duplicate message: ${s}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),sn(e)){if(!e.method.endsWith(yf))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:te.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Go({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else rn(e)&&this.events.emit(de.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,$s.inbound),this.events.emit(de.message,e))}async acknowledgePayload(e){const t=Ls(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Me.payload,this.onPayloadHandler),this.provider.off(Me.connect,this.onConnectHandler),this.provider.off(Me.disconnect,this.onDisconnectHandler),this.provider.off(Me.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Po();Wd(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(_i.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Yd())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(de.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},j.toMiliseconds(wf)))))}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function zy(){}function Wo(i){if(!i||typeof i!="object")return!1;const e=Object.getPrototypeOf(i);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(i)==="[object Object]":!1}function Jo(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Qo(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const By="[object RegExp]",Ky="[object String]",Vy="[object Number]",Hy="[object Boolean]",Yo="[object Arguments]",Fy="[object Symbol]",Gy="[object Date]",Wy="[object Map]",Jy="[object Set]",Qy="[object Array]",Yy="[object Function]",Zy="[object ArrayBuffer]",mr="[object Object]",Xy="[object Error]",ew="[object DataView]",tw="[object Uint8Array]",iw="[object Uint8ClampedArray]",sw="[object Uint16Array]",rw="[object Uint32Array]",nw="[object BigUint64Array]",ow="[object Int8Array]",aw="[object Int16Array]",cw="[object Int32Array]",hw="[object BigInt64Array]",lw="[object Float32Array]",uw="[object Float64Array]";function pw(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function dw(i,e,t){return Mi(i,e,void 0,void 0,void 0,void 0,t)}function Mi(i,e,t,s,r,n,o){const a=o(i,e,t,s,r,n);if(a!==void 0)return a;if(typeof i==typeof e)switch(typeof i){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return i===e;case"number":return i===e||Object.is(i,e);case"function":return i===e;case"object":return Vi(i,e,n,o)}return Vi(i,e,n,o)}function Vi(i,e,t,s){if(Object.is(i,e))return!0;let r=Qo(i),n=Qo(e);if(r===Yo&&(r=mr),n===Yo&&(n=mr),r!==n)return!1;switch(r){case Ky:return i.toString()===e.toString();case Vy:{const c=i.valueOf(),h=e.valueOf();return pw(c,h)}case Hy:case Gy:case Fy:return Object.is(i.valueOf(),e.valueOf());case By:return i.source===e.source&&i.flags===e.flags;case Yy:return i===e}t=t??new Map;const o=t.get(i),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(i,e),t.set(e,i);try{switch(r){case Wy:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!Mi(h,e.get(c),c,i,e,t,s))return!1;return!0}case Jy:{if(i.size!==e.size)return!1;const c=Array.from(i.values()),h=Array.from(e.values());for(let l=0;l<c.length;l++){const u=c[l],p=h.findIndex(d=>Mi(u,d,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case Qy:case tw:case iw:case sw:case rw:case nw:case ow:case aw:case cw:case hw:case lw:case uw:{if(typeof Ie<"u"&&Ie.isBuffer(i)!==Ie.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!Mi(i[c],e[c],c,i,e,t,s))return!1;return!0}case Zy:return i.byteLength!==e.byteLength?!1:Vi(new Uint8Array(i),new Uint8Array(e),t,s);case ew:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:Vi(new Uint8Array(i),new Uint8Array(e),t,s);case Xy:return i.name===e.name&&i.message===e.message;case mr:{if(!(Vi(i.constructor,e.constructor,t,s)||Wo(i)&&Wo(e)))return!1;const c=[...Object.keys(i),...Jo(i)],h=[...Object.keys(e),...Jo(e)];if(c.length!==h.length)return!1;for(let l=0;l<c.length;l++){const u=c[l],p=i[u];if(!Object.hasOwn(e,u))return!1;const d=e[u];if(!Mi(p,d,u,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function gw(i,e){return dw(i,e,zy)}var fw=Object.defineProperty,Zo=Object.getOwnPropertySymbols,mw=Object.prototype.hasOwnProperty,yw=Object.prototype.propertyIsEnumerable,Gr=(i,e,t)=>e in i?fw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xo=(i,e)=>{for(var t in e||(e={}))mw.call(e,t)&&Gr(i,t,e[t]);if(Zo)for(var t of Zo(e))yw.call(e,t)&&Gr(i,t,e[t]);return i},Se=(i,e,t)=>Gr(i,typeof e!="symbol"?e+"":e,t);class Kt extends Wg{constructor(e,t,s,r=ot,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,Se(this,"map",new Map),Se(this,"version",bf),Se(this,"cached",[]),Se(this,"initialized",!1),Se(this,"getKey"),Se(this,"storagePrefix",ot),Se(this,"recentlyDeleted",[]),Se(this,"recentlyDeletedLimit",200),Se(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!we(o)?this.map.set(this.getKey(o),o):$d(o)?this.map.set(o.id,o):Sd(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Se(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())}),Se(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Se(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>gw(a[c],o[c]))):this.values)),Se(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=Xo(Xo({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Se(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=$e(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return Ce(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}=N("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}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}=N("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}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ww=Object.defineProperty,bw=(i,e,t)=>e in i?ww(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,B=(i,e,t)=>bw(i,typeof e!="symbol"?e+"":e,t);class vw{constructor(e,t){this.core=e,this.logger=t,B(this,"name",_f),B(this,"version",Pf),B(this,"events",new tn),B(this,"pairings"),B(this,"initialized",!1),B(this,"storagePrefix",ot),B(this,"ignoredPayloadTypes",[mt]),B(this,"registeredMethods",[]),B(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),B(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),B(this,"create",async s=>{this.isInitialized();const r=Dr(),n=await this.core.crypto.setSymKey(r),o=ce(j.FIVE_MINUTES),a={protocol:Tc},c={topic:n,expiry:o,relay:a,active:!1,methods:s?.methods},h=fo({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:s?.methods});return this.events.emit(jt.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:s?.transportType}),{topic:n,uri:h}}),B(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s?.uri,trace:[it.pairing_started]}});this.isValidPair(s,r);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=go(s.uri);r.props.properties.topic=n,r.addTrace(it.pairing_uri_validation_success),r.addTrace(it.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(it.existing_pairing),l.active)throw r.setError(pt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(it.pairing_not_expired)}const u=c||ce(j.FIVE_MINUTES),p={topic:n,relay:a,expiry:u,active:!1,methods:h};this.core.expirer.set(n,u),await this.pairings.set(n,p),r.addTrace(it.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(jt.create,p),r.addTrace(it.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(it.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(pt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(d){throw r.setError(pt.subscribe_pairing_topic_failure),d}return r.addTrace(it.subscribe_pairing_topic_success),p}),B(this,"activate",async({topic:s})=>{this.isInitialized();const r=ce(j.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),B(this,"ping",async s=>{this.isInitialized(),await this.isValidPing(s),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=s;if(this.pairings.keys.includes(r)){const n=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ct();this.events.once(J("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),B(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),B(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),B(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),B(this,"disconnect",async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:r}=s;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Q("USER_DISCONNECTED")),await this.deletePairing(r))}),B(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return fo({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),B(this,"sendRequest",async(s,r,n)=>{const o=kt(r,n),a=await this.core.crypto.encode(s,o),c=Ri[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),B(this,"sendResult",async(s,r,n)=>{const o=Ls(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=Ri[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),B(this,"sendError",async(s,r,n)=>{const o=$a(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=Ri[c]?Ri[c].res:Ri.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),B(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,Q("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),B(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>Et(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),B(this,"onRelayEventRequest",async s=>{const{topic:r,payload:n}=s;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,n);default:return await this.onUnknownRpcMethodRequest(r,n)}}),B(this,"onRelayEventResponse",async s=>{const{topic:r,payload:n}=s,o=(await this.core.history.get(r,n.id)).request.method;return o==="wc_pairingPing"?this.onPairingPingResponse(r,n):this.onUnknownRpcMethodResponse(o)}),B(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(jt.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),B(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{ut(r)?this.events.emit(J("pairing_ping",n),{}):st(r)&&this.events.emit(J("pairing_ping",n),{error:r.error})},500)}),B(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(jt.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),B(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Q("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,s,a),this.logger.error(a)}catch(a){await this.sendError(n,s,a),this.logger.error(a)}}),B(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(Q("WC_METHOD_UNSUPPORTED",s))}),B(this,"isValidPair",(s,r)=>{var n;if(!xe(s)){const{message:a}=N("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(pt.malformed_pairing_uri),new Error(a)}if(!Pd(s.uri)){const{message:a}=N("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(pt.malformed_pairing_uri),new Error(a)}const o=go(s?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=N("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(pt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=N("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(pt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&j.toMiliseconds(o?.expiryTimestamp)<Date.now()){r.setError(pt.pairing_expired);const{message:a}=N("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),B(this,"isValidPing",async s=>{if(!xe(s)){const{message:n}=N("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),B(this,"isValidDisconnect",async s=>{if(!xe(s)){const{message:n}=N("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),B(this,"isValidPairingTopic",async s=>{if(!ne(s,!1)){const{message:r}=N("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=N("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(Et(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=N("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=$e(t,this.name),this.pairings=new Kt(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ce(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(de.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==te.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);sn(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):rn(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,s)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(ze.expired,async e=>{const{topic:t}=Ha(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(jt.expire,{topic:t}))})}}var Ew=Object.defineProperty,Iw=(i,e,t)=>e in i?Ew(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>Iw(i,typeof e!="symbol"?e+"":e,t);class _w extends Vg{constructor(e,t){super(e,t),this.core=e,this.logger=t,ye(this,"records",new Map),ye(this,"events",new St.EventEmitter),ye(this,"name",$f),ye(this,"version",Sf),ye(this,"cached",[]),ye(this,"initialized",!1),ye(this,"storagePrefix",ot),ye(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.records.set(s.id,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ye(this,"set",(s,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:s,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:s,request:{method:r.method,params:r.params||null},chainId:n,expiry:ce(j.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(He.created,o)}),ye(this,"resolve",async s=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:s}),!this.records.has(s.id))return;const r=await this.getRecord(s.id);typeof r.response>"u"&&(r.response=st(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(He.updated,r))}),ye(this,"get",async(s,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:s,id:r}),await this.getRecord(r))),ye(this,"delete",(s,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(n=>{if(n.topic===s){if(typeof r<"u"&&n.id!==r)return;this.records.delete(n.id),this.events.emit(He.deleted,n)}}),this.persist()}),ye(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),ye(this,"on",(s,r)=>{this.events.on(s,r)}),ye(this,"once",(s,r)=>{this.events.once(s,r)}),ye(this,"off",(s,r)=>{this.events.off(s,r)}),ye(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:kt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:s}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(He.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=N("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(He.created,e=>{const t=He.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(He.updated,e=>{const t=He.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(He.deleted,e=>{const t=He.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(_i.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{j.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(He.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Pw=Object.defineProperty,$w=(i,e,t)=>e in i?Pw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ee=(i,e,t)=>$w(i,typeof e!="symbol"?e+"":e,t);class Sw extends Qg{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ee(this,"expirations",new Map),Ee(this,"events",new St.EventEmitter),Ee(this,"name",Of),Ee(this,"version",xf),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",ot),Ee(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ee(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ee(this,"set",(s,r)=>{this.isInitialized();const n=this.formatTarget(s),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(ze.created,{target:n,expiration:o})}),Ee(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),Ee(this,"del",s=>{if(this.isInitialized(),this.has(s)){const r=this.formatTarget(s),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(ze.deleted,{target:r,expiration:n})}}),Ee(this,"on",(s,r)=>{this.events.on(s,r)}),Ee(this,"once",(s,r)=>{this.events.once(s,r)}),Ee(this,"off",(s,r)=>{this.events.off(s,r)}),Ee(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=$e(t,this.name)}get context(){return Ce(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 Ol(e);if(typeof e=="number")return xl(e);const{message:t}=N("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(ze.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=N("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:s}=N("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;j.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(ze.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(_i.pulse,()=>this.checkExpirations()),this.events.on(ze.created,e=>{const t=ze.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ze.expired,e=>{const t=ze.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(ze.deleted,e=>{const t=ze.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ow=Object.defineProperty,xw=(i,e,t)=>e in i?Ow(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,re=(i,e,t)=>xw(i,typeof e!="symbol"?e+"":e,t);class Aw extends Yg{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,re(this,"name",Af),re(this,"abortController"),re(this,"isDevEnv"),re(this,"verifyUrlV3",Cf),re(this,"storagePrefix",ot),re(this,"version",Ac),re(this,"publicKey"),re(this,"fetchPromise"),re(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&j.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),re(this,"register",async r=>{if(!Si()||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 h=yt.getDocument(),l=this.startAbortTimer(j.ONE_SECOND*5),u=await new Promise((p,d)=>{const g=()=>{window.removeEventListener("message",f),h.body.removeChild(y),d("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const y=h.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",g,{signal:this.abortController.signal});const f=b=>{if(b.data&&typeof b.data=="string")try{const w=JSON.parse(b.data);if(w.type==="verify_attestation"){if(_r(w.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(y),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",f),p(w.attestation===null?"":w.attestation)}}catch(w){this.logger.warn(w)}};h.body.appendChild(y),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),re(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(_r(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(r?.verifyUrl);return this.fetchAttestation(o,c)}),re(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(j.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}),re(this,"getVerifyUrl",r=>{let n=r||Ki;return Nf.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ki}`),n=Ki),n}),re(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(j.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)}}),re(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),re(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),re(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")}}),re(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),re(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}),re(this,"validateAttestation",(r,n)=>{const o=sd(r,n.publicKey),a={hasExpired:j.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=$e(t,this.name),this.abortController=new AbortController,this.isDevEnv=on(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ce(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),j.toMiliseconds(e))}}var Tw=Object.defineProperty,Cw=(i,e,t)=>e in i?Tw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ea=(i,e,t)=>Cw(i,typeof e!="symbol"?e+"":e,t);class Nw extends Zg{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,ea(this,"context",Rf),ea(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${jf}/${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=$e(t,this.context)}}var Rw=Object.defineProperty,ta=Object.getOwnPropertySymbols,jw=Object.prototype.hasOwnProperty,qw=Object.prototype.propertyIsEnumerable,Wr=(i,e,t)=>e in i?Rw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ki=(i,e)=>{for(var t in e||(e={}))jw.call(e,t)&&Wr(i,t,e[t]);if(ta)for(var t of ta(e))qw.call(e,t)&&Wr(i,t,e[t]);return i},he=(i,e,t)=>Wr(i,typeof e!="symbol"?e+"":e,t);class kw extends Xg{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,he(this,"context",kf),he(this,"storagePrefix",ot),he(this,"storageVersion",qf),he(this,"events",new Map),he(this,"shouldPersist",!1),he(this,"init",async()=>{if(!on())try{const r={eventId:Dn(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ka(this.core.relayer.protocol,this.core.relayer.version,Ur)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),he(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=Dn(),l=this.core.projectId||"",u=Date.now(),p=ki({eventId:h,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(h));return this.telemetryEnabled&&(this.events.set(h,p),this.shouldPersist=!0),p}),he(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 ki(ki({},a),this.setMethods(a.eventId))}),he(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),he(this,"setEventListeners",()=>{this.core.heartbeat.on(_i.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{j.fromMiliseconds(Date.now())-j.fromMiliseconds(r.timestamp)>Df&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),he(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),he(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)}),he(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)}),he(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),he(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,ki(ki({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),he(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)}}),he(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Lf}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ur}${n}`,{method:"POST",body:JSON.stringify(r)})}),he(this,"getAppDomain",()=>Ba().url),this.logger=$e(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var Dw=Object.defineProperty,ia=Object.getOwnPropertySymbols,Lw=Object.prototype.hasOwnProperty,Mw=Object.prototype.propertyIsEnumerable,Jr=(i,e,t)=>e in i?Dw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,sa=(i,e)=>{for(var t in e||(e={}))Lw.call(e,t)&&Jr(i,t,e[t]);if(ia)for(var t of ia(e))Mw.call(e,t)&&Jr(i,t,e[t]);return i},ee=(i,e,t)=>Jr(i,typeof e!="symbol"?e+"":e,t);let Uw=class Kc extends Ug{constructor(e){var t;super(e),ee(this,"protocol",xc),ee(this,"version",Ac),ee(this,"name",Mr),ee(this,"relayUrl"),ee(this,"projectId"),ee(this,"customStoragePrefix"),ee(this,"events",new St.EventEmitter),ee(this,"logger"),ee(this,"heartbeat"),ee(this,"relayer"),ee(this,"crypto"),ee(this,"storage"),ee(this,"history"),ee(this,"expirer"),ee(this,"pairing"),ee(this,"verify"),ee(this,"echoClient"),ee(this,"linkModeSupportedApps"),ee(this,"eventClient"),ee(this,"initialized",!1),ee(this,"logChunkController"),ee(this,"on",(a,c)=>this.events.on(a,c)),ee(this,"once",(a,c)=>this.events.once(a,c)),ee(this,"off",(a,c)=>this.events.off(a,c)),ee(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ee(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:te.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e?.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Cc,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Fs({level:typeof e?.logger=="string"&&e.logger?e.logger:of.logger,name:Mr}),{logger:n,chunkLoggerController:o}=Dg({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(t=this.logChunkController)!=null&&t.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=$e(n,this.name),this.heartbeat=new dh,this.crypto=new dy(this,this.logger,e?.keychain),this.history=new _w(this,this.logger),this.expirer=new Sw(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Eg(sa(sa({},af),e?.storageOptions)),this.relayer=new Uy({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new vw(this,this.logger),this.verify=new Aw(this,this.logger,this.storage),this.echoClient=new Nw(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new kw(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Kc(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(vf,s),t}get context(){return Ce(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(ko,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(ko)||[],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}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,s=`${t}_count`;return globalThis[s]=(globalThis[s]||0)+1,globalThis[s]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[s]} times.`),globalThis[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[s]=e}catch(s){console.warn("Failed to set global WalletConnect core",s)}}isGlobalCoreDisabled(){try{return typeof Ui<"u"&&nf.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const zw=Uw,Vc="wc",Hc=2,Fc="client",fn=`${Vc}@${Hc}:${Fc}:`,yr={name:Fc,logger:"error"},ra="WALLETCONNECT_DEEPLINK_CHOICE",Bw="proposal",na="Proposal expired",Kw="session",Qt=j.SEVEN_DAYS,Vw="engine",le={wc_sessionPropose:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1104},res:{ttl:j.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1106},res:{ttl:j.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:j.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1112},res:{ttl:j.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:j.ONE_DAY,prompt:!1,tag:1114},res:{ttl:j.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:j.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:j.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:j.FIVE_MINUTES,prompt:!1,tag:1119}}},wr={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},tt={idle:"IDLE",active:"ACTIVE"},oa={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Hw="request",Fw=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Gw="wc",Ww="auth",Jw="authKeys",Qw="pairingTopics",Yw="requests",Ws=`${Gw}@${1.5}:${Ww}:`,Ss=`${Ws}:PUB_KEY`;var Zw=Object.defineProperty,Xw=Object.defineProperties,eb=Object.getOwnPropertyDescriptors,aa=Object.getOwnPropertySymbols,tb=Object.prototype.hasOwnProperty,ib=Object.prototype.propertyIsEnumerable,Qr=(i,e,t)=>e in i?Zw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,X=(i,e)=>{for(var t in e||(e={}))tb.call(e,t)&&Qr(i,t,e[t]);if(aa)for(var t of aa(e))ib.call(e,t)&&Qr(i,t,e[t]);return i},_e=(i,e)=>Xw(i,eb(e)),S=(i,e,t)=>Qr(i,typeof e!="symbol"?e+"":e,t);class sb extends rf{constructor(e){super(e),S(this,"name",Vw),S(this,"events",new tn),S(this,"initialized",!1),S(this,"requestQueue",{state:tt.idle,queue:[]}),S(this,"sessionRequestQueue",{state:tt.idle,queue:[]}),S(this,"requestQueueDelay",j.ONE_SECOND),S(this,"expectedPairingMethodMap",new Map),S(this,"recentlyDeletedMap",new Map),S(this,"recentlyDeletedLimit",200),S(this,"relayMessageCache",[]),S(this,"pendingSessions",new Map),S(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(le)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay)))}),S(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=_e(X({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=bd(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=s;let l=r,u,p=!1;try{if(l){const m=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."),p=m.active}}catch(m){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),m}if(!l||!p){const{topic:m,uri:E}=await this.client.core.pairing.create();l=m,u=E}if(!l){const{message:m}=N("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(m)}const d=await this.client.core.crypto.generateKeyPair(),g=le.wc_sessionPropose.req.ttl||j.FIVE_MINUTES,y=ce(g),f=_e(X(X({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:Tc}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:wt()}),b=J("session_connect",f.id),{reject:w,resolve:P,done:A}=Ct(g,na),R=({id:m})=>{m===f.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(f.id),this.events.emit(b,{error:{message:na,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(b,({error:m,session:E})=>{this.client.events.off("proposal_expire",R),m?w(m):E&&P(E)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:u,approval:A}}),S(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(s){throw this.client.logger.error("pair() failed"),s}}),S(this,"approve",async t=>{var s,r,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(s=t?.id)==null?void 0:s.toString(),trace:[Fe.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(I){throw o.setError(At.no_internet_connection),I}try{await this.isValidProposalId(t?.id)}catch(I){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),o.setError(At.proposal_not_found),I}try{await this.isValidApprove(t)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(At.session_approve_namespace_validation_failure),I}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=t,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:y,requiredNamespaces:f,optionalNamespaces:b}=d;let w=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:g});w||(w=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Fe.session_approve_started,properties:{topic:g,trace:[Fe.session_approve_started,Fe.session_namespaces_validation_success]}}));const P=await this.client.core.crypto.generateKeyPair(),A=y.publicKey,R=await this.client.core.crypto.generateSharedKey(P,A),m=X(X(X({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:P,metadata:this.client.metadata},expiry:ce(Qt)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),E=te.relay;w.addTrace(Fe.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:E})}catch(I){throw w.setError(At.subscribe_session_topic_failure),I}w.addTrace(Fe.subscribe_session_topic_success);const _=_e(X({},m),{topic:R,requiredNamespaces:f,optionalNamespaces:b,pairingTopic:g,acknowledged:!1,self:m.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:P,transportType:te.relay});await this.client.session.set(R,_),w.addTrace(Fe.store_session);try{w.addTrace(Fe.publishing_session_settle),await this.sendRequest({topic:R,method:"wc_sessionSettle",params:m,throwOnFailedPublish:!0}).catch(I=>{throw w?.setError(At.session_settle_publish_failure),I}),w.addTrace(Fe.session_settle_publish_success),w.addTrace(Fe.publishing_session_approve),await this.sendResult({id:a,topic:g,result:{relay:{protocol:c??"irn"},responderPublicKey:P},throwOnFailedPublish:!0}).catch(I=>{throw w?.setError(At.session_approve_publish_failure),I}),w.addTrace(Fe.session_approve_publish_success)}catch(I){throw this.client.logger.error(I),this.client.session.delete(R,Q("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),I}return this.client.core.eventClient.deleteEvent({eventId:w.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:y.metadata}),await this.client.proposal.delete(a,Q("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(R,ce(Qt)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}}),S(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:s,reason:r}=t;let n;try{n=this.client.proposal.get(s).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${s}) failed`),o}n&&(await this.sendError({id:s,topic:n,error:r,rpcOpts:le.wc_sessionPropose.reject}),await this.client.proposal.delete(s,Q("USER_DISCONNECTED")))}),S(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:s,namespaces:r}=t,{done:n,resolve:o,reject:a}=Ct(),c=wt(),h=li().toString(),l=this.client.session.get(s).namespaces;return this.events.once(J("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(s,{namespaces:r}),await this.sendRequest({topic:s,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(u=>{this.client.logger.error(u),this.client.session.update(s,{namespaces:l}),a(u)}),{acknowledged:n}}),S(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:s}=t,r=wt(),{done:n,resolve:o,reject:a}=Ct();return this.events.once(J("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ce(Qt)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),S(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:s,request:r,topic:n,expiry:o=le.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);a?.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const c=wt(),h=li().toString(),{done:l,resolve:u,reject:p}=Ct(o,"Request expired. Please try again.");this.events.once(J("session_request",c),({error:b,result:w})=>{b?p(b):u(w)});const d="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:{request:_e(X({},r),{expiryTimestamp:ce(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(b=>p(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const y={request:_e(X({},r),{expiryTimestamp:ce(o)}),chainId:s},f=this.shouldSetTVF(d,y);return await Promise.all([new Promise(async b=>{await this.sendRequest(X({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:y,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,y)})).catch(w=>p(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),b()}),new Promise(async b=>{var w;if(!((w=a.sessionConfig)!=null&&w.disableDeepLink)){const P=await Nl(this.client.core.storage,ra);await Al({id:c,topic:n,wcDeepLink:P})}b()}),l()]).then(b=>b[2])}),S(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:s,response:r}=t,{id:n}=r,o=this.client.session.get(s);o.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);ut(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):st(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),S(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:s}=t;if(this.client.session.keys.includes(s)){const r=wt(),n=li().toString(),{done:o,resolve:a,reject:c}=Ct();this.events.once(J("session_ping",r),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:s,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(s)&&(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:s}))}),S(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:s,event:r,chainId:n}=t,o=li().toString(),a=wt();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),S(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:s}=t;if(this.client.session.keys.includes(s))await this.sendRequest({topic:s,method:"wc_sessionDelete",params:Q("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:s,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(s))await this.client.core.pairing.disconnect({topic:s});else{const{message:r}=N("MISMATCHED_TOPIC",`Session or pairing topic not found: ${s}`);throw new Error(r)}}),S(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>Id(s,t)))),S(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),S(this,"authenticate",async(t,s)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=s&&this.client.core.linkModeSupportedApps.includes(s)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?te.link_mode:te.relay;o===te.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:d,nbf:g,methods:y=[],expiry:f}=t,b=[...t.resources||[]],{topic:w,uri:P}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:w,uri:P}});const A=await this.client.core.crypto.generateKeyPair(),R=Is(A);if(await Promise.all([this.client.auth.authKeys.set(Ss,{responseTopic:R,publicKey:A}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:w})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${w}`),y.length>0){const{namespace:O}=gi(a[0]);let D=Pu(O,"request",y);Es(b)&&(D=Su(D,b.pop())),b.push(D)}const m=f&&f>le.wc_sessionAuthenticate.req.ttl?f:le.wc_sessionAuthenticate.req.ttl,E={authPayload:{type:p??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:d,nbf:g,resources:b},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:ce(m)},_={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},I={requiredNamespaces:{},optionalNamespaces:_,relays:[{protocol:"irn"}],pairingTopic:w,proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:ce(le.wc_sessionPropose.req.ttl),id:wt()},{done:C,resolve:T,reject:q}=Ct(m,"Request expired"),M=wt(),v=J("session_connect",I.id),$=J("session_request",M),x=async({error:O,session:D})=>{this.events.off($,k),O?q(O):D&&T({session:D})},k=async O=>{var D,U,z;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),O.error){const ae=Q("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===ae.code?void 0:(this.events.off(v,x),q(O.error.message))}await this.deleteProposal(I.id),this.events.off(v,x);const{cacaos:W,responder:V}=O.result,ie=[],Y=[];for(const ae of W){await Hn({cacao:ae,projectId:this.client.core.projectId})||(this.client.logger.error(ae,"Signature verification failed"),q(Q("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:xt}=ae,at=Es(xt.resources),Ze=[xr(xt.iss)],ct=Ts(xt.iss);if(at){const Ht=Fn(at),as=Gn(at);ie.push(...Ht),Ze.push(...as)}for(const Ht of Ze)Y.push(`${Ht}:${ct}`)}const ve=await this.client.core.crypto.generateSharedKey(A,V.publicKey);let oe;ie.length>0&&(oe={topic:ve,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:V,controller:V.publicKey,expiry:ce(Qt),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:w,namespaces:bo([...new Set(ie)],[...new Set(Y)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,oe),w&&await this.client.core.pairing.updateMetadata({topic:w,metadata:V.metadata}),oe=this.client.session.get(ve)),(D=this.client.metadata.redirect)!=null&&D.linkMode&&(U=V.metadata.redirect)!=null&&U.linkMode&&(z=V.metadata.redirect)!=null&&z.universal&&s&&(this.client.core.addLinkModeSupportedApp(V.metadata.redirect.universal),this.client.session.update(ve,{transportType:te.link_mode})),T({auths:W,session:oe})};this.events.once(v,x),this.events.once($,k);let L;try{if(n){const O=kt("wc_sessionAuthenticate",E,M);this.client.core.history.set(w,O);const D=await this.client.core.crypto.encode("",O,{type:ss,encoding:It});L=ds(s,w,D)}else await Promise.all([this.sendRequest({topic:w,method:"wc_sessionAuthenticate",params:E,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:M}),this.sendRequest({topic:w,method:"wc_sessionPropose",params:I,expiry:le.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:I.id})])}catch(O){throw this.events.off(v,x),this.events.off($,k),O}return await this.setProposal(I.id,I),await this.setAuthRequest(M,{request:_e(X({},E),{verifyContext:{}}),pairingTopic:w,transportType:o}),{uri:L??P,response:C}}),S(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[Tt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(ji.no_internet_connection),f}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(ji.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||te.relay;a===te.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=Is(c),u={type:mt,receiverPublicKey:c,senderPublicKey:h},p=[],d=[];for(const f of r){if(!await Hn({cacao:f,projectId:this.client.core.projectId})){n.setError(ji.invalid_cacao);const R=Q("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:R,encodeOpts:u}),new Error(R.message)}n.addTrace(Tt.cacaos_verified);const{p:b}=f,w=Es(b.resources),P=[xr(b.iss)],A=Ts(b.iss);if(w){const R=Fn(w),m=Gn(w);p.push(...R),P.push(...m)}for(const R of P)d.push(`${R}:${A}`)}const g=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Tt.create_authenticated_session_topic);let y;if(p?.length>0){y={topic:g,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ce(Qt),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:bo([...new Set(p)],[...new Set(d)]),transportType:a},n.addTrace(Tt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(f){throw n.setError(ji.subscribe_authenticated_session_topic_failure),f}n.addTrace(Tt.subscribe_authenticated_session_topic_success),await this.client.session.set(g,y),n.addTrace(Tt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Tt.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:s,result:{cacaos:r,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(f){throw n.setError(ji.authenticated_session_approve_publish_failure),f}return await this.client.auth.requests.delete(s,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:y}}),S(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:s,reason:r}=t,n=this.getPendingAuthRequest(s);if(!n)throw new Error(`Could not find pending auth request with id ${s}`);n.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Is(o),h={type:mt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:le.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(s,{message:"rejected",code:0}),await this.client.proposal.delete(s,Q("USER_DISCONNECTED"))}),S(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return ec(s,r)}),S(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)}),S(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const s=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!==s.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(s){this.client.logger.error(s)}}),S(this,"deleteSession",async t=>{var s;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,Q("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(ra).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,Q("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=tt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),S(this,"deleteProposal",async(t,s)=>{if(s)try{const r=this.client.proposal.get(t);this.client.core.eventClient.getEvent({topic:r.pairingTopic})?.setError(At.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Q("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),S(this,"deletePendingSessionRequest",async(t,s,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,s),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=tt.idle,this.client.events.emit("session_request_expire",{id:t}))}),S(this,"deletePendingAuthRequest",async(t,s,r=!1)=>{await Promise.all([this.client.auth.requests.delete(t,s),r?Promise.resolve():this.client.core.expirer.del(t)])}),S(this,"setExpiry",async(t,s)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,s),await this.client.session.update(t,{expiry:s}))}),S(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ce(le.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),S(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=te.relay}=s;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})}),S(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ce(le.wc_sessionRequest.req.ttl);this.client.core.expirer.set(s,a),await this.client.pendingRequest.set(s,{id:s,topic:r,params:n,verifyContext:o})}),S(this,"sendRequest",async t=>{const{topic:s,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:u}=t,p=kt(r,n,c);let d;const g=!!l;try{const b=g?It:Je;d=await this.client.core.crypto.encode(s,p,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),b}let y;if(Fw.includes(r)){const b=rt(JSON.stringify(p)),w=rt(d);y=await this.client.core.verify.register({id:w,decryptedId:b})}const f=le[r].req;if(f.attestation=y,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(s,p),g){const b=ds(l,s,d);await globalThis.Linking.openURL(b,this.client.name)}else{const b=le[r].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=_e(X({},u),{correlationId:p.id}),h?(b.internal=_e(X({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,d,b)):this.client.core.relayer.publish(s,d,b).catch(w=>this.client.logger.error(w))}return p.id}),S(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=Ls(s,n);let l;const u=c&&typeof globalThis?.Linking<"u";try{const g=u?It:Je;l=await this.client.core.crypto.encode(r,h,_e(X({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let p,d;try{p=await this.client.core.history.get(r,s);const g=p.request;try{this.shouldSetTVF(g.method,g.params)&&(d=this.getTVFParams(s,g.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),g}if(u){const g=ds(c,r,l);await globalThis.Linking.openURL(g,this.client.name)}else{const g=p.request.method,y=le[g].res;y.tvf=_e(X({},d),{correlationId:s}),o?(y.internal=_e(X({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,y)):this.client.core.relayer.publish(r,l,y).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(h)}),S(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=$a(s,n);let l;const u=c&&typeof globalThis?.Linking<"u";try{const d=u?It:Je;l=await this.client.core.crypto.encode(r,h,_e(X({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),d}let p;try{p=await this.client.core.history.get(r,s)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),d}if(u){const d=ds(c,r,l);await globalThis.Linking.openURL(d,this.client.name)}else{const d=p.request.method,g=a||le[d].res;this.client.core.relayer.publish(r,l,g)}await this.client.core.history.resolve(h)}),S(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;Et(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=>{Et(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),S(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),S(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),S(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===tt.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=tt.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=tt.idle}),S(this,"processRequest",async t=>{const{topic:s,payload:r,attestation:n,transportType:o,encryptedId:a}=t,c=r.method;if(!this.shouldIgnorePairingRequest({topic:s,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:s,payload:r,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(s,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(s,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(s,r);case"wc_sessionPing":return await this.onSessionPingRequest(s,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(s,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(s,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:s,payload:r,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),S(this,"onRelayEventResponse",async t=>{const{topic:s,payload:r,transportType:n}=t,o=(await this.client.core.history.get(s,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(s,r,n);case"wc_sessionSettle":return this.onSessionSettleResponse(s,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(s,r);case"wc_sessionExtend":return this.onSessionExtendResponse(s,r);case"wc_sessionPing":return this.onSessionPingResponse(s,r);case"wc_sessionRequest":return this.onSessionRequestResponse(s,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(s,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),S(this,"onRelayEventUnknownPayload",t=>{const{topic:s}=t,{message:r}=N("MISSING_OR_INVALID",`Decoded payload on topic ${s} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),S(this,"shouldIgnorePairingRequest",t=>{const{topic:s,requestMethod:r}=t,n=this.expectedPairingMethodMap.get(s);return!n||n.includes(r)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),S(this,"onSessionProposeRequest",async t=>{const{topic:s,payload:r,attestation:n,encryptedId:o}=t,{params:a,id:c}=r;try{const h=this.client.core.eventClient.getEvent({topic:s});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),h?.setError(pt.proposal_listener_not_found)),this.isValidConnect(X({},r.params));const l=a.expiryTimestamp||ce(le.wc_sessionPropose.req.ttl),u=X({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:rt(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h?.addTrace(it.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:p})}catch(h){await this.sendError({id:c,topic:s,error:h,rpcOpts:le.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),S(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(ut(s)){const{result:o}=s;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 h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(n,{sessionTopic:l,pairingTopic:t,proposalId:n,publicKey:c});const u=await this.client.core.relayer.subscribe(l,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:t})}else if(st(s)){await this.client.proposal.delete(n,Q("USER_DISCONNECTED"));const o=J("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:s.error})}}),S(this,"onSessionSettleRequest",async(t,s)=>{const{id:r,params:n}=s;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=s.params,d=[...this.pendingSessions.values()].find(f=>f.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const g=this.client.proposal.get(d.proposalId),y=_e(X(X(X({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),{transportType:te.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(J("session_connect",d.proposalId),{session:y}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:s.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),S(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;ut(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(J("session_approve",r),{})):st(s)&&(await this.client.session.delete(t,Q("USER_DISCONNECTED")),this.events.emit(J("session_approve",r),{error:s.error}))}),S(this,"onSessionUpdateRequest",async(t,s)=>{const{params:r,id:n}=s;try{const o=`${t}_session_update`,a=Ni.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:Q("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(X({topic:t},r));try{Ni.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 Ni.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)}}),S(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),S(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=J("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ut(s)?this.events.emit(J("session_update",r),{}):st(s)&&this.events.emit(J("session_update",r),{error:s.error})}),S(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ce(Qt)),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)}}),S(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=J("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ut(s)?this.events.emit(J("session_extend",r),{}):st(s)&&this.events.emit(J("session_extend",r),{error:s.error})}),S(this,"onSessionPingRequest",async(t,s)=>{const{id:r}=s;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)}}),S(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=J("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);ut(s)?this.events.emit(J("session_ping",r),{}):st(s)&&this.events.emit(J("session_ping",r),{error:s.error})},500)}),S(this,"onSessionDeleteRequest",async(t,s)=>{const{id:r}=s;try{this.isValidDisconnect({topic:t,reason:s.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(de.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:Q("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),S(this,"onSessionRequest",async t=>{var s,r,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:l}=t,{id:u,params:p}=a;try{await this.isValidRequest(X({topic:o},p));const d=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:rt(JSON.stringify(kt("wc_sessionRequest",p,u))),encryptedId:h,metadata:d.peer.metadata,transportType:l}),y={id:u,topic:o,params:p,verifyContext:g};await this.setPendingSessionRequest(y),l===te.link_mode&&(s=d.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=d.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(d){await this.sendError({id:u,topic:o,error:d}),this.client.logger.error(d)}}),S(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=J("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ut(s)?this.events.emit(J("session_request",r),{result:s.result}):st(s)&&this.events.emit(J("session_request",r),{error:s.error})}),S(this,"onSessionEventRequest",async(t,s)=>{const{id:r,params:n}=s;try{const o=`${t}_session_event_${n.event.name}`,a=Ni.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(X({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),Ni.set(o,r)}catch(o){await this.sendError({id:r,topic:t,error:o}),this.client.logger.error(o)}}),S(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),ut(s)?this.events.emit(J("session_request",r),{result:s.result}):st(s)&&this.events.emit(J("session_request",r),{error:s.error})}),S(this,"onSessionAuthenticateRequest",async t=>{var s;const{topic:r,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:h,authPayload:l,expiryTimestamp:u}=n.params,p=await this.getVerifyContext({attestationId:o,hash:rt(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),d={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:p,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:d,pairingTopic:r,transportType:c}),c===te.link_mode&&(s=h.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:p})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),d={type:mt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:d,rpcOpts:le.wc_sessionAuthenticate.autoReject,appLink:p})}}),S(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),S(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=tt.idle,this.processSessionRequestQueue()},j.toMiliseconds(this.requestQueueDelay))}),S(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:s})=>{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=J("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(J("session_request",n.request.id),{error:s})})}),S(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===tt.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=tt.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),S(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),S(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const s=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);s&&this.onSessionProposeRequest({topic:t.topic,payload:kt("wc_sessionPropose",_e(X({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),S(this,"isValidConnect",async t=>{if(!xe(t)){const{message:h}=N("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:s,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(we(s)||await this.isValidPairingTopic(s),!jd(c)){const{message:h}=N("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!we(r)&&$t(r)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(r,"requiredNamespaces")}if(!we(n)&&$t(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>h.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}}),S(this,"validateNamespaces",(t,s)=>{const r=Rd(t,"connect()",s);if(r)throw new Error(r.message)}),S(this,"isValidApprove",async t=>{if(!xe(t))throw new Error(N("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:s,namespaces:r,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(s),await this.isValidProposalId(s);const c=this.client.proposal.get(s),h=hr(r,"approve()");if(h)throw new Error(h.message);const l=Io(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!ne(n,!0)){const{message:u}=N("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(p=>u.has(p)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),S(this,"isValidReject",async t=>{if(!xe(t)){const{message:n}=N("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!kd(r)){const{message:n}=N("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),S(this,"isValidSessionSettleRequest",t=>{if(!xe(t)){const{message:h}=N("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!Sc(s)){const{message:h}=N("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=Od(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=hr(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Et(o)){const{message:h}=N("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),S(this,"isValidUpdate",async t=>{if(!xe(t)){const{message:c}=N("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:s,namespaces:r}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const n=this.client.session.get(s),o=hr(r,"update()");if(o)throw new Error(o.message);const a=Io(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),S(this,"isValidExtend",async t=>{if(!xe(t)){const{message:r}=N("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:s}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s)}),S(this,"isValidRequest",async t=>{if(!xe(t)){const{message:c}=N("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:s,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const{namespaces:a}=this.client.session.get(s);if(!Eo(a,n)){const{message:c}=N("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Dd(r)){const{message:c}=N("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!Ud(a,n,r.method)){const{message:c}=N("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Vd(o,wr)){const{message:c}=N("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${wr.min} and ${wr.max}`);throw new Error(c)}}),S(this,"isValidRespond",async t=>{var s;if(!xe(t)){const{message:o}=N("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:r,response:n}=t;try{await this.isValidSessionTopic(r)}catch(o){throw(s=t?.response)!=null&&s.id&&this.cleanupAfterResponse(t),o}if(!Ld(n)){const{message:o}=N("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),S(this,"isValidPing",async t=>{if(!xe(t)){const{message:r}=N("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),S(this,"isValidEmit",async t=>{if(!xe(t)){const{message:a}=N("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:s,event:r,chainId:n}=t;await this.isValidSessionTopic(s);const{namespaces:o}=this.client.session.get(s);if(!Eo(o,n)){const{message:a}=N("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Md(r)){const{message:a}=N("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!zd(o,n,r.name)){const{message:a}=N("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),S(this,"isValidDisconnect",async t=>{if(!xe(t)){const{message:r}=N("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),S(this,"isValidAuthenticate",t=>{const{chains:s,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(s)||s.length===0)throw new Error("chains is required and must be a non-empty array");if(!ne(r,!1))throw new Error("uri is required parameter");if(!ne(n,!1))throw new Error("domain is required parameter");if(!ne(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>gi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=gi(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),S(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||Ki,validation:"UNKNOWN",origin:o.url||""}};try{if(a===te.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:s,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),S(this,"validateSessionProps",(t,s)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=N("MISSING_OR_INVALID",`${s} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),S(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),S(this,"addToRecentlyDeleted",(t,s)=>{if(this.recentlyDeletedMap.set(t,s),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)}}}),S(this,"checkRecentlyDeleted",t=>{const s=this.recentlyDeletedMap.get(t);if(s){const{message:r}=N("MISSING_OR_INVALID",`Record was recently deleted - ${s}: ${t}`);throw new Error(r)}}),S(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,u,p;return!t||s!==te.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&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((l=t?.redirect)==null?void 0:l.universal)!==void 0&&((u=t?.redirect)==null?void 0:u.universal)!==""&&((p=t?.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof globalThis?.Linking<"u"}),S(this,"getAppLinkIfEnabled",(t,s)=>{var r;return this.isLinkModeEnabled(t,s)?(r=t?.redirect)==null?void 0:r.universal:void 0}),S(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=kn(t,"topic")||"",r=decodeURIComponent(kn(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:te.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),S(this,"registerLinkModeListeners",async()=>{var t;if(on()||Ot()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=globalThis?.Linking;if(typeof s<"u"){s.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await s.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),S(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(oa).includes(r.method)}),S(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return _e(X({correlationId:t,rpcMethods:[a],chainId:s.chainId},this.isValidContractData(s.request.params)&&{contractAddresses:[(o=(n=s.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{}}),S(this,"isValidContractData",t=>{var s;if(!t)return!1;try{const r=t?.data||((s=t?.[0])==null?void 0:s.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}),S(this,"extractTxHashesFromResult",(t,s)=>{try{const r=oa[t];if(typeof s=="string")return[s];const n=s[r.key];if(Qe(n))return t==="solana_signAllTransactions"?n.map(o=>lu(o)):n;if(typeof n=="string")return[n]}catch(r){this.client.logger.warn("Error extracting tx hashes from result",r)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[s,r]of Object.entries(t))for(const n of r)try{await this.onProviderMessageEvent({topic:s,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${s}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=N("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(de.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Ss)?this.client.auth.authKeys.get(Ss):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===te.link_mode?It:Je});sn(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:rt(s)})):rn(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)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,s)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ze.expired,async e=>{const{topic:t,id:s}=Ha(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,N("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,N("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):s&&(await this.deleteProposal(s,!0),this.client.events.emit("proposal_expire",{id:s}))})}registerPairingEvents(){this.client.core.pairing.events.on(jt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(jt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ne(e,!1)){const{message:t}=N("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}=N("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=N("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ne(e,!1)){const{message:t}=N("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}=N("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=N("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=N("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(ne(e,!1)){const{message:t}=N("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=N("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!qd(e)){const{message:t}=N("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=N("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=N("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class rb extends Kt{constructor(e,t){super(e,t,Bw,fn),this.core=e,this.logger=t}}let nb=class extends Kt{constructor(e,t){super(e,t,Kw,fn),this.core=e,this.logger=t}};class ob extends Kt{constructor(e,t){super(e,t,Hw,fn,s=>s.id),this.core=e,this.logger=t}}class ab extends Kt{constructor(e,t){super(e,t,Jw,Ws,()=>Ss),this.core=e,this.logger=t}}class cb extends Kt{constructor(e,t){super(e,t,Qw,Ws),this.core=e,this.logger=t}}class hb extends Kt{constructor(e,t){super(e,t,Yw,Ws,s=>s.id),this.core=e,this.logger=t}}var lb=Object.defineProperty,ub=(i,e,t)=>e in i?lb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,br=(i,e,t)=>ub(i,typeof e!="symbol"?e+"":e,t);class pb{constructor(e,t){this.core=e,this.logger=t,br(this,"authKeys"),br(this,"pairingTopics"),br(this,"requests"),this.authKeys=new ab(this.core,this.logger),this.pairingTopics=new cb(this.core,this.logger),this.requests=new hb(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var db=Object.defineProperty,gb=(i,e,t)=>e in i?db(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,K=(i,e,t)=>gb(i,typeof e!="symbol"?e+"":e,t);let fb=class Gc extends sf{constructor(e){super(e),K(this,"protocol",Vc),K(this,"version",Hc),K(this,"name",yr.name),K(this,"metadata"),K(this,"core"),K(this,"logger"),K(this,"events",new St.EventEmitter),K(this,"engine"),K(this,"session"),K(this,"proposal"),K(this,"pendingRequest"),K(this,"auth"),K(this,"signConfig"),K(this,"on",(s,r)=>this.events.on(s,r)),K(this,"once",(s,r)=>this.events.once(s,r)),K(this,"off",(s,r)=>this.events.off(s,r)),K(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),K(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),K(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),K(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),K(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),K(this,"rejectSessionAuthenticate",async s=>{try{return await this.engine.rejectSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),this.name=e?.name||yr.name,this.metadata=_l(e?.metadata),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:rs(Fs({level:e?.logger||yr.logger}));this.core=e?.core||new zw(e),this.logger=$e(t,this.name),this.session=new nb(this.core,this.logger),this.proposal=new rb(this.core,this.logger),this.pendingRequest=new ob(this.core,this.logger),this.engine=new sb(this),this.auth=new pb(this.core,this.logger)}static async init(e){const t=new Gc(e);return await t.initialize(),t}get context(){return Ce(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()},j.toMiliseconds(j.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const ca="error",mb="wss://relay.walletconnect.org",yb="wc",wb="universal_provider",ms=`${yb}@2:${wb}:`,Wc="https://rpc.walletconnect.org/v1/",hi="generic",bb=`${Wc}bundler`,Ve={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function vb(){}function mn(i){return i==null||typeof i!="object"&&typeof i!="function"}function yn(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Eb(i){if(mn(i))return i;if(Array.isArray(i)||yn(i)||i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);const e=Object.getPrototypeOf(i),t=e.constructor;if(i instanceof Date||i instanceof Map||i instanceof Set)return new t(i);if(i instanceof RegExp){const s=new t(i);return s.lastIndex=i.lastIndex,s}if(i instanceof DataView)return new t(i.buffer.slice(0));if(i instanceof Error){const s=new t(i.message);return s.stack=i.stack,s.name=i.name,s.cause=i.cause,s}if(typeof File<"u"&&i instanceof File)return new t([i],i.name,{type:i.type,lastModified:i.lastModified});if(typeof i=="object"){const s=Object.create(e);return Object.assign(s,i)}return i}function ha(i){return typeof i=="object"&&i!==null}function Jc(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Qc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Ib="[object RegExp]",Yc="[object String]",Zc="[object Number]",Xc="[object Boolean]",eh="[object Arguments]",_b="[object Symbol]",Pb="[object Date]",$b="[object Map]",Sb="[object Set]",Ob="[object Array]",xb="[object ArrayBuffer]",Ab="[object Object]",Tb="[object DataView]",Cb="[object Uint8Array]",Nb="[object Uint8ClampedArray]",Rb="[object Uint16Array]",jb="[object Uint32Array]",qb="[object Int8Array]",kb="[object Int16Array]",Db="[object Int32Array]",Lb="[object Float32Array]",Mb="[object Float64Array]";function Ub(i,e){return di(i,void 0,i,new Map,e)}function di(i,e,t,s=new Map,r=void 0){const n=r?.(i,e,t,s);if(n!=null)return n;if(mn(i))return i;if(s.has(i))return s.get(i);if(Array.isArray(i)){const o=new Array(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=di(i[a],a,t,s,r);return Object.hasOwn(i,"index")&&(o.index=i.index),Object.hasOwn(i,"input")&&(o.input=i.input),o}if(i instanceof Date)return new Date(i.getTime());if(i instanceof RegExp){const o=new RegExp(i.source,i.flags);return o.lastIndex=i.lastIndex,o}if(i instanceof Map){const o=new Map;s.set(i,o);for(const[a,c]of i)o.set(a,di(c,a,t,s,r));return o}if(i instanceof Set){const o=new Set;s.set(i,o);for(const a of i)o.add(di(a,void 0,t,s,r));return o}if(typeof Ie<"u"&&Ie.isBuffer(i))return i.subarray();if(yn(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=di(i[a],a,t,s,r);return o}if(i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);if(i instanceof DataView){const o=new DataView(i.buffer.slice(0),i.byteOffset,i.byteLength);return s.set(i,o),qt(o,i,t,s,r),o}if(typeof File<"u"&&i instanceof File){const o=new File([i],i.name,{type:i.type});return s.set(i,o),qt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),qt(o,i,t,s,r),o}if(i instanceof Error){const o=new i.constructor;return s.set(i,o),o.message=i.message,o.name=i.name,o.stack=i.stack,o.cause=i.cause,qt(o,i,t,s,r),o}if(typeof i=="object"&&zb(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),qt(o,i,t,s,r),o}return i}function qt(i,e,t=i,s,r){const n=[...Object.keys(e),...Jc(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=di(e[a],a,t,s,r))}}function zb(i){switch(Qc(i)){case eh:case Ob:case xb:case Tb:case Xc:case Pb:case Lb:case Mb:case qb:case kb:case Db:case $b:case Zc:case Ab:case Ib:case Sb:case Yc:case _b:case Cb:case Nb:case Rb:case jb:return!0;default:return!1}}function Bb(i,e){return Ub(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case Zc:case Yc:case Xc:{const o=new i.constructor(i?.valueOf());return qt(o,i),o}case eh:{const o={};return qt(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function la(i){return Bb(i)}function ua(i){return i!==null&&typeof i=="object"&&Qc(i)==="[object Arguments]"}function Kb(i){return yn(i)}function Vb(i){if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const t=i[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(i,Symbol.toStringTag)?.writable?!1:i.toString()===`[object ${t}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function Hb(i,...e){const t=e.slice(0,-1),s=e[e.length-1];let r=i;for(let n=0;n<t.length;n++){const o=t[n];r=Yr(r,o,s,new Map)}return r}function Yr(i,e,t,s){if(mn(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return Eb(s.get(e));if(s.set(e,i),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const r=[...Object.keys(e),...Jc(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(ua(a)&&(a={...a}),ua(c)&&(c={...c}),typeof Ie<"u"&&Ie.isBuffer(a)&&(a=la(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],u=Reflect.ownKeys(c);for(let p=0;p<u.length;p++){const d=u[p];l[d]=c[d]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||ha(c)&&ha(a)?i[o]=Yr(c,a,t,s):c==null&&Vb(a)?i[o]=Yr({},a,t,s):c==null&&Kb(a)?i[o]=la(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Fb(i,...e){return Hb(i,...e,vb)}var Gb=Object.defineProperty,Wb=Object.defineProperties,Jb=Object.getOwnPropertyDescriptors,pa=Object.getOwnPropertySymbols,Qb=Object.prototype.hasOwnProperty,Yb=Object.prototype.propertyIsEnumerable,da=(i,e,t)=>e in i?Gb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ys=(i,e)=>{for(var t in e||(e={}))Qb.call(e,t)&&da(i,t,e[t]);if(pa)for(var t of pa(e))Yb.call(e,t)&&da(i,t,e[t]);return i},Zb=(i,e)=>Wb(i,Jb(e));function Le(i,e,t){var s;const r=gi(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Wc}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Vt(i){return i.includes(":")?i.split(":")[1]:i}function th(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function Xb(i,e){const t=Object.keys(e.namespaces).filter(r=>r.includes(i));if(!t.length)return[];const s=[];return t.forEach(r=>{const n=e.namespaces[r].accounts;s.push(...n)}),s}function ws(i={},e={}){const t=ga(i),s=ga(e);return Fb(t,s)}function ga(i){var e,t,s,r,n;const o={};if(!$t(i))return o;for(const[a,c]of Object.entries(i)){const h=Hs(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},d=pi(a);o[d]=Zb(ys(ys({},o[d]),c),{chains:nt(h,(e=o[d])==null?void 0:e.chains),methods:nt(l,(t=o[d])==null?void 0:t.methods),events:nt(u,(s=o[d])==null?void 0:s.events)}),($t(p)||$t(((r=o[d])==null?void 0:r.rpcMap)||{}))&&(o[d].rpcMap=ys(ys({},p),(n=o[d])==null?void 0:n.rpcMap))}return o}function fa(i){return i.includes(":")?i.split(":")[2]:i}function ma(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Hs(t)?[t]:s.chains?s.chains:th(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function vr(i){return typeof i=="number"?i:i.includes("0x")?parseInt(i,16):(i=i.includes(":")?i.split(":")[1]:i,isNaN(Number(i))?i:Number(i))}const ih={},G=i=>ih[i],Er=(i,e)=>{ih[i]=e};var ev=Object.defineProperty,tv=(i,e,t)=>e in i?ev(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Yt=(i,e,t)=>tv(i,typeof e!="symbol"?e+"":e,t);class iv{constructor(e){Yt(this,"name","polkadot"),Yt(this,"client"),Yt(this,"httpProviders"),Yt(this,"events"),Yt(this,"namespace"),Yt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var sv=Object.defineProperty,rv=Object.defineProperties,nv=Object.getOwnPropertyDescriptors,ya=Object.getOwnPropertySymbols,ov=Object.prototype.hasOwnProperty,av=Object.prototype.propertyIsEnumerable,Zr=(i,e,t)=>e in i?sv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,wa=(i,e)=>{for(var t in e||(e={}))ov.call(e,t)&&Zr(i,t,e[t]);if(ya)for(var t of ya(e))av.call(e,t)&&Zr(i,t,e[t]);return i},ba=(i,e)=>rv(i,nv(e)),Zt=(i,e,t)=>Zr(i,typeof e!="symbol"?e+"":e,t);class cv{constructor(e){Zt(this,"name","eip155"),Zt(this,"client"),Zt(this,"chainId"),Zt(this,"namespace"),Zt(this,"httpProviders"),Zt(this,"events"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s=t||Le(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=parseInt(Vt(t));e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[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,s;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:(s=this.namespace.chains)==null?void 0:s[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,s,r,n,o;const a=(s=(t=e.request)==null?void 0:t.params)==null?void 0:s[0],c=((n=(r=e.request)==null?void 0:r.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u?.[h];const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ba(wa({},l.sessionProperties||{}),{capabilities:ba(wa({},u||{}),{[h]:p})})})}catch(d){console.warn("Failed to update session with capabilities",d)}return p}async getCallStatus(e){var t,s;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=(s=r.sessionProperties)==null?void 0:s.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 s;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(kt("eth_getUserOperationReceipt",[(s=t.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${bb}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var hv=Object.defineProperty,lv=(i,e,t)=>e in i?hv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xt=(i,e,t)=>lv(i,typeof e!="symbol"?e+"":e,t);class uv{constructor(e){Xt(this,"name","solana"),Xt(this,"client"),Xt(this,"httpProviders"),Xt(this,"events"),Xt(this,"namespace"),Xt(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var pv=Object.defineProperty,dv=(i,e,t)=>e in i?pv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ei=(i,e,t)=>dv(i,typeof e!="symbol"?e+"":e,t);class gv{constructor(e){ei(this,"name","cosmos"),ei(this,"client"),ei(this,"httpProviders"),ei(this,"events"),ei(this,"namespace"),ei(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var fv=Object.defineProperty,mv=(i,e,t)=>e in i?fv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ti=(i,e,t)=>mv(i,typeof e!="symbol"?e+"":e,t);class yv{constructor(e){ti(this,"name","algorand"),ti(this,"client"),ti(this,"httpProviders"),ti(this,"events"),ti(this,"namespace"),ti(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const s=t||Le(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.chainId=e,this.events.emit(Ve.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 s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new Ke(new Ye(s,G("disableProviderPing")))}}var wv=Object.defineProperty,bv=(i,e,t)=>e in i?wv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ii=(i,e,t)=>bv(i,typeof e!="symbol"?e+"":e,t);class vv{constructor(e){ii(this,"name","cip34"),ii(this,"client"),ii(this,"httpProviders"),ii(this,"events"),ii(this,"namespace"),ii(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s=this.getCardanoRPCUrl(t),r=Vt(t);e[r]=this.createHttpProvider(r,s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var Ev=Object.defineProperty,Iv=(i,e,t)=>e in i?Ev(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,si=(i,e,t)=>Iv(i,typeof e!="symbol"?e+"":e,t);class _v{constructor(e){si(this,"name","elrond"),si(this,"client"),si(this,"httpProviders"),si(this,"events"),si(this,"namespace"),si(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var Pv=Object.defineProperty,$v=(i,e,t)=>e in i?Pv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ri=(i,e,t)=>$v(i,typeof e!="symbol"?e+"":e,t);class Sv{constructor(e){ri(this,"name","multiversx"),ri(this,"client"),ri(this,"httpProviders"),ri(this,"events"),ri(this,"namespace"),ri(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var Ov=Object.defineProperty,xv=(i,e,t)=>e in i?Ov(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ni=(i,e,t)=>xv(i,typeof e!="symbol"?e+"":e,t);class Av{constructor(e){ni(this,"name","near"),ni(this,"client"),ni(this,"httpProviders"),ni(this,"events"),ni(this,"namespace"),ni(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||Le(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(Ve.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 s;e[t]=this.createHttpProvider(t,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace);return typeof s>"u"?void 0:new Ke(new Ye(s,G("disableProviderPing")))}}var Tv=Object.defineProperty,Cv=(i,e,t)=>e in i?Tv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oi=(i,e,t)=>Cv(i,typeof e!="symbol"?e+"":e,t);class Nv{constructor(e){oi(this,"name","tezos"),oi(this,"client"),oi(this,"httpProviders"),oi(this,"events"),oi(this,"namespace"),oi(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||Le(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(Ve.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 s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace);return typeof s>"u"?void 0:new Ke(new Ye(s))}}var Rv=Object.defineProperty,jv=(i,e,t)=>e in i?Rv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ai=(i,e,t)=>jv(i,typeof e!="symbol"?e+"":e,t);class qv{constructor(e){ai(this,"name",hi),ai(this,"client"),ai(this,"httpProviders"),ai(this,"events"),ai(this,"namespace"),ai(this,"chainId"),this.namespace=e.namespace,this.events=G("events"),this.client=G("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(Ve.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 s={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(r=>{const n=gi(r);s[`${n.namespace}:${n.reference}`]=this.createHttpProvider(r)}),s}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||Le(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ke(new Ye(s,G("disableProviderPing")))}}var kv=Object.defineProperty,Dv=Object.defineProperties,Lv=Object.getOwnPropertyDescriptors,va=Object.getOwnPropertySymbols,Mv=Object.prototype.hasOwnProperty,Uv=Object.prototype.propertyIsEnumerable,Xr=(i,e,t)=>e in i?kv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bs=(i,e)=>{for(var t in e||(e={}))Mv.call(e,t)&&Xr(i,t,e[t]);if(va)for(var t of va(e))Uv.call(e,t)&&Xr(i,t,e[t]);return i},Ir=(i,e)=>Dv(i,Lv(e)),Ue=(i,e,t)=>Xr(i,typeof e!="symbol"?e+"":e,t);let zv=class sh{constructor(e){Ue(this,"client"),Ue(this,"namespaces"),Ue(this,"optionalNamespaces"),Ue(this,"sessionProperties"),Ue(this,"scopedProperties"),Ue(this,"events",new tn),Ue(this,"rpcProviders",{}),Ue(this,"session"),Ue(this,"providerOpts"),Ue(this,"logger"),Ue(this,"uri"),Ue(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:rs(Fs({level:e?.logger||ca})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new sh(e);return await t.initialize(),t}async request(e,t,s){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:bs({},e),chainId:`${r}:${n}`,topic:this.session.topic,expiry:s})}sendAsync(e,t,s,r){const n=new Date().getTime();this.request(e,s,r).then(o=>t(null,Ls(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,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Q("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:s,response:r}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const n=await r();if(this.session=n.session,this.session){const o=ma(this.session.namespaces);this.namespaces=ws(this.namespaces,o),await 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:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const r=await s();this.session=r;const n=ma(r.namespaces);return this.namespaces=ws(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[s,r]=this.validateChain(e),n=this.getProvider(s);n.name===hi?n.setDefaultChain(`${s}:${r}`,t):n.setDefaultChain(r,t)}catch(s){if(!/Please call connect/.test(s.message))throw s}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(Qe(t)){for(const s of t)e.deletePairings?this.client.core.expirer.set(s.topic,0):await this.client.core.relayer.subscriber.unsubscribe(s.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,t;if(this.client=this.providerOpts.client||await fb.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ca,relayUrl:this.providerOpts.relayUrl||mb,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(s){throw this.logger.error("Failed to get session",s),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const s=this.client.session.getAll();this.session=s[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>pi(t)))];Er("client",this.client),Er("events",this.events),Er("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=Xb(t,this.session),r=th(s),n=ws(this.namespaces,this.optionalNamespaces),o=Ir(bs({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new cv({namespace:o});break;case"algorand":this.rpcProviders[t]=new yv({namespace:o});break;case"solana":this.rpcProviders[t]=new uv({namespace:o});break;case"cosmos":this.rpcProviders[t]=new gv({namespace:o});break;case"polkadot":this.rpcProviders[t]=new iv({namespace:o});break;case"cip34":this.rpcProviders[t]=new vv({namespace:o});break;case"elrond":this.rpcProviders[t]=new _v({namespace:o});break;case"multiversx":this.rpcProviders[t]=new Sv({namespace:o});break;case"near":this.rpcProviders[t]=new Av({namespace:o});break;case"tezos":this.rpcProviders[t]=new Nv({namespace:o});break;default:this.rpcProviders[hi]?this.rpcProviders[hi].updateNamespace(o):this.rpcProviders[hi]=new qv({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:s}=e;s===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:s,topic:r}=e;if(r!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=s;if(n.name==="accountsChanged"){const o=n.data;o&&Qe(o)&&this.events.emit("accountsChanged",o.map(fa))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=pi(o),h=vr(o)!==vr(a)?`${c}:${vr(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,r;if(e!==((s=this.session)==null?void 0:s.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Ir(bs({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ir(bs({},Q("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Ve.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[hi]}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:s={},sessionProperties:r,scopedProperties:n}=e;this.optionalNamespaces=ws(t,s),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,s]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(o=>pi(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&s)return[t,s];const r=pi(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()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[s,r]=this.validateChain(e);if(!r)return;this.updateNamespaceChain(s,r),this.events.emit("chainChanged",r);const n=this.getProvider(s).getDefaultChain();t||this.getProvider(s).setDefaultChain(r),this.emitAccountsChangedOnChainChange({namespace:s,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:s}){var r,n;try{if(t===s)return;const o=(n=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(fa);if(!Qe(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const s=this.namespaces[e]?e:`${e}:${t}`,r={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[s]?this.namespaces[s]&&(this.namespaces[s].defaultChain=t):this.namespaces[s]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.setItem(`${ms}/${e}${r}`,t)}async getFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${ms}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${ms}/${e}${s}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const s of t)s.startsWith(ms)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const Bv=zv,Kv="wc",Vv="ethereum_provider",Hv=`${Kv}@2:${Vv}:`,Fv="https://rpc.walletconnect.org/v1/",qs=["eth_sendTransaction","personal_sign"],rh=["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_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],ks=["chainChanged","accountsChanged"],nh=["chainChanged","accountsChanged","message","disconnect","connect"],Gv=async()=>{const{createAppKit:i}=await Pa(()=>import("./core-BGvtiIgG.js").then(e=>e.u),__vite__mapDeps([9,1,2,3,4,7,8,10,11,12,13]));return i};var Wv=Object.defineProperty,Jv=Object.defineProperties,Qv=Object.getOwnPropertyDescriptors,Ea=Object.getOwnPropertySymbols,Yv=Object.prototype.hasOwnProperty,Zv=Object.prototype.propertyIsEnumerable,en=(i,e,t)=>e in i?Wv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Nt=(i,e)=>{for(var t in e||(e={}))Yv.call(e,t)&&en(i,t,e[t]);if(Ea)for(var t of Ea(e))Zv.call(e,t)&&en(i,t,e[t]);return i},Di=(i,e)=>Jv(i,Qv(e)),Re=(i,e,t)=>en(i,typeof e!="symbol"?e+"":e,t);function Ds(i){return Number(i[0].split(":")[1])}function vs(i){return`0x${i.toString(16)}`}function Xv(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Qe(e))throw new Error("Invalid chains");const c={chains:e,methods:s||qs,events:n||ks,rpcMap:Nt({},e.length?{[Ds(e)]:a[Ds(e)]}:{})},h=n?.filter(d=>!ks.includes(d)),l=s?.filter(d=>!qs.includes(d));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=h?.length&&l?.length||!t,p={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:rh))],events:[...new Set(c.events.concat(o!=null&&o.length?o:nh))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class Js{constructor(){Re(this,"events",new St.EventEmitter),Re(this,"namespace","eip155"),Re(this,"accounts",[]),Re(this,"signer"),Re(this,"chainId",1),Re(this,"modal"),Re(this,"rpc"),Re(this,"STORAGE_KEY",Hv),Re(this,"on",(e,t)=>(this.events.on(e,t),this)),Re(this,"once",(e,t)=>(this.events.once(e,t),this)),Re(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),Re(this,"off",(e,t)=>(this.events.off(e,t),this)),Re(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new Js;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,s){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),s)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:s,optional:r}=Xv(this.rpc);try{const n=await new Promise(async(a,c)=>{var h,l;this.rpc.showQrModal&&((h=this.modal)==null||h.open(),(l=this.modal)==null||l.subscribeState(p=>{!p.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Di(Nt({namespaces:Nt({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e?.pairingTopic,scopedProperties:u})).then(p=>{a(p)}).catch(p=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(p.message))})});if(!n)return;const o=Cn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:vs(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){var s;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const r=await new Promise(async(o,a)=>{var c,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Di(Nt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=r.session;if(n){const o=Cn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:vs(this.chainId)})}return r}catch(r){throw this.signer.logger.error(r),r}finally{(s=this.modal)==null||s.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:s}=t;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",vs(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",Di(Nt({},Q("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",vs(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,s,r]=e.split(":");return{chainId:`${t}:${s}`,address:r}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,s;const r=(t=e?.chains)!=null?t:[],n=(s=e?.optionalChains)!=null?s:[],o=r.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=r.length?e?.methods||qs:[],c=r.length?e?.events||ks:[],h=e?.optionalMethods||[],l=e?.optionalEvents||[],u=e?.rpcMap||this.buildRpcMap(o,e.projectId),p=e?.qrModalOptions||void 0;return{chains:r?.map(d=>this.formatChainId(d)),optionalChains:n.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:h,optionalEvents:l,rpcMap:u,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:p,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const s={};return e.forEach(r=>{s[r]=this.getRpcUrl(r,t)}),s}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ds(this.rpc.chains):Ds(this.rpc.optionalChains),this.signer=await Bv.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let t;try{const s=await Gv(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return lE}),n=r(Di(Nt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=s(Di(Nt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:s,rpcMap:r}=e;t&&Qe(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)})),s&&Qe(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=r?.[n]||this.getRpcUrl(n)}))}getRpcUrl(e,t){var s;return((s=this.rpc.rpcMap)==null?void 0:s[e])||`${Fv}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(t=>this.parseAccount(t))}}const eE=Js;var tE=Object.defineProperty,iE=Object.defineProperties,sE=Object.getOwnPropertyDescriptors,Ia=Object.getOwnPropertySymbols,rE=Object.prototype.hasOwnProperty,nE=Object.prototype.propertyIsEnumerable,_a=(i,e,t)=>e in i?tE(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oh=(i,e)=>{for(var t in e||(e={}))rE.call(e,t)&&_a(i,t,e[t]);if(Ia)for(var t of Ia(e))nE.call(e,t)&&_a(i,t,e[t]);return i},oE=(i,e)=>iE(i,sE(e));function aE(i){if(i)return{"--w3m-font-family":i["--wcm-font-family"],"--w3m-accent":i["--wcm-accent-color"],"--w3m-color-mix":i["--wcm-background-color"],"--w3m-z-index":i["--wcm-z-index"]?Number(i["--wcm-z-index"]):void 0,"--w3m-qr-color":i["--wcm-accent-color"],"--w3m-font-size-master":i["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":i["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const cE=i=>{const[e,t]=i.split(":");return ah({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function hE(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(cE).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(u=>{var p;return u.id===((p=i.defaultChain)==null?void 0:p.id)}),l={projectId:i.projectId,networks:c,themeMode:i.themeMode,themeVariables:aE(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:oE(oh({},i.metadata),{name:((t=i.metadata)==null?void 0:t.name)||"WalletConnect",description:((s=i.metadata)==null?void 0:s.description)||"Connect to WalletConnect-compatible wallets",url:((r=i.metadata)==null?void 0:r.url)||"https://walletconnect.org",icons:((n=i.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:i.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(i.explorerRecommendedWalletIds)?i.explorerRecommendedWalletIds:[],excludeWalletIds:i.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(i.explorerExcludedWalletIds)?i.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=i.mobileWallets)!=null&&o.length||(a=i.desktopWallets)!=null&&a.length){const u=[...(i.mobileWallets||[]).map(g=>({id:g.id,name:g.name,links:g.links})),...(i.desktopWallets||[]).map(g=>({id:g.id,name:g.name,links:{native:g.links.native,universal:g.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],d=u.filter(g=>!p.includes(g.id));d.length&&(l.customWallets=d)}return l}function ah(i){return oh({formatters:void 0,fees:void 0,serializers:void 0},i)}var lE=Object.freeze({__proto__:null,convertWCMToAppKitOptions:hE,defineChain:ah});const FE=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:eE,OPTIONAL_EVENTS:nh,OPTIONAL_METHODS:rh,REQUIRED_EVENTS:ks,REQUIRED_METHODS:qs,default:Js},Symbol.toStringTag,{value:"Module"}));export{Dg as A,$e as E,Gh as H,rs as O,_n as a,Dh as b,wE as c,yE as d,Ms as e,EE as f,vE as g,Be as h,Te as i,zi as j,rl as k,Fs as l,Eg as m,FE as n,bE as r,Ra as t,Wh as w,Ce as y};
|