@dcl/shop 0.1.0-29030398160.commit-dedc8ac → 0.1.0-29111917255.commit-e6715c3
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/{AnimatedBackground-8aI4vJAl.js → AnimatedBackground-BYKnsBtz.js} +1 -1
- package/assets/{Assets-O86HcPf_.js → Assets-ClVmauZ2.js} +1 -1
- package/assets/{Button-D1faXtxc.js → Button-CgZSqnGW.js} +1 -1
- package/assets/{Cart-wT4YY2XB.js → Cart-Up06p7ew.js} +1 -1
- package/assets/{CircularProgress-ByISsJtD.js → CircularProgress-BbGH0RSH.js} +1 -1
- package/assets/{Collection-B-SrzrlP.js → Collection-DvK8DQsK.js} +1 -1
- package/assets/{ConstantsUtil-DrWe0yob.js → ConstantsUtil-CiDezLbv.js} +1 -1
- package/assets/{Creator-3SRIb5GI.js → Creator-ClUMhdS6.js} +1 -1
- package/assets/{ExchangeController-CtvD9TxU.js → ExchangeController-DdSsjFTm.js} +1 -1
- package/assets/{GetCredits-BntbDm9-.js → GetCredits-7W0xZLwI.js} +2 -2
- package/assets/{HelpersUtil-zGctDzqI.js → HelpersUtil-CbFvbY-T.js} +1 -1
- package/assets/{ImportListings-DvqpDa-s.js → ImportListings-tpyUcfqZ.js} +1 -1
- package/assets/ItemDetail-CZQ3QPE1.js +2 -0
- package/assets/{Market-Hqywp2wQ.js → Market-CRtp3AGM.js} +1 -1
- package/assets/{MenuItem-BzIPsU3-.js → MenuItem-BLQsL8Vh.js} +1 -1
- package/assets/{MyAssets-nfsXXyUv.js → MyAssets-Cp2z98Lz.js} +1 -1
- package/assets/{MyFavorites-B6_8hr5-.js → MyFavorites-_R79W8pO.js} +1 -1
- package/assets/{MyPurchases-33hyTefC.js → MyPurchases-DJYHRbWz.js} +1 -1
- package/assets/{NetworkUtil-Ddexw9-U.js → NetworkUtil-DDES604E.js} +1 -1
- package/assets/{NotFound-DXluG5-7.js → NotFound-6FTGg4R1.js} +1 -1
- package/assets/{RealCheckout-tQms6dAo.js → RealCheckout-BemiXyZF.js} +1 -1
- package/assets/{ShopFooterInner-DV3X__jb.js → ShopFooterInner-KJ2oezRg.js} +2 -2
- package/assets/{Success-BblXOFEG.js → Success-CXjLiyYm.js} +1 -1
- package/assets/{SvgIcon-CVoRZ89M.js → SvgIcon-DtxoFXOd.js} +1 -1
- package/assets/{SwapController-BEHLqATV.js → SwapController-C07T-0ls.js} +1 -1
- package/assets/{TradeService-a9BKe-Oz.js → TradeService-D4PrM9vt.js} +1 -1
- package/assets/{W3MFrameProviderSingleton-HtGM3kiI.js → W3MFrameProviderSingleton-DXEpVsCm.js} +3 -3
- package/assets/{WebCryptoP256-bPjiT7wY.js → WebCryptoP256-B1xyhPdr.js} +1 -1
- package/assets/{basic-awR2CJat.js → basic-Dq4Wpic2.js} +1 -1
- package/assets/{biconomy-CBCMLM9k.js → biconomy-BQtB5Ab0.js} +1 -1
- package/assets/{buy-C8v-ou6b.js → buy-6ORWjZW_.js} +1 -1
- package/assets/{buy-gasless-CUtIigP0.js → buy-gasless-DL6o_Lwi.js} +1 -1
- package/assets/{ccip-BMCE_sFa.js → ccip-DgHj7djR.js} +1 -1
- package/assets/{ccip-DiW7RkRR.js → ccip-Zo_y8Ko9.js} +1 -1
- package/assets/{chains-CMJ6lVMG.js → chains-Bk629xE3.js} +1 -1
- package/assets/{collection-D-oaSVfu.js → collection-B8w_ujSk.js} +1 -1
- package/assets/{common-GsSQn_vD.js → common-CEkVtB9E.js} +1 -1
- package/assets/{controller-CJz3LUjz.js → controller-CNZZBumM.js} +2 -2
- package/assets/{core-CGoVaJvD.js → core-C_RCjMc6.js} +4 -4
- package/assets/{custom-CLQCvu9h.js → custom-BM-_NC1p.js} +1 -1
- package/assets/{data-capture-C1enk8q3.js → data-capture-Clu_u_4e.js} +1 -1
- package/assets/decimals-C7k-JLnD.js +1 -0
- package/assets/{decimals-C8GSUqDy.js → decimals-DYUDFeSV.js} +1 -1
- package/assets/{detectExtension-Bdev6B_Y.js → detectExtension-b3FK4NnW.js} +1 -1
- package/assets/{email-DI1UmfjV.js → email-C0z3A7sK.js} +1 -1
- package/assets/{embedded-wallet-CUaCp934.js → embedded-wallet-COvvX2Qp.js} +1 -1
- package/assets/{engine-NUwMDIUh.js → engine-Cs_nlYqC.js} +1 -1
- package/assets/{estimate-l1-fee-CkQ_-gw6.js → estimate-l1-fee-oTYMvZsv.js} +1 -1
- package/assets/eth_estimateGas-D2h2NKDU.js +1 -0
- package/assets/{eth_getStorageAt-DqNZYObO.js → eth_getStorageAt-nxicedso.js} +1 -1
- package/assets/eth_getTransactionCount-CYYgSGiU.js +1 -0
- package/assets/{ethereum-CjiWK1L5.js → ethereum-CdeRZR9J.js} +1 -1
- package/assets/{ethers-DHDSyreX.js → ethers-JeCAM1sd.js} +1 -1
- package/assets/{extractIPFS-COY4B3_o.js → extractIPFS-DzIizex4.js} +1 -1
- package/assets/{features-DW4K2ZKu.js → features-Ck7HAsYI.js} +1 -1
- package/assets/{fetchTokenMetadata-D4vVc_nQ.js → fetchTokenMetadata-CvdEl9__.js} +2 -2
- package/assets/{generateUtilityClasses-D15hK3nM.js → generateUtilityClasses-C3jgMIyn.js} +1 -1
- package/assets/get-ecosystem-wallet-info-B4ca6uUn.js +1 -0
- package/assets/{getBalance-CndsdQzG.js → getBalance-BS9M_tBF.js} +2 -2
- package/assets/{getInstalledModules-BZgUgPCr.js → getInstalledModules-TJvbccgJ.js} +1 -1
- package/assets/{getNFT-Bw4qn7ry.js → getNFT-BlQFGY94.js} +2 -2
- package/assets/{getNFT-BQyw29TQ.js → getNFT-Xlc7XB2G.js} +1 -1
- package/assets/{hashTypedData-CaO8N883.js → hashTypedData-B7sBgfoL.js} +1 -1
- package/assets/{hashTypedData-Er6Ia-O7.js → hashTypedData-CEYoWftx.js} +1 -1
- package/assets/{import-NJqh-zgj.js → import-J8FWHnju.js} +1 -1
- package/assets/{in-app-wallet-calls-BDq_Ik7W.js → in-app-wallet-calls-GDlqBGpw.js} +1 -1
- package/assets/{index-C6xmzvY-.js → index-2dkhZZEZ.js} +1 -1
- package/assets/{index-DwQ4pw8v.js → index-6YdbHDXd.js} +1 -1
- package/assets/{index-Dav5KOrd.js → index-B0PvzweT.js} +1 -1
- package/assets/{index-Buf412yH.js → index-B11b--Yh.js} +1 -1
- package/assets/{index-Hn-DbSZA.js → index-B5Oqojt4.js} +1 -1
- package/assets/{index-PQMQyCqV.js → index-B5nwKjyJ.js} +1 -1
- package/assets/{index-Dq7Rlnvq.js → index-B6-wCRdo.js} +1 -1
- package/assets/{index-BseAcDfV.js → index-BA1ToKo5.js} +3 -3
- package/assets/{index-BdBYQDrP.js → index-BBTg_Taa.js} +1 -1
- package/assets/{index-DrcFvB51.js → index-BLF3lLRE.js} +1 -1
- package/assets/{index-P5U8LYs6.js → index-BNjQhTuO.js} +1 -1
- package/assets/{index-DRm7xERf.js → index-BNsmSCur.js} +1 -1
- package/assets/{index-Bo34Cx12.js → index-BRAKTMPG.js} +1 -1
- package/assets/{index-BOwZsNrV.js → index-B_xrDWUL.js} +1 -1
- package/assets/{index-Ddmzqmxk.js → index-BcvgfIV4.js} +1 -1
- package/assets/{index-CdfeQ7YK.js → index-BcyJUD4U.js} +1 -1
- package/assets/{index-BUaGOTLN.js → index-BeymNI6W.js} +1 -1
- package/assets/{index-CWz8eoAl.js → index-BgtBi25O.js} +1 -1
- package/assets/{index-zGd0k6zk.js → index-Bj-x5N2U.js} +1 -1
- package/assets/{index-CyDCPwX2.js → index-Blc7OGRU.js} +1 -1
- package/assets/{index-FrZezou7.js → index-BnrCQ-kr.js} +1 -1
- package/assets/{index-BKg37Q5D.js → index-Bu2DcNS5.js} +1 -1
- package/assets/{index-DXfwhNfH.js → index-C9P6N44e.js} +2 -2
- package/assets/{index-Dmfk0azd.js → index-CI_HQD35.js} +39 -39
- package/assets/{index-FcUvAZuZ.js → index-CMib98th.js} +1 -1
- package/assets/{index-KUsuHO11.js → index-CPc95Sx-.js} +1 -1
- package/assets/{index-ccNJtibX.js → index-CS7PjWbj.js} +3 -3
- package/assets/{index-BuKyqX4w.js → index-CSh-BHOv.js} +1 -1
- package/assets/{index-2l5r0dRI.js → index-CZ8lEqAg.js} +2 -2
- package/assets/{index-BABCyrjx.js → index-ChHYiWiR.js} +1 -1
- package/assets/{index-CDOPdFEN.js → index-CkCZBr-g.js} +1 -1
- package/assets/{index-D-VYD1II.js → index-Cl4u62mB.js} +1 -1
- package/assets/{index-C1RysQbA.js → index-CoACJ04N.js} +1 -1
- package/assets/{index-C6QyIhnE.js → index-CptRe6qL.js} +2 -2
- package/assets/{index-Dm67LTtv.js → index-CxQiq4b6.js} +1 -1
- package/assets/{index-BoZx7TrW.js → index-Cye62OPB.js} +1 -1
- package/assets/{index-LDSpzB15.js → index-D-lax9BR.js} +1 -1
- package/assets/{index-AgzyxgSU.js → index-DA60UT_n.js} +1 -1
- package/assets/{index-emGKKyxf.js → index-DFJdN6PH.js} +1 -1
- package/assets/{index-BRyy9_FL.js → index-DGSeBOvG.js} +1 -1
- package/assets/{index-BEzzzIlC.js → index-DSUWwVug.js} +1 -1
- package/assets/{index-CWHR1ZBn.js → index-DUnXGO0a.js} +1 -1
- package/assets/{index-DieH8QTn.js → index-DWEAO5Zp.js} +1 -1
- package/assets/{index-CDAYsxA6.js → index-DWk4e-hQ.js} +1 -1
- package/assets/{index-CCxw-foK.js → index-DZ8SABwK.js} +1 -1
- package/assets/{index-BZIVWDQd.js → index-D_vsPbWD.js} +1 -1
- package/assets/{index-CRhrr6gN.js → index-DjbM69kL.js} +1 -1
- package/assets/{index-BexyLNIk.js → index-DnPCa8RK.js} +1 -1
- package/assets/{index-CfKqUBFA.js → index-DoS7CfZ4.js} +2 -2
- package/assets/{index-j1oJp18p.js → index-Dv6YT5k2.js} +1 -1
- package/assets/{index-DVQRwKte.js → index-S-U9uSud.js} +1 -1
- package/assets/{index-CmcvhZsS.js → index-_AHcKVpB.js} +1 -1
- package/assets/{index-BqIdYoG8.js → index-dE2OwwEn.js} +1 -1
- package/assets/{index-mLXaZKmk.js → index-pJLySSiV.js} +1 -1
- package/assets/{index-CENZ1Xjd.js → index-t3MAsdpb.js} +1 -1
- package/assets/{index-DJCTaNyE.js → index-ulcskxUh.js} +1 -1
- package/assets/{index-Gr3BFRx7.js → index-yq7Vx7EH.js} +1 -1
- package/assets/{index.es-7keraYJG.js → index.es-BQrA1NgE.js} +4 -4
- package/assets/{index.es-C2X55s9j.js → index.es-CbOKB2xh.js} +1 -1
- package/assets/{index.es-DZDKrrOX.js → index.es-Cz73nZm3.js} +1 -1
- package/assets/{localBatchGatewayRequest-ntoba0Xt.js → localBatchGatewayRequest-DVz1EzYT.js} +1 -1
- package/assets/{mana-rate-D_DTt_S8.js → mana-rate-PT3JDtK4.js} +1 -1
- package/assets/{native-7uSYstXA.js → native-C_y7cRlS.js} +1 -1
- package/assets/network-Bdkbzo_l.js +1 -0
- package/assets/{networks-DvMCxuQT.js → networks-DVx7-Y5v.js} +1 -1
- package/assets/{onramp-D4LFsmfg.js → onramp-DWqw8mwD.js} +1 -1
- package/assets/{openzeppelin-CJAun2pO.js → openzeppelin-B2NGugOR.js} +1 -1
- package/assets/{ownerOf-DrmYf79A.js → ownerOf-BoMFaGBI.js} +1 -1
- package/assets/{parseNft-Yzo9Plhx.js → parseNft-DdgcBV60.js} +2 -2
- package/assets/{parseSignature-3yq9FfJP.js → parseSignature-BMBhmj1o.js} +3 -3
- package/assets/{parseSignature-h2iJV3NZ.js → parseSignature-Cu4M83H5.js} +1 -1
- package/assets/{pay-with-exchange-BWW2tZIp.js → pay-with-exchange-B3xXFySH.js} +1 -1
- package/assets/{qr-overlay-hYqgRnm0.js → qr-overlay-DXC6ldlf.js} +1 -1
- package/assets/{receive-BMHwXxqP.js → receive-C-M9SmxL.js} +1 -1
- package/assets/{resolveImplementation-DS1nY4sc.js → resolveImplementation-D1Bqtnhr.js} +1 -1
- package/assets/{rpc-BC6ESxMB.js → rpc-DE1f6rs1.js} +1 -1
- package/assets/{secp256k1-DNCGSF8O.js → secp256k1-B39Q-Q6x.js} +1 -1
- package/assets/{secp256k1-BQuyxdaC.js → secp256k1-CrKymG_Q.js} +1 -1
- package/assets/{secp256k1-CrZRZ9L5.js → secp256k1-D1Tuv2c6.js} +1 -1
- package/assets/{send-B62L18Hx.js → send-C1EU45CZ.js} +1 -1
- package/assets/{send-batch-transaction-De_pBpa_.js → send-batch-transaction-BTFORkZH.js} +1 -1
- package/assets/{send-eip712-transaction-D-GzcP3o.js → send-eip712-transaction-CJ_pjExq.js} +2 -2
- package/assets/{send-gasless-transaction-Iil1KVOe.js → send-gasless-transaction-CHYN-ATV.js} +2 -2
- package/assets/{sendRawTransaction-BqauPPYf.js → sendRawTransaction-YUhe5FDd.js} +3 -3
- package/assets/{serializeTransaction-B4qzULZO.js → serializeTransaction-xu35AVgP.js} +1 -1
- package/assets/{session-proposal-C4Cz1cln.js → session-proposal-BZLBnV_x.js} +1 -1
- package/assets/{session-request-De0p90UO.js → session-request-mA9oQfs4.js} +2 -2
- package/assets/{sha256-bg_KfcLv.js → sha256-De0VIEFf.js} +1 -1
- package/assets/{signing-BGpVago5.js → signing-DqVkCMNZ.js} +5 -5
- package/assets/{socials-vOukOtuh.js → socials-BImUXGbF.js} +1 -1
- package/assets/{swaps-FEWWVCcs.js → swaps-B8Tuo6Pt.js} +1 -1
- package/assets/{thirdweb-C8ToELvu.js → thirdweb-BPuxSwTj.js} +3 -3
- package/assets/{totalSupply-C5jxuFw1.js → totalSupply-Bbiy7170.js} +1 -1
- package/assets/{transactionReceipt-CbcThGoC.js → transactionReceipt-BcAWHNof.js} +1 -1
- package/assets/{transactions-CaxBviMm.js → transactions-N8K1pD5P.js} +1 -1
- package/assets/{useInfiniteGrid-BiC1UMEK.js → useInfiniteGrid-CVs5pP6I.js} +1 -1
- package/assets/{utils-nbkSUjEy.js → utils-BmX8TqzP.js} +1 -1
- package/assets/{verifyHash-JbNzrsYR.js → verifyHash-CnnSGyZz.js} +1 -1
- package/assets/{w3m-modal-BfRGsEzF.js → w3m-modal-DJII43ig.js} +1 -1
- package/assets/{w3m-modal-BUwENQ4T.js → w3m-modal-DWJdJGvu.js} +1 -1
- package/assets/{wait-for-tx-receipt-BJDKOLGI.js → wait-for-tx-receipt-D0UsY_wi.js} +1 -1
- package/assets/{wallet-kind-CuaDlRao.js → wallet-kind-C-lIAMBM.js} +1 -1
- package/assets/{wallets-BnBHCJi8.js → wallets-KGduOTOw.js} +6 -6
- package/assets/{web-connector-CJKlFm6H.js → web-connector-Ca9PblTL.js} +3 -3
- package/assets/{writeContract-CtBYiULm.js → writeContract-dj4TlIky.js} +1 -1
- package/assets/{zora-sepolia-BQEmh41Y.js → zora-sepolia-kNKNf7Kl.js} +1 -1
- package/assets/{zoraTestnet-CJMxifqR.js → zoraTestnet-BhynxBH0.js} +1 -1
- package/index.html +8 -8
- package/package.json +2 -2
- package/assets/ItemDetail-CjSWRE3L.js +0 -2
- package/assets/decimals-DnNelAv5.js +0 -1
- package/assets/eth_estimateGas-DaI_qfS7.js +0 -1
- package/assets/eth_getTransactionCount-BBYhaRkF.js +0 -1
- package/assets/get-ecosystem-wallet-info-QCLNyKk6.js +0 -1
- package/assets/network-CFFySFe9.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-
|
|
2
|
-
import{_ as $a,F as me}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=Oa}walk(e){return xa(this,e)}}function xa(i,e){return e!=null&&e(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?xa(i.cause,e):e?null:i}class Aa extends zt{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 $i(i,{dir:e,size:t=32}={}){return typeof i=="string"?Ph(i,{dir:e,size:t}):$h(i,{dir:e,size:t})}function Ph(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new Aa({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function $h(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new Aa({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 Sh extends zt{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 Oh extends zt{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Si(i,{size:e}){if(In(i)>e)throw new Oh({givenSize:In(i),maxSize:e})}function $r(i,e={}){const{signed:t}=e;e.size&&Si(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 xh(i,e={}){return Number($r(i,e))}const Ah=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Sr(i,e={}){return typeof i=="number"||typeof i=="bigint"?Ta(i,e):typeof i=="string"?Nh(i,e):typeof i=="boolean"?Ch(i,e):Ca(i,e)}function Ch(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(Si(t,{size:e.size}),$i(t,{size:e.size})):t}function Ca(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=Ah[i[r]];const s=`0x${t}`;return typeof e.size=="number"?(Si(s,{size:e.size}),$i(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 Sh({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?$i(a,{size:s}):a}const Th=new TextEncoder;function Nh(i,e={}){const t=Th.encode(i);return Ca(t,e)}const Rh=new TextEncoder;function jh(i,e={}){return typeof i=="number"||typeof i=="bigint"?kh(i,e):typeof i=="boolean"?qh(i,e):Wi(i)?Na(i,e):Ra(i,e)}function qh(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(Si(t,{size:e.size}),$i(t,{size:e.size})):t}const ut={zero:48,nine:57,A:65,F:70,a:97,f:102};function _n(i){if(i>=ut.zero&&i<=ut.nine)return i-ut.zero;if(i>=ut.A&&i<=ut.F)return i-(ut.A-10);if(i>=ut.a&&i<=ut.f)return i-(ut.a-10)}function Na(i,e={}){let t=i;e.size&&(Si(t,{size:e.size}),t=$i(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=_n(s.charCodeAt(a++)),h=_n(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new zt(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function kh(i,e){const t=Ta(i,e);return Na(t)}function Ra(i,e={}){const t=Rh.encode(i);return typeof e.size=="number"?(Si(t,{size:e.size}),$i(t,{dir:"right",size:e.size})):t}function Cs(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Dh(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function zs(i,...e){if(!Dh(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 EE(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Cs(i.outputLen),Cs(i.blockLen)}function Pn(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 Lh(i,e){zs(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const us=BigInt(2**32-1),$n=BigInt(32);function Mh(i,e=!1){return e?{h:Number(i&us),l:Number(i>>$n&us)}:{h:Number(i>>$n&us)|0,l:Number(i&us)|0}}function Uh(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}=Mh(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const zh=(i,e,t)=>i<<t|e>>>32-t,Bh=(i,e,t)=>e<<t|i>>>32-t,Kh=(i,e,t)=>e<<t-32|i>>>64-t,Vh=(i,e,t)=>i<<t-32|e>>>64-t,Gt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Hh(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function IE(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function _E(i,e){return i<<32-e|i>>>e}const Sn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Fh(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function On(i){for(let e=0;e<i.length;e++)i[e]=Fh(i[e])}function Gh(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function ja(i){return typeof i=="string"&&(i=Gh(i)),zs(i),i}function PE(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];zs(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 Wh{clone(){return this._cloneInto()}}function Jh(i){const e=s=>i().update(ja(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function $E(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 qa=[],ka=[],Da=[],Qh=BigInt(0),Ni=BigInt(1),Yh=BigInt(2),Zh=BigInt(7),Xh=BigInt(256),el=BigInt(113);for(let i=0,e=Ni,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],qa.push(2*(5*s+t)),ka.push((i+1)*(i+2)/2%64);let r=Qh;for(let n=0;n<7;n++)e=(e<<Ni^(e>>Zh)*el)%Xh,e&Yh&&(r^=Ni<<(Ni<<BigInt(n))-Ni);Da.push(r)}const[tl,il]=Uh(Da,!0),xn=(i,e,t)=>t>32?Kh(i,e,t):zh(i,e,t),An=(i,e,t)=>t>32?Vh(i,e,t):Bh(i,e,t);function sl(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=xn(h,l,1)^t[a],p=An(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=ka[o],c=xn(r,n,a),h=An(r,n,a),l=qa[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]^=tl[s],i[1]^=il[s]}t.fill(0)}class on extends Wh{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,Cs(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Hh(this.state)}keccak(){Sn||On(this.state32),sl(this.state32,this.rounds),Sn||On(this.state32),this.posOut=0,this.pos=0}update(e){Pn(this);const{blockLen:t,state:s}=this;e=ja(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){Pn(this,!1),zs(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 Cs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Lh(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 on(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 rl=(i,e,t)=>Jh(()=>new on(e,i,t)),nl=rl(1,136,256/8);function La(i,e){const t=e||"hex",s=nl(Wi(i,{strict:!1})?jh(i):i);return t==="bytes"?s:Sr(s)}class ol 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 Zs=new ol(8192);function al(i,e){if(Zs.has(`${i}.${e}`))return Zs.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),s=La(Ra(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 Zs.set(`${i}.${e}`,n),n}function cl(i){const e=La(`0x${i.substring(4)}`).substring(26);return al(`0x${e}`)}async function hl({hash:i,signature:e}){const t=Wi(i)?i:Sr(i),{secp256k1:s}=await $a(async()=>{const{secp256k1:o}=await import("./secp256k1-CrZRZ9L5.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11]));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),f=Cn(d);return new s.Signature($r(h),$r(l)).addRecoveryBit(f)}const o=Wi(e)?e:Sr(e),a=xh(`0x${o.slice(130)}`),c=Cn(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Cn(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 ll({hash:i,signature:e}){return cl(await hl({hash:i,signature:e}))}function Ma(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Ki(i,e){e||(e=i.reduce((r,n)=>r+n.length,0));const t=Ma(e);let s=0;for(const r of i)t.set(r,s),s+=r.length;return t}function Ua(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Tn=Ua("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Xs=Ua("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=Ma(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),za={utf8:Tn,"utf-8":Tn,hex:bn.base16,latin1:Xs,ascii:Xs,binary:Xs,...bn};function Ke(i,e="utf8"){const t=za[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=za[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 ul={};const pl=":";function gi(i){const[e,t]=i.split(pl);return{namespace:e,reference:t}}function Nn(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 Ba(i,e){return i.includes(":")?[i]:e.chains||[]}var dl=Object.defineProperty,fl=Object.defineProperties,gl=Object.getOwnPropertyDescriptors,Rn=Object.getOwnPropertySymbols,ml=Object.prototype.hasOwnProperty,yl=Object.prototype.propertyIsEnumerable,jn=(i,e,t)=>e in i?dl(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qn=(i,e)=>{for(var t in e||(e={}))ml.call(e,t)&&jn(i,t,e[t]);if(Rn)for(var t of Rn(e))yl.call(e,t)&&jn(i,t,e[t]);return i},wl=(i,e)=>fl(i,gl(e));const bl="ReactNative",Le={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},vl="js";function Ts(){return typeof Bi<"u"&&typeof Bi.versions<"u"&&typeof Bi.versions.node<"u"}function At(){return!bt.getDocument()&&!!bt.getNavigator()&&navigator.product===bl}function El(){return At()&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"&&(B==null?void 0:B.Platform.OS)==="android"}function Il(){return At()&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"&&(B==null?void 0:B.Platform.OS)==="ios"}function Oi(){return!Ts()&&!!bt.getNavigator()&&!!bt.getDocument()}function es(){return At()?Le.reactNative:Ts()?Le.node:Oi()?Le.browser:Le.unknown}function kn(){var i;try{return At()&&typeof B<"u"&&typeof(B==null?void 0:B.Application)<"u"?(i=B.Application)==null?void 0:i.applicationId:void 0}catch{return}}function _l(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 Pl(i){var e,t;const s=Ka();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==null?void 0:i.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(r=>r!=="")),wl(qn(qn({},s),i),{url:(i==null?void 0:i.url)||s.url,name:(i==null?void 0:i.name)||s.name,description:(i==null?void 0:i.description)||s.description,icons:(t=i==null?void 0: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 Ka(){return hh.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function $l(){if(es()===Le.reactNative&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"){const{OS:t,Version:s}=B.Platform;return[t,s].join("-")}const i=uh();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 Sl(){var i;const e=es();return e===Le.browser?[e,((i=bt.getLocation())==null?void 0:i.host)||"unknown"].join(":"):e}function Va(i,e,t){const s=$l(),r=Sl();return[[i,e].join("-"),[vl,t].join("-"),s,r].join("/")}function Ol({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Va(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=_l(h[1]||"",u);return h[0]+"?"+p}function Mt(i,e){return i.filter(t=>e.includes(t)).length===i.length}function Or(i){return Object.fromEntries(i.entries())}function xr(i){return new Map(Object.entries(i))}function Rt(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 Ha(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 xl(i){return Ha("topic",i)}function Al(i){return Ha("id",i)}function Fa(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 he(i,e){return j.fromMiliseconds(Date.now()+j.toMiliseconds(i))}function _t(i){return Date.now()>=j.toMiliseconds(i)}function Q(i,e){return`${i}${e?`:${e}`:""}`}function ot(i=[],e=[]){return[...new Set([...i,...e])]}async function Cl({id:i,topic:e,wcDeepLink:t}){var s;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=Tl(n,i,e),a=es();if(a===Le.browser){if(!((s=bt.getDocument())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Nl(o)}else a===Le.reactNative&&typeof(B==null?void 0:B.Linking)<"u"&&await B.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}${kl(s,!0)}`}else r=`${r}/wc?${s}`;return r}function Nl(i){let e="_self";ql()?e="_top":(jl()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Rl(i,e){let t="";try{if(Oi()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function Dn(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function Ln(){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 an(){return typeof Bi<"u"&&ul.IS_VITEST==="true"}function jl(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function ql(){try{return window.self!==window.top}catch{return!1}}function kl(i,e=!1){const t=me.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Ga(i){return me.from(i,"base64").toString("utf-8")}function Dl(i){return new Promise(e=>setTimeout(e,i))}function Ji(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Ll(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ts(i,...e){if(!Ll(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 cn(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ji(i.outputLen),Ji(i.blockLen)}function mi(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 Wa(i,e){ts(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ps=BigInt(2**32-1),Mn=BigInt(32);function Ml(i,e=!1){return e?{h:Number(i&ps),l:Number(i>>Mn&ps)}:{h:Number(i>>Mn&ps)|0,l:Number(i&ps)|0}}function Ul(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}=Ml(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const zl=(i,e,t)=>i<<t|e>>>32-t,Bl=(i,e,t)=>e<<t|i>>>32-t,Kl=(i,e,t)=>e<<t-32|i>>>64-t,Vl=(i,e,t)=>i<<t-32|e>>>64-t,Wt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Hl(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function er(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function et(i,e){return i<<32-e|i>>>e}const Un=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Fl(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function zn(i){for(let e=0;e<i.length;e++)i[e]=Fl(i[e])}function Gl(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function yi(i){return typeof i=="string"&&(i=Gl(i)),ts(i),i}function Wl(...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}let hn=class{clone(){return this._cloneInto()}};function Ja(i){const e=s=>i().update(yi(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function xi(i=32){if(Wt&&typeof Wt.getRandomValues=="function")return Wt.getRandomValues(new Uint8Array(i));if(Wt&&typeof Wt.randomBytes=="function")return Wt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Qa=[],Ya=[],Za=[],Jl=BigInt(0),Ri=BigInt(1),Ql=BigInt(2),Yl=BigInt(7),Zl=BigInt(256),Xl=BigInt(113);for(let i=0,e=Ri,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Qa.push(2*(5*s+t)),Ya.push((i+1)*(i+2)/2%64);let r=Jl;for(let n=0;n<7;n++)e=(e<<Ri^(e>>Yl)*Xl)%Zl,e&Ql&&(r^=Ri<<(Ri<<BigInt(n))-Ri);Za.push(r)}const[eu,tu]=Ul(Za,!0),Bn=(i,e,t)=>t>32?Kl(i,e,t):zl(i,e,t),Kn=(i,e,t)=>t>32?Vl(i,e,t):Bl(i,e,t);function iu(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=Bn(h,l,1)^t[a],p=Kn(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=Ya[o],c=Bn(r,n,a),h=Kn(r,n,a),l=Qa[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]^=eu[s],i[1]^=tu[s]}t.fill(0)}let su=class Xa extends hn{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,Ji(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Hl(this.state)}keccak(){Un||zn(this.state32),iu(this.state32,this.rounds),Un||zn(this.state32),this.posOut=0,this.pos=0}update(e){mi(this);const{blockLen:t,state:s}=this;e=yi(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){mi(this,!1),ts(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 Ji(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Wa(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 Xa(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 ru=(i,e,t)=>Ja(()=>new su(e,i,t)),nu=ru(1,136,256/8),ou="https://rpc.walletconnect.org/v1";function ec(i){const e=`Ethereum Signed Message:
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-D1Tuv2c6.js","assets/index-CI_HQD35.js","assets/react-Vu6nbGi5.js","assets/ethers-JeCAM1sd.js","assets/index-DCrqkiFN.css","assets/index-C9P6N44e.js","assets/index-Blc7OGRU.js","assets/index-BcyJUD4U.js","assets/index-nibyPLVP.js","assets/index-CJdot1dH.js","assets/index.es-CbOKB2xh.js","assets/browser-ponyfill-rND5WOqr.js","assets/core-C_RCjMc6.js","assets/NetworkUtil-DDES604E.js","assets/W3MFrameProviderSingleton-DXEpVsCm.js","assets/lit-element-B3y9oplH.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as $a,F as me}from"./index-CI_HQD35.js";import{e as xt,N as sn}from"./index-C9P6N44e.js";import{g as B,p as Bi}from"./ethers-JeCAM1sd.js";import{d as bn,e as hh,g as j,h as bt,C as lh,j as uh,k as Pr,l as ph,m as ls,a as As,s as Gi,I as _i,n as dh,c as Lt,r as Pi,o as Ve,q as fh,t as rn,u as nn,b as Us,P as vn,Q as gh,v as mh,w as ui,f as Sa,x as dt,y as rt,z as vt}from"./index-Blc7OGRU.js";import{c as yh,a as wh,k as bh,d as vh,s as Eh,g as En}from"./index-nibyPLVP.js";import{g as Ih}from"./react-Vu6nbGi5.js";import{r as _h}from"./index-CJdot1dH.js";import"./index-BcyJUD4U.js";import{f as Ze}from"./index.es-CbOKB2xh.js";function Wi(i,{strict:e=!0}={}){return!i||typeof i!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(i):i.startsWith("0x")}function In(i){return Wi(i,{strict:!1})?Math.ceil((i.length-2)/2):i.length}const Oa="2.23.2";let Ti={getDocsUrl:({docsBaseUrl:i,docsPath:e="",docsSlug:t})=>e?`${i??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${Oa}`};class zt extends Error{constructor(e,t={}){var a;const s=(()=>{var c;return t.cause instanceof zt?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),r=t.cause instanceof zt&&t.cause.docsPath||t.docsPath,n=(a=Ti.getDocsUrl)==null?void 0:a.call(Ti,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...s?[`Details: ${s}`]:[],...Ti.version?[`Version: ${Ti.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=Oa}walk(e){return xa(this,e)}}function xa(i,e){return e!=null&&e(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?xa(i.cause,e):e?null:i}class Aa extends zt{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 $i(i,{dir:e,size:t=32}={}){return typeof i=="string"?Ph(i,{dir:e,size:t}):$h(i,{dir:e,size:t})}function Ph(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new Aa({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function $h(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new Aa({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 Sh extends zt{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 Oh extends zt{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Si(i,{size:e}){if(In(i)>e)throw new Oh({givenSize:In(i),maxSize:e})}function $r(i,e={}){const{signed:t}=e;e.size&&Si(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 xh(i,e={}){return Number($r(i,e))}const Ah=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Sr(i,e={}){return typeof i=="number"||typeof i=="bigint"?Ta(i,e):typeof i=="string"?Nh(i,e):typeof i=="boolean"?Ch(i,e):Ca(i,e)}function Ch(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(Si(t,{size:e.size}),$i(t,{size:e.size})):t}function Ca(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=Ah[i[r]];const s=`0x${t}`;return typeof e.size=="number"?(Si(s,{size:e.size}),$i(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 Sh({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?$i(a,{size:s}):a}const Th=new TextEncoder;function Nh(i,e={}){const t=Th.encode(i);return Ca(t,e)}const Rh=new TextEncoder;function jh(i,e={}){return typeof i=="number"||typeof i=="bigint"?kh(i,e):typeof i=="boolean"?qh(i,e):Wi(i)?Na(i,e):Ra(i,e)}function qh(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(Si(t,{size:e.size}),$i(t,{size:e.size})):t}const ut={zero:48,nine:57,A:65,F:70,a:97,f:102};function _n(i){if(i>=ut.zero&&i<=ut.nine)return i-ut.zero;if(i>=ut.A&&i<=ut.F)return i-(ut.A-10);if(i>=ut.a&&i<=ut.f)return i-(ut.a-10)}function Na(i,e={}){let t=i;e.size&&(Si(t,{size:e.size}),t=$i(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=_n(s.charCodeAt(a++)),h=_n(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new zt(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function kh(i,e){const t=Ta(i,e);return Na(t)}function Ra(i,e={}){const t=Rh.encode(i);return typeof e.size=="number"?(Si(t,{size:e.size}),$i(t,{dir:"right",size:e.size})):t}function Cs(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Dh(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function zs(i,...e){if(!Dh(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 EE(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Cs(i.outputLen),Cs(i.blockLen)}function Pn(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 Lh(i,e){zs(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const us=BigInt(2**32-1),$n=BigInt(32);function Mh(i,e=!1){return e?{h:Number(i&us),l:Number(i>>$n&us)}:{h:Number(i>>$n&us)|0,l:Number(i&us)|0}}function Uh(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}=Mh(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const zh=(i,e,t)=>i<<t|e>>>32-t,Bh=(i,e,t)=>e<<t|i>>>32-t,Kh=(i,e,t)=>e<<t-32|i>>>64-t,Vh=(i,e,t)=>i<<t-32|e>>>64-t,Gt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Hh(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function IE(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function _E(i,e){return i<<32-e|i>>>e}const Sn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Fh(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function On(i){for(let e=0;e<i.length;e++)i[e]=Fh(i[e])}function Gh(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function ja(i){return typeof i=="string"&&(i=Gh(i)),zs(i),i}function PE(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];zs(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 Wh{clone(){return this._cloneInto()}}function Jh(i){const e=s=>i().update(ja(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function $E(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 qa=[],ka=[],Da=[],Qh=BigInt(0),Ni=BigInt(1),Yh=BigInt(2),Zh=BigInt(7),Xh=BigInt(256),el=BigInt(113);for(let i=0,e=Ni,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],qa.push(2*(5*s+t)),ka.push((i+1)*(i+2)/2%64);let r=Qh;for(let n=0;n<7;n++)e=(e<<Ni^(e>>Zh)*el)%Xh,e&Yh&&(r^=Ni<<(Ni<<BigInt(n))-Ni);Da.push(r)}const[tl,il]=Uh(Da,!0),xn=(i,e,t)=>t>32?Kh(i,e,t):zh(i,e,t),An=(i,e,t)=>t>32?Vh(i,e,t):Bh(i,e,t);function sl(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=xn(h,l,1)^t[a],p=An(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=ka[o],c=xn(r,n,a),h=An(r,n,a),l=qa[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]^=tl[s],i[1]^=il[s]}t.fill(0)}class on extends Wh{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,Cs(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Hh(this.state)}keccak(){Sn||On(this.state32),sl(this.state32,this.rounds),Sn||On(this.state32),this.posOut=0,this.pos=0}update(e){Pn(this);const{blockLen:t,state:s}=this;e=ja(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){Pn(this,!1),zs(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 Cs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Lh(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 on(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 rl=(i,e,t)=>Jh(()=>new on(e,i,t)),nl=rl(1,136,256/8);function La(i,e){const t=e||"hex",s=nl(Wi(i,{strict:!1})?jh(i):i);return t==="bytes"?s:Sr(s)}class ol 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 Zs=new ol(8192);function al(i,e){if(Zs.has(`${i}.${e}`))return Zs.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),s=La(Ra(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 Zs.set(`${i}.${e}`,n),n}function cl(i){const e=La(`0x${i.substring(4)}`).substring(26);return al(`0x${e}`)}async function hl({hash:i,signature:e}){const t=Wi(i)?i:Sr(i),{secp256k1:s}=await $a(async()=>{const{secp256k1:o}=await import("./secp256k1-D1Tuv2c6.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11]));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),f=Cn(d);return new s.Signature($r(h),$r(l)).addRecoveryBit(f)}const o=Wi(e)?e:Sr(e),a=xh(`0x${o.slice(130)}`),c=Cn(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function Cn(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 ll({hash:i,signature:e}){return cl(await hl({hash:i,signature:e}))}function Ma(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Ki(i,e){e||(e=i.reduce((r,n)=>r+n.length,0));const t=Ma(e);let s=0;for(const r of i)t.set(r,s),s+=r.length;return t}function Ua(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Tn=Ua("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Xs=Ua("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=Ma(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),za={utf8:Tn,"utf-8":Tn,hex:bn.base16,latin1:Xs,ascii:Xs,binary:Xs,...bn};function Ke(i,e="utf8"){const t=za[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=za[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 ul={};const pl=":";function gi(i){const[e,t]=i.split(pl);return{namespace:e,reference:t}}function Nn(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 Ba(i,e){return i.includes(":")?[i]:e.chains||[]}var dl=Object.defineProperty,fl=Object.defineProperties,gl=Object.getOwnPropertyDescriptors,Rn=Object.getOwnPropertySymbols,ml=Object.prototype.hasOwnProperty,yl=Object.prototype.propertyIsEnumerable,jn=(i,e,t)=>e in i?dl(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qn=(i,e)=>{for(var t in e||(e={}))ml.call(e,t)&&jn(i,t,e[t]);if(Rn)for(var t of Rn(e))yl.call(e,t)&&jn(i,t,e[t]);return i},wl=(i,e)=>fl(i,gl(e));const bl="ReactNative",Le={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},vl="js";function Ts(){return typeof Bi<"u"&&typeof Bi.versions<"u"&&typeof Bi.versions.node<"u"}function At(){return!bt.getDocument()&&!!bt.getNavigator()&&navigator.product===bl}function El(){return At()&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"&&(B==null?void 0:B.Platform.OS)==="android"}function Il(){return At()&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"&&(B==null?void 0:B.Platform.OS)==="ios"}function Oi(){return!Ts()&&!!bt.getNavigator()&&!!bt.getDocument()}function es(){return At()?Le.reactNative:Ts()?Le.node:Oi()?Le.browser:Le.unknown}function kn(){var i;try{return At()&&typeof B<"u"&&typeof(B==null?void 0:B.Application)<"u"?(i=B.Application)==null?void 0:i.applicationId:void 0}catch{return}}function _l(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 Pl(i){var e,t;const s=Ka();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==null?void 0:i.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(r=>r!=="")),wl(qn(qn({},s),i),{url:(i==null?void 0:i.url)||s.url,name:(i==null?void 0:i.name)||s.name,description:(i==null?void 0:i.description)||s.description,icons:(t=i==null?void 0: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 Ka(){return hh.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function $l(){if(es()===Le.reactNative&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"){const{OS:t,Version:s}=B.Platform;return[t,s].join("-")}const i=uh();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 Sl(){var i;const e=es();return e===Le.browser?[e,((i=bt.getLocation())==null?void 0:i.host)||"unknown"].join(":"):e}function Va(i,e,t){const s=$l(),r=Sl();return[[i,e].join("-"),[vl,t].join("-"),s,r].join("/")}function Ol({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Va(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},p=_l(h[1]||"",u);return h[0]+"?"+p}function Mt(i,e){return i.filter(t=>e.includes(t)).length===i.length}function Or(i){return Object.fromEntries(i.entries())}function xr(i){return new Map(Object.entries(i))}function Rt(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 Ha(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 xl(i){return Ha("topic",i)}function Al(i){return Ha("id",i)}function Fa(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 he(i,e){return j.fromMiliseconds(Date.now()+j.toMiliseconds(i))}function _t(i){return Date.now()>=j.toMiliseconds(i)}function Q(i,e){return`${i}${e?`:${e}`:""}`}function ot(i=[],e=[]){return[...new Set([...i,...e])]}async function Cl({id:i,topic:e,wcDeepLink:t}){var s;try{if(!t)return;const r=typeof t=="string"?JSON.parse(t):t,n=r==null?void 0:r.href;if(typeof n!="string")return;const o=Tl(n,i,e),a=es();if(a===Le.browser){if(!((s=bt.getDocument())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Nl(o)}else a===Le.reactNative&&typeof(B==null?void 0:B.Linking)<"u"&&await B.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}${kl(s,!0)}`}else r=`${r}/wc?${s}`;return r}function Nl(i){let e="_self";ql()?e="_top":(jl()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Rl(i,e){let t="";try{if(Oi()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function Dn(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function Ln(){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 an(){return typeof Bi<"u"&&ul.IS_VITEST==="true"}function jl(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function ql(){try{return window.self!==window.top}catch{return!1}}function kl(i,e=!1){const t=me.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Ga(i){return me.from(i,"base64").toString("utf-8")}function Dl(i){return new Promise(e=>setTimeout(e,i))}function Ji(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Ll(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ts(i,...e){if(!Ll(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 cn(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ji(i.outputLen),Ji(i.blockLen)}function mi(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 Wa(i,e){ts(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ps=BigInt(2**32-1),Mn=BigInt(32);function Ml(i,e=!1){return e?{h:Number(i&ps),l:Number(i>>Mn&ps)}:{h:Number(i>>Mn&ps)|0,l:Number(i&ps)|0}}function Ul(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}=Ml(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const zl=(i,e,t)=>i<<t|e>>>32-t,Bl=(i,e,t)=>e<<t|i>>>32-t,Kl=(i,e,t)=>e<<t-32|i>>>64-t,Vl=(i,e,t)=>i<<t-32|e>>>64-t,Wt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Hl(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function er(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function et(i,e){return i<<32-e|i>>>e}const Un=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Fl(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function zn(i){for(let e=0;e<i.length;e++)i[e]=Fl(i[e])}function Gl(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function yi(i){return typeof i=="string"&&(i=Gl(i)),ts(i),i}function Wl(...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}let hn=class{clone(){return this._cloneInto()}};function Ja(i){const e=s=>i().update(yi(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function xi(i=32){if(Wt&&typeof Wt.getRandomValues=="function")return Wt.getRandomValues(new Uint8Array(i));if(Wt&&typeof Wt.randomBytes=="function")return Wt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Qa=[],Ya=[],Za=[],Jl=BigInt(0),Ri=BigInt(1),Ql=BigInt(2),Yl=BigInt(7),Zl=BigInt(256),Xl=BigInt(113);for(let i=0,e=Ri,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Qa.push(2*(5*s+t)),Ya.push((i+1)*(i+2)/2%64);let r=Jl;for(let n=0;n<7;n++)e=(e<<Ri^(e>>Yl)*Xl)%Zl,e&Ql&&(r^=Ri<<(Ri<<BigInt(n))-Ri);Za.push(r)}const[eu,tu]=Ul(Za,!0),Bn=(i,e,t)=>t>32?Kl(i,e,t):zl(i,e,t),Kn=(i,e,t)=>t>32?Vl(i,e,t):Bl(i,e,t);function iu(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=Bn(h,l,1)^t[a],p=Kn(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=Ya[o],c=Bn(r,n,a),h=Kn(r,n,a),l=Qa[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]^=eu[s],i[1]^=tu[s]}t.fill(0)}let su=class Xa extends hn{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,Ji(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Hl(this.state)}keccak(){Un||zn(this.state32),iu(this.state32,this.rounds),Un||zn(this.state32),this.posOut=0,this.pos=0}update(e){mi(this);const{blockLen:t,state:s}=this;e=yi(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){mi(this,!1),ts(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 Ji(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Wa(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 Xa(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 ru=(i,e,t)=>Ja(()=>new su(e,i,t)),nu=ru(1,136,256/8),ou="https://rpc.walletconnect.org/v1";function ec(i){const e=`Ethereum Signed Message:
|
|
4
4
|
${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+me.from(nu(t)).toString("hex")}async function au(i,e,t,s,r,n){switch(t.t){case"eip191":return await cu(i,e,t.s);case"eip1271":return await hu(i,e,t.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function cu(i,e,t){return(await ll({hash:ec(e),signature:t})).toLowerCase()===i.toLowerCase()}async function hu(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=ec(e).substring(2),p=a+u+c+h+l,d=await fetch(`${n||ou}/?chainId=${s}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:lu(),jsonrpc:"2.0",method:"eth_call",params:[{to:i,data:p},"latest"]})}),{result:f}=await d.json();return f?f.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function lu(){return Date.now()+Math.floor(Math.random()*1e3)}function uu(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=me.from(i,"base64").slice(1,65);return ph.encode(n)}var pu=Object.defineProperty,du=Object.defineProperties,fu=Object.getOwnPropertyDescriptors,Vn=Object.getOwnPropertySymbols,gu=Object.prototype.hasOwnProperty,mu=Object.prototype.propertyIsEnumerable,Hn=(i,e,t)=>e in i?pu(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,yu=(i,e)=>{for(var t in e||(e={}))gu.call(e,t)&&Hn(i,t,e[t]);if(Vn)for(var t of Vn(e))mu.call(e,t)&&Hn(i,t,e[t]);return i},wu=(i,e)=>du(i,fu(e));const bu="did:pkh:",ln=i=>i==null?void 0:i.split(":"),vu=i=>{const e=i&&ln(i);if(e)return i.includes(bu)?e[3]:e[1]},Ar=i=>{const e=i&&ln(i);if(e)return e[2]+":"+e[3]},Ns=i=>{const e=i&&ln(i);if(e)return e.pop()};async function Fn(i){const{cacao:e,projectId:t}=i,{s,p:r}=e,n=tc(r,r.iss),o=Ns(r.iss);return await au(o,n,s,Ar(r.iss),t)}const tc=(i,e)=>{const t=`${i.domain} wants you to sign in with your Ethereum account:`,s=Ns(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: ${vu(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,f=_s(i.resources);if(f){const y=Qi(f);r=Au(r,y)}return[t,s,"",r,"",n,o,a,c,h,l,u,p,d].filter(y=>y!=null).join(`
|
|
6
6
|
`)};function Eu(i){return me.from(JSON.stringify(i)).toString("base64")}function Iu(i){return JSON.parse(me.from(i,"base64").toString("utf-8"))}function Bt(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 _u(i,e,t,s={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[i]:Pu(e,t,s)}}}function Pu(i,e,t={}){e=e==null?void 0:e.sort((r,n)=>r.localeCompare(n));const s=e.map(r=>({[`${i}/${r}`]:[t]}));return Object.assign({},...s)}function ic(i){return Bt(i),`urn:recap:${Eu(i).replace(/=/g,"")}`}function Qi(i){const e=Iu(i.replace("urn:recap:",""));return Bt(e),e}function $u(i,e,t){const s=_u(i,e,t);return ic(s)}function Su(i){return i&&i.includes("urn:recap:")}function Ou(i,e){const t=Qi(i),s=Qi(e),r=xu(t,s);return ic(r)}function xu(i,e){Bt(i),Bt(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]=wu(yu({},s.att[r]),{[a]:((c=i.att[r])==null?void 0:c[a])||((h=e.att[r])==null?void 0:h[a])})})}),s}function Au(i="",e){Bt(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 Gn(i){var e;const t=Qi(i);Bt(t);const s=(e=t.att)==null?void 0:e.eip155;return s?Object.keys(s).map(r=>r.split("/")[1]):[]}function Wn(i){const e=Qi(i);Bt(e);const t=[];return Object.values(e.att).forEach(s=>{Object.values(s).forEach(r=>{var n;(n=r==null?void 0:r[0])!=null&&n.chains&&t.push(r[0].chains)})}),[...new Set(t.flat())]}function _s(i){if(!i)return;const e=i==null?void 0:i[i.length-1];return Su(e)?e:void 0}function tr(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function sc(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function De(i,...e){if(!sc(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 Jn(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 Cu(i,e){De(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Qn(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const St=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),Tu=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Nu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Nu)throw new Error("Non little-endian hardware is not supported");function Ru(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function Cr(i){if(typeof i=="string")i=Ru(i);else if(sc(i))i=Tr(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function ju(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function qu(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 ku=(i,e)=>{function t(s,...r){if(De(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?De(h):De(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&De(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");De(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,De(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(De(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 Yn(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&&!Du(e))throw new Error("invalid output, must be aligned");return e}function Zn(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 Du(i){return i.byteOffset%4===0}function Tr(i){return Uint8Array.from(i)}function wi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const rc=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),Lu=rc("expand 16-byte k"),Mu=rc("expand 32-byte k"),Uu=St(Lu),zu=St(Mu);function F(i,e){return i<<e|i>>>32-e}function Nr(i){return i.byteOffset%4===0}const ds=64,Bu=16,nc=2**32-1,Xn=new Uint32Array;function Ku(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(ds),l=St(h),u=Nr(r)&&Nr(n),p=u?St(r):Xn,d=u?St(n):Xn;for(let f=0;f<c;o++){if(i(e,t,s,l,o,a),o>=nc)throw new Error("arx: counter overflow");const y=Math.min(ds,c-f);if(u&&y===ds){const g=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let b=0,w;b<Bu;b++)w=g+b,d[w]=p[w]^l[b];f+=ds;continue}for(let g=0,b;g<y;g++)b=f+g,n[b]=r[b]^h[g];f+=y}}function Vu(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=ju({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return tr(r),tr(o),Qn(n),Qn(t),(a,c,h,l,u=0)=>{De(a),De(c),De(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),De(l),tr(u),u<0||u>=nc)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 f=a.length,y,g;if(f===32)d.push(y=Tr(a)),g=zu;else if(f===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),g=Uu,d.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${f}`);Nr(c)||d.push(c=Tr(c));const b=St(y);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(g,b,St(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=St(c);return Ku(i,g,b,P,h,l,u,o),wi(...d),l}}const ye=(i,e)=>i[e++]&255|(i[e++]&255)<<8;class Hu{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=Cr(e),De(e,32);const t=ye(e,0),s=ye(e,2),r=ye(e,4),n=ye(e,6),o=ye(e,8),a=ye(e,10),c=ye(e,12),h=ye(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]=ye(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],f=o[7],y=o[8],g=o[9],b=ye(e,t+0),w=ye(e,t+2),P=ye(e,t+4),A=ye(e,t+6),N=ye(e,t+8),m=ye(e,t+10),E=ye(e,t+12),_=ye(e,t+14);let I=n[0]+(b&8191),T=n[1]+((b>>>13|w<<3)&8191),C=n[2]+((w>>>10|P<<6)&8191),q=n[3]+((P>>>7|A<<9)&8191),M=n[4]+((A>>>4|N<<12)&8191),v=n[5]+(N>>>1&8191),$=n[6]+((N>>>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+T*(5*g)+C*(5*y)+q*(5*f)+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+T*a+C*(5*g)+q*(5*y)+M*(5*f);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+T*c+C*a+q*(5*g)+M*(5*y);O=z>>>13,z&=8191,z+=v*(5*f)+$*(5*d)+x*(5*p)+k*(5*u)+L*(5*l),O+=z>>>13,z&=8191;let J=O+I*l+T*h+C*c+q*a+M*(5*g);O=J>>>13,J&=8191,J+=v*(5*y)+$*(5*f)+x*(5*d)+k*(5*p)+L*(5*u),O+=J>>>13,J&=8191;let H=O+I*u+T*l+C*h+q*c+M*a;O=H>>>13,H&=8191,H+=v*(5*g)+$*(5*y)+x*(5*f)+k*(5*d)+L*(5*p),O+=H>>>13,H&=8191;let se=O+I*p+T*u+C*l+q*h+M*c;O=se>>>13,se&=8191,se+=v*a+$*(5*g)+x*(5*y)+k*(5*f)+L*(5*d),O+=se>>>13,se&=8191;let Z=O+I*d+T*p+C*u+q*l+M*h;O=Z>>>13,Z&=8191,Z+=v*c+$*a+x*(5*g)+k*(5*y)+L*(5*f),O+=Z>>>13,Z&=8191;let Ie=O+I*f+T*d+C*p+q*u+M*l;O=Ie>>>13,Ie&=8191,Ie+=v*h+$*c+x*a+k*(5*g)+L*(5*y),O+=Ie>>>13,Ie&=8191;let ae=O+I*y+T*f+C*d+q*p+M*u;O=ae>>>13,ae&=8191,ae+=v*l+$*h+x*c+k*a+L*(5*g),O+=ae>>>13,ae&=8191;let ce=O+I*g+T*y+C*f+q*d+M*p;O=ce>>>13,ce&=8191,ce+=v*u+$*l+x*h+k*c+L*a,O+=ce>>>13,ce&=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]=J,n[4]=H,n[5]=se,n[6]=Z,n[7]=Ie,n[8]=ae,n[9]=ce}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;wi(s)}update(e){Jn(this);const{buffer:t,blockLen:s}=this;e=Cr(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(){wi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Jn(this),Cu(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 Fu(i){const e=(s,r)=>i(r).update(Cr(s)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>i(s),e}const Gu=Fu(i=>new Hu(i));function Wu(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],f=e[4],y=e[5],g=e[6],b=e[7],w=r,P=t[0],A=t[1],N=t[2],m=o,E=a,_=c,I=h,T=l,C=u,q=p,M=d,v=f,$=y,x=g,k=b,L=w,O=P,D=A,U=N;for(let J=0;J<n;J+=2)m=m+T|0,L=F(L^m,16),v=v+L|0,T=F(T^v,12),m=m+T|0,L=F(L^m,8),v=v+L|0,T=F(T^v,7),E=E+C|0,O=F(O^E,16),$=$+O|0,C=F(C^$,12),E=E+C|0,O=F(O^E,8),$=$+O|0,C=F(C^$,7),_=_+q|0,D=F(D^_,16),x=x+D|0,q=F(q^x,12),_=_+q|0,D=F(D^_,8),x=x+D|0,q=F(q^x,7),I=I+M|0,U=F(U^I,16),k=k+U|0,M=F(M^k,12),I=I+M|0,U=F(U^I,8),k=k+U|0,M=F(M^k,7),m=m+C|0,U=F(U^m,16),x=x+U|0,C=F(C^x,12),m=m+C|0,U=F(U^m,8),x=x+U|0,C=F(C^x,7),E=E+q|0,L=F(L^E,16),k=k+L|0,q=F(q^k,12),E=E+q|0,L=F(L^E,8),k=k+L|0,q=F(q^k,7),_=_+M|0,O=F(O^_,16),v=v+O|0,M=F(M^v,12),_=_+M|0,O=F(O^_,8),v=v+O|0,M=F(M^v,7),I=I+T|0,D=F(D^I,16),$=$+D|0,T=F(T^$,12),I=I+T|0,D=F(D^I,8),$=$+D|0,T=F(T^$,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+T|0,s[z++]=u+C|0,s[z++]=p+q|0,s[z++]=d+M|0,s[z++]=f+v|0,s[z++]=y+$|0,s[z++]=g+x|0,s[z++]=b+k|0,s[z++]=w+L|0,s[z++]=P+O|0,s[z++]=A+D|0,s[z++]=N+U|0}const Ju=Vu(Wu,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Qu=new Uint8Array(16),eo=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(Qu.subarray(t))},Yu=new Uint8Array(32);function to(i,e,t,s,r){const n=i(e,t,Yu),o=Gu.create(n);r&&eo(o,r),eo(o,s);const a=new Uint8Array(16),c=Tu(a);Zn(c,0,BigInt(r?r.length:0),!0),Zn(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return wi(n,a),h}const Zu=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=Yn(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=to(i,e,t,a,s);return n.set(c,o),wi(c),n},decrypt(r,n){n=Yn(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=to(i,e,t,o,s);if(!qu(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),wi(c),n}}),oc=ku({blockSize:64,nonceLength:12,tagLength:16},Zu(Ju));let ac=class extends hn{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,cn(e);const s=yi(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 mi(this),this.iHash.update(e),this}digestInto(e){mi(this),ts(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 Bs=(i,e,t)=>new ac(i,e).update(t).digest();Bs.create=(i,e)=>new ac(i,e);function Xu(i,e,t){return cn(i),t===void 0&&(t=new Uint8Array(i.outputLen)),Bs(i,yi(t),yi(e))}const ir=new Uint8Array([0]),io=new Uint8Array;function ep(i,e,t,s=32){if(cn(i),Ji(s),s>255*i.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(s/i.outputLen);t===void 0&&(t=io);const n=new Uint8Array(r*i.outputLen),o=Bs.create(i,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<r;h++)ir[0]=h+1,a.update(h===0?io:c).update(t).update(ir).digestInto(c),n.set(c,i.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),ir.fill(0),n.slice(0,s)}const tp=(i,e,t,s,r)=>ep(i,Xu(i,e,t),s,r);function ip(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 sp(i,e,t){return i&e^~i&t}function rp(i,e,t){return i&e^i&t^e&t}let np=class extends hn{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=er(this.buffer)}update(e){mi(this);const{view:t,buffer:s,blockLen:r}=this;e=yi(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=er(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){mi(this),Wa(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;ip(s,r-8,BigInt(this.length*8),n),this.process(s,0);const a=er(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 op=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]),Et=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),It=new Uint32Array(64);class ap extends np{constructor(){super(64,32,8,!1),this.A=Et[0]|0,this.B=Et[1]|0,this.C=Et[2]|0,this.D=Et[3]|0,this.E=Et[4]|0,this.F=Et[5]|0,this.G=Et[6]|0,this.H=Et[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)It[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=It[u-15],d=It[u-2],f=et(p,7)^et(p,18)^p>>>3,y=et(d,17)^et(d,19)^d>>>10;It[u]=y+It[u-7]+f+It[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=et(a,6)^et(a,11)^et(a,25),d=l+p+sp(a,c,h)+op[u]+It[u]|0,f=(et(s,2)^et(s,13)^et(s,22))+rp(s,r,n)|0;l=h,h=c,c=a,a=o+d|0,o=n,n=r,r=s,s=d+f|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(){It.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const is=Ja(()=>new ap);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ks=BigInt(0),Vs=BigInt(1),cp=BigInt(2);function Kt(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ss(i){if(!Kt(i))throw new Error("Uint8Array expected")}function bi(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const hp=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function vi(i){ss(i);let e="";for(let t=0;t<i.length;t++)e+=hp[i[t]];return e}function pi(i){const e=i.toString(16);return e.length&1?"0"+e:e}function un(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?Ks:BigInt("0x"+i)}const pt={_0:48,_9:57,A:65,F:70,a:97,f:102};function so(i){if(i>=pt._0&&i<=pt._9)return i-pt._0;if(i>=pt.A&&i<=pt.F)return i-(pt.A-10);if(i>=pt.a&&i<=pt.f)return i-(pt.a-10)}function Ei(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=so(i.charCodeAt(n)),a=so(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 Ut(i){return un(vi(i))}function Yi(i){return ss(i),un(vi(Uint8Array.from(i).reverse()))}function Ii(i,e){return Ei(i.toString(16).padStart(e*2,"0"))}function Hs(i,e){return Ii(i,e).reverse()}function lp(i){return Ei(pi(i))}function ke(i,e,t){let s;if(typeof e=="string")try{s=Ei(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(Kt(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 Zi(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];ss(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 up(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 pp(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const sr=i=>typeof i=="bigint"&&Ks<=i;function Fs(i,e,t){return sr(i)&&sr(e)&&sr(t)&&e<=i&&i<t}function yt(i,e,t,s){if(!Fs(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function cc(i){let e;for(e=0;i>Ks;i>>=Vs,e+=1);return e}function dp(i,e){return i>>BigInt(e)&Vs}function fp(i,e,t){return i|(t?Vs:Ks)<<BigInt(e)}const pn=i=>(cp<<BigInt(i-1))-Vs,rr=i=>new Uint8Array(i),ro=i=>Uint8Array.from(i);function hc(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=rr(i),r=rr(i),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...l)=>t(r,s,...l),c=(l=rr())=>{r=a(ro([0]),l),s=a(),l.length!==0&&(r=a(ro([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 Zi(...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"||Kt(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 Ai(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 mp=()=>{throw new Error("not implemented")};function Rr(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 yp=Object.freeze({__proto__:null,isBytes:Kt,abytes:ss,abool:bi,bytesToHex:vi,numberToHexUnpadded:pi,hexToNumber:un,hexToBytes:Ei,bytesToNumberBE:Ut,bytesToNumberLE:Yi,numberToBytesBE:Ii,numberToBytesLE:Hs,numberToVarBytesBE:lp,ensureBytes:ke,concatBytes:Zi,equalBytes:up,utf8ToBytes:pp,inRange:Fs,aInRange:yt,bitLen:cc,bitGet:dp,bitSet:fp,bitMask:pn,createHmacDrbg:hc,validateObject:Ai,notImplemented:mp,memoized:Rr});const ge=BigInt(0),re=BigInt(1),qt=BigInt(2),wp=BigInt(3),jr=BigInt(4),no=BigInt(5),oo=BigInt(8);function Ce(i,e){const t=i%e;return t>=ge?t:e+t}function lc(i,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===re)return ge;let s=re;for(;e>ge;)e&re&&(s=s*i%t),i=i*i%t,e>>=re;return s}function Je(i,e,t){let s=i;for(;e-- >ge;)s*=s,s%=t;return s}function qr(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=Ce(i,e),s=e,r=ge,n=re;for(;t!==ge;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==re)throw new Error("invert: does not exist");return Ce(r,e)}function bp(i){const e=(i-re)/qt;let t,s,r;for(t=i-re,s=0;t%qt===ge;t/=qt,s++);for(r=qt;r<i&&lc(r,e,i)!==i-re;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+re)/jr;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+re)/qt;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 f=o.sqr(u);p<c&&!o.eql(f,o.ONE);p++)f=o.sqr(f);const d=o.pow(h,re<<BigInt(c-p-1));h=o.sqr(d),l=o.mul(l,d),u=o.mul(u,h),c=p}return l}}function vp(i){if(i%jr===wp){const e=(i+re)/jr;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%oo===no){const e=(i-no)/oo;return function(t,s){const r=t.mul(s,qt),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,qt),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 bp(i)}const Ep=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ip(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Ep.reduce((s,r)=>(s[r]="function",s),e);return Ai(i,t)}function _p(i,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return i.ONE;if(t===re)return e;let s=i.ONE,r=e;for(;t>ge;)t&re&&(s=i.mul(s,r)),r=i.sqr(r),t>>=re;return s}function Pp(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 uc(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function pc(i,e,t=!1,s={}){if(i<=ge)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=uc(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:pn(r),ZERO:ge,ONE:re,create:c=>Ce(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&re)===re,neg:c=>Ce(-c,i),eql:(c,h)=>c===h,sqr:c=>Ce(c*c,i),add:(c,h)=>Ce(c+h,i),sub:(c,h)=>Ce(c-h,i),mul:(c,h)=>Ce(c*h,i),pow:(c,h)=>_p(a,c,h),div:(c,h)=>Ce(c*qr(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>qr(c,i),sqrt:s.sqrt||(c=>(o||(o=vp(i)),o(a,c))),invertBatch:c=>Pp(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?Hs(c,n):Ii(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Yi(c):Ut(c)}});return Object.freeze(a)}function dc(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 fc(i){const e=dc(i);return e+Math.ceil(e/2)}function $p(i,e,t=!1){const s=i.length,r=dc(e),n=fc(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?Yi(i):Ut(i),a=Ce(o,e-re)+re;return t?Hs(a,r):Ii(a,r)}const ao=BigInt(0),fs=BigInt(1);function nr(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 or(i,e){gc(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function Sp(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 Op(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 ar=new WeakMap,mc=new WeakMap;function cr(i){return mc.get(i)||1}function xp(i,e){return{constTimeNegate:nr,hasPrecomputes(t){return cr(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>ao;)s&fs&&(r=r.add(n)),n=n.double(),s>>=fs;return r},precomputeWindow(t,s){const{windows:r,windowSize:n}=or(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}=or(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 f=Number(r&h);r>>=u,f>o&&(f-=l,r+=fs);const y=d,g=d+Math.abs(f)-1,b=p%2!==0,w=f<0;f===0?c=c.add(nr(b,s[y])):a=a.add(nr(w,s[g]))}return{p:a,f:c}},wNAFUnsafe(t,s,r,n=i.ZERO){const{windows:o,windowSize:a}=or(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===ao)break;let d=Number(r&c);if(r>>=l,d>a&&(d-=h,r+=fs),d===0)continue;let f=s[p+Math.abs(d)-1];d<0&&(f=f.negate()),n=n.add(f)}return n},getPrecomputes(t,s,r){let n=ar.get(s);return n||(n=this.precomputeWindow(s,t),t!==1&&ar.set(s,r(n))),n},wNAFCached(t,s,r){const n=cr(t);return this.wNAF(n,this.getPrecomputes(n,t,r),s)},wNAFCachedUnsafe(t,s,r,n){const o=cr(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),mc.set(t,s),ar.delete(t)}}}function Ap(i,e,t,s){if(Sp(t,i),Op(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=cc(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 f=s[d],y=Number(f>>BigInt(u)&BigInt(a));c[y]=c[y].add(t[d])}let p=r;for(let d=c.length-1,f=r;d>0;d--)f=f.add(c[d]),p=p.add(f);if(l=l.add(p),u!==0)for(let d=0;d<o;d++)l=l.double()}return l}function yc(i){return Ip(i.Fp),Ai(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...uc(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Jt=BigInt(0),hr=BigInt(1);function Cp(i){return Ai(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function Tp(i){const e=Cp(i),{P:t}=e,s=w=>Ce(w,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(w=>w),c=e.powPminus2||(w=>lc(w,t-BigInt(2),t));function h(w,P,A){const N=s(w*(P-A));return P=s(P-N),A=s(A+N),[P,A]}const l=(e.a-BigInt(2))/BigInt(4);function u(w,P){yt("u",w,Jt,t),yt("scalar",P,Jt,t);const A=P,N=w;let m=hr,E=Jt,_=w,I=hr,T=Jt,C;for(let M=BigInt(r-1);M>=Jt;M--){const v=A>>M&hr;T^=v,C=h(T,m,_),m=C[0],_=C[1],C=h(T,E,I),E=C[0],I=C[1],T=v;const $=m+E,x=s($*$),k=m-E,L=s(k*k),O=x-L,D=_+I,U=_-I,z=s(U*$),J=s(D*k),H=z+J,se=z-J;_=s(H*H),I=s(N*s(se*se)),m=s(x*L),E=s(O*(x+s(l*O)))}C=h(T,m,_),m=C[0],_=C[1],C=h(T,E,I),E=C[0],I=C[1];const q=c(E);return s(m*q)}function p(w){return Hs(s(w),n)}function d(w){const P=ke("u coordinate",w,n);return o===32&&(P[31]&=127),Yi(P)}function f(w){const P=ke("scalar",w),A=P.length;if(A!==n&&A!==o){let N=""+n+" or "+o;throw new Error("invalid scalar, expected "+N+" bytes, got "+A)}return Yi(a(P))}function y(w,P){const A=d(P),N=f(w),m=u(A,N);if(m===Jt)throw new Error("invalid private or public key received");return p(m)}const g=p(e.Gu);function b(w){return y(w,g)}return{scalarMult:y,scalarMultBase:b,getSharedSecret:(w,P)=>y(w,P),getPublicKey:w=>b(w),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:g}}const kr=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Np=BigInt(1),co=BigInt(2),Rp=BigInt(3),jp=BigInt(5);BigInt(8);function qp(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=kr,o=i*i%n*i%n,a=Je(o,co,n)*o%n,c=Je(a,Np,n)*i%n,h=Je(c,jp,n)*c%n,l=Je(h,e,n)*h%n,u=Je(l,t,n)*l%n,p=Je(u,s,n)*u%n,d=Je(p,r,n)*p%n,f=Je(d,r,n)*p%n,y=Je(f,e,n)*h%n;return{pow_p_5_8:Je(y,co,n)*i%n,b2:o}}function kp(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const Dr=Tp({P:kr,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=kr,{pow_p_5_8:t,b2:s}=qp(i);return Ce(Je(t,Rp,e)*s,e)},adjustScalarBytes:kp,randomBytes:xi});function ho(i){i.lowS!==void 0&&bi("lowS",i.lowS),i.prehash!==void 0&&bi("prehash",i.prehash)}function Dp(i){const e=yc(i);Ai(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:Lp,hexToBytes:Mp}=yp;class Up extends Error{constructor(e=""){super(e)}}const gt={Err:Up,_tlv:{encode:(i,e)=>{const{Err:t}=gt;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=pi(s);if(r.length/2&128)throw new t("tlv.encode: long form length too big");const n=s>127?pi(r.length/2|128):"";return pi(i)+n+r+e},decode(i,e){const{Err:t}=gt;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}=gt;if(i<mt)throw new e("integer: negative integers are not allowed");let t=pi(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}=gt;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 Lp(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=gt,r=typeof i=="string"?Mp(i):i;ss(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}=gt,s=e.encode(2,t.encode(i.r)),r=e.encode(2,t.encode(i.s)),n=s+r;return e.encode(48,n)}},mt=BigInt(0),de=BigInt(1);BigInt(2);const lo=BigInt(3);BigInt(4);function zp(i){const e=Dp(i),{Fp:t}=e,s=pc(e.n,e.nBitLength),r=e.toBytes||((y,g,b)=>{const w=g.toAffine();return Zi(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),n=e.fromBytes||(y=>{const g=y.subarray(1),b=t.fromBytes(g.subarray(0,t.BYTES)),w=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:b,y:w}});function o(y){const{a:g,b}=e,w=t.sqr(y),P=t.mul(w,y);return t.add(t.add(P,t.mul(y,g)),b)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Fs(y,de,e.n)}function c(y){const{allowedPrivateKeyLengths:g,nByteLength:b,wrapPrivateKey:w,n:P}=e;if(g&&typeof y!="bigint"){if(Kt(y)&&(y=vi(y)),typeof y!="string"||!g.includes(y.length))throw new Error("invalid private key");y=y.padStart(b*2,"0")}let A;try{A=typeof y=="bigint"?y:Ut(ke("private key",y,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof y)}return w&&(A=Ce(A,P)),yt("private key",A,de,P),A}function h(y){if(!(y instanceof p))throw new Error("ProjectivePoint expected")}const l=Rr((y,g)=>{const{px:b,py:w,pz:P}=y;if(t.eql(P,t.ONE))return{x:b,y:w};const A=y.is0();g==null&&(g=A?t.ONE:t.inv(P));const N=t.mul(b,g),m=t.mul(w,g),E=t.mul(P,g);if(A)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:N,y:m}}),u=Rr(y=>{if(y.is0()){if(e.allowInfinityPoint&&!t.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:g,y:b}=y.toAffine();if(!t.isValid(g)||!t.isValid(b))throw new Error("bad point: x or y not FE");const w=t.sqr(b),P=o(g);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(g,b,w){if(this.px=g,this.py=b,this.pz=w,g==null||!t.isValid(g))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(g){const{x:b,y:w}=g||{};if(!g||!t.isValid(b)||!t.isValid(w))throw new Error("invalid affine point");if(g 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(g){const b=t.invertBatch(g.map(w=>w.pz));return g.map((w,P)=>w.toAffine(b[P])).map(p.fromAffine)}static fromHex(g){const b=p.fromAffine(n(ke("pointHex",g)));return b.assertValidity(),b}static fromPrivateKey(g){return p.BASE.multiply(c(g))}static msm(g,b){return Ap(p,s,g,b)}_setWindowSize(g){f.setWindowSize(this,g)}assertValidity(){u(this)}hasEvenY(){const{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){h(g);const{px:b,py:w,pz:P}=this,{px:A,py:N,pz:m}=g,E=t.eql(t.mul(b,m),t.mul(A,P)),_=t.eql(t.mul(w,m),t.mul(N,P));return E&&_}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:g,b}=e,w=t.mul(b,lo),{px:P,py:A,pz:N}=this;let m=t.ZERO,E=t.ZERO,_=t.ZERO,I=t.mul(P,P),T=t.mul(A,A),C=t.mul(N,N),q=t.mul(P,A);return q=t.add(q,q),_=t.mul(P,N),_=t.add(_,_),m=t.mul(g,_),E=t.mul(w,C),E=t.add(m,E),m=t.sub(T,E),E=t.add(T,E),E=t.mul(m,E),m=t.mul(q,m),_=t.mul(w,_),C=t.mul(g,C),q=t.sub(I,C),q=t.mul(g,q),q=t.add(q,_),_=t.add(I,I),I=t.add(_,I),I=t.add(I,C),I=t.mul(I,q),E=t.add(E,I),C=t.mul(A,N),C=t.add(C,C),I=t.mul(C,q),m=t.sub(m,I),_=t.mul(C,T),_=t.add(_,_),_=t.add(_,_),new p(m,E,_)}add(g){h(g);const{px:b,py:w,pz:P}=this,{px:A,py:N,pz:m}=g;let E=t.ZERO,_=t.ZERO,I=t.ZERO;const T=e.a,C=t.mul(e.b,lo);let q=t.mul(b,A),M=t.mul(w,N),v=t.mul(P,m),$=t.add(b,w),x=t.add(A,N);$=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(N,m),k=t.mul(k,E),E=t.add(M,v),k=t.sub(k,E),I=t.mul(T,x),E=t.mul(C,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(T,v),x=t.mul(C,x),M=t.add(M,v),v=t.sub(q,v),v=t.mul(T,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(g){return this.add(g.negate())}is0(){return this.equals(p.ZERO)}wNAF(g){return f.wNAFCached(this,g,p.normalizeZ)}multiplyUnsafe(g){const{endo:b,n:w}=e;yt("scalar",g,mt,w);const P=p.ZERO;if(g===mt)return P;if(this.is0()||g===de)return this;if(!b||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,g,p.normalizeZ);let{k1neg:A,k1:N,k2neg:m,k2:E}=b.splitScalar(g),_=P,I=P,T=this;for(;N>mt||E>mt;)N&de&&(_=_.add(T)),E&de&&(I=I.add(T)),T=T.double(),N>>=de,E>>=de;return A&&(_=_.negate()),m&&(I=I.negate()),I=new p(t.mul(I.px,b.beta),I.py,I.pz),_.add(I)}multiply(g){const{endo:b,n:w}=e;yt("scalar",g,de,w);let P,A;if(b){const{k1neg:N,k1:m,k2neg:E,k2:_}=b.splitScalar(g);let{p:I,f:T}=this.wNAF(m),{p:C,f:q}=this.wNAF(_);I=f.constTimeNegate(N,I),C=f.constTimeNegate(E,C),C=new p(t.mul(C.px,b.beta),C.py,C.pz),P=I.add(C),A=T.add(q)}else{const{p:N,f:m}=this.wNAF(g);P=N,A=m}return p.normalizeZ([P,A])[0]}multiplyAndAddUnsafe(g,b,w){const P=p.BASE,A=(m,E)=>E===mt||E===de||!m.equals(P)?m.multiplyUnsafe(E):m.multiply(E),N=A(this,b).add(A(g,w));return N.is0()?void 0:N}toAffine(g){return l(this,g)}isTorsionFree(){const{h:g,isTorsionFree:b}=e;if(g===de)return!0;if(b)return b(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:g,clearCofactor:b}=e;return g===de?this:b?b(p,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return bi("isCompressed",g),this.assertValidity(),r(p,this,g)}toHex(g=!0){return bi("isCompressed",g),vi(this.toRawBytes(g))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const d=e.nBitLength,f=xp(p,e.endo?Math.ceil(d/2):d);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Bp(i){const e=yc(i);return Ai(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Kp(i){const e=Bp(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(v){return Ce(v,s)}function a(v){return qr(v,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=zp({...e,toBytes(v,$,x){const k=$.toAffine(),L=t.toBytes(k.x),O=Zi;return bi("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=Ut(k);if(!Fs(L,de,t.ORDER))throw new Error("Point is not on curve");const O=l(L);let D;try{D=t.sqrt(O)}catch(z){const J=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+J)}const U=(D&de)===de;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=>vi(Ii(v,e.nByteLength));function d(v){const $=s>>de;return v>$}function f(v){return d(v)?o(-v):v}const y=(v,$,x)=>Ut(v.slice($,x));class g{constructor($,x,k){this.r=$,this.s=x,this.recovery=k,this.assertValidity()}static fromCompact($){const x=e.nByteLength;return $=ke("compactSignature",$,x*2),new g(y($,0,x),y($,x,2*x))}static fromDER($){const{r:x,s:k}=gt.toSig(ke("DER",$));return new g(x,k)}assertValidity(){yt("r",this.r,de,s),yt("s",this.s,de,s)}addRecoveryBit($){return new g(this.r,this.s,$)}recoverPublicKey($){const{r:x,s:k,recovery:L}=this,O=m(ke("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)),J=a(D),H=o(-O*J),se=o(k*J),Z=c.BASE.multiplyAndAddUnsafe(z,H,se);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Ei(this.toDERHex())}toDERHex(){return gt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ei(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=fc(e.n);return $p(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 $=Kt(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 N=e.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");const $=Ut(v),x=v.length*8-e.nBitLength;return x>0?$>>BigInt(x):$},m=e.bits2int_modN||function(v){return o(N(v))},E=pn(e.nBitLength);function _(v){return yt("num < 2^"+e.nBitLength,v,mt,E),Ii(v,e.nByteLength)}function I(v,$,x=T){if(["recovered","canonical"].some(ae=>ae 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=ke("msgHash",v),ho(x),D&&(v=ke("prehashed msgHash",k(v)));const z=m(v),J=h($),H=[_(J),_(z)];if(U!=null&&U!==!1){const ae=U===!0?L(t.BYTES):U;H.push(ke("extraEntropy",ae))}const se=Zi(...H),Z=z;function Ie(ae){const ce=N(ae);if(!u(ce))return;const Ct=a(ce),ct=c.BASE.multiply(ce).toAffine(),Xe=o(ct.x);if(Xe===mt)return;const ht=o(Ct*o(Z+Xe*J));if(ht===mt)return;let lt=(ct.x===Xe?0:2)|Number(ct.y&de),hs=ht;return O&&d(ht)&&(hs=f(ht),lt^=1),new g(Xe,hs,lt)}return{seed:se,k2sig:Ie}}const T={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function q(v,$,x=T){const{seed:k,k2sig:L}=I(v,$,x),O=e;return hc(O.hash.outputLen,O.nByteLength,O.hmac)(k,L)}c.BASE._setWindowSize(8);function M(v,$,x,k=C){var ht;const L=v;$=ke("msgHash",$),x=ke("publicKey",x);const{lowS:O,prehash:D,format:U}=k;if(ho(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"||Kt(L),J=!z&&!U&&typeof L=="object"&&L!==null&&typeof L.r=="bigint"&&typeof L.s=="bigint";if(!z&&!J)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let H,se;try{if(J&&(H=new g(L.r,L.s)),z){try{U!=="compact"&&(H=g.fromDER(L))}catch(lt){if(!(lt instanceof gt.Err))throw lt}!H&&U!=="der"&&(H=g.fromCompact(L))}se=c.fromHex(x)}catch{return!1}if(!H||O&&H.hasHighS())return!1;D&&($=e.hash($));const{r:Z,s:Ie}=H,ae=m($),ce=a(Ie),Ct=o(ae*ce),ct=o(Z*ce),Xe=(ht=c.BASE.multiplyAndAddUnsafe(se,Ct,ct))==null?void 0:ht.toAffine();return Xe?o(Xe.x)===Z:!1}return{CURVE:e,getPublicKey:w,getSharedSecret:A,sign:q,verify:M,ProjectivePoint:c,Signature:g,utils:b}}function Vp(i){return{hash:i,hmac:(e,...t)=>Bs(i,e,Wl(...t)),randomBytes:xi}}function Hp(i,e){const t=s=>Kp({...i,...Vp(s)});return{...t(e),create:t}}const wc=pc(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Fp=wc.create(BigInt("-3")),Gp=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Wp=Hp({a:Fp,b:Gp,Fp:wc,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},is),bc="base10",$e="base16",Qe="base64pad",Pt="base64url",rs="utf8",vc=0,wt=1,ns=2,Jp=0,uo=1,Vi=12,dn=32;function Qp(){const i=Dr.utils.randomPrivateKey(),e=Dr.getPublicKey(i);return{privateKey:Te(i,$e),publicKey:Te(e,$e)}}function Lr(){const i=xi(dn);return Te(i,$e)}function Yp(i,e){const t=Dr.getSharedSecret(Ke(i,$e),Ke(e,$e)),s=tp(is,t,void 0,void 0,dn);return Te(s,$e)}function Ps(i){const e=is(Ke(i,$e));return Te(e,$e)}function nt(i){const e=is(Ke(i,rs));return Te(e,$e)}function Ec(i){return Ke(`${i}`,bc)}function Vt(i){return Number(Te(i,bc))}function Ic(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function _c(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Zp(i){const e=Ec(typeof i.type<"u"?i.type:vc);if(Vt(e)===wt&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?Ke(i.senderPublicKey,$e):void 0,s=typeof i.iv<"u"?Ke(i.iv,$e):xi(Vi),r=Ke(i.symKey,$e),n=oc(r,s).encrypt(Ke(i.message,rs)),o=Pc({type:e,sealed:n,iv:s,senderPublicKey:t});return i.encoding===Pt?Ic(o):o}function Xp(i){const e=Ke(i.symKey,$e),{sealed:t,iv:s}=Xi({encoded:i.encoded,encoding:i.encoding}),r=oc(e,s).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return Te(r,rs)}function ed(i,e){const t=Ec(ns),s=xi(Vi),r=Ke(i,rs),n=Pc({type:t,sealed:r,iv:s});return e===Pt?Ic(n):n}function td(i,e){const{sealed:t}=Xi({encoded:i,encoding:e});return Te(t,rs)}function Pc(i){if(Vt(i.type)===ns)return Te(Ki([i.type,i.sealed]),Qe);if(Vt(i.type)===wt){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Te(Ki([i.type,i.senderPublicKey,i.iv,i.sealed]),Qe)}return Te(Ki([i.type,i.iv,i.sealed]),Qe)}function Xi(i){const e=(i.encoding||Qe)===Pt?_c(i.encoded):i.encoded,t=Ke(e,Qe),s=t.slice(Jp,uo),r=uo;if(Vt(s)===wt){const c=r+dn,h=c+Vi,l=t.slice(r,c),u=t.slice(c,h),p=t.slice(h);return{type:s,sealed:p,iv:u,senderPublicKey:l}}if(Vt(s)===ns){const c=t.slice(r),h=xi(Vi);return{type:s,sealed:c,iv:h}}const n=r+Vi,o=t.slice(r,n),a=t.slice(n);return{type:s,sealed:a,iv:o}}function id(i,e){const t=Xi({encoded:i,encoding:e==null?void 0:e.encoding});return $c({type:Vt(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Te(t.senderPublicKey,$e):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function $c(i){const e=(i==null?void 0:i.type)||vc;if(e===wt){if(typeof(i==null?void 0:i.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(i==null?void 0:i.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:i==null?void 0:i.senderPublicKey,receiverPublicKey:i==null?void 0:i.receiverPublicKey}}function po(i){return i.type===wt&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function fo(i){return i.type===ns}function sd(i){const e=me.from(i.x,"base64"),t=me.from(i.y,"base64");return Ki([new Uint8Array([4]),e,t])}function rd(i,e){const[t,s,r]=i.split("."),n=me.from(_c(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=is(c),l=sd(e);if(!Wp.verify(Ki([o,a]),h,l))throw new Error("Invalid signature");return Pr(i).payload}const nd="irn";function Rs(i){return(i==null?void 0:i.relay)||{protocol:nd}}function Ui(i){const e=lh[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function od(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=Ga(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:ad(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:od(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function ad(i){return i.startsWith("//")?i.substring(2):i}function cd(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 mo(i){const e=new URLSearchParams,t=cd(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 gs(i,e,t){return`${i}?wc_ev=${t}&topic=${e}`}var hd=Object.defineProperty,ld=Object.defineProperties,ud=Object.getOwnPropertyDescriptors,yo=Object.getOwnPropertySymbols,pd=Object.prototype.hasOwnProperty,dd=Object.prototype.propertyIsEnumerable,wo=(i,e,t)=>e in i?hd(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,fd=(i,e)=>{for(var t in e||(e={}))pd.call(e,t)&&wo(i,t,e[t]);if(yo)for(var t of yo(e))dd.call(e,t)&&wo(i,t,e[t]);return i},gd=(i,e)=>ld(i,ud(e));function Ci(i){const e=[];return i.forEach(t=>{const[s,r]=t.split(":");e.push(`${s}:${r}`)}),e}function md(i){const e=[];return Object.values(i).forEach(t=>{e.push(...Ci(t.accounts))}),e}function yd(i,e){const t=[];return Object.values(i).forEach(s=>{Ci(s.accounts).includes(e)&&t.push(...s.methods)}),t}function wd(i,e){const t=[];return Object.values(i).forEach(s=>{Ci(s.accounts).includes(e)&&t.push(...s.events)}),t}function Gs(i){return i.includes(":")}function di(i){return Gs(i)?i.split(":")[0]:i}function bo(i){var e,t,s;const r={};if(!Ot(i))return r;for(const[n,o]of Object.entries(i)){const a=Gs(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],l=di(n);r[l]=gd(fd({},r[l]),{chains:ot(a,(e=r[l])==null?void 0:e.chains),methods:ot(c,(t=r[l])==null?void 0:t.methods),events:ot(h,(s=r[l])==null?void 0:s.events)})}return r}function bd(i){const e={};return i==null||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 vo(i,e){e=e.map(s=>s.replace("did:pkh:",""));const t=bd(e);for(const[s,r]of Object.entries(t))r.methods?r.methods=ot(r.methods,i):r.methods=i,r.events=["chainChanged","accountsChanged"];return t}function vd(i,e){var t,s,r,n,o,a;const c=bo(i),h=bo(e),l={},u=Object.keys(c).concat(Object.keys(h));for(const p of u)l[p]={chains:ot((t=c[p])==null?void 0:t.chains,(s=h[p])==null?void 0:s.chains),methods:ot((r=c[p])==null?void 0:r.methods,(n=h[p])==null?void 0:n.methods),events:ot((o=c[p])==null?void 0:o.events,(a=h[p])==null?void 0:a.events)};return l}const Ed={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}},Id={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 R(i,e){const{message:t,code:s}=Id[i];return{message:e?`${t} ${e}`:t,code:s}}function Y(i,e){const{message:t,code:s}=Ed[i];return{message:e?`${t} ${e}`:t,code:s}}function Ye(i,e){return!!Array.isArray(i)}function Ot(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}function ve(i){return typeof i>"u"}function oe(i,e){return e&&ve(i)?!0:typeof i=="string"&&!!i.trim().length}function fn(i,e){return e&&ve(i)?!0:typeof i=="number"&&!isNaN(i)}function _d(i,e){const{requiredNamespaces:t}=e,s=Object.keys(i.namespaces),r=Object.keys(t);let n=!0;return Mt(r,s)?(s.forEach(o=>{const{accounts:a,methods:c,events:h}=i.namespaces[o],l=Ci(a),u=t[o];(!Mt(Ba(o,u),l)||!Mt(u.methods,c)||!Mt(u.events,h))&&(n=!1)}),n):!1}function js(i){return oe(i,!1)&&i.includes(":")?i.split(":").length===2:!1}function Pd(i){if(oe(i,!1)&&i.includes(":")){const e=i.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&js(t)}}return!1}function $d(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(oe(i,!1)){if(e(i))return!0;const t=Ga(i);return e(t)}}catch{}return!1}function Sd(i){var e;return(e=i==null?void 0:i.proposer)==null?void 0:e.publicKey}function Od(i){return i==null?void 0:i.topic}function xd(i,e){let t=null;return oe(i==null?void 0:i.publicKey,!1)||(t=R("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function Eo(i){let e=!0;return Ye(i)?i.length&&(e=i.every(t=>oe(t,!1))):e=!1,e}function Ad(i,e,t){let s=null;return Ye(e)&&e.length?e.forEach(r=>{s||js(r)||(s=Y("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):js(i)||(s=Y("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 Cd(i,e,t){let s=null;return Object.entries(i).forEach(([r,n])=>{if(s)return;const o=Ad(r,Ba(r,n),`${e} ${t}`);o&&(s=o)}),s}function Td(i,e){let t=null;return Ye(i)?i.forEach(s=>{t||Pd(s)||(t=Y("UNSUPPORTED_ACCOUNTS",`${e}, account ${s} should be a string and conform to "namespace:chainId:address" format`))}):t=Y("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function Nd(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=Td(s==null?void 0:s.accounts,`${e} namespace`);r&&(t=r)}),t}function Rd(i,e){let t=null;return Eo(i==null?void 0:i.methods)?Eo(i==null?void 0:i.events)||(t=Y("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Y("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Sc(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=Rd(s,`${e}, namespace`);r&&(t=r)}),t}function jd(i,e,t){let s=null;if(i&&Ot(i)){const r=Sc(i,e);r&&(s=r);const n=Cd(i,e,t);n&&(s=n)}else s=R("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return s}function lr(i,e){let t=null;if(i&&Ot(i)){const s=Sc(i,e);s&&(t=s);const r=Nd(i,e);r&&(t=r)}else t=R("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Oc(i){return oe(i.protocol,!0)}function qd(i,e){let t=!1;return i?i&&Ye(i)&&i.length&&i.forEach(s=>{t=Oc(s)}):t=!0,t}function kd(i){return typeof i=="number"}function Ae(i){return typeof i<"u"&&typeof i!==null}function Dd(i){return!(!i||typeof i!="object"||!i.code||!fn(i.code,!1)||!i.message||!oe(i.message,!1))}function Ld(i){return!(ve(i)||!oe(i.method,!1))}function Md(i){return!(ve(i)||ve(i.result)&&ve(i.error)||!fn(i.id,!1)||!oe(i.jsonrpc,!1))}function Ud(i){return!(ve(i)||!oe(i.name,!1))}function Io(i,e){return!(!js(e)||!md(i).includes(e))}function zd(i,e,t){return oe(t,!1)?yd(i,e).includes(t):!1}function Bd(i,e,t){return oe(t,!1)?wd(i,e).includes(t):!1}function _o(i,e,t){let s=null;const r=Kd(i),n=Vd(e),o=Object.keys(r),a=Object.keys(n),c=Po(Object.keys(i)),h=Po(Object.keys(e)),l=c.filter(u=>!h.includes(u));return l.length&&(s=R("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
|
|
@@ -9,4 +9,4 @@ ${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+me.from(nu(t)).toString(
|
|
|
9
9
|
Required: ${o.toString()}
|
|
10
10
|
Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||s)return;const p=Ci(e[u].accounts);p.includes(u)||(s=R("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||(Mt(r[u].methods,n[u].methods)?Mt(r[u].events,n[u].events)||(s=R("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=R("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function Kd(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 Po(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Vd(i){const e={};return Object.keys(i).forEach(t=>{if(t.includes(":"))e[t]=i[t];else{const s=Ci(i[t].accounts);s==null||s.forEach(r=>{e[r]={accounts:i[t].accounts.filter(n=>n.includes(`${r}:`)),methods:i[t].methods,events:i[t].events}})}}),e}function Hd(i,e){return fn(i,!1)&&i<=e.max&&i>=e.min}function $o(){const i=es();return new Promise(e=>{switch(i){case Le.browser:e(Fd());break;case Le.reactNative:e(Gd());break;case Le.node:e(Wd());break;default:e(!0)}})}function Fd(){return Oi()&&(navigator==null?void 0:navigator.onLine)}async function Gd(){if(At()&&typeof B<"u"&&B!=null&&B.NetInfo){const i=await(B==null?void 0:B.NetInfo.fetch());return i==null?void 0:i.isConnected}return!0}function Wd(){return!0}function Jd(i){switch(es()){case Le.browser:Qd(i);break;case Le.reactNative:Yd(i);break}}function Qd(i){!At()&&Oi()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function Yd(i){var e;At()&&typeof B<"u"&&B!=null&&B.NetInfo&&((e=B)==null||e.NetInfo.addEventListener(t=>i(t==null?void 0:t.isConnected)))}function Zd(){var i;return Oi()&&bt.getDocument()?((i=bt.getDocument())==null?void 0:i.visibilityState)==="visible":!0}const ur={};class ji{static get(e){return ur[e]}static set(e,t){ur[e]=t}static delete(e){delete ur[e]}}function Xd(i){return!i||typeof i.then!="function"?Promise.resolve(i):i}function pe(i,...e){try{return Xd(i(...e))}catch(t){return Promise.reject(t)}}function ef(i){const e=typeof i;return i===null||e!=="object"&&e!=="function"}function tf(i){const e=Object.getPrototypeOf(i);return!e||e.isPrototypeOf(Object)}function $s(i){if(ef(i))return String(i);if(tf(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 Mr="base64:";function sf(i){return typeof i=="string"?i:Mr+of(i)}function rf(i){return typeof i!="string"||!i.startsWith(Mr)?i:nf(i.slice(Mr.length))}function nf(i){return globalThis.Buffer?me.from(i,"base64"):Uint8Array.from(globalThis.atob(i),e=>e.codePointAt(0))}function of(i){return globalThis.Buffer?me.from(i).toString("base64"):globalThis.btoa(String.fromCodePoint(...i))}function xe(i){var e;return i&&((e=i.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function af(...i){return xe(i.join(":"))}function ms(i){return i=xe(i),i?i+":":""}function cf(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 hf(i,e){return e?i.startsWith(e)&&i[i.length-1]!=="$":i[i.length-1]!=="$"}const lf="memory",uf=()=>{const i=new Map;return{name:lf,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 pf(i={}){const e={mounts:{"":i.driver||uf()},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=xe(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 So(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=f=>{let y=p.get(f.base);return y||(y={driver:f.driver,base:f.base,items:[]},p.set(f.base,y)),y};for(const f of h){const y=typeof f=="string",g=xe(y?f:f.key),b=y?void 0:f.value,w=y||!f.options?l:{...l,...f.options},P=t(g);d(P).items.push({key:g,value:b,relativeKey:P.relativeKey,options:w})}return Promise.all([...p.values()].map(f=>u(f))).then(f=>f.flat())},c={hasItem(h,l={}){h=xe(h);const{relativeKey:u,driver:p}=t(h);return pe(p.hasItem,u,l)},getItem(h,l={}){h=xe(h);const{relativeKey:u,driver:p}=t(h);return pe(p.getItem,u,l).then(d=>ls(d))},getItems(h,l={}){return a(h,l,u=>u.driver.getItems?pe(u.driver.getItems,u.items.map(p=>({key:p.relativeKey,options:p.options})),l).then(p=>p.map(d=>({key:af(u.base,d.key),value:ls(d.value)}))):Promise.all(u.items.map(p=>pe(u.driver.getItem,p.relativeKey,p.options).then(d=>({key:p.key,value:ls(d)})))))},getItemRaw(h,l={}){h=xe(h);const{relativeKey:u,driver:p}=t(h);return p.getItemRaw?pe(p.getItemRaw,u,l):pe(p.getItem,u,l).then(d=>rf(d))},async setItem(h,l,u={}){if(l===void 0)return c.removeItem(h);h=xe(h);const{relativeKey:p,driver:d}=t(h);d.setItem&&(await pe(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 pe(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=>pe(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=xe(h);const{relativeKey:p,driver:d}=t(h);if(d.setItemRaw)await pe(d.setItemRaw,p,l,u);else if(d.setItem)await pe(d.setItem,p,sf(l),u);else return;d.watch||r("update",h)},async removeItem(h,l={}){typeof l=="boolean"&&(l={removeMeta:l}),h=xe(h);const{relativeKey:u,driver:p}=t(h);p.removeItem&&(await pe(p.removeItem,u,l),(l.removeMeta||l.removeMata)&&await pe(p.removeItem,u+"$",l),p.watch||r("remove",h))},async getMeta(h,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),h=xe(h);const{relativeKey:u,driver:p}=t(h),d=Object.create(null);if(p.getMeta&&Object.assign(d,await pe(p.getMeta,u,l)),!l.nativeOnly){const f=await pe(p.getItem,u+"$",l).then(y=>ls(y));f&&typeof f=="object"&&(typeof f.atime=="string"&&(f.atime=new Date(f.atime)),typeof f.mtime=="string"&&(f.mtime=new Date(f.mtime)),Object.assign(d,f))}return d},setMeta(h,l,u={}){return this.setItem(h+"$",l,u)},removeMeta(h,l={}){return this.removeItem(h+"$",l)},async getKeys(h,l={}){var g;h=ms(h);const u=s(h,!0);let p=[];const d=[];let f=!0;for(const b of u){(g=b.driver.flags)!=null&&g.maxDepth||(f=!1);const w=await pe(b.driver.getKeys,b.relativeBase,l);for(const P of w){const A=b.mountpoint+xe(P);p.some(N=>A.startsWith(N))||d.push(A)}p=[b.mountpoint,...p.filter(P=>!P.startsWith(b.mountpoint))]}const y=l.maxDepth!==void 0&&!f;return d.filter(b=>(!y||cf(b,l.maxDepth))&&hf(b,h))},async clear(h,l={}){h=ms(h),await Promise.all(s(h,!1).map(async u=>{if(u.driver.clear)return pe(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=>Oo(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=ms(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(So(l,r,h)).then(u=>{e.unwatch[h]=u}).catch(console.error),c},async unmount(h,l=!0){var u,p;h=ms(h),!(!h||!e.mounts[h])&&(e.watching&&h in e.unwatch&&((p=(u=e.unwatch)[h])==null||p.call(u),delete e.unwatch[h]),l&&await Oo(e.mounts[h]),e.mountpoints=e.mountpoints.filter(d=>d!==h),delete e.mounts[h])},getMount(h=""){h=xe(h)+":";const l=t(h);return{driver:l.driver,base:l.base}},getMounts(h="",l={}){return h=xe(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 So(i,e,t){return i.watch?i.watch((s,r)=>e(s,t+r)):()=>{}}async function Oo(i){typeof i.dispose=="function"&&await pe(i.dispose)}const df="idb-keyval";var ff=(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:df,options:i,async hasItem(r){return!(typeof await En(t(r),s)>"u")},async getItem(r){return await En(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 gf="WALLET_CONNECT_V2_INDEXED_DB",mf="keyvaluestorage";let yf=class{constructor(){this.indexedDb=pf({driver:ff({dbName:gf,storeName:mf})})}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,Gi(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var pr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof B<"u"?B:typeof self<"u"?self:{},Ss={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 pr<"u"&&pr.localStorage?Ss.exports=pr.localStorage:typeof window<"u"&&window.localStorage?Ss.exports=window.localStorage:Ss.exports=new e})();function wf(i){var e;return[i[0],As((e=i[1])!=null?e:"")]}let bf=class{constructor(){this.localStorage=Ss.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(wf)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return As(t)}async setItem(e,t){this.localStorage.setItem(e,Gi(t))}async removeItem(e){this.localStorage.removeItem(e)}};const vf="wc_storage_version",xo=1,Ef=async(i,e,t)=>{const s=vf,r=await e.getItem(s);if(r&&r>=xo){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,xo),t(e),If(i,o)},If=async(i,e)=>{e.length&&e.forEach(async t=>{await i.removeItem(t)})};let _f=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new bf;this.storage=e;try{const t=new yf;Ef(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 dr,Ao;function Pf(){if(Ao)return dr;Ao=1;const i=_h();dr=r;const e=N().console||{},t={mapHttpRequest:f,mapHttpResponse:f,wrapRequestSerializer:y,wrapResponseSerializer:y,wrapErrorSerializer:y,req:f,res:f,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||{},T=s(m.browser.serialize,I);let C=m.browser.serialize;Array.isArray(m.browser.serialize)&&m.browser.serialize.indexOf("!stdSerializers.err")>-1&&(C=!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=g),Object.defineProperty(v,"levelVal",{get:x}),Object.defineProperty(v,"level",{get:k,set:L});const $={transmit:E,serialize:T,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=g,v.serializers=I,v._serialize=T,v._stdErrSerialize=C,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||{},T&&D.serializers&&(U.serializers=D.serializers);const z=U.serializers;if(T&&z){var J=Object.assign({},I,z),H=m.browser.serialize===!0?Object.keys(J):T;delete D.serializers,c([D],H,J,this._stdErrSerialize)}function se(Z){this._childLevel=(Z._childLevel|0)+1,this.error=h(Z,D,"error"),this.fatal=h(Z,D,"fatal"),this.warn=h(Z,D,"warn"),this.info=h(Z,D,"info"),this.debug=h(Z,D,"debug"),this.trace=h(Z,D,"trace"),J&&(this.serializers=J,this._serialize=H),E&&(this._logEvent=u([].concat(Z._logEvent.bindings,D)))}return se.prototype=this,new se(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 T=Object.getPrototypeOf(E);E[_]=E.levelVal>E.levels.values[_]?g:T[_]?T[_]:e[_]||e[I]||g,o(m,E,_)}function o(m,E,_){!m.transmit&&E[_]===g||(E[_]=(function(I){return function(){const C=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,C)):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:C,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 T=_.slice();let C=T[0];const q={};I&&(q.time=I),q.level=r.levels.values[E];let M=(m._childLevel|0)+1;if(M<1&&(M=1),C!==null&&typeof C=="object"){for(;M--&&typeof T[0]=="object";)Object.assign(q,T.shift());C=T.length?i(T.shift(),T):void 0}else typeof C=="string"&&(C=i(T.shift(),T));return C!==void 0&&(q.msg=C),q}function c(m,E,_,I){for(const T in m)if(I&&m[T]instanceof Error)m[T]=r.stdSerializers.err(m[T]);else if(typeof m[T]=="object"&&!Array.isArray(m[T]))for(const C in m[T])E&&E.indexOf(C)>-1&&C in _&&(m[T][C]=_[C](m[T][C]))}function h(m,E,_){return function(){const I=new Array(1+arguments.length);I[0]=E;for(var T=1;T<I.length;T++)I[T]=arguments[T-1];return m[_].apply(this,I)}}function l(m,E,_){const I=E.send,T=E.ts,C=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=T,m._logEvent.messages=_.filter(function($){return v.indexOf($)===-1}),m._logEvent.level.label=C,m._logEvent.level.value=q,I(C,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 f(){return{}}function y(m){return m}function g(){}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 N(){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 dr}var hi=Pf();const os=Ih(hi),$f={level:"info"},as="custom_context",gn=1e3*1024;let Sf=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}},Co=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new Sf(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}}}}},xc=class{constructor(e,t=gn){this.level=e??"error",this.levelValue=hi.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new Co(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===hi.levels.values.error?console.error(e):t===hi.levels.values.warn?console.warn(e):t===hi.levels.values.debug?console.debug(e):t===hi.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Gi({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 Co(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(Gi({extraMetadata:e})),new Blob(t,{type:"application/json"})}},Of=class{constructor(e,t=gn){this.baseChunkLogger=new xc(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)}},xf=class{constructor(e,t=gn){this.baseChunkLogger=new xc(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 Af=Object.defineProperty,Cf=Object.defineProperties,Tf=Object.getOwnPropertyDescriptors,To=Object.getOwnPropertySymbols,Nf=Object.prototype.hasOwnProperty,Rf=Object.prototype.propertyIsEnumerable,No=(i,e,t)=>e in i?Af(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qs=(i,e)=>{for(var t in e||(e={}))Nf.call(e,t)&&No(i,t,e[t]);if(To)for(var t of To(e))Rf.call(e,t)&&No(i,t,e[t]);return i},ks=(i,e)=>Cf(i,Tf(e));function Ws(i){return ks(qs({},i),{level:(i==null?void 0:i.level)||$f.level})}function jf(i,e=as){return i[e]||""}function qf(i,e,t=as){return i[t]=e,i}function Ne(i,e=as){let t="";return typeof i.bindings>"u"?t=jf(i,e):t=i.bindings().context||"",t}function kf(i,e,t=as){const s=Ne(i,t);return s.trim()?`${s}/${e}`:e}function Se(i,e,t=as){const s=kf(i,e,t),r=i.child({context:s});return qf(r,s,t)}function Df(i){var e,t;const s=new Of((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:os(ks(qs({},i.opts),{level:"trace",browser:ks(qs({},(t=i.opts)==null?void 0:t.browser),{write:r=>s.write(r)})})),chunkLoggerController:s}}function Lf(i){var e;const t=new xf((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:os(ks(qs({},i.opts),{level:"trace"}),t),chunkLoggerController:t}}function Mf(i){return typeof i.loggerOverride<"u"&&typeof i.loggerOverride!="string"?{logger:i.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Df(i):Lf(i)}var Uf=Object.defineProperty,zf=(i,e,t)=>e in i?Uf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ro=(i,e,t)=>zf(i,typeof e!="symbol"?e+"":e,t);let Bf=class extends _i{constructor(e){super(),this.opts=e,Ro(this,"protocol","wc"),Ro(this,"version",2)}};var Kf=Object.defineProperty,Vf=(i,e,t)=>e in i?Kf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Hf=(i,e,t)=>Vf(i,e+"",t);let Ff=class extends _i{constructor(e,t){super(),this.core=e,this.logger=t,Hf(this,"records",new Map)}},Gf=class{constructor(e,t){this.logger=e,this.core=t}};class Wf extends _i{constructor(e,t){super(),this.relayer=e,this.logger=t}}let Jf=class extends _i{constructor(e){super()}},Qf=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},Yf=class extends _i{constructor(e,t){super(),this.relayer=e,this.logger=t}},Zf=class extends _i{constructor(e,t){super(),this.core=e,this.logger=t}},Xf=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},eg=class{constructor(e,t){this.projectId=e,this.logger=t}},tg=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var ig=Object.defineProperty,sg=(i,e,t)=>e in i?ig(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,jo=(i,e,t)=>sg(i,typeof e!="symbol"?e+"":e,t);let rg=class{constructor(e){this.opts=e,jo(this,"protocol","wc"),jo(this,"version",2)}},ng=class{constructor(e){this.client=e}};var og={};const Ac="wc",Cc=2,Ur="core",at=`${Ac}@2:${Ur}:`,ag={logger:"error"},cg={database:":memory:"},hg="crypto",qo="client_ed25519_seed",lg=j.ONE_DAY,ug="keychain",pg="0.3",dg="messages",fg="0.3",ko=j.SIX_HOURS,gg="publisher",Tc="irn",mg="error",Nc="wss://relay.walletconnect.org",yg="relayer",fe={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},wg="_subscription",Ue={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},bg=.1,zr="2.21.1",ie={link_mode:"link_mode",relay:"relay"},Os={inbound:"inbound",outbound:"outbound"},vg="0.3",Eg="WALLETCONNECT_CLIENT_ID",Do="WALLETCONNECT_LINK_MODE_APPS",qe={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Ig="subscription",_g="0.3",Pg="pairing",$g="0.3",qi={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}}},kt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Fe={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Sg="history",Og="0.3",xg="expirer",Be={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Ag="0.3",Cg="verify-api",Tg="https://verify.walletconnect.com",Rc="https://verify.walletconnect.org",Hi=Rc,Ng=`${Hi}/v3`,Rg=[Tg,Rc],jg="echo",qg="https://echo.walletconnect.com",st={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"},ft={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"},Ge={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"},Tt={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"},Nt={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"},ki={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"},kg=.1,Dg="event-client",Lg=86400,Mg="https://pulse.walletconnect.org/batch";function Ug(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(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,b=0,w=f.length;b!==w&&f[b]===0;)b++,y++;for(var P=(w-b)*l+1>>>0,A=new Uint8Array(P);b!==w;){for(var N=f[b],m=0,E=P-1;(N!==0||m<g)&&E!==-1;E--,m++)N+=256*A[E]>>>0,A[E]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");g=m,b++}for(var _=P-g;_!==P&&A[_]===0;)_++;for(var I=c.repeat(y);_<P;++_)I+=i.charAt(A[_]);return I}function p(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,b=0;f[y]===c;)g++,y++;for(var w=(f.length-y)*h+1>>>0,P=new Uint8Array(w);f[y];){var A=t[f.charCodeAt(y)];if(A===255)return;for(var N=0,m=w-1;(A!==0||N<b)&&m!==-1;m--,N++)A+=a*P[m]>>>0,P[m]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");b=N,y++}if(f[y]!==" "){for(var E=w-b;E!==w&&P[E]===0;)E++;for(var _=new Uint8Array(g+(w-E)),I=g;E!==w;)_[I++]=P[E++];return _}}}function d(f){var y=p(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:d}}var zg=Ug,Bg=zg;const jc=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")},Kg=i=>new TextEncoder().encode(i),Vg=i=>new TextDecoder().decode(i);class Hg{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 Fg{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 qc(this,e)}}class Gg{constructor(e){this.decoders=e}or(e){return qc(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 qc=(i,e)=>new Gg({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Wg{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Hg(e,t,s),this.decoder=new Fg(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Js=({name:i,prefix:e,encode:t,decode:s})=>new Wg(i,e,t,s),cs=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=Bg(t,e);return Js({prefix:i,name:e,encode:s,decode:n=>jc(r(n))})},Jg=(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},Qg=(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},Ee=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>Js({prefix:e,name:i,encode(r){return Qg(r,s,t)},decode(r){return Jg(r,s,t,i)}}),Yg=Js({prefix:"\0",name:"identity",encode:i=>Vg(i),decode:i=>Kg(i)});var Zg=Object.freeze({__proto__:null,identity:Yg});const Xg=Ee({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var em=Object.freeze({__proto__:null,base2:Xg});const tm=Ee({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var im=Object.freeze({__proto__:null,base8:tm});const sm=cs({prefix:"9",name:"base10",alphabet:"0123456789"});var rm=Object.freeze({__proto__:null,base10:sm});const nm=Ee({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),om=Ee({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var am=Object.freeze({__proto__:null,base16:nm,base16upper:om});const cm=Ee({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hm=Ee({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),lm=Ee({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),um=Ee({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),pm=Ee({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dm=Ee({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fm=Ee({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gm=Ee({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),mm=Ee({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ym=Object.freeze({__proto__:null,base32:cm,base32upper:hm,base32pad:lm,base32padupper:um,base32hex:pm,base32hexupper:dm,base32hexpad:fm,base32hexpadupper:gm,base32z:mm});const wm=cs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bm=cs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vm=Object.freeze({__proto__:null,base36:wm,base36upper:bm});const Em=cs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Im=cs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var _m=Object.freeze({__proto__:null,base58btc:Em,base58flickr:Im});const Pm=Ee({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$m=Ee({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Sm=Ee({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Om=Ee({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var xm=Object.freeze({__proto__:null,base64:Pm,base64pad:$m,base64url:Sm,base64urlpad:Om});const kc=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Am=kc.reduce((i,e,t)=>(i[t]=e,i),[]),Cm=kc.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Tm(i){return i.reduce((e,t)=>(e+=Am[t],e),"")}function Nm(i){const e=[];for(const t of i){const s=Cm[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Rm=Js({prefix:"🚀",name:"base256emoji",encode:Tm,decode:Nm});var jm=Object.freeze({__proto__:null,base256emoji:Rm}),qm=Dc,Lo=128,km=-128,Dm=Math.pow(2,31);function Dc(i,e,t){e=e||[],t=t||0;for(var s=t;i>=Dm;)e[t++]=i&255|Lo,i/=128;for(;i&km;)e[t++]=i&255|Lo,i>>>=7;return e[t]=i|0,Dc.bytes=t-s+1,e}var Lm=Br,Mm=128,Mo=127;function Br(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw Br.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&Mo)<<r:(o&Mo)*Math.pow(2,r),r+=7}while(o>=Mm);return Br.bytes=n-s,t}var Um=Math.pow(2,7),zm=Math.pow(2,14),Bm=Math.pow(2,21),Km=Math.pow(2,28),Vm=Math.pow(2,35),Hm=Math.pow(2,42),Fm=Math.pow(2,49),Gm=Math.pow(2,56),Wm=Math.pow(2,63),Jm=function(i){return i<Um?1:i<zm?2:i<Bm?3:i<Km?4:i<Vm?5:i<Hm?6:i<Fm?7:i<Gm?8:i<Wm?9:10},Qm={encode:qm,decode:Lm,encodingLength:Jm},Lc=Qm;const Uo=(i,e,t=0)=>(Lc.encode(i,e,t),e),zo=i=>Lc.encodingLength(i),Kr=(i,e)=>{const t=e.byteLength,s=zo(i),r=s+zo(t),n=new Uint8Array(r+t);return Uo(i,n,0),Uo(t,n,s),n.set(e,r),new Ym(i,t,e,n)};class Ym{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Mc=({name:i,code:e,encode:t})=>new Zm(i,e,t);class Zm{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?Kr(this.code,t):t.then(s=>Kr(this.code,s))}else throw Error("Unknown type, must be binary type")}}const Uc=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Xm=Mc({name:"sha2-256",code:18,encode:Uc("SHA-256")}),ey=Mc({name:"sha2-512",code:19,encode:Uc("SHA-512")});var ty=Object.freeze({__proto__:null,sha256:Xm,sha512:ey});const zc=0,iy="identity",Bc=jc,sy=i=>Kr(zc,Bc(i)),ry={code:zc,name:iy,encode:Bc,digest:sy};var ny=Object.freeze({__proto__:null,identity:ry});new TextEncoder,new TextDecoder;const Bo={...Zg,...em,...im,...rm,...am,...ym,...vm,..._m,...xm,...jm};({...ty,...ny});function oy(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Kc(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Ko=Kc("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),fr=Kc("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=oy(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),ay={utf8:Ko,"utf-8":Ko,hex:Bo.base16,latin1:fr,ascii:fr,binary:fr,...Bo};function cy(i,e="utf8"){const t=ay[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 hy=Object.defineProperty,ly=(i,e,t)=>e in i?hy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,tt=(i,e,t)=>ly(i,typeof e!="symbol"?e+"":e,t);class uy{constructor(e,t){this.core=e,this.logger=t,tt(this,"keychain",new Map),tt(this,"name",ug),tt(this,"version",pg),tt(this,"initialized",!1),tt(this,"storagePrefix",at),tt(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),tt(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),tt(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),tt(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=R("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),tt(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=Se(t,this.name)}get context(){return Ne(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Or(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?xr(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var py=Object.defineProperty,dy=(i,e,t)=>e in i?py(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,we=(i,e,t)=>dy(i,typeof e!="symbol"?e+"":e,t);class fy{constructor(e,t,s){this.core=e,this.logger=t,we(this,"name",hg),we(this,"keychain"),we(this,"randomSessionIdentifier",Lr()),we(this,"initialized",!1),we(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),we(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),we(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=vn(r);return gh(n.publicKey)}),we(this,"generateKeyPair",()=>{this.isInitialized();const r=Qp();return this.setPrivateKey(r.publicKey,r.privateKey)}),we(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=vn(n),a=this.randomSessionIdentifier;return await mh(a,r,lg,o)}),we(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Yp(a,n);return this.setSymKey(c,o)}),we(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||Ps(r);return await this.keychain.set(o,r),o}),we(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),we(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),we(this,"encode",async(r,n,o)=>{this.isInitialized();const a=$c(o),c=Gi(n);if(fo(a))return ed(c,o==null?void 0:o.encoding);if(po(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 Zp({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),we(this,"decode",async(r,n,o)=>{this.isInitialized();const a=id(n,o);if(fo(a)){const c=td(n,o==null?void 0:o.encoding);return As(c)}if(po(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Xp({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return As(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),we(this,"getPayloadType",(r,n=Qe)=>{const o=Xi({encoded:r,encoding:n});return Vt(o.type)}),we(this,"getPayloadSenderPublicKey",(r,n=Qe)=>{const o=Xi({encoded:r,encoding:n});return o.senderPublicKey?Te(o.senderPublicKey,$e):void 0}),this.core=e,this.logger=Se(t,this.name),this.keychain=s||new uy(this.core,this.logger)}get context(){return Ne(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(qo)}catch{e=Lr(),await this.keychain.set(qo,e)}return cy(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var gy=Object.defineProperty,my=Object.defineProperties,yy=Object.getOwnPropertyDescriptors,Vo=Object.getOwnPropertySymbols,wy=Object.prototype.hasOwnProperty,by=Object.prototype.propertyIsEnumerable,Vr=(i,e,t)=>e in i?gy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vy=(i,e)=>{for(var t in e||(e={}))wy.call(e,t)&&Vr(i,t,e[t]);if(Vo)for(var t of Vo(e))by.call(e,t)&&Vr(i,t,e[t]);return i},Ey=(i,e)=>my(i,yy(e)),Re=(i,e,t)=>Vr(i,typeof e!="symbol"?e+"":e,t);class Iy extends Gf{constructor(e,t){super(e,t),this.logger=e,this.core=t,Re(this,"messages",new Map),Re(this,"messagesWithoutClientAck",new Map),Re(this,"name",dg),Re(this,"version",fg),Re(this,"initialized",!1),Re(this,"storagePrefix",at),Re(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}}}),Re(this,"set",async(s,r,n)=>{this.isInitialized();const o=nt(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===Os.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,Ey(vy({},c),{[o]:r}))}return await this.persist(),o}),Re(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Re(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}),Re(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=nt(r);return typeof n[o]<"u"}),Re(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=nt(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Re(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=Se(e,this.name),this.core=t}get context(){return Ne(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,Or(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Or(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?xr(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?xr(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _y=Object.defineProperty,Py=Object.defineProperties,$y=Object.getOwnPropertyDescriptors,Ho=Object.getOwnPropertySymbols,Sy=Object.prototype.hasOwnProperty,Oy=Object.prototype.propertyIsEnumerable,Hr=(i,e,t)=>e in i?_y(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ys=(i,e)=>{for(var t in e||(e={}))Sy.call(e,t)&&Hr(i,t,e[t]);if(Ho)for(var t of Ho(e))Oy.call(e,t)&&Hr(i,t,e[t]);return i},gr=(i,e)=>Py(i,$y(e)),We=(i,e,t)=>Hr(i,typeof e!="symbol"?e+"":e,t);class xy extends Wf{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,We(this,"events",new xt.EventEmitter),We(this,"name",gg),We(this,"queue",new Map),We(this,"publishTimeout",j.toMiliseconds(j.ONE_MINUTE)),We(this,"initialPublishTimeout",j.toMiliseconds(j.ONE_SECOND*15)),We(this,"needsTransportRestart",!1),We(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==null?void 0:n.ttl)||ko,c=Rs(n),h=(n==null?void 0:n.prompt)||!1,l=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||ui().toString(),p={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},d=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const f=new Promise(async y=>{const g=({id:w})=>{p.opts.id===w&&(this.removeRequestFromQueue(w),this.relayer.events.removeListener(fe.publish,g),y(p))};this.relayer.events.on(fe.publish,g);const b=$t(new Promise((w,P)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(w).catch(A=>{this.logger.warn(A,A==null?void 0:A.message),P(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await b,this.events.removeListener(fe.publish,g)}catch(w){this.queue.set(u,gr(ys({},p),{attempt:1})),this.logger.warn(w,w==null?void 0:w.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await $t(f,this.publishTimeout,d)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(u)}}),We(this,"on",(s,r)=>{this.events.on(s,r)}),We(this,"once",(s,r)=>{this.events.once(s,r)}),We(this,"off",(s,r)=>{this.events.off(s,r)}),We(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=Se(t,this.name),this.registerEventListeners()}get context(){return Ne(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=ko,prompt:h,tag:l,id:u,attestation:p,tvf:d}=e,f={method:Ui(Rs().protocol).publish,params:ys({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},d),id:u};ve((t=f.params)==null?void 0:t.prompt)&&((s=f.params)==null||delete s.prompt),ve((r=f.params)==null?void 0:r.tag)&&((n=f.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const y=await this.relayer.request(f);return this.relayer.events.emit(fe.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(ys({},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(ys({},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(Pi.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(fe.connection_stalled);return}this.checkQueue()}),this.relayer.on(fe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Ay=Object.defineProperty,Cy=(i,e,t)=>e in i?Ay(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qt=(i,e,t)=>Cy(i,typeof e!="symbol"?e+"":e,t);class Ty{constructor(){Qt(this,"map",new Map),Qt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),Qt(this,"get",e=>this.map.get(e)||[]),Qt(this,"exists",(e,t)=>this.get(e).includes(t)),Qt(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)}),Qt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Ny=Object.defineProperty,Ry=Object.defineProperties,jy=Object.getOwnPropertyDescriptors,Fo=Object.getOwnPropertySymbols,qy=Object.prototype.hasOwnProperty,ky=Object.prototype.propertyIsEnumerable,Fr=(i,e,t)=>e in i?Ny(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Di=(i,e)=>{for(var t in e||(e={}))qy.call(e,t)&&Fr(i,t,e[t]);if(Fo)for(var t of Fo(e))ky.call(e,t)&&Fr(i,t,e[t]);return i},mr=(i,e)=>Ry(i,jy(e)),X=(i,e,t)=>Fr(i,typeof e!="symbol"?e+"":e,t);class Dy extends Yf{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,X(this,"subscriptions",new Map),X(this,"topicMap",new Ty),X(this,"events",new xt.EventEmitter),X(this,"name",Ig),X(this,"version",_g),X(this,"pending",new Map),X(this,"cached",[]),X(this,"initialized",!1),X(this,"storagePrefix",at),X(this,"subscribeTimeout",j.toMiliseconds(j.ONE_MINUTE)),X(this,"initialSubscribeTimeout",j.toMiliseconds(j.ONE_SECOND*15)),X(this,"clientId"),X(this,"batchSubscribeTopicsLimit",500),X(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),X(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=Rs(r),o={topic:s,relay:n,transportType:r==null?void 0: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}}),X(this,"unsubscribe",async(s,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(s,r.id,r):await this.unsubscribeByTopic(s,r)}),X(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),X(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),X(this,"on",(s,r)=>{this.events.on(s,r)}),X(this,"once",(s,r)=>{this.events.once(s,r)}),X(this,"off",(s,r)=>{this.events.off(s,r)}),X(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),X(this,"start",async()=>{await this.onConnect()}),X(this,"stop",async()=>{await this.onDisconnect()}),X(this,"restart",async()=>{await this.restore(),await this.onRestart()}),X(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)}),X(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Pi.pulse,async()=>{await this.checkPending()}),this.events.on(qe.created,async s=>{const r=qe.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(qe.deleted,async s=>{const r=qe.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=Se(t,this.name),this.clientId=""}get context(){return Ne(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=Rs(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Y("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==null?void 0:s.transportType)===ie.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Ui(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==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((s==null?void 0:s.transportType)===ie.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(qe.created,u),l(p.id))};this.events.on(qe.created,u);try{const p=await $t(new Promise((d,f)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y==null?void 0:y.message),f(y)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(qe.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(fe.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Ui(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(fe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Ui(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(fe.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Ui(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,mr(Di({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Di({},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,Di({},t)),this.topicMap.set(t.topic,e),this.events.emit(qe.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}=R("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(qe.deleted,mr(Di({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(qe.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(qe.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=R("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=>mr(Di({},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 Dl(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}=R("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 nt(e+await this.getClientId())}}var Ly=Object.defineProperty,Go=Object.getOwnPropertySymbols,My=Object.prototype.hasOwnProperty,Uy=Object.prototype.propertyIsEnumerable,Gr=(i,e,t)=>e in i?Ly(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wo=(i,e)=>{for(var t in e||(e={}))My.call(e,t)&&Gr(i,t,e[t]);if(Go)for(var t of Go(e))Uy.call(e,t)&&Gr(i,t,e[t]);return i},G=(i,e,t)=>Gr(i,typeof e!="symbol"?e+"":e,t);class zy extends Jf{constructor(e){super(e),G(this,"protocol","wc"),G(this,"version",2),G(this,"core"),G(this,"logger"),G(this,"events",new xt.EventEmitter),G(this,"provider"),G(this,"messages"),G(this,"subscriber"),G(this,"publisher"),G(this,"name",yg),G(this,"transportExplicitlyClosed",!1),G(this,"initialized",!1),G(this,"connectionAttemptInProgress",!1),G(this,"relayUrl"),G(this,"projectId"),G(this,"packageName"),G(this,"bundleId"),G(this,"hasExperiencedNetworkDisruption",!1),G(this,"pingTimeout"),G(this,"heartBeatTimeout",j.toMiliseconds(j.THIRTY_SECONDS+j.FIVE_SECONDS)),G(this,"reconnectTimeout"),G(this,"connectPromise"),G(this,"reconnectInProgress",!1),G(this,"requestsInFlight",[]),G(this,"connectTimeout",j.toMiliseconds(j.ONE_SECOND*15)),G(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||ui().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}}),G(this,"resetPingTimeout",()=>{Ts()&&(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==null?void 0:o.message)}},this.heartBeatTimeout))}),G(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),G(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(fe.connect)}),G(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),G(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(fe.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),G(this,"registerProviderListeners",()=>{this.provider.on(Ue.payload,this.onPayloadHandler),this.provider.on(Ue.connect,this.onConnectHandler),this.provider.on(Ue.disconnect,this.onDisconnectHandler),this.provider.on(Ue.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Se(e.logger,this.name):os(Ws({level:e.logger||mg})),this.messages=new Iy(this.logger,e.core),this.subscriber=new Dy(this,this.logger),this.publisher=new xy(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Nc,this.projectId=e.projectId,El()?this.packageName=kn():Il()&&(this.bundleId=kn()),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==null?void 0:e.message)}}get context(){return Ne(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:ie.relay},Os.outbound)}async subscribe(e,t){var s,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((s=t==null?void 0:t.internal)==null?void 0:s.throwOnFailedPublish)>"u"?!0:(r=t==null?void 0: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(qe.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(qe.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,Wo({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 $o())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const 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==null?void 0: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=he(j.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(fe.message,e),await this.recordMessageEvent(e,Os.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(Ue.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(Ue.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(Ue.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Ue.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(Ts())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==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ve(new fh(Ol({sdkVersion:zr,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}),rn(e)){if(!e.method.endsWith(wg))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:ie.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Wo({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else nn(e)&&this.events.emit(fe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Os.inbound),this.events.emit(fe.message,e))}async acknowledgePayload(e){const t=Us(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Ue.payload,this.onPayloadHandler),this.provider.off(Ue.connect,this.onConnectHandler),this.provider.off(Ue.disconnect,this.onDisconnectHandler),this.provider.off(Ue.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await $o();Jd(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s==null?void 0:s.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Pi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Zd())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t==null?void 0:t.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(fe.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},j.toMiliseconds(bg)))))}isInitialized(){if(!this.initialized){const{message:e}=R("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 By(){}function Jo(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 Qo(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Yo(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Ky="[object RegExp]",Vy="[object String]",Hy="[object Number]",Fy="[object Boolean]",Zo="[object Arguments]",Gy="[object Symbol]",Wy="[object Date]",Jy="[object Map]",Qy="[object Set]",Yy="[object Array]",Zy="[object Function]",Xy="[object ArrayBuffer]",yr="[object Object]",ew="[object Error]",tw="[object DataView]",iw="[object Uint8Array]",sw="[object Uint8ClampedArray]",rw="[object Uint16Array]",nw="[object Uint32Array]",ow="[object BigUint64Array]",aw="[object Int8Array]",cw="[object Int16Array]",hw="[object Int32Array]",lw="[object BigInt64Array]",uw="[object Float32Array]",pw="[object Float64Array]";function dw(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function fw(i,e,t){return zi(i,e,void 0,void 0,void 0,void 0,t)}function zi(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 Fi(i,e,n,o)}return Fi(i,e,n,o)}function Fi(i,e,t,s){if(Object.is(i,e))return!0;let r=Yo(i),n=Yo(e);if(r===Zo&&(r=yr),n===Zo&&(n=yr),r!==n)return!1;switch(r){case Vy:return i.toString()===e.toString();case Hy:{const c=i.valueOf(),h=e.valueOf();return dw(c,h)}case Fy:case Wy:case Gy:return Object.is(i.valueOf(),e.valueOf());case Ky:return i.source===e.source&&i.flags===e.flags;case Zy: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 Jy:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!zi(h,e.get(c),c,i,e,t,s))return!1;return!0}case Qy:{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=>zi(u,d,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case Yy:case iw:case sw:case rw:case nw:case ow:case aw:case cw:case hw:case lw:case uw:case pw:{if(typeof me<"u"&&me.isBuffer(i)!==me.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!zi(i[c],e[c],c,i,e,t,s))return!1;return!0}case Xy:return i.byteLength!==e.byteLength?!1:Fi(new Uint8Array(i),new Uint8Array(e),t,s);case tw:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:Fi(new Uint8Array(i),new Uint8Array(e),t,s);case ew:return i.name===e.name&&i.message===e.message;case yr:{if(!(Fi(i.constructor,e.constructor,t,s)||Jo(i)&&Jo(e)))return!1;const c=[...Object.keys(i),...Qo(i)],h=[...Object.keys(e),...Qo(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(!zi(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 fw(i,e,By)}var mw=Object.defineProperty,Xo=Object.getOwnPropertySymbols,yw=Object.prototype.hasOwnProperty,ww=Object.prototype.propertyIsEnumerable,Wr=(i,e,t)=>e in i?mw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ea=(i,e)=>{for(var t in e||(e={}))yw.call(e,t)&&Wr(i,t,e[t]);if(Xo)for(var t of Xo(e))ww.call(e,t)&&Wr(i,t,e[t]);return i},Oe=(i,e,t)=>Wr(i,typeof e!="symbol"?e+"":e,t);class Ht extends Qf{constructor(e,t,s,r=at,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,Oe(this,"map",new Map),Oe(this,"version",vg),Oe(this,"cached",[]),Oe(this,"initialized",!1),Oe(this,"getKey"),Oe(this,"storagePrefix",at),Oe(this,"recentlyDeleted",[]),Oe(this,"recentlyDeletedLimit",200),Oe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ve(o)?this.map.set(this.getKey(o),o):Sd(o)?this.map.set(o.id,o):Od(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Oe(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())}),Oe(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Oe(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>gw(a[c],o[c]))):this.values)),Oe(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=ea(ea({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Oe(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=Se(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return Ne(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}=R("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=R("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}=R("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}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var bw=Object.defineProperty,vw=(i,e,t)=>e in i?bw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,K=(i,e,t)=>vw(i,typeof e!="symbol"?e+"":e,t);class Ew{constructor(e,t){this.core=e,this.logger=t,K(this,"name",Pg),K(this,"version",$g),K(this,"events",new sn),K(this,"pairings"),K(this,"initialized",!1),K(this,"storagePrefix",at),K(this,"ignoredPayloadTypes",[wt]),K(this,"registeredMethods",[]),K(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),K(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),K(this,"create",async s=>{this.isInitialized();const r=Lr(),n=await this.core.crypto.setSymKey(r),o=he(j.FIVE_MINUTES),a={protocol:Tc},c={topic:n,expiry:o,relay:a,active:!1,methods:s==null?void 0:s.methods},h=mo({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:s==null?void 0:s.methods});return this.events.emit(kt.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:s==null?void 0:s.transportType}),{topic:n,uri:h}}),K(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s==null?void 0:s.uri,trace:[st.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(st.pairing_uri_validation_success),r.addTrace(st.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(st.existing_pairing),l.active)throw r.setError(ft.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(st.pairing_not_expired)}const u=c||he(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(st.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(kt.create,p),r.addTrace(st.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(st.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(ft.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(d){throw r.setError(ft.subscribe_pairing_topic_failure),d}return r.addTrace(st.subscribe_pairing_topic_success),p}),K(this,"activate",async({topic:s})=>{this.isInitialized();const r=he(j.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),K(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}=Rt();this.events.once(Q("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),K(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),K(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),K(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),K(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",Y("USER_DISCONNECTED")),await this.deletePairing(r))}),K(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return mo({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),K(this,"sendRequest",async(s,r,n)=>{const o=Lt(r,n),a=await this.core.crypto.encode(s,o),c=qi[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),K(this,"sendResult",async(s,r,n)=>{const o=Us(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=qi[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),K(this,"sendError",async(s,r,n)=>{const o=Sa(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=qi[c]?qi[c].res:qi.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),K(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,Y("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),K(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>_t(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),K(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)}}),K(this,"onRelayEventResponse",async s=>{const{topic:r,payload:n}=s,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),K(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(kt.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),K(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{dt(r)?this.events.emit(Q("pairing_ping",n),{}):rt(r)&&this.events.emit(Q("pairing_ping",n),{error:r.error})},500)}),K(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(kt.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),K(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Y("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)}}),K(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(Y("WC_METHOD_UNSUPPORTED",s))}),K(this,"isValidPair",(s,r)=>{var n;if(!Ae(s)){const{message:a}=R("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(ft.malformed_pairing_uri),new Error(a)}if(!$d(s.uri)){const{message:a}=R("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(ft.malformed_pairing_uri),new Error(a)}const o=go(s==null?void 0:s.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(ft.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(ft.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&j.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(ft.pairing_expired);const{message:a}=R("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),K(this,"isValidPing",async s=>{if(!Ae(s)){const{message:n}=R("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),K(this,"isValidDisconnect",async s=>{if(!Ae(s)){const{message:n}=R("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),K(this,"isValidPairingTopic",async s=>{if(!oe(s,!1)){const{message:r}=R("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(_t(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=R("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=Se(t,this.name),this.pairings=new Ht(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ne(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(fe.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==ie.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);rn(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):nn(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(Be.expired,async e=>{const{topic:t}=Fa(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(kt.expire,{topic:t}))})}}var Iw=Object.defineProperty,_w=(i,e,t)=>e in i?Iw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,be=(i,e,t)=>_w(i,typeof e!="symbol"?e+"":e,t);class Pw extends Ff{constructor(e,t){super(e,t),this.core=e,this.logger=t,be(this,"records",new Map),be(this,"events",new xt.EventEmitter),be(this,"name",Sg),be(this,"version",Og),be(this,"cached",[]),be(this,"initialized",!1),be(this,"storagePrefix",at),be(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)}),be(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:he(j.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Fe.created,o)}),be(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=rt(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(Fe.updated,r))}),be(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))),be(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(Fe.deleted,n)}}),this.persist()}),be(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),be(this,"on",(s,r)=>{this.events.on(s,r)}),be(this,"once",(s,r)=>{this.events.once(s,r)}),be(this,"off",(s,r)=>{this.events.off(s,r)}),be(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=Se(t,this.name)}get context(){return Ne(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:Lt(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}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Fe.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=R("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(Fe.created,e=>{const t=Fe.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fe.updated,e=>{const t=Fe.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fe.deleted,e=>{const t=Fe.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(Pi.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(Fe.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $w=Object.defineProperty,Sw=(i,e,t)=>e in i?$w(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,_e=(i,e,t)=>Sw(i,typeof e!="symbol"?e+"":e,t);class Ow extends Zf{constructor(e,t){super(e,t),this.core=e,this.logger=t,_e(this,"expirations",new Map),_e(this,"events",new xt.EventEmitter),_e(this,"name",xg),_e(this,"version",Ag),_e(this,"cached",[]),_e(this,"initialized",!1),_e(this,"storagePrefix",at),_e(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)}),_e(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),_e(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(Be.created,{target:n,expiration:o})}),_e(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),_e(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(Be.deleted,{target:r,expiration:n})}}),_e(this,"on",(s,r)=>{this.events.on(s,r)}),_e(this,"once",(s,r)=>{this.events.once(s,r)}),_e(this,"off",(s,r)=>{this.events.off(s,r)}),_e(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=Se(t,this.name)}get context(){return Ne(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 xl(e);if(typeof e=="number")return Al(e);const{message:t}=R("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(Be.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=R("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}=R("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(Be.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Pi.pulse,()=>this.checkExpirations()),this.events.on(Be.created,e=>{const t=Be.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Be.expired,e=>{const t=Be.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Be.deleted,e=>{const t=Be.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xw=Object.defineProperty,Aw=(i,e,t)=>e in i?xw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ne=(i,e,t)=>Aw(i,typeof e!="symbol"?e+"":e,t);class Cw extends Xf{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,ne(this,"name",Cg),ne(this,"abortController"),ne(this,"isDevEnv"),ne(this,"verifyUrlV3",Ng),ne(this,"storagePrefix",at),ne(this,"version",Cc),ne(this,"publicKey"),ne(this,"fetchPromise"),ne(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()))}),ne(this,"register",async r=>{if(!Oi()||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=bt.getDocument(),l=this.startAbortTimer(j.ONE_SECOND*5),u=await new Promise((p,d)=>{const f=()=>{window.removeEventListener("message",g),h.body.removeChild(y),d("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const y=h.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",f,{signal:this.abortController.signal});const g=b=>{if(b.data&&typeof b.data=="string")try{const w=JSON.parse(b.data);if(w.type==="verify_attestation"){if(Pr(w.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(y),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",g),p(w.attestation===null?"":w.attestation)}}catch(w){this.logger.warn(w)}};h.body.appendChild(y),window.addEventListener("message",g,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),ne(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(Pr(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==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),ne(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}),ne(this,"getVerifyUrl",r=>{let n=r||Hi;return Rg.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Hi}`),n=Hi),n}),ne(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)}}),ne(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),ne(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ne(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")}}),ne(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ne(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}),ne(this,"validateAttestation",(r,n)=>{const o=rd(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=Se(t,this.name),this.abortController=new AbortController,this.isDevEnv=an(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ne(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),j.toMiliseconds(e))}}var Tw=Object.defineProperty,Nw=(i,e,t)=>e in i?Tw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ta=(i,e,t)=>Nw(i,typeof e!="symbol"?e+"":e,t);class Rw extends eg{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,ta(this,"context",jg),ta(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${qg}/${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=Se(t,this.context)}}var jw=Object.defineProperty,ia=Object.getOwnPropertySymbols,qw=Object.prototype.hasOwnProperty,kw=Object.prototype.propertyIsEnumerable,Jr=(i,e,t)=>e in i?jw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Li=(i,e)=>{for(var t in e||(e={}))qw.call(e,t)&&Jr(i,t,e[t]);if(ia)for(var t of ia(e))kw.call(e,t)&&Jr(i,t,e[t]);return i},le=(i,e,t)=>Jr(i,typeof e!="symbol"?e+"":e,t);class Dw extends tg{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,le(this,"context",Dg),le(this,"storagePrefix",at),le(this,"storageVersion",kg),le(this,"events",new Map),le(this,"shouldPersist",!1),le(this,"init",async()=>{if(!an())try{const r={eventId:Ln(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Va(this.core.relayer.protocol,this.core.relayer.version,zr)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),le(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=Ln(),l=this.core.projectId||"",u=Date.now(),p=Li({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}),le(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 Li(Li({},a),this.setMethods(a.eventId))}),le(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),le(this,"setEventListeners",()=>{this.core.heartbeat.on(Pi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{j.fromMiliseconds(Date.now())-j.fromMiliseconds(r.timestamp)>Lg&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),le(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),le(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)}),le(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)}),le(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),le(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,Li(Li({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),le(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)}}),le(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Mg}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${zr}${n}`,{method:"POST",body:JSON.stringify(r)})}),le(this,"getAppDomain",()=>Ka().url),this.logger=Se(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 Lw=Object.defineProperty,sa=Object.getOwnPropertySymbols,Mw=Object.prototype.hasOwnProperty,Uw=Object.prototype.propertyIsEnumerable,Qr=(i,e,t)=>e in i?Lw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ra=(i,e)=>{for(var t in e||(e={}))Mw.call(e,t)&&Qr(i,t,e[t]);if(sa)for(var t of sa(e))Uw.call(e,t)&&Qr(i,t,e[t]);return i},te=(i,e,t)=>Qr(i,typeof e!="symbol"?e+"":e,t);let zw=class Vc extends Bf{constructor(e){var t;super(e),te(this,"protocol",Ac),te(this,"version",Cc),te(this,"name",Ur),te(this,"relayUrl"),te(this,"projectId"),te(this,"customStoragePrefix"),te(this,"events",new xt.EventEmitter),te(this,"logger"),te(this,"heartbeat"),te(this,"relayer"),te(this,"crypto"),te(this,"storage"),te(this,"history"),te(this,"expirer"),te(this,"pairing"),te(this,"verify"),te(this,"echoClient"),te(this,"linkModeSupportedApps"),te(this,"eventClient"),te(this,"initialized",!1),te(this,"logChunkController"),te(this,"on",(a,c)=>this.events.on(a,c)),te(this,"once",(a,c)=>this.events.once(a,c)),te(this,"off",(a,c)=>this.events.off(a,c)),te(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),te(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ie.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Nc,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Ws({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:ag.logger,name:Ur}),{logger:n,chunkLoggerController:o}=Mf({opts:r,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0: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=Se(n,this.name),this.heartbeat=new dh,this.crypto=new fy(this,this.logger,e==null?void 0:e.keychain),this.history=new Pw(this,this.logger),this.expirer=new Ow(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new _f(ra(ra({},cg),e==null?void 0:e.storageOptions)),this.relayer=new zy({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ew(this,this.logger),this.verify=new Cw(this,this.logger,this.storage),this.echoClient=new Rw(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Dw(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Vc(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(Eg,s),t}get context(){return Ne(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(Do,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(Do)||[],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 Bi<"u"&&og.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const Bw=zw,Hc="wc",Fc=2,Gc="client",mn=`${Hc}@${Fc}:${Gc}:`,wr={name:Gc,logger:"error"},na="WALLETCONNECT_DEEPLINK_CHOICE",Kw="proposal",oa="Proposal expired",Vw="session",Yt=j.SEVEN_DAYS,Hw="engine",ue={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}}},br={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},it={idle:"IDLE",active:"ACTIVE"},aa={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Fw="request",Gw=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Ww="wc",Jw="auth",Qw="authKeys",Yw="pairingTopics",Zw="requests",Qs=`${Ww}@${1.5}:${Jw}:`,xs=`${Qs}:PUB_KEY`;var Xw=Object.defineProperty,eb=Object.defineProperties,tb=Object.getOwnPropertyDescriptors,ca=Object.getOwnPropertySymbols,ib=Object.prototype.hasOwnProperty,sb=Object.prototype.propertyIsEnumerable,Yr=(i,e,t)=>e in i?Xw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ee=(i,e)=>{for(var t in e||(e={}))ib.call(e,t)&&Yr(i,t,e[t]);if(ca)for(var t of ca(e))sb.call(e,t)&&Yr(i,t,e[t]);return i},Pe=(i,e)=>eb(i,tb(e)),S=(i,e,t)=>Yr(i,typeof e!="symbol"?e+"":e,t);class rb extends ng{constructor(e){super(e),S(this,"name",Hw),S(this,"events",new sn),S(this,"initialized",!1),S(this,"requestQueue",{state:it.idle,queue:[]}),S(this,"sessionRequestQueue",{state:it.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(ue)}),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=Pe(ee({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=vd(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}=R("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(m)}const d=await this.client.core.crypto.generateKeyPair(),f=ue.wc_sessionPropose.req.ttl||j.FIVE_MINUTES,y=he(f),g=Pe(ee(ee({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:vt()}),b=Q("session_connect",g.id),{reject:w,resolve:P,done:A}=Rt(f,oa),N=({id:m})=>{m===g.id&&(this.client.events.off("proposal_expire",N),this.pendingSessions.delete(g.id),this.events.emit(b,{error:{message:oa,code:0}}))};return this.client.events.on("proposal_expire",N),this.events.once(b,({error:m,session:E})=>{this.client.events.off("proposal_expire",N),m?w(m):E&&P(E)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:g,throwOnFailedPublish:!0,clientRpcId:g.id}),await this.setProposal(g.id,g),{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==null?void 0:t.id)==null?void 0:s.toString(),trace:[Ge.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(I){throw o.setError(Tt.no_internet_connection),I}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(I){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(Tt.proposal_not_found),I}try{await this.isValidApprove(t)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Tt.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:f,proposer:y,requiredNamespaces:g,optionalNamespaces:b}=d;let w=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});w||(w=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Ge.session_approve_started,properties:{topic:f,trace:[Ge.session_approve_started,Ge.session_namespaces_validation_success]}}));const P=await this.client.core.crypto.generateKeyPair(),A=y.publicKey,N=await this.client.core.crypto.generateSharedKey(P,A),m=ee(ee(ee({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:P,metadata:this.client.metadata},expiry:he(Yt)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),E=ie.relay;w.addTrace(Ge.subscribing_session_topic);try{await this.client.core.relayer.subscribe(N,{transportType:E})}catch(I){throw w.setError(Tt.subscribe_session_topic_failure),I}w.addTrace(Ge.subscribe_session_topic_success);const _=Pe(ee({},m),{topic:N,requiredNamespaces:g,optionalNamespaces:b,pairingTopic:f,acknowledged:!1,self:m.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:P,transportType:ie.relay});await this.client.session.set(N,_),w.addTrace(Ge.store_session);try{w.addTrace(Ge.publishing_session_settle),await this.sendRequest({topic:N,method:"wc_sessionSettle",params:m,throwOnFailedPublish:!0}).catch(I=>{throw w==null||w.setError(Tt.session_settle_publish_failure),I}),w.addTrace(Ge.session_settle_publish_success),w.addTrace(Ge.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:P},throwOnFailedPublish:!0}).catch(I=>{throw w==null||w.setError(Tt.session_approve_publish_failure),I}),w.addTrace(Ge.session_approve_publish_success)}catch(I){throw this.client.logger.error(I),this.client.session.delete(N,Y("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(N),I}return this.client.core.eventClient.deleteEvent({eventId:w.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:y.metadata}),await this.client.proposal.delete(a,Y("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(N,he(Yt)),{topic:N,acknowledged:()=>Promise.resolve(this.client.session.get(N))}}),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:ue.wc_sessionPropose.reject}),await this.client.proposal.delete(s,Y("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}=Rt(),c=vt(),h=ui().toString(),l=this.client.session.get(s).namespaces;return this.events.once(Q("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=vt(),{done:n,resolve:o,reject:a}=Rt();return this.events.once(Q("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,he(Yt)),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=ue.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===ie.relay&&await this.confirmOnlineStateOrThrow();const c=vt(),h=ui().toString(),{done:l,resolve:u,reject:p}=Rt(o,"Request expired. Please try again.");this.events.once(Q("session_request",c),({error:b,result:w})=>{b?p(b):u(w)});const d="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:{request:Pe(ee({},r),{expiryTimestamp:he(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(b=>p(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const y={request:Pe(ee({},r),{expiryTimestamp:he(o)}),chainId:s},g=this.shouldSetTVF(d,y);return await Promise.all([new Promise(async b=>{await this.sendRequest(ee({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:y,expiry:o,throwOnFailedPublish:!0},g&&{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 Rl(this.client.core.storage,na);await Cl({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===ie.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);dt(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):rt(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=vt(),n=ui().toString(),{done:o,resolve:a,reject:c}=Rt();this.events.once(Q("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=ui().toString(),a=vt();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:Y("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}=R("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=>_d(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?ie.link_mode:ie.relay;o===ie.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:d,nbf:f,methods:y=[],expiry:g}=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(),N=Ps(A);if(await Promise.all([this.client.auth.authKeys.set(xs,{responseTopic:N,publicKey:A}),this.client.auth.pairingTopics.set(N,{topic:N,pairingTopic:w})]),await this.client.core.relayer.subscribe(N,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${w}`),y.length>0){const{namespace:O}=gi(a[0]);let D=$u(O,"request",y);_s(b)&&(D=Ou(D,b.pop())),b.push(D)}const m=g&&g>ue.wc_sessionAuthenticate.req.ttl?g:ue.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:f,resources:b},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:he(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:he(ue.wc_sessionPropose.req.ttl),id:vt()},{done:T,resolve:C,reject:q}=Rt(m,"Request expired"),M=vt(),v=Q("session_connect",I.id),$=Q("session_request",M),x=async({error:O,session:D})=>{this.events.off($,k),O?q(O):D&&C({session:D})},k=async O=>{var D,U,z;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),O.error){const ce=Y("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===ce.code?void 0:(this.events.off(v,x),q(O.error.message))}await this.deleteProposal(I.id),this.events.off(v,x);const{cacaos:J,responder:H}=O.result,se=[],Z=[];for(const ce of J){await Fn({cacao:ce,projectId:this.client.core.projectId})||(this.client.logger.error(ce,"Signature verification failed"),q(Y("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ct}=ce,ct=_s(Ct.resources),Xe=[Ar(Ct.iss)],ht=Ns(Ct.iss);if(ct){const lt=Gn(ct),hs=Wn(ct);se.push(...lt),Xe.push(...hs)}for(const lt of Xe)Z.push(`${lt}:${ht}`)}const Ie=await this.client.core.crypto.generateSharedKey(A,H.publicKey);let ae;se.length>0&&(ae={topic:Ie,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:H,controller:H.publicKey,expiry:he(Yt),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:w,namespaces:vo([...new Set(se)],[...new Set(Z)]),transportType:o},await this.client.core.relayer.subscribe(Ie,{transportType:o}),await this.client.session.set(Ie,ae),w&&await this.client.core.pairing.updateMetadata({topic:w,metadata:H.metadata}),ae=this.client.session.get(Ie)),(D=this.client.metadata.redirect)!=null&&D.linkMode&&(U=H.metadata.redirect)!=null&&U.linkMode&&(z=H.metadata.redirect)!=null&&z.universal&&s&&(this.client.core.addLinkModeSupportedApp(H.metadata.redirect.universal),this.client.session.update(Ie,{transportType:ie.link_mode})),C({auths:J,session:ae})};this.events.once(v,x),this.events.once($,k);let L;try{if(n){const O=Lt("wc_sessionAuthenticate",E,M);this.client.core.history.set(w,O);const D=await this.client.core.crypto.encode("",O,{type:ns,encoding:Pt});L=gs(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:ue.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:Pe(ee({},E),{verifyContext:{}}),pairingTopic:w,transportType:o}),{uri:L??P,response:T}}),S(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[Nt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(g){throw n.setError(ki.no_internet_connection),g}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(ki.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||ie.relay;a===ie.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=Ps(c),u={type:wt,receiverPublicKey:c,senderPublicKey:h},p=[],d=[];for(const g of r){if(!await Fn({cacao:g,projectId:this.client.core.projectId})){n.setError(ki.invalid_cacao);const N=Y("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:N,encodeOpts:u}),new Error(N.message)}n.addTrace(Nt.cacaos_verified);const{p:b}=g,w=_s(b.resources),P=[Ar(b.iss)],A=Ns(b.iss);if(w){const N=Gn(w),m=Wn(w);p.push(...N),P.push(...m)}for(const N of P)d.push(`${N}:${A}`)}const f=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Nt.create_authenticated_session_topic);let y;if((p==null?void 0:p.length)>0){y={topic:f,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:he(Yt),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:vo([...new Set(p)],[...new Set(d)]),transportType:a},n.addTrace(Nt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(g){throw n.setError(ki.subscribe_authenticated_session_topic_failure),g}n.addTrace(Nt.subscribe_authenticated_session_topic_success),await this.client.session.set(f,y),n.addTrace(Nt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Nt.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(g){throw n.setError(ki.authenticated_session_approve_publish_failure),g}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===ie.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ps(o),h={type:wt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:ue.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,Y("USER_DISCONNECTED"))}),S(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return tc(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,Y("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(na).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,Y("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=it.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),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(Tt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Y("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=it.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,he(ue.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),S(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=ie.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||he(ue.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=Lt(r,n,c);let d;const f=!!l;try{const b=f?Pt:Qe;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(Gw.includes(r)){const b=nt(JSON.stringify(p)),w=nt(d);y=await this.client.core.verify.register({id:w,decryptedId:b})}const g=ue[r].req;if(g.attestation=y,o&&(g.ttl=o),a&&(g.id=a),this.client.core.history.set(s,p),f){const b=gs(l,s,d);await B.Linking.openURL(b,this.client.name)}else{const b=ue[r].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=Pe(ee({},u),{correlationId:p.id}),h?(b.internal=Pe(ee({},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=Us(s,n);let l;const u=c&&typeof(B==null?void 0:B.Linking)<"u";try{const f=u?Pt:Qe;l=await this.client.core.crypto.encode(r,h,Pe(ee({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),f}let p,d;try{p=await this.client.core.history.get(r,s);const f=p.request;try{this.shouldSetTVF(f.method,f.params)&&(d=this.getTVFParams(s,f.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),f}if(u){const f=gs(c,r,l);await B.Linking.openURL(f,this.client.name)}else{const f=p.request.method,y=ue[f].res;y.tvf=Pe(ee({},d),{correlationId:s}),o?(y.internal=Pe(ee({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,y)):this.client.core.relayer.publish(r,l,y).catch(g=>this.client.logger.error(g))}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=Sa(s,n);let l;const u=c&&typeof(B==null?void 0:B.Linking)<"u";try{const d=u?Pt:Qe;l=await this.client.core.crypto.encode(r,h,Pe(ee({},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=gs(c,r,l);await B.Linking.openURL(d,this.client.name)}else{const d=p.request.method,f=a||ue[d].res;this.client.core.relayer.publish(r,l,f)}await this.client.core.history.resolve(h)}),S(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;_t(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=>{_t(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===it.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=it.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=it.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}=R("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==null||h.setError(ft.proposal_listener_not_found)),this.isValidConnect(ee({},r.params));const l=a.expiryTimestamp||he(ue.wc_sessionPropose.req.ttl),u=ee({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:nt(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h==null||h.addTrace(st.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:ue.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),S(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(dt(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(rt(s)){await this.client.proposal.delete(n,Y("USER_DISCONNECTED"));const o=Q("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(g=>g.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const f=this.client.proposal.get(d.proposalId),y=Pe(ee(ee(ee({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.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:ie.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(Q("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;dt(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Q("session_approve",r),{})):rt(s)&&(await this.client.session.delete(t,Y("USER_DISCONNECTED")),this.events.emit(Q("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=ji.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:Y("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ee({topic:t},r));try{ji.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 ji.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=Q("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);dt(s)?this.events.emit(Q("session_update",r),{}):rt(s)&&this.events.emit(Q("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,he(Yt)),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=Q("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);dt(s)?this.events.emit(Q("session_extend",r),{}):rt(s)&&this.events.emit(Q("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=Q("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);dt(s)?this.events.emit(Q("session_ping",r),{}):rt(s)&&this.events.emit(Q("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(fe.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:Y("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(ee({topic:o},p));const d=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:nt(JSON.stringify(Lt("wc_sessionRequest",p,u))),encryptedId:h,metadata:d.peer.metadata,transportType:l}),y={id:u,topic:o,params:p,verifyContext:f};await this.setPendingSessionRequest(y),l===ie.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=Q("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);dt(s)?this.events.emit(Q("session_request",r),{result:s.result}):rt(s)&&this.events.emit(Q("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=ji.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(ee({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),ji.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}),dt(s)?this.events.emit(Q("session_request",r),{result:s.result}):rt(s)&&this.events.emit(Q("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:nt(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===ie.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:wt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:d,rpcOpts:ue.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=it.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=Q("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Q("session_request",n.request.id),{error:s})})}),S(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===it.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=it.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:Lt("wc_sessionPropose",Pe(ee({},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(!Ae(t)){const{message:h}=R("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(ve(s)||await this.isValidPairingTopic(s),!qd(c)){const{message:h}=R("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!ve(r)&&Ot(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(!ve(n)&&Ot(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),ve(o)||this.validateSessionProps(o,"sessionProperties"),!ve(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=jd(t,"connect()",s);if(r)throw new Error(r.message)}),S(this,"isValidApprove",async t=>{if(!Ae(t))throw new Error(R("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=lr(r,"approve()");if(h)throw new Error(h.message);const l=_o(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!oe(n,!0)){const{message:u}=R("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(ve(o)||this.validateSessionProps(o,"sessionProperties"),!ve(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(!Ae(t)){const{message:n}=R("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!Dd(r)){const{message:n}=R("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),S(this,"isValidSessionSettleRequest",t=>{if(!Ae(t)){const{message:h}=R("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!Oc(s)){const{message:h}=R("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=xd(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=lr(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(_t(o)){const{message:h}=R("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),S(this,"isValidUpdate",async t=>{if(!Ae(t)){const{message:c}=R("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=lr(r,"update()");if(o)throw new Error(o.message);const a=_o(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),S(this,"isValidExtend",async t=>{if(!Ae(t)){const{message:r}=R("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(!Ae(t)){const{message:c}=R("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(!Io(a,n)){const{message:c}=R("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Ld(r)){const{message:c}=R("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!zd(a,n,r.method)){const{message:c}=R("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Hd(o,br)){const{message:c}=R("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${br.min} and ${br.max}`);throw new Error(c)}}),S(this,"isValidRespond",async t=>{var s;if(!Ae(t)){const{message:o}=R("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==null?void 0:t.response)!=null&&s.id&&this.cleanupAfterResponse(t),o}if(!Md(n)){const{message:o}=R("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),S(this,"isValidPing",async t=>{if(!Ae(t)){const{message:r}=R("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),S(this,"isValidEmit",async t=>{if(!Ae(t)){const{message:a}=R("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(!Io(o,n)){const{message:a}=R("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Ud(r)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Bd(o,n,r.name)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),S(this,"isValidDisconnect",async t=>{if(!Ae(t)){const{message:r}=R("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(!oe(r,!1))throw new Error("uri is required parameter");if(!oe(n,!1))throw new Error("domain is required parameter");if(!oe(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||Hi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ie.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}=R("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}=R("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!==ie.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==null?void 0:t.redirect)==null?void 0:l.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((p=t==null?void 0:t.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(B==null?void 0:B.Linking)<"u"}),S(this,"getAppLinkIfEnabled",(t,s)=>{var r;return this.isLinkModeEnabled(t,s)?(r=t==null?void 0: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=Dn(t,"topic")||"",r=decodeURIComponent(Dn(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:ie.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),S(this,"registerLinkModeListeners",async()=>{var t;if(an()||At()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=B==null?void 0:B.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(aa).includes(r.method)}),S(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return Pe(ee({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==null?void 0:t.data)||((s=t==null?void 0: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=aa[t];if(typeof s=="string")return[s];const n=s[r.key];if(Ye(n))return t==="solana_signAllTransactions"?n.map(o=>uu(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}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(fe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(xs)?this.client.auth.authKeys.get(xs):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===ie.link_mode?Pt:Qe});rn(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:nt(s)})):nn(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(Be.expired,async e=>{const{topic:t,id:s}=Fa(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,R("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,R("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(kt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(kt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!oe(e,!1)){const{message:t}=R("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}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(_t(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=R("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!oe(e,!1)){const{message:t}=R("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}=R("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(_t(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=R("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=R("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(oe(e,!1)){const{message:t}=R("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=R("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!kd(e)){const{message:t}=R("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=R("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(_t(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=R("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class nb extends Ht{constructor(e,t){super(e,t,Kw,mn),this.core=e,this.logger=t}}let ob=class extends Ht{constructor(e,t){super(e,t,Vw,mn),this.core=e,this.logger=t}};class ab extends Ht{constructor(e,t){super(e,t,Fw,mn,s=>s.id),this.core=e,this.logger=t}}class cb extends Ht{constructor(e,t){super(e,t,Qw,Qs,()=>xs),this.core=e,this.logger=t}}class hb extends Ht{constructor(e,t){super(e,t,Yw,Qs),this.core=e,this.logger=t}}class lb extends Ht{constructor(e,t){super(e,t,Zw,Qs,s=>s.id),this.core=e,this.logger=t}}var ub=Object.defineProperty,pb=(i,e,t)=>e in i?ub(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vr=(i,e,t)=>pb(i,typeof e!="symbol"?e+"":e,t);class db{constructor(e,t){this.core=e,this.logger=t,vr(this,"authKeys"),vr(this,"pairingTopics"),vr(this,"requests"),this.authKeys=new cb(this.core,this.logger),this.pairingTopics=new hb(this.core,this.logger),this.requests=new lb(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var fb=Object.defineProperty,gb=(i,e,t)=>e in i?fb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,V=(i,e,t)=>gb(i,typeof e!="symbol"?e+"":e,t);let mb=class Wc extends rg{constructor(e){super(e),V(this,"protocol",Hc),V(this,"version",Fc),V(this,"name",wr.name),V(this,"metadata"),V(this,"core"),V(this,"logger"),V(this,"events",new xt.EventEmitter),V(this,"engine"),V(this,"session"),V(this,"proposal"),V(this,"pendingRequest"),V(this,"auth"),V(this,"signConfig"),V(this,"on",(s,r)=>this.events.on(s,r)),V(this,"once",(s,r)=>this.events.once(s,r)),V(this,"off",(s,r)=>this.events.off(s,r)),V(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),V(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),V(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),V(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),V(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"rejectSessionAuthenticate",async s=>{try{return await this.engine.rejectSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||wr.name,this.metadata=Pl(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:os(Ws({level:(e==null?void 0:e.logger)||wr.logger}));this.core=(e==null?void 0:e.core)||new Bw(e),this.logger=Se(t,this.name),this.session=new ob(this.core,this.logger),this.proposal=new nb(this.core,this.logger),this.pendingRequest=new ab(this.core,this.logger),this.engine=new rb(this),this.auth=new db(this.core,this.logger)}static async init(e){const t=new Wc(e);return await t.initialize(),t}get context(){return Ne(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 ha="error",yb="wss://relay.walletconnect.org",wb="wc",bb="universal_provider",ws=`${wb}@2:${bb}:`,Jc="https://rpc.walletconnect.org/v1/",li="generic",vb=`${Jc}bundler`,He={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Eb(){}function yn(i){return i==null||typeof i!="object"&&typeof i!="function"}function wn(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Ib(i){if(yn(i))return i;if(Array.isArray(i)||wn(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 la(i){return typeof i=="object"&&i!==null}function Qc(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Yc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const _b="[object RegExp]",Zc="[object String]",Xc="[object Number]",eh="[object Boolean]",th="[object Arguments]",Pb="[object Symbol]",$b="[object Date]",Sb="[object Map]",Ob="[object Set]",xb="[object Array]",Ab="[object ArrayBuffer]",Cb="[object Object]",Tb="[object DataView]",Nb="[object Uint8Array]",Rb="[object Uint8ClampedArray]",jb="[object Uint16Array]",qb="[object Uint32Array]",kb="[object Int8Array]",Db="[object Int16Array]",Lb="[object Int32Array]",Mb="[object Float32Array]",Ub="[object Float64Array]";function zb(i,e){return fi(i,void 0,i,new Map,e)}function fi(i,e,t,s=new Map,r=void 0){const n=r==null?void 0:r(i,e,t,s);if(n!=null)return n;if(yn(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]=fi(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,fi(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(fi(a,void 0,t,s,r));return o}if(typeof me<"u"&&me.isBuffer(i))return i.subarray();if(wn(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=fi(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),Dt(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),Dt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),Dt(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,Dt(o,i,t,s,r),o}if(typeof i=="object"&&Bb(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),Dt(o,i,t,s,r),o}return i}function Dt(i,e,t=i,s,r){const n=[...Object.keys(e),...Qc(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=fi(e[a],a,t,s,r))}}function Bb(i){switch(Yc(i)){case th:case xb:case Ab:case Tb:case eh:case $b:case Mb:case Ub:case kb:case Db:case Lb:case Sb:case Xc:case Cb:case _b:case Ob:case Zc:case Pb:case Nb:case Rb:case jb:case qb:return!0;default:return!1}}function Kb(i,e){return zb(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case Xc:case Zc:case eh:{const o=new i.constructor(i==null?void 0:i.valueOf());return Dt(o,i),o}case th:{const o={};return Dt(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function ua(i){return Kb(i)}function pa(i){return i!==null&&typeof i=="object"&&Yc(i)==="[object Arguments]"}function Vb(i){return wn(i)}function Hb(i){var t;if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const s=i[Symbol.toStringTag];return s==null||!((t=Object.getOwnPropertyDescriptor(i,Symbol.toStringTag))!=null&&t.writable)?!1:i.toString()===`[object ${s}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function Fb(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=Zr(r,o,s,new Map)}return r}function Zr(i,e,t,s){if(yn(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return Ib(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),...Qc(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(pa(a)&&(a={...a}),pa(c)&&(c={...c}),typeof me<"u"&&me.isBuffer(a)&&(a=ua(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)||la(c)&&la(a)?i[o]=Zr(c,a,t,s):c==null&&Hb(a)?i[o]=Zr({},a,t,s):c==null&&Vb(a)?i[o]=ua(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Gb(i,...e){return Fb(i,...e,Eb)}var Wb=Object.defineProperty,Jb=Object.defineProperties,Qb=Object.getOwnPropertyDescriptors,da=Object.getOwnPropertySymbols,Yb=Object.prototype.hasOwnProperty,Zb=Object.prototype.propertyIsEnumerable,fa=(i,e,t)=>e in i?Wb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bs=(i,e)=>{for(var t in e||(e={}))Yb.call(e,t)&&fa(i,t,e[t]);if(da)for(var t of da(e))Zb.call(e,t)&&fa(i,t,e[t]);return i},Xb=(i,e)=>Jb(i,Qb(e));function Me(i,e,t){var s;const r=gi(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Jc}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Ft(i){return i.includes(":")?i.split(":")[1]:i}function ih(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function ev(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 vs(i={},e={}){const t=ga(i),s=ga(e);return Gb(t,s)}function ga(i){var e,t,s,r,n;const o={};if(!Ot(i))return o;for(const[a,c]of Object.entries(i)){const h=Gs(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},d=di(a);o[d]=Xb(bs(bs({},o[d]),c),{chains:ot(h,(e=o[d])==null?void 0:e.chains),methods:ot(l,(t=o[d])==null?void 0:t.methods),events:ot(u,(s=o[d])==null?void 0:s.events)}),(Ot(p)||Ot(((r=o[d])==null?void 0:r.rpcMap)||{}))&&(o[d].rpcMap=bs(bs({},p),(n=o[d])==null?void 0:n.rpcMap))}return o}function ma(i){return i.includes(":")?i.split(":")[2]:i}function ya(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Gs(t)?[t]:s.chains?s.chains:ih(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Er(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 sh={},W=i=>sh[i],Ir=(i,e)=>{sh[i]=e};var tv=Object.defineProperty,iv=(i,e,t)=>e in i?tv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Zt=(i,e,t)=>iv(i,typeof e!="symbol"?e+"":e,t);class sv{constructor(e){Zt(this,"name","polkadot"),Zt(this,"client"),Zt(this,"httpProviders"),Zt(this,"events"),Zt(this,"namespace"),Zt(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var rv=Object.defineProperty,nv=Object.defineProperties,ov=Object.getOwnPropertyDescriptors,wa=Object.getOwnPropertySymbols,av=Object.prototype.hasOwnProperty,cv=Object.prototype.propertyIsEnumerable,Xr=(i,e,t)=>e in i?rv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ba=(i,e)=>{for(var t in e||(e={}))av.call(e,t)&&Xr(i,t,e[t]);if(wa)for(var t of wa(e))cv.call(e,t)&&Xr(i,t,e[t]);return i},va=(i,e)=>nv(i,ov(e)),Xt=(i,e,t)=>Xr(i,typeof e!="symbol"?e+"":e,t);class hv{constructor(e){Xt(this,"name","eip155"),Xt(this,"client"),Xt(this,"chainId"),Xt(this,"namespace"),Xt(this,"httpProviders"),Xt(this,"events"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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||Me(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("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(Ft(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==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u==null?void 0:u[h];const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:va(ba({},l.sessionProperties||{}),{capabilities:va(ba({},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(Lt("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`${vb}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var lv=Object.defineProperty,uv=(i,e,t)=>e in i?lv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ei=(i,e,t)=>uv(i,typeof e!="symbol"?e+"":e,t);class pv{constructor(e){ei(this,"name","solana"),ei(this,"client"),ei(this,"httpProviders"),ei(this,"events"),ei(this,"namespace"),ei(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var dv=Object.defineProperty,fv=(i,e,t)=>e in i?dv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ti=(i,e,t)=>fv(i,typeof e!="symbol"?e+"":e,t);class gv{constructor(e){ti(this,"name","cosmos"),ti(this,"client"),ti(this,"httpProviders"),ti(this,"events"),ti(this,"namespace"),ti(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var mv=Object.defineProperty,yv=(i,e,t)=>e in i?mv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ii=(i,e,t)=>yv(i,typeof e!="symbol"?e+"":e,t);class wv{constructor(e){ii(this,"name","algorand"),ii(this,"client"),ii(this,"httpProviders"),ii(this,"events"),ii(this,"namespace"),ii(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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||Me(`${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(He.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||Me(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new Ve(new Ze(s,W("disableProviderPing")))}}var bv=Object.defineProperty,vv=(i,e,t)=>e in i?bv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,si=(i,e,t)=>vv(i,typeof e!="symbol"?e+"":e,t);class Ev{constructor(e){si(this,"name","cip34"),si(this,"client"),si(this,"httpProviders"),si(this,"events"),si(this,"namespace"),si(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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 Ve(new Ze(s,W("disableProviderPing")))}}var Iv=Object.defineProperty,_v=(i,e,t)=>e in i?Iv(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 Pv{constructor(e){ri(this,"name","elrond"),ri(this,"client"),ri(this,"httpProviders"),ri(this,"events"),ri(this,"namespace"),ri(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var $v=Object.defineProperty,Sv=(i,e,t)=>e in i?$v(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ni=(i,e,t)=>Sv(i,typeof e!="symbol"?e+"":e,t);class Ov{constructor(e){ni(this,"name","multiversx"),ni(this,"client"),ni(this,"httpProviders"),ni(this,"events"),ni(this,"namespace"),ni(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var xv=Object.defineProperty,Av=(i,e,t)=>e in i?xv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oi=(i,e,t)=>Av(i,typeof e!="symbol"?e+"":e,t);class Cv{constructor(e){oi(this,"name","near"),oi(this,"client"),oi(this,"httpProviders"),oi(this,"events"),oi(this,"namespace"),oi(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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||Me(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(He.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||Me(e,this.namespace);return typeof s>"u"?void 0:new Ve(new Ze(s,W("disableProviderPing")))}}var Tv=Object.defineProperty,Nv=(i,e,t)=>e in i?Tv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ai=(i,e,t)=>Nv(i,typeof e!="symbol"?e+"":e,t);class Rv{constructor(e){ai(this,"name","tezos"),ai(this,"client"),ai(this,"httpProviders"),ai(this,"events"),ai(this,"namespace"),ai(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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||Me(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(He.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||Me(e,this.namespace);return typeof s>"u"?void 0:new Ve(new Ze(s))}}var jv=Object.defineProperty,qv=(i,e,t)=>e in i?jv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ci=(i,e,t)=>qv(i,typeof e!="symbol"?e+"":e,t);class kv{constructor(e){ci(this,"name",li),ci(this,"client"),ci(this,"httpProviders"),ci(this,"events"),ci(this,"namespace"),ci(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var Dv=Object.defineProperty,Lv=Object.defineProperties,Mv=Object.getOwnPropertyDescriptors,Ea=Object.getOwnPropertySymbols,Uv=Object.prototype.hasOwnProperty,zv=Object.prototype.propertyIsEnumerable,en=(i,e,t)=>e in i?Dv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Es=(i,e)=>{for(var t in e||(e={}))Uv.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},_r=(i,e)=>Lv(i,Mv(e)),ze=(i,e,t)=>en(i,typeof e!="symbol"?e+"":e,t);let Bv=class rh{constructor(e){ze(this,"client"),ze(this,"namespaces"),ze(this,"optionalNamespaces"),ze(this,"sessionProperties"),ze(this,"scopedProperties"),ze(this,"events",new sn),ze(this,"rpcProviders",{}),ze(this,"session"),ze(this,"providerOpts"),ze(this,"logger"),ze(this,"uri"),ze(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:os(Ws({level:(e==null?void 0:e.logger)||ha})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new rh(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:Es({},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,Us(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:Y("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=ya(this.session.namespaces);this.namespaces=vs(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=ya(r.namespaces);return this.namespaces=vs(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===li?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(Ye(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 mb.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ha,relayUrl:this.providerOpts.relayUrl||yb,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=>di(t)))];Ir("client",this.client),Ir("events",this.events),Ir("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=ev(t,this.session),r=ih(s),n=vs(this.namespaces,this.optionalNamespaces),o=_r(Es({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new hv({namespace:o});break;case"algorand":this.rpcProviders[t]=new wv({namespace:o});break;case"solana":this.rpcProviders[t]=new pv({namespace:o});break;case"cosmos":this.rpcProviders[t]=new gv({namespace:o});break;case"polkadot":this.rpcProviders[t]=new sv({namespace:o});break;case"cip34":this.rpcProviders[t]=new Ev({namespace:o});break;case"elrond":this.rpcProviders[t]=new Pv({namespace:o});break;case"multiversx":this.rpcProviders[t]=new Ov({namespace:o});break;case"near":this.rpcProviders[t]=new Cv({namespace:o});break;case"tezos":this.rpcProviders[t]=new Rv({namespace:o});break;default:this.rpcProviders[li]?this.rpcProviders[li].updateNamespace(o):this.rpcProviders[li]=new kv({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&&Ye(o)&&this.events.emit("accountsChanged",o.map(ma))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=di(o),h=Er(o)!==Er(a)?`${c}:${Er(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=_r(Es({},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",_r(Es({},Y("USER_DISCONNECTED")),{data:e.topic})))}),this.on(He.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[li]}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=vs(t,s),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,s]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(o=>di(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=di(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(ma);if(!Ye(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(`${ws}/${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(`${ws}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${ws}/${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(ws)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const Kv=Bv,Vv="wc",Hv="ethereum_provider",Fv=`${Vv}@2:${Hv}:`,Gv="https://rpc.walletconnect.org/v1/",Ds=["eth_sendTransaction","personal_sign"],nh=["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"],Ls=["chainChanged","accountsChanged"],oh=["chainChanged","accountsChanged","message","disconnect","connect"],Wv=async()=>{const{createAppKit:i}=await $a(()=>import("./core-CGoVaJvD.js").then(e=>e.u),__vite__mapDeps([12,1,2,3,4,5,6,7,10,11,13,14,15]));return i};var Jv=Object.defineProperty,Qv=Object.defineProperties,Yv=Object.getOwnPropertyDescriptors,Ia=Object.getOwnPropertySymbols,Zv=Object.prototype.hasOwnProperty,Xv=Object.prototype.propertyIsEnumerable,tn=(i,e,t)=>e in i?Jv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,jt=(i,e)=>{for(var t in e||(e={}))Zv.call(e,t)&&tn(i,t,e[t]);if(Ia)for(var t of Ia(e))Xv.call(e,t)&&tn(i,t,e[t]);return i},Mi=(i,e)=>Qv(i,Yv(e)),je=(i,e,t)=>tn(i,typeof e!="symbol"?e+"":e,t);function Ms(i){return Number(i[0].split(":")[1])}function Is(i){return`0x${i.toString(16)}`}function eE(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Ye(e))throw new Error("Invalid chains");const c={chains:e,methods:s||Ds,events:n||Ls,rpcMap:jt({},e.length?{[Ms(e)]:a[Ms(e)]}:{})},h=n==null?void 0:n.filter(d=>!Ls.includes(d)),l=s==null?void 0:s.filter(d=>!Ds.includes(d));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=(h==null?void 0:h.length)&&(l==null?void 0:l.length)||!t,p={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:nh))],events:[...new Set(c.events.concat(o!=null&&o.length?o:oh))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class Ys{constructor(){je(this,"events",new xt.EventEmitter),je(this,"namespace","eip155"),je(this,"accounts",[]),je(this,"signer"),je(this,"chainId",1),je(this,"modal"),je(this,"rpc"),je(this,"STORAGE_KEY",Fv),je(this,"on",(e,t)=>(this.events.on(e,t),this)),je(this,"once",(e,t)=>(this.events.once(e,t),this)),je(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),je(this,"off",(e,t)=>(this.events.off(e,t),this)),je(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new Ys;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}=eE(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(Mi(jt({namespaces:jt({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e==null?void 0: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=Nn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Is(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==null?void 0: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(Mi(jt({},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=Nn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Is(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",Is(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",Mi(jt({},Y("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",Is(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==null?void 0:e.chains)!=null?t:[],n=(s=e==null?void 0: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==null?void 0:e.methods)||Ds:[],c=r.length?(e==null?void 0:e.events)||Ls:[],h=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],u=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),p=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:r==null?void 0: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?Ms(this.rpc.chains):Ms(this.rpc.optionalChains),this.signer=await Kv.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 Wv(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return uE}),n=r(Mi(jt({},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(Mi(jt({},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&&Ye(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=(r==null?void 0:r[n])||this.getRpcUrl(n)})),s&&Ye(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s==null?void 0:s.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=(r==null?void 0:r[n])||this.getRpcUrl(n)}))}getRpcUrl(e,t){var s;return((s=this.rpc.rpcMap)==null?void 0:s[e])||`${Gv}?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==null?void 0:t.accounts),this.setAccounts(t==null?void 0: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 tE=Ys;var iE=Object.defineProperty,sE=Object.defineProperties,rE=Object.getOwnPropertyDescriptors,_a=Object.getOwnPropertySymbols,nE=Object.prototype.hasOwnProperty,oE=Object.prototype.propertyIsEnumerable,Pa=(i,e,t)=>e in i?iE(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ah=(i,e)=>{for(var t in e||(e={}))nE.call(e,t)&&Pa(i,t,e[t]);if(_a)for(var t of _a(e))oE.call(e,t)&&Pa(i,t,e[t]);return i},aE=(i,e)=>sE(i,rE(e));function cE(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 hE=i=>{const[e,t]=i.split(":");return ch({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function lE(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(hE).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:cE(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:aE(ah({},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(f=>({id:f.id,name:f.name,links:f.links})),...(i.desktopWallets||[]).map(f=>({id:f.id,name:f.name,links:{native:f.links.native,universal:f.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],d=u.filter(f=>!p.includes(f.id));d.length&&(l.customWallets=d)}return l}function ch(i){return ah({formatters:void 0,fees:void 0,serializers:void 0},i)}var uE=Object.freeze({__proto__:null,convertWCMToAppKitOptions:lE,defineChain:ch});const QE=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:tE,OPTIONAL_EVENTS:oh,OPTIONAL_METHODS:nh,REQUIRED_EVENTS:Ls,REQUIRED_METHODS:Ds,default:Ys},Symbol.toStringTag,{value:"Module"}));export{Mf as A,Se as E,Wh as H,os as O,Pn as a,Lh as b,IE as c,EE as d,zs as e,$E as f,PE as g,Ke as h,Te as i,Ki as j,nl as k,Ws as l,_f as m,QE as n,_E as r,ja as t,Jh as w,Ne as y};
|
|
12
|
+
Approved: ${p.toString()}`))}),o.forEach(u=>{s||(Mt(r[u].methods,n[u].methods)?Mt(r[u].events,n[u].events)||(s=R("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=R("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function Kd(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 Po(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Vd(i){const e={};return Object.keys(i).forEach(t=>{if(t.includes(":"))e[t]=i[t];else{const s=Ci(i[t].accounts);s==null||s.forEach(r=>{e[r]={accounts:i[t].accounts.filter(n=>n.includes(`${r}:`)),methods:i[t].methods,events:i[t].events}})}}),e}function Hd(i,e){return fn(i,!1)&&i<=e.max&&i>=e.min}function $o(){const i=es();return new Promise(e=>{switch(i){case Le.browser:e(Fd());break;case Le.reactNative:e(Gd());break;case Le.node:e(Wd());break;default:e(!0)}})}function Fd(){return Oi()&&(navigator==null?void 0:navigator.onLine)}async function Gd(){if(At()&&typeof B<"u"&&B!=null&&B.NetInfo){const i=await(B==null?void 0:B.NetInfo.fetch());return i==null?void 0:i.isConnected}return!0}function Wd(){return!0}function Jd(i){switch(es()){case Le.browser:Qd(i);break;case Le.reactNative:Yd(i);break}}function Qd(i){!At()&&Oi()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function Yd(i){var e;At()&&typeof B<"u"&&B!=null&&B.NetInfo&&((e=B)==null||e.NetInfo.addEventListener(t=>i(t==null?void 0:t.isConnected)))}function Zd(){var i;return Oi()&&bt.getDocument()?((i=bt.getDocument())==null?void 0:i.visibilityState)==="visible":!0}const ur={};class ji{static get(e){return ur[e]}static set(e,t){ur[e]=t}static delete(e){delete ur[e]}}function Xd(i){return!i||typeof i.then!="function"?Promise.resolve(i):i}function pe(i,...e){try{return Xd(i(...e))}catch(t){return Promise.reject(t)}}function ef(i){const e=typeof i;return i===null||e!=="object"&&e!=="function"}function tf(i){const e=Object.getPrototypeOf(i);return!e||e.isPrototypeOf(Object)}function $s(i){if(ef(i))return String(i);if(tf(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 Mr="base64:";function sf(i){return typeof i=="string"?i:Mr+of(i)}function rf(i){return typeof i!="string"||!i.startsWith(Mr)?i:nf(i.slice(Mr.length))}function nf(i){return globalThis.Buffer?me.from(i,"base64"):Uint8Array.from(globalThis.atob(i),e=>e.codePointAt(0))}function of(i){return globalThis.Buffer?me.from(i).toString("base64"):globalThis.btoa(String.fromCodePoint(...i))}function xe(i){var e;return i&&((e=i.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function af(...i){return xe(i.join(":"))}function ms(i){return i=xe(i),i?i+":":""}function cf(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 hf(i,e){return e?i.startsWith(e)&&i[i.length-1]!=="$":i[i.length-1]!=="$"}const lf="memory",uf=()=>{const i=new Map;return{name:lf,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 pf(i={}){const e={mounts:{"":i.driver||uf()},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=xe(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 So(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=f=>{let y=p.get(f.base);return y||(y={driver:f.driver,base:f.base,items:[]},p.set(f.base,y)),y};for(const f of h){const y=typeof f=="string",g=xe(y?f:f.key),b=y?void 0:f.value,w=y||!f.options?l:{...l,...f.options},P=t(g);d(P).items.push({key:g,value:b,relativeKey:P.relativeKey,options:w})}return Promise.all([...p.values()].map(f=>u(f))).then(f=>f.flat())},c={hasItem(h,l={}){h=xe(h);const{relativeKey:u,driver:p}=t(h);return pe(p.hasItem,u,l)},getItem(h,l={}){h=xe(h);const{relativeKey:u,driver:p}=t(h);return pe(p.getItem,u,l).then(d=>ls(d))},getItems(h,l={}){return a(h,l,u=>u.driver.getItems?pe(u.driver.getItems,u.items.map(p=>({key:p.relativeKey,options:p.options})),l).then(p=>p.map(d=>({key:af(u.base,d.key),value:ls(d.value)}))):Promise.all(u.items.map(p=>pe(u.driver.getItem,p.relativeKey,p.options).then(d=>({key:p.key,value:ls(d)})))))},getItemRaw(h,l={}){h=xe(h);const{relativeKey:u,driver:p}=t(h);return p.getItemRaw?pe(p.getItemRaw,u,l):pe(p.getItem,u,l).then(d=>rf(d))},async setItem(h,l,u={}){if(l===void 0)return c.removeItem(h);h=xe(h);const{relativeKey:p,driver:d}=t(h);d.setItem&&(await pe(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 pe(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=>pe(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=xe(h);const{relativeKey:p,driver:d}=t(h);if(d.setItemRaw)await pe(d.setItemRaw,p,l,u);else if(d.setItem)await pe(d.setItem,p,sf(l),u);else return;d.watch||r("update",h)},async removeItem(h,l={}){typeof l=="boolean"&&(l={removeMeta:l}),h=xe(h);const{relativeKey:u,driver:p}=t(h);p.removeItem&&(await pe(p.removeItem,u,l),(l.removeMeta||l.removeMata)&&await pe(p.removeItem,u+"$",l),p.watch||r("remove",h))},async getMeta(h,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),h=xe(h);const{relativeKey:u,driver:p}=t(h),d=Object.create(null);if(p.getMeta&&Object.assign(d,await pe(p.getMeta,u,l)),!l.nativeOnly){const f=await pe(p.getItem,u+"$",l).then(y=>ls(y));f&&typeof f=="object"&&(typeof f.atime=="string"&&(f.atime=new Date(f.atime)),typeof f.mtime=="string"&&(f.mtime=new Date(f.mtime)),Object.assign(d,f))}return d},setMeta(h,l,u={}){return this.setItem(h+"$",l,u)},removeMeta(h,l={}){return this.removeItem(h+"$",l)},async getKeys(h,l={}){var g;h=ms(h);const u=s(h,!0);let p=[];const d=[];let f=!0;for(const b of u){(g=b.driver.flags)!=null&&g.maxDepth||(f=!1);const w=await pe(b.driver.getKeys,b.relativeBase,l);for(const P of w){const A=b.mountpoint+xe(P);p.some(N=>A.startsWith(N))||d.push(A)}p=[b.mountpoint,...p.filter(P=>!P.startsWith(b.mountpoint))]}const y=l.maxDepth!==void 0&&!f;return d.filter(b=>(!y||cf(b,l.maxDepth))&&hf(b,h))},async clear(h,l={}){h=ms(h),await Promise.all(s(h,!1).map(async u=>{if(u.driver.clear)return pe(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=>Oo(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=ms(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(So(l,r,h)).then(u=>{e.unwatch[h]=u}).catch(console.error),c},async unmount(h,l=!0){var u,p;h=ms(h),!(!h||!e.mounts[h])&&(e.watching&&h in e.unwatch&&((p=(u=e.unwatch)[h])==null||p.call(u),delete e.unwatch[h]),l&&await Oo(e.mounts[h]),e.mountpoints=e.mountpoints.filter(d=>d!==h),delete e.mounts[h])},getMount(h=""){h=xe(h)+":";const l=t(h);return{driver:l.driver,base:l.base}},getMounts(h="",l={}){return h=xe(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 So(i,e,t){return i.watch?i.watch((s,r)=>e(s,t+r)):()=>{}}async function Oo(i){typeof i.dispose=="function"&&await pe(i.dispose)}const df="idb-keyval";var ff=(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:df,options:i,async hasItem(r){return!(typeof await En(t(r),s)>"u")},async getItem(r){return await En(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 gf="WALLET_CONNECT_V2_INDEXED_DB",mf="keyvaluestorage";let yf=class{constructor(){this.indexedDb=pf({driver:ff({dbName:gf,storeName:mf})})}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,Gi(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var pr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof B<"u"?B:typeof self<"u"?self:{},Ss={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 pr<"u"&&pr.localStorage?Ss.exports=pr.localStorage:typeof window<"u"&&window.localStorage?Ss.exports=window.localStorage:Ss.exports=new e})();function wf(i){var e;return[i[0],As((e=i[1])!=null?e:"")]}let bf=class{constructor(){this.localStorage=Ss.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(wf)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return As(t)}async setItem(e,t){this.localStorage.setItem(e,Gi(t))}async removeItem(e){this.localStorage.removeItem(e)}};const vf="wc_storage_version",xo=1,Ef=async(i,e,t)=>{const s=vf,r=await e.getItem(s);if(r&&r>=xo){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,xo),t(e),If(i,o)},If=async(i,e)=>{e.length&&e.forEach(async t=>{await i.removeItem(t)})};let _f=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new bf;this.storage=e;try{const t=new yf;Ef(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 dr,Ao;function Pf(){if(Ao)return dr;Ao=1;const i=_h();dr=r;const e=N().console||{},t={mapHttpRequest:f,mapHttpResponse:f,wrapRequestSerializer:y,wrapResponseSerializer:y,wrapErrorSerializer:y,req:f,res:f,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||{},T=s(m.browser.serialize,I);let C=m.browser.serialize;Array.isArray(m.browser.serialize)&&m.browser.serialize.indexOf("!stdSerializers.err")>-1&&(C=!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=g),Object.defineProperty(v,"levelVal",{get:x}),Object.defineProperty(v,"level",{get:k,set:L});const $={transmit:E,serialize:T,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=g,v.serializers=I,v._serialize=T,v._stdErrSerialize=C,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||{},T&&D.serializers&&(U.serializers=D.serializers);const z=U.serializers;if(T&&z){var J=Object.assign({},I,z),H=m.browser.serialize===!0?Object.keys(J):T;delete D.serializers,c([D],H,J,this._stdErrSerialize)}function se(Z){this._childLevel=(Z._childLevel|0)+1,this.error=h(Z,D,"error"),this.fatal=h(Z,D,"fatal"),this.warn=h(Z,D,"warn"),this.info=h(Z,D,"info"),this.debug=h(Z,D,"debug"),this.trace=h(Z,D,"trace"),J&&(this.serializers=J,this._serialize=H),E&&(this._logEvent=u([].concat(Z._logEvent.bindings,D)))}return se.prototype=this,new se(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 T=Object.getPrototypeOf(E);E[_]=E.levelVal>E.levels.values[_]?g:T[_]?T[_]:e[_]||e[I]||g,o(m,E,_)}function o(m,E,_){!m.transmit&&E[_]===g||(E[_]=(function(I){return function(){const C=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,C)):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:C,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 T=_.slice();let C=T[0];const q={};I&&(q.time=I),q.level=r.levels.values[E];let M=(m._childLevel|0)+1;if(M<1&&(M=1),C!==null&&typeof C=="object"){for(;M--&&typeof T[0]=="object";)Object.assign(q,T.shift());C=T.length?i(T.shift(),T):void 0}else typeof C=="string"&&(C=i(T.shift(),T));return C!==void 0&&(q.msg=C),q}function c(m,E,_,I){for(const T in m)if(I&&m[T]instanceof Error)m[T]=r.stdSerializers.err(m[T]);else if(typeof m[T]=="object"&&!Array.isArray(m[T]))for(const C in m[T])E&&E.indexOf(C)>-1&&C in _&&(m[T][C]=_[C](m[T][C]))}function h(m,E,_){return function(){const I=new Array(1+arguments.length);I[0]=E;for(var T=1;T<I.length;T++)I[T]=arguments[T-1];return m[_].apply(this,I)}}function l(m,E,_){const I=E.send,T=E.ts,C=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=T,m._logEvent.messages=_.filter(function($){return v.indexOf($)===-1}),m._logEvent.level.label=C,m._logEvent.level.value=q,I(C,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 f(){return{}}function y(m){return m}function g(){}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 N(){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 dr}var hi=Pf();const os=Ih(hi),$f={level:"info"},as="custom_context",gn=1e3*1024;let Sf=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}},Co=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new Sf(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}}}}},xc=class{constructor(e,t=gn){this.level=e??"error",this.levelValue=hi.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new Co(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===hi.levels.values.error?console.error(e):t===hi.levels.values.warn?console.warn(e):t===hi.levels.values.debug?console.debug(e):t===hi.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Gi({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 Co(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(Gi({extraMetadata:e})),new Blob(t,{type:"application/json"})}},Of=class{constructor(e,t=gn){this.baseChunkLogger=new xc(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)}},xf=class{constructor(e,t=gn){this.baseChunkLogger=new xc(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 Af=Object.defineProperty,Cf=Object.defineProperties,Tf=Object.getOwnPropertyDescriptors,To=Object.getOwnPropertySymbols,Nf=Object.prototype.hasOwnProperty,Rf=Object.prototype.propertyIsEnumerable,No=(i,e,t)=>e in i?Af(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qs=(i,e)=>{for(var t in e||(e={}))Nf.call(e,t)&&No(i,t,e[t]);if(To)for(var t of To(e))Rf.call(e,t)&&No(i,t,e[t]);return i},ks=(i,e)=>Cf(i,Tf(e));function Ws(i){return ks(qs({},i),{level:(i==null?void 0:i.level)||$f.level})}function jf(i,e=as){return i[e]||""}function qf(i,e,t=as){return i[t]=e,i}function Ne(i,e=as){let t="";return typeof i.bindings>"u"?t=jf(i,e):t=i.bindings().context||"",t}function kf(i,e,t=as){const s=Ne(i,t);return s.trim()?`${s}/${e}`:e}function Se(i,e,t=as){const s=kf(i,e,t),r=i.child({context:s});return qf(r,s,t)}function Df(i){var e,t;const s=new Of((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:os(ks(qs({},i.opts),{level:"trace",browser:ks(qs({},(t=i.opts)==null?void 0:t.browser),{write:r=>s.write(r)})})),chunkLoggerController:s}}function Lf(i){var e;const t=new xf((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:os(ks(qs({},i.opts),{level:"trace"}),t),chunkLoggerController:t}}function Mf(i){return typeof i.loggerOverride<"u"&&typeof i.loggerOverride!="string"?{logger:i.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Df(i):Lf(i)}var Uf=Object.defineProperty,zf=(i,e,t)=>e in i?Uf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ro=(i,e,t)=>zf(i,typeof e!="symbol"?e+"":e,t);let Bf=class extends _i{constructor(e){super(),this.opts=e,Ro(this,"protocol","wc"),Ro(this,"version",2)}};var Kf=Object.defineProperty,Vf=(i,e,t)=>e in i?Kf(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Hf=(i,e,t)=>Vf(i,e+"",t);let Ff=class extends _i{constructor(e,t){super(),this.core=e,this.logger=t,Hf(this,"records",new Map)}},Gf=class{constructor(e,t){this.logger=e,this.core=t}};class Wf extends _i{constructor(e,t){super(),this.relayer=e,this.logger=t}}let Jf=class extends _i{constructor(e){super()}},Qf=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},Yf=class extends _i{constructor(e,t){super(),this.relayer=e,this.logger=t}},Zf=class extends _i{constructor(e,t){super(),this.core=e,this.logger=t}},Xf=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},eg=class{constructor(e,t){this.projectId=e,this.logger=t}},tg=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var ig=Object.defineProperty,sg=(i,e,t)=>e in i?ig(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,jo=(i,e,t)=>sg(i,typeof e!="symbol"?e+"":e,t);let rg=class{constructor(e){this.opts=e,jo(this,"protocol","wc"),jo(this,"version",2)}},ng=class{constructor(e){this.client=e}};var og={};const Ac="wc",Cc=2,Ur="core",at=`${Ac}@2:${Ur}:`,ag={logger:"error"},cg={database:":memory:"},hg="crypto",qo="client_ed25519_seed",lg=j.ONE_DAY,ug="keychain",pg="0.3",dg="messages",fg="0.3",ko=j.SIX_HOURS,gg="publisher",Tc="irn",mg="error",Nc="wss://relay.walletconnect.org",yg="relayer",fe={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},wg="_subscription",Ue={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},bg=.1,zr="2.21.1",ie={link_mode:"link_mode",relay:"relay"},Os={inbound:"inbound",outbound:"outbound"},vg="0.3",Eg="WALLETCONNECT_CLIENT_ID",Do="WALLETCONNECT_LINK_MODE_APPS",qe={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Ig="subscription",_g="0.3",Pg="pairing",$g="0.3",qi={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}}},kt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Fe={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Sg="history",Og="0.3",xg="expirer",Be={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Ag="0.3",Cg="verify-api",Tg="https://verify.walletconnect.com",Rc="https://verify.walletconnect.org",Hi=Rc,Ng=`${Hi}/v3`,Rg=[Tg,Rc],jg="echo",qg="https://echo.walletconnect.com",st={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"},ft={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"},Ge={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"},Tt={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"},Nt={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"},ki={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"},kg=.1,Dg="event-client",Lg=86400,Mg="https://pulse.walletconnect.org/batch";function Ug(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(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,b=0,w=f.length;b!==w&&f[b]===0;)b++,y++;for(var P=(w-b)*l+1>>>0,A=new Uint8Array(P);b!==w;){for(var N=f[b],m=0,E=P-1;(N!==0||m<g)&&E!==-1;E--,m++)N+=256*A[E]>>>0,A[E]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");g=m,b++}for(var _=P-g;_!==P&&A[_]===0;)_++;for(var I=c.repeat(y);_<P;++_)I+=i.charAt(A[_]);return I}function p(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,b=0;f[y]===c;)g++,y++;for(var w=(f.length-y)*h+1>>>0,P=new Uint8Array(w);f[y];){var A=t[f.charCodeAt(y)];if(A===255)return;for(var N=0,m=w-1;(A!==0||N<b)&&m!==-1;m--,N++)A+=a*P[m]>>>0,P[m]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");b=N,y++}if(f[y]!==" "){for(var E=w-b;E!==w&&P[E]===0;)E++;for(var _=new Uint8Array(g+(w-E)),I=g;E!==w;)_[I++]=P[E++];return _}}}function d(f){var y=p(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:d}}var zg=Ug,Bg=zg;const jc=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")},Kg=i=>new TextEncoder().encode(i),Vg=i=>new TextDecoder().decode(i);class Hg{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 Fg{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 qc(this,e)}}class Gg{constructor(e){this.decoders=e}or(e){return qc(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 qc=(i,e)=>new Gg({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Wg{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Hg(e,t,s),this.decoder=new Fg(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Js=({name:i,prefix:e,encode:t,decode:s})=>new Wg(i,e,t,s),cs=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=Bg(t,e);return Js({prefix:i,name:e,encode:s,decode:n=>jc(r(n))})},Jg=(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},Qg=(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},Ee=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>Js({prefix:e,name:i,encode(r){return Qg(r,s,t)},decode(r){return Jg(r,s,t,i)}}),Yg=Js({prefix:"\0",name:"identity",encode:i=>Vg(i),decode:i=>Kg(i)});var Zg=Object.freeze({__proto__:null,identity:Yg});const Xg=Ee({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var em=Object.freeze({__proto__:null,base2:Xg});const tm=Ee({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var im=Object.freeze({__proto__:null,base8:tm});const sm=cs({prefix:"9",name:"base10",alphabet:"0123456789"});var rm=Object.freeze({__proto__:null,base10:sm});const nm=Ee({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),om=Ee({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var am=Object.freeze({__proto__:null,base16:nm,base16upper:om});const cm=Ee({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hm=Ee({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),lm=Ee({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),um=Ee({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),pm=Ee({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dm=Ee({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fm=Ee({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gm=Ee({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),mm=Ee({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ym=Object.freeze({__proto__:null,base32:cm,base32upper:hm,base32pad:lm,base32padupper:um,base32hex:pm,base32hexupper:dm,base32hexpad:fm,base32hexpadupper:gm,base32z:mm});const wm=cs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bm=cs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vm=Object.freeze({__proto__:null,base36:wm,base36upper:bm});const Em=cs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Im=cs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var _m=Object.freeze({__proto__:null,base58btc:Em,base58flickr:Im});const Pm=Ee({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$m=Ee({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Sm=Ee({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Om=Ee({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var xm=Object.freeze({__proto__:null,base64:Pm,base64pad:$m,base64url:Sm,base64urlpad:Om});const kc=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Am=kc.reduce((i,e,t)=>(i[t]=e,i),[]),Cm=kc.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Tm(i){return i.reduce((e,t)=>(e+=Am[t],e),"")}function Nm(i){const e=[];for(const t of i){const s=Cm[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const Rm=Js({prefix:"🚀",name:"base256emoji",encode:Tm,decode:Nm});var jm=Object.freeze({__proto__:null,base256emoji:Rm}),qm=Dc,Lo=128,km=-128,Dm=Math.pow(2,31);function Dc(i,e,t){e=e||[],t=t||0;for(var s=t;i>=Dm;)e[t++]=i&255|Lo,i/=128;for(;i&km;)e[t++]=i&255|Lo,i>>>=7;return e[t]=i|0,Dc.bytes=t-s+1,e}var Lm=Br,Mm=128,Mo=127;function Br(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw Br.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&Mo)<<r:(o&Mo)*Math.pow(2,r),r+=7}while(o>=Mm);return Br.bytes=n-s,t}var Um=Math.pow(2,7),zm=Math.pow(2,14),Bm=Math.pow(2,21),Km=Math.pow(2,28),Vm=Math.pow(2,35),Hm=Math.pow(2,42),Fm=Math.pow(2,49),Gm=Math.pow(2,56),Wm=Math.pow(2,63),Jm=function(i){return i<Um?1:i<zm?2:i<Bm?3:i<Km?4:i<Vm?5:i<Hm?6:i<Fm?7:i<Gm?8:i<Wm?9:10},Qm={encode:qm,decode:Lm,encodingLength:Jm},Lc=Qm;const Uo=(i,e,t=0)=>(Lc.encode(i,e,t),e),zo=i=>Lc.encodingLength(i),Kr=(i,e)=>{const t=e.byteLength,s=zo(i),r=s+zo(t),n=new Uint8Array(r+t);return Uo(i,n,0),Uo(t,n,s),n.set(e,r),new Ym(i,t,e,n)};class Ym{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Mc=({name:i,code:e,encode:t})=>new Zm(i,e,t);class Zm{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?Kr(this.code,t):t.then(s=>Kr(this.code,s))}else throw Error("Unknown type, must be binary type")}}const Uc=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Xm=Mc({name:"sha2-256",code:18,encode:Uc("SHA-256")}),ey=Mc({name:"sha2-512",code:19,encode:Uc("SHA-512")});var ty=Object.freeze({__proto__:null,sha256:Xm,sha512:ey});const zc=0,iy="identity",Bc=jc,sy=i=>Kr(zc,Bc(i)),ry={code:zc,name:iy,encode:Bc,digest:sy};var ny=Object.freeze({__proto__:null,identity:ry});new TextEncoder,new TextDecoder;const Bo={...Zg,...em,...im,...rm,...am,...ym,...vm,..._m,...xm,...jm};({...ty,...ny});function oy(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Kc(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Ko=Kc("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),fr=Kc("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=oy(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),ay={utf8:Ko,"utf-8":Ko,hex:Bo.base16,latin1:fr,ascii:fr,binary:fr,...Bo};function cy(i,e="utf8"){const t=ay[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 hy=Object.defineProperty,ly=(i,e,t)=>e in i?hy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,tt=(i,e,t)=>ly(i,typeof e!="symbol"?e+"":e,t);class uy{constructor(e,t){this.core=e,this.logger=t,tt(this,"keychain",new Map),tt(this,"name",ug),tt(this,"version",pg),tt(this,"initialized",!1),tt(this,"storagePrefix",at),tt(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),tt(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),tt(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),tt(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=R("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),tt(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=Se(t,this.name)}get context(){return Ne(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Or(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?xr(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var py=Object.defineProperty,dy=(i,e,t)=>e in i?py(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,we=(i,e,t)=>dy(i,typeof e!="symbol"?e+"":e,t);class fy{constructor(e,t,s){this.core=e,this.logger=t,we(this,"name",hg),we(this,"keychain"),we(this,"randomSessionIdentifier",Lr()),we(this,"initialized",!1),we(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),we(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),we(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=vn(r);return gh(n.publicKey)}),we(this,"generateKeyPair",()=>{this.isInitialized();const r=Qp();return this.setPrivateKey(r.publicKey,r.privateKey)}),we(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=vn(n),a=this.randomSessionIdentifier;return await mh(a,r,lg,o)}),we(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Yp(a,n);return this.setSymKey(c,o)}),we(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||Ps(r);return await this.keychain.set(o,r),o}),we(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),we(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),we(this,"encode",async(r,n,o)=>{this.isInitialized();const a=$c(o),c=Gi(n);if(fo(a))return ed(c,o==null?void 0:o.encoding);if(po(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 Zp({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),we(this,"decode",async(r,n,o)=>{this.isInitialized();const a=id(n,o);if(fo(a)){const c=td(n,o==null?void 0:o.encoding);return As(c)}if(po(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Xp({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return As(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),we(this,"getPayloadType",(r,n=Qe)=>{const o=Xi({encoded:r,encoding:n});return Vt(o.type)}),we(this,"getPayloadSenderPublicKey",(r,n=Qe)=>{const o=Xi({encoded:r,encoding:n});return o.senderPublicKey?Te(o.senderPublicKey,$e):void 0}),this.core=e,this.logger=Se(t,this.name),this.keychain=s||new uy(this.core,this.logger)}get context(){return Ne(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(qo)}catch{e=Lr(),await this.keychain.set(qo,e)}return cy(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var gy=Object.defineProperty,my=Object.defineProperties,yy=Object.getOwnPropertyDescriptors,Vo=Object.getOwnPropertySymbols,wy=Object.prototype.hasOwnProperty,by=Object.prototype.propertyIsEnumerable,Vr=(i,e,t)=>e in i?gy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vy=(i,e)=>{for(var t in e||(e={}))wy.call(e,t)&&Vr(i,t,e[t]);if(Vo)for(var t of Vo(e))by.call(e,t)&&Vr(i,t,e[t]);return i},Ey=(i,e)=>my(i,yy(e)),Re=(i,e,t)=>Vr(i,typeof e!="symbol"?e+"":e,t);class Iy extends Gf{constructor(e,t){super(e,t),this.logger=e,this.core=t,Re(this,"messages",new Map),Re(this,"messagesWithoutClientAck",new Map),Re(this,"name",dg),Re(this,"version",fg),Re(this,"initialized",!1),Re(this,"storagePrefix",at),Re(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}}}),Re(this,"set",async(s,r,n)=>{this.isInitialized();const o=nt(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===Os.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,Ey(vy({},c),{[o]:r}))}return await this.persist(),o}),Re(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Re(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}),Re(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=nt(r);return typeof n[o]<"u"}),Re(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=nt(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Re(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=Se(e,this.name),this.core=t}get context(){return Ne(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,Or(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Or(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?xr(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?xr(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _y=Object.defineProperty,Py=Object.defineProperties,$y=Object.getOwnPropertyDescriptors,Ho=Object.getOwnPropertySymbols,Sy=Object.prototype.hasOwnProperty,Oy=Object.prototype.propertyIsEnumerable,Hr=(i,e,t)=>e in i?_y(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ys=(i,e)=>{for(var t in e||(e={}))Sy.call(e,t)&&Hr(i,t,e[t]);if(Ho)for(var t of Ho(e))Oy.call(e,t)&&Hr(i,t,e[t]);return i},gr=(i,e)=>Py(i,$y(e)),We=(i,e,t)=>Hr(i,typeof e!="symbol"?e+"":e,t);class xy extends Wf{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,We(this,"events",new xt.EventEmitter),We(this,"name",gg),We(this,"queue",new Map),We(this,"publishTimeout",j.toMiliseconds(j.ONE_MINUTE)),We(this,"initialPublishTimeout",j.toMiliseconds(j.ONE_SECOND*15)),We(this,"needsTransportRestart",!1),We(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==null?void 0:n.ttl)||ko,c=Rs(n),h=(n==null?void 0:n.prompt)||!1,l=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||ui().toString(),p={topic:s,message:r,opts:{ttl:a,relay:c,prompt:h,tag:l,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},d=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const f=new Promise(async y=>{const g=({id:w})=>{p.opts.id===w&&(this.removeRequestFromQueue(w),this.relayer.events.removeListener(fe.publish,g),y(p))};this.relayer.events.on(fe.publish,g);const b=$t(new Promise((w,P)=>{this.rpcPublish({topic:s,message:r,ttl:a,prompt:h,tag:l,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(w).catch(A=>{this.logger.warn(A,A==null?void 0:A.message),P(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await b,this.events.removeListener(fe.publish,g)}catch(w){this.queue.set(u,gr(ys({},p),{attempt:1})),this.logger.warn(w,w==null?void 0:w.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await $t(f,this.publishTimeout,d)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(u)}}),We(this,"on",(s,r)=>{this.events.on(s,r)}),We(this,"once",(s,r)=>{this.events.once(s,r)}),We(this,"off",(s,r)=>{this.events.off(s,r)}),We(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=Se(t,this.name),this.registerEventListeners()}get context(){return Ne(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=ko,prompt:h,tag:l,id:u,attestation:p,tvf:d}=e,f={method:Ui(Rs().protocol).publish,params:ys({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},d),id:u};ve((t=f.params)==null?void 0:t.prompt)&&((s=f.params)==null||delete s.prompt),ve((r=f.params)==null?void 0:r.tag)&&((n=f.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const y=await this.relayer.request(f);return this.relayer.events.emit(fe.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(ys({},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(ys({},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(Pi.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(fe.connection_stalled);return}this.checkQueue()}),this.relayer.on(fe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var Ay=Object.defineProperty,Cy=(i,e,t)=>e in i?Ay(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qt=(i,e,t)=>Cy(i,typeof e!="symbol"?e+"":e,t);class Ty{constructor(){Qt(this,"map",new Map),Qt(this,"set",(e,t)=>{const s=this.get(e);this.exists(e,t)||this.map.set(e,[...s,t])}),Qt(this,"get",e=>this.map.get(e)||[]),Qt(this,"exists",(e,t)=>this.get(e).includes(t)),Qt(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)}),Qt(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var Ny=Object.defineProperty,Ry=Object.defineProperties,jy=Object.getOwnPropertyDescriptors,Fo=Object.getOwnPropertySymbols,qy=Object.prototype.hasOwnProperty,ky=Object.prototype.propertyIsEnumerable,Fr=(i,e,t)=>e in i?Ny(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Di=(i,e)=>{for(var t in e||(e={}))qy.call(e,t)&&Fr(i,t,e[t]);if(Fo)for(var t of Fo(e))ky.call(e,t)&&Fr(i,t,e[t]);return i},mr=(i,e)=>Ry(i,jy(e)),X=(i,e,t)=>Fr(i,typeof e!="symbol"?e+"":e,t);class Dy extends Yf{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,X(this,"subscriptions",new Map),X(this,"topicMap",new Ty),X(this,"events",new xt.EventEmitter),X(this,"name",Ig),X(this,"version",_g),X(this,"pending",new Map),X(this,"cached",[]),X(this,"initialized",!1),X(this,"storagePrefix",at),X(this,"subscribeTimeout",j.toMiliseconds(j.ONE_MINUTE)),X(this,"initialSubscribeTimeout",j.toMiliseconds(j.ONE_SECOND*15)),X(this,"clientId"),X(this,"batchSubscribeTopicsLimit",500),X(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),X(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=Rs(r),o={topic:s,relay:n,transportType:r==null?void 0: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}}),X(this,"unsubscribe",async(s,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(s,r.id,r):await this.unsubscribeByTopic(s,r)}),X(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),X(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),X(this,"on",(s,r)=>{this.events.on(s,r)}),X(this,"once",(s,r)=>{this.events.once(s,r)}),X(this,"off",(s,r)=>{this.events.off(s,r)}),X(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),X(this,"start",async()=>{await this.onConnect()}),X(this,"stop",async()=>{await this.onDisconnect()}),X(this,"restart",async()=>{await this.restore(),await this.onRestart()}),X(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)}),X(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Pi.pulse,async()=>{await this.checkPending()}),this.events.on(qe.created,async s=>{const r=qe.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(qe.deleted,async s=>{const r=qe.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=Se(t,this.name),this.clientId=""}get context(){return Ne(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=Rs(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Y("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==null?void 0:s.transportType)===ie.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Ui(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==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((s==null?void 0:s.transportType)===ie.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(qe.created,u),l(p.id))};this.events.on(qe.created,u);try{const p=await $t(new Promise((d,f)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y==null?void 0:y.message),f(y)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(qe.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(fe.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Ui(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(fe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Ui(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(fe.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Ui(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,mr(Di({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Di({},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,Di({},t)),this.topicMap.set(t.topic,e),this.events.emit(qe.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}=R("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(qe.deleted,mr(Di({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(qe.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(qe.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=R("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=>mr(Di({},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 Dl(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}=R("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 nt(e+await this.getClientId())}}var Ly=Object.defineProperty,Go=Object.getOwnPropertySymbols,My=Object.prototype.hasOwnProperty,Uy=Object.prototype.propertyIsEnumerable,Gr=(i,e,t)=>e in i?Ly(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Wo=(i,e)=>{for(var t in e||(e={}))My.call(e,t)&&Gr(i,t,e[t]);if(Go)for(var t of Go(e))Uy.call(e,t)&&Gr(i,t,e[t]);return i},G=(i,e,t)=>Gr(i,typeof e!="symbol"?e+"":e,t);class zy extends Jf{constructor(e){super(e),G(this,"protocol","wc"),G(this,"version",2),G(this,"core"),G(this,"logger"),G(this,"events",new xt.EventEmitter),G(this,"provider"),G(this,"messages"),G(this,"subscriber"),G(this,"publisher"),G(this,"name",yg),G(this,"transportExplicitlyClosed",!1),G(this,"initialized",!1),G(this,"connectionAttemptInProgress",!1),G(this,"relayUrl"),G(this,"projectId"),G(this,"packageName"),G(this,"bundleId"),G(this,"hasExperiencedNetworkDisruption",!1),G(this,"pingTimeout"),G(this,"heartBeatTimeout",j.toMiliseconds(j.THIRTY_SECONDS+j.FIVE_SECONDS)),G(this,"reconnectTimeout"),G(this,"connectPromise"),G(this,"reconnectInProgress",!1),G(this,"requestsInFlight",[]),G(this,"connectTimeout",j.toMiliseconds(j.ONE_SECOND*15)),G(this,"request",async t=>{var s,r;this.logger.debug("Publishing Request Payload");const n=t.id||ui().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}}),G(this,"resetPingTimeout",()=>{Ts()&&(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==null?void 0:o.message)}},this.heartBeatTimeout))}),G(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),G(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(fe.connect)}),G(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),G(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(fe.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),G(this,"registerProviderListeners",()=>{this.provider.on(Ue.payload,this.onPayloadHandler),this.provider.on(Ue.connect,this.onConnectHandler),this.provider.on(Ue.disconnect,this.onDisconnectHandler),this.provider.on(Ue.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Se(e.logger,this.name):os(Ws({level:e.logger||mg})),this.messages=new Iy(this.logger,e.core),this.subscriber=new Dy(this,this.logger),this.publisher=new xy(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Nc,this.projectId=e.projectId,El()?this.packageName=kn():Il()&&(this.bundleId=kn()),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==null?void 0:e.message)}}get context(){return Ne(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:ie.relay},Os.outbound)}async subscribe(e,t){var s,r,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((s=t==null?void 0:t.internal)==null?void 0:s.throwOnFailedPublish)>"u"?!0:(r=t==null?void 0: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(qe.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(qe.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,Wo({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 $o())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const 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==null?void 0: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=he(j.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(fe.message,e),await this.recordMessageEvent(e,Os.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(Ue.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(Ue.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(Ue.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Ue.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(Ts())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==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ve(new fh(Ol({sdkVersion:zr,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}),rn(e)){if(!e.method.endsWith(wg))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:ie.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Wo({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else nn(e)&&this.events.emit(fe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Os.inbound),this.events.emit(fe.message,e))}async acknowledgePayload(e){const t=Us(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Ue.payload,this.onPayloadHandler),this.provider.off(Ue.connect,this.onConnectHandler),this.provider.off(Ue.disconnect,this.onDisconnectHandler),this.provider.off(Ue.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await $o();Jd(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(s=>this.logger.error(s,s==null?void 0:s.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Pi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Zd())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t==null?void 0:t.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(fe.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},j.toMiliseconds(bg)))))}isInitialized(){if(!this.initialized){const{message:e}=R("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 By(){}function Jo(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 Qo(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Yo(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const Ky="[object RegExp]",Vy="[object String]",Hy="[object Number]",Fy="[object Boolean]",Zo="[object Arguments]",Gy="[object Symbol]",Wy="[object Date]",Jy="[object Map]",Qy="[object Set]",Yy="[object Array]",Zy="[object Function]",Xy="[object ArrayBuffer]",yr="[object Object]",ew="[object Error]",tw="[object DataView]",iw="[object Uint8Array]",sw="[object Uint8ClampedArray]",rw="[object Uint16Array]",nw="[object Uint32Array]",ow="[object BigUint64Array]",aw="[object Int8Array]",cw="[object Int16Array]",hw="[object Int32Array]",lw="[object BigInt64Array]",uw="[object Float32Array]",pw="[object Float64Array]";function dw(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function fw(i,e,t){return zi(i,e,void 0,void 0,void 0,void 0,t)}function zi(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 Fi(i,e,n,o)}return Fi(i,e,n,o)}function Fi(i,e,t,s){if(Object.is(i,e))return!0;let r=Yo(i),n=Yo(e);if(r===Zo&&(r=yr),n===Zo&&(n=yr),r!==n)return!1;switch(r){case Vy:return i.toString()===e.toString();case Hy:{const c=i.valueOf(),h=e.valueOf();return dw(c,h)}case Fy:case Wy:case Gy:return Object.is(i.valueOf(),e.valueOf());case Ky:return i.source===e.source&&i.flags===e.flags;case Zy: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 Jy:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!zi(h,e.get(c),c,i,e,t,s))return!1;return!0}case Qy:{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=>zi(u,d,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case Yy:case iw:case sw:case rw:case nw:case ow:case aw:case cw:case hw:case lw:case uw:case pw:{if(typeof me<"u"&&me.isBuffer(i)!==me.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!zi(i[c],e[c],c,i,e,t,s))return!1;return!0}case Xy:return i.byteLength!==e.byteLength?!1:Fi(new Uint8Array(i),new Uint8Array(e),t,s);case tw:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:Fi(new Uint8Array(i),new Uint8Array(e),t,s);case ew:return i.name===e.name&&i.message===e.message;case yr:{if(!(Fi(i.constructor,e.constructor,t,s)||Jo(i)&&Jo(e)))return!1;const c=[...Object.keys(i),...Qo(i)],h=[...Object.keys(e),...Qo(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(!zi(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 fw(i,e,By)}var mw=Object.defineProperty,Xo=Object.getOwnPropertySymbols,yw=Object.prototype.hasOwnProperty,ww=Object.prototype.propertyIsEnumerable,Wr=(i,e,t)=>e in i?mw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ea=(i,e)=>{for(var t in e||(e={}))yw.call(e,t)&&Wr(i,t,e[t]);if(Xo)for(var t of Xo(e))ww.call(e,t)&&Wr(i,t,e[t]);return i},Oe=(i,e,t)=>Wr(i,typeof e!="symbol"?e+"":e,t);class Ht extends Qf{constructor(e,t,s,r=at,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,Oe(this,"map",new Map),Oe(this,"version",vg),Oe(this,"cached",[]),Oe(this,"initialized",!1),Oe(this,"getKey"),Oe(this,"storagePrefix",at),Oe(this,"recentlyDeleted",[]),Oe(this,"recentlyDeletedLimit",200),Oe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ve(o)?this.map.set(this.getKey(o),o):Sd(o)?this.map.set(o.id,o):Od(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Oe(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())}),Oe(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Oe(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>gw(a[c],o[c]))):this.values)),Oe(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=ea(ea({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Oe(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=Se(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return Ne(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}=R("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=R("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}=R("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}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var bw=Object.defineProperty,vw=(i,e,t)=>e in i?bw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,K=(i,e,t)=>vw(i,typeof e!="symbol"?e+"":e,t);class Ew{constructor(e,t){this.core=e,this.logger=t,K(this,"name",Pg),K(this,"version",$g),K(this,"events",new sn),K(this,"pairings"),K(this,"initialized",!1),K(this,"storagePrefix",at),K(this,"ignoredPayloadTypes",[wt]),K(this,"registeredMethods",[]),K(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),K(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),K(this,"create",async s=>{this.isInitialized();const r=Lr(),n=await this.core.crypto.setSymKey(r),o=he(j.FIVE_MINUTES),a={protocol:Tc},c={topic:n,expiry:o,relay:a,active:!1,methods:s==null?void 0:s.methods},h=mo({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:r,relay:a,expiryTimestamp:o,methods:s==null?void 0:s.methods});return this.events.emit(kt.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:s==null?void 0:s.transportType}),{topic:n,uri:h}}),K(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s==null?void 0:s.uri,trace:[st.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(st.pairing_uri_validation_success),r.addTrace(st.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(st.existing_pairing),l.active)throw r.setError(ft.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(st.pairing_not_expired)}const u=c||he(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(st.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(kt.create,p),r.addTrace(st.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(st.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(ft.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(d){throw r.setError(ft.subscribe_pairing_topic_failure),d}return r.addTrace(st.subscribe_pairing_topic_success),p}),K(this,"activate",async({topic:s})=>{this.isInitialized();const r=he(j.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),K(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}=Rt();this.events.once(Q("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),K(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),K(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),K(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),K(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",Y("USER_DISCONNECTED")),await this.deletePairing(r))}),K(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return mo({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),K(this,"sendRequest",async(s,r,n)=>{const o=Lt(r,n),a=await this.core.crypto.encode(s,o),c=qi[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),K(this,"sendResult",async(s,r,n)=>{const o=Us(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=qi[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),K(this,"sendError",async(s,r,n)=>{const o=Sa(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=qi[c]?qi[c].res:qi.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),K(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,Y("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),K(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>_t(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),K(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)}}),K(this,"onRelayEventResponse",async s=>{const{topic:r,payload:n}=s,o=(await this.core.history.get(r,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,n);default:return this.onUnknownRpcMethodResponse(o)}}),K(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(kt.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),K(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{dt(r)?this.events.emit(Q("pairing_ping",n),{}):rt(r)&&this.events.emit(Q("pairing_ping",n),{error:r.error})},500)}),K(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(kt.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),K(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Y("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)}}),K(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(Y("WC_METHOD_UNSUPPORTED",s))}),K(this,"isValidPair",(s,r)=>{var n;if(!Ae(s)){const{message:a}=R("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(ft.malformed_pairing_uri),new Error(a)}if(!$d(s.uri)){const{message:a}=R("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(ft.malformed_pairing_uri),new Error(a)}const o=go(s==null?void 0:s.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(ft.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(ft.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&j.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(ft.pairing_expired);const{message:a}=R("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),K(this,"isValidPing",async s=>{if(!Ae(s)){const{message:n}=R("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),K(this,"isValidDisconnect",async s=>{if(!Ae(s)){const{message:n}=R("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),K(this,"isValidPairingTopic",async s=>{if(!oe(s,!1)){const{message:r}=R("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(_t(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=R("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=Se(t,this.name),this.pairings=new Ht(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ne(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(fe.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==ie.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);rn(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):nn(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(Be.expired,async e=>{const{topic:t}=Fa(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(kt.expire,{topic:t}))})}}var Iw=Object.defineProperty,_w=(i,e,t)=>e in i?Iw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,be=(i,e,t)=>_w(i,typeof e!="symbol"?e+"":e,t);class Pw extends Ff{constructor(e,t){super(e,t),this.core=e,this.logger=t,be(this,"records",new Map),be(this,"events",new xt.EventEmitter),be(this,"name",Sg),be(this,"version",Og),be(this,"cached",[]),be(this,"initialized",!1),be(this,"storagePrefix",at),be(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)}),be(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:he(j.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Fe.created,o)}),be(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=rt(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(Fe.updated,r))}),be(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))),be(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(Fe.deleted,n)}}),this.persist()}),be(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),be(this,"on",(s,r)=>{this.events.on(s,r)}),be(this,"once",(s,r)=>{this.events.once(s,r)}),be(this,"off",(s,r)=>{this.events.off(s,r)}),be(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=Se(t,this.name)}get context(){return Ne(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:Lt(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}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Fe.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=R("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(Fe.created,e=>{const t=Fe.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fe.updated,e=>{const t=Fe.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Fe.deleted,e=>{const t=Fe.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(Pi.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(Fe.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $w=Object.defineProperty,Sw=(i,e,t)=>e in i?$w(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,_e=(i,e,t)=>Sw(i,typeof e!="symbol"?e+"":e,t);class Ow extends Zf{constructor(e,t){super(e,t),this.core=e,this.logger=t,_e(this,"expirations",new Map),_e(this,"events",new xt.EventEmitter),_e(this,"name",xg),_e(this,"version",Ag),_e(this,"cached",[]),_e(this,"initialized",!1),_e(this,"storagePrefix",at),_e(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)}),_e(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),_e(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(Be.created,{target:n,expiration:o})}),_e(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),_e(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(Be.deleted,{target:r,expiration:n})}}),_e(this,"on",(s,r)=>{this.events.on(s,r)}),_e(this,"once",(s,r)=>{this.events.once(s,r)}),_e(this,"off",(s,r)=>{this.events.off(s,r)}),_e(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=Se(t,this.name)}get context(){return Ne(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 xl(e);if(typeof e=="number")return Al(e);const{message:t}=R("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(Be.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=R("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}=R("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(Be.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Pi.pulse,()=>this.checkExpirations()),this.events.on(Be.created,e=>{const t=Be.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Be.expired,e=>{const t=Be.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Be.deleted,e=>{const t=Be.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xw=Object.defineProperty,Aw=(i,e,t)=>e in i?xw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ne=(i,e,t)=>Aw(i,typeof e!="symbol"?e+"":e,t);class Cw extends Xf{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,ne(this,"name",Cg),ne(this,"abortController"),ne(this,"isDevEnv"),ne(this,"verifyUrlV3",Ng),ne(this,"storagePrefix",at),ne(this,"version",Cc),ne(this,"publicKey"),ne(this,"fetchPromise"),ne(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()))}),ne(this,"register",async r=>{if(!Oi()||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=bt.getDocument(),l=this.startAbortTimer(j.ONE_SECOND*5),u=await new Promise((p,d)=>{const f=()=>{window.removeEventListener("message",g),h.body.removeChild(y),d("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const y=h.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",f,{signal:this.abortController.signal});const g=b=>{if(b.data&&typeof b.data=="string")try{const w=JSON.parse(b.data);if(w.type==="verify_attestation"){if(Pr(w.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(y),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",g),p(w.attestation===null?"":w.attestation)}}catch(w){this.logger.warn(w)}};h.body.appendChild(y),window.addEventListener("message",g,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),ne(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(Pr(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==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),ne(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}),ne(this,"getVerifyUrl",r=>{let n=r||Hi;return Rg.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Hi}`),n=Hi),n}),ne(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)}}),ne(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),ne(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ne(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")}}),ne(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ne(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}),ne(this,"validateAttestation",(r,n)=>{const o=rd(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=Se(t,this.name),this.abortController=new AbortController,this.isDevEnv=an(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ne(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),j.toMiliseconds(e))}}var Tw=Object.defineProperty,Nw=(i,e,t)=>e in i?Tw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ta=(i,e,t)=>Nw(i,typeof e!="symbol"?e+"":e,t);class Rw extends eg{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,ta(this,"context",jg),ta(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${qg}/${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=Se(t,this.context)}}var jw=Object.defineProperty,ia=Object.getOwnPropertySymbols,qw=Object.prototype.hasOwnProperty,kw=Object.prototype.propertyIsEnumerable,Jr=(i,e,t)=>e in i?jw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Li=(i,e)=>{for(var t in e||(e={}))qw.call(e,t)&&Jr(i,t,e[t]);if(ia)for(var t of ia(e))kw.call(e,t)&&Jr(i,t,e[t]);return i},le=(i,e,t)=>Jr(i,typeof e!="symbol"?e+"":e,t);class Dw extends tg{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,le(this,"context",Dg),le(this,"storagePrefix",at),le(this,"storageVersion",kg),le(this,"events",new Map),le(this,"shouldPersist",!1),le(this,"init",async()=>{if(!an())try{const r={eventId:Ln(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Va(this.core.relayer.protocol,this.core.relayer.version,zr)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),le(this,"createEvent",r=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=r,h=Ln(),l=this.core.projectId||"",u=Date.now(),p=Li({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}),le(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 Li(Li({},a),this.setMethods(a.eventId))}),le(this,"deleteEvent",r=>{const{eventId:n}=r;this.events.delete(n),this.shouldPersist=!0}),le(this,"setEventListeners",()=>{this.core.heartbeat.on(Pi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{j.fromMiliseconds(Date.now())-j.fromMiliseconds(r.timestamp)>Lg&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),le(this,"setMethods",r=>({addTrace:n=>this.addTrace(r,n),setError:n=>this.setError(r,n)})),le(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)}),le(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)}),le(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),le(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,Li(Li({},n),this.setMethods(n.eventId)))})}catch(r){this.logger.warn(r)}}),le(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)}}),le(this,"sendEvent",async r=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Mg}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${zr}${n}`,{method:"POST",body:JSON.stringify(r)})}),le(this,"getAppDomain",()=>Ka().url),this.logger=Se(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 Lw=Object.defineProperty,sa=Object.getOwnPropertySymbols,Mw=Object.prototype.hasOwnProperty,Uw=Object.prototype.propertyIsEnumerable,Qr=(i,e,t)=>e in i?Lw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ra=(i,e)=>{for(var t in e||(e={}))Mw.call(e,t)&&Qr(i,t,e[t]);if(sa)for(var t of sa(e))Uw.call(e,t)&&Qr(i,t,e[t]);return i},te=(i,e,t)=>Qr(i,typeof e!="symbol"?e+"":e,t);let zw=class Vc extends Bf{constructor(e){var t;super(e),te(this,"protocol",Ac),te(this,"version",Cc),te(this,"name",Ur),te(this,"relayUrl"),te(this,"projectId"),te(this,"customStoragePrefix"),te(this,"events",new xt.EventEmitter),te(this,"logger"),te(this,"heartbeat"),te(this,"relayer"),te(this,"crypto"),te(this,"storage"),te(this,"history"),te(this,"expirer"),te(this,"pairing"),te(this,"verify"),te(this,"echoClient"),te(this,"linkModeSupportedApps"),te(this,"eventClient"),te(this,"initialized",!1),te(this,"logChunkController"),te(this,"on",(a,c)=>this.events.on(a,c)),te(this,"once",(a,c)=>this.events.once(a,c)),te(this,"off",(a,c)=>this.events.off(a,c)),te(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),te(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ie.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(s)try{return this.customStoragePrefix=s.customStoragePrefix,this.logger=s.logger,this.heartbeat=s.heartbeat,this.crypto=s.crypto,this.history=s.history,this.expirer=s.expirer,this.storage=s.storage,this.relayer=s.relayer,this.pairing=s.pairing,this.verify=s.verify,this.echoClient=s.echoClient,this.linkModeSupportedApps=s.linkModeSupportedApps,this.eventClient=s.eventClient,this.initialized=s.initialized,this.logChunkController=s.logChunkController,s}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Nc,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Ws({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:ag.logger,name:Ur}),{logger:n,chunkLoggerController:o}=Mf({opts:r,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0: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=Se(n,this.name),this.heartbeat=new dh,this.crypto=new fy(this,this.logger,e==null?void 0:e.keychain),this.history=new Pw(this,this.logger),this.expirer=new Ow(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new _f(ra(ra({},cg),e==null?void 0:e.storageOptions)),this.relayer=new zy({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Ew(this,this.logger),this.verify=new Cw(this,this.logger,this.storage),this.echoClient=new Rw(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Dw(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new Vc(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(Eg,s),t}get context(){return Ne(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(Do,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(Do)||[],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 Bi<"u"&&og.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const Bw=zw,Hc="wc",Fc=2,Gc="client",mn=`${Hc}@${Fc}:${Gc}:`,wr={name:Gc,logger:"error"},na="WALLETCONNECT_DEEPLINK_CHOICE",Kw="proposal",oa="Proposal expired",Vw="session",Yt=j.SEVEN_DAYS,Hw="engine",ue={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}}},br={min:j.FIVE_MINUTES,max:j.SEVEN_DAYS},it={idle:"IDLE",active:"ACTIVE"},aa={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Fw="request",Gw=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Ww="wc",Jw="auth",Qw="authKeys",Yw="pairingTopics",Zw="requests",Qs=`${Ww}@${1.5}:${Jw}:`,xs=`${Qs}:PUB_KEY`;var Xw=Object.defineProperty,eb=Object.defineProperties,tb=Object.getOwnPropertyDescriptors,ca=Object.getOwnPropertySymbols,ib=Object.prototype.hasOwnProperty,sb=Object.prototype.propertyIsEnumerable,Yr=(i,e,t)=>e in i?Xw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ee=(i,e)=>{for(var t in e||(e={}))ib.call(e,t)&&Yr(i,t,e[t]);if(ca)for(var t of ca(e))sb.call(e,t)&&Yr(i,t,e[t]);return i},Pe=(i,e)=>eb(i,tb(e)),S=(i,e,t)=>Yr(i,typeof e!="symbol"?e+"":e,t);class rb extends ng{constructor(e){super(e),S(this,"name",Hw),S(this,"events",new sn),S(this,"initialized",!1),S(this,"requestQueue",{state:it.idle,queue:[]}),S(this,"sessionRequestQueue",{state:it.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(ue)}),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=Pe(ee({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=vd(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}=R("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(m)}const d=await this.client.core.crypto.generateKeyPair(),f=ue.wc_sessionPropose.req.ttl||j.FIVE_MINUTES,y=he(f),g=Pe(ee(ee({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:vt()}),b=Q("session_connect",g.id),{reject:w,resolve:P,done:A}=Rt(f,oa),N=({id:m})=>{m===g.id&&(this.client.events.off("proposal_expire",N),this.pendingSessions.delete(g.id),this.events.emit(b,{error:{message:oa,code:0}}))};return this.client.events.on("proposal_expire",N),this.events.once(b,({error:m,session:E})=>{this.client.events.off("proposal_expire",N),m?w(m):E&&P(E)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:g,throwOnFailedPublish:!0,clientRpcId:g.id}),await this.setProposal(g.id,g),{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==null?void 0:t.id)==null?void 0:s.toString(),trace:[Ge.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(I){throw o.setError(Tt.no_internet_connection),I}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(I){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(Tt.proposal_not_found),I}try{await this.isValidApprove(t)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Tt.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:f,proposer:y,requiredNamespaces:g,optionalNamespaces:b}=d;let w=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});w||(w=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Ge.session_approve_started,properties:{topic:f,trace:[Ge.session_approve_started,Ge.session_namespaces_validation_success]}}));const P=await this.client.core.crypto.generateKeyPair(),A=y.publicKey,N=await this.client.core.crypto.generateSharedKey(P,A),m=ee(ee(ee({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:P,metadata:this.client.metadata},expiry:he(Yt)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),E=ie.relay;w.addTrace(Ge.subscribing_session_topic);try{await this.client.core.relayer.subscribe(N,{transportType:E})}catch(I){throw w.setError(Tt.subscribe_session_topic_failure),I}w.addTrace(Ge.subscribe_session_topic_success);const _=Pe(ee({},m),{topic:N,requiredNamespaces:g,optionalNamespaces:b,pairingTopic:f,acknowledged:!1,self:m.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:P,transportType:ie.relay});await this.client.session.set(N,_),w.addTrace(Ge.store_session);try{w.addTrace(Ge.publishing_session_settle),await this.sendRequest({topic:N,method:"wc_sessionSettle",params:m,throwOnFailedPublish:!0}).catch(I=>{throw w==null||w.setError(Tt.session_settle_publish_failure),I}),w.addTrace(Ge.session_settle_publish_success),w.addTrace(Ge.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:P},throwOnFailedPublish:!0}).catch(I=>{throw w==null||w.setError(Tt.session_approve_publish_failure),I}),w.addTrace(Ge.session_approve_publish_success)}catch(I){throw this.client.logger.error(I),this.client.session.delete(N,Y("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(N),I}return this.client.core.eventClient.deleteEvent({eventId:w.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:y.metadata}),await this.client.proposal.delete(a,Y("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(N,he(Yt)),{topic:N,acknowledged:()=>Promise.resolve(this.client.session.get(N))}}),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:ue.wc_sessionPropose.reject}),await this.client.proposal.delete(s,Y("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}=Rt(),c=vt(),h=ui().toString(),l=this.client.session.get(s).namespaces;return this.events.once(Q("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=vt(),{done:n,resolve:o,reject:a}=Rt();return this.events.once(Q("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,he(Yt)),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=ue.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===ie.relay&&await this.confirmOnlineStateOrThrow();const c=vt(),h=ui().toString(),{done:l,resolve:u,reject:p}=Rt(o,"Request expired. Please try again.");this.events.once(Q("session_request",c),({error:b,result:w})=>{b?p(b):u(w)});const d="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:{request:Pe(ee({},r),{expiryTimestamp:he(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(b=>p(b)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const y={request:Pe(ee({},r),{expiryTimestamp:he(o)}),chainId:s},g=this.shouldSetTVF(d,y);return await Promise.all([new Promise(async b=>{await this.sendRequest(ee({clientRpcId:c,relayRpcId:h,topic:n,method:d,params:y,expiry:o,throwOnFailedPublish:!0},g&&{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 Rl(this.client.core.storage,na);await Cl({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===ie.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);dt(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):rt(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=vt(),n=ui().toString(),{done:o,resolve:a,reject:c}=Rt();this.events.once(Q("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=ui().toString(),a=vt();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:Y("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}=R("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=>_d(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?ie.link_mode:ie.relay;o===ie.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:d,nbf:f,methods:y=[],expiry:g}=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(),N=Ps(A);if(await Promise.all([this.client.auth.authKeys.set(xs,{responseTopic:N,publicKey:A}),this.client.auth.pairingTopics.set(N,{topic:N,pairingTopic:w})]),await this.client.core.relayer.subscribe(N,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${w}`),y.length>0){const{namespace:O}=gi(a[0]);let D=$u(O,"request",y);_s(b)&&(D=Ou(D,b.pop())),b.push(D)}const m=g&&g>ue.wc_sessionAuthenticate.req.ttl?g:ue.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:f,resources:b},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:he(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:he(ue.wc_sessionPropose.req.ttl),id:vt()},{done:T,resolve:C,reject:q}=Rt(m,"Request expired"),M=vt(),v=Q("session_connect",I.id),$=Q("session_request",M),x=async({error:O,session:D})=>{this.events.off($,k),O?q(O):D&&C({session:D})},k=async O=>{var D,U,z;if(await this.deletePendingAuthRequest(M,{message:"fulfilled",code:0}),O.error){const ce=Y("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return O.error.code===ce.code?void 0:(this.events.off(v,x),q(O.error.message))}await this.deleteProposal(I.id),this.events.off(v,x);const{cacaos:J,responder:H}=O.result,se=[],Z=[];for(const ce of J){await Fn({cacao:ce,projectId:this.client.core.projectId})||(this.client.logger.error(ce,"Signature verification failed"),q(Y("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ct}=ce,ct=_s(Ct.resources),Xe=[Ar(Ct.iss)],ht=Ns(Ct.iss);if(ct){const lt=Gn(ct),hs=Wn(ct);se.push(...lt),Xe.push(...hs)}for(const lt of Xe)Z.push(`${lt}:${ht}`)}const Ie=await this.client.core.crypto.generateSharedKey(A,H.publicKey);let ae;se.length>0&&(ae={topic:Ie,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:H,controller:H.publicKey,expiry:he(Yt),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:w,namespaces:vo([...new Set(se)],[...new Set(Z)]),transportType:o},await this.client.core.relayer.subscribe(Ie,{transportType:o}),await this.client.session.set(Ie,ae),w&&await this.client.core.pairing.updateMetadata({topic:w,metadata:H.metadata}),ae=this.client.session.get(Ie)),(D=this.client.metadata.redirect)!=null&&D.linkMode&&(U=H.metadata.redirect)!=null&&U.linkMode&&(z=H.metadata.redirect)!=null&&z.universal&&s&&(this.client.core.addLinkModeSupportedApp(H.metadata.redirect.universal),this.client.session.update(Ie,{transportType:ie.link_mode})),C({auths:J,session:ae})};this.events.once(v,x),this.events.once($,k);let L;try{if(n){const O=Lt("wc_sessionAuthenticate",E,M);this.client.core.history.set(w,O);const D=await this.client.core.crypto.encode("",O,{type:ns,encoding:Pt});L=gs(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:ue.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:Pe(ee({},E),{verifyContext:{}}),pairingTopic:w,transportType:o}),{uri:L??P,response:T}}),S(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[Nt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(g){throw n.setError(ki.no_internet_connection),g}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(ki.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||ie.relay;a===ie.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=Ps(c),u={type:wt,receiverPublicKey:c,senderPublicKey:h},p=[],d=[];for(const g of r){if(!await Fn({cacao:g,projectId:this.client.core.projectId})){n.setError(ki.invalid_cacao);const N=Y("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:N,encodeOpts:u}),new Error(N.message)}n.addTrace(Nt.cacaos_verified);const{p:b}=g,w=_s(b.resources),P=[Ar(b.iss)],A=Ns(b.iss);if(w){const N=Gn(w),m=Wn(w);p.push(...N),P.push(...m)}for(const N of P)d.push(`${N}:${A}`)}const f=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Nt.create_authenticated_session_topic);let y;if((p==null?void 0:p.length)>0){y={topic:f,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:he(Yt),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:vo([...new Set(p)],[...new Set(d)]),transportType:a},n.addTrace(Nt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(g){throw n.setError(ki.subscribe_authenticated_session_topic_failure),g}n.addTrace(Nt.subscribe_authenticated_session_topic_success),await this.client.session.set(f,y),n.addTrace(Nt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Nt.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(g){throw n.setError(ki.authenticated_session_approve_publish_failure),g}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===ie.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ps(o),h={type:wt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:s,topic:c,error:r,encodeOpts:h,rpcOpts:ue.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,Y("USER_DISCONNECTED"))}),S(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return tc(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,Y("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(na).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,Y("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=it.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),n=this.client.core.eventClient.getEvent({topic:r.pairingTopic});n==null||n.setError(Tt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Y("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=it.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,he(ue.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),S(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=ie.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||he(ue.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=Lt(r,n,c);let d;const f=!!l;try{const b=f?Pt:Qe;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(Gw.includes(r)){const b=nt(JSON.stringify(p)),w=nt(d);y=await this.client.core.verify.register({id:w,decryptedId:b})}const g=ue[r].req;if(g.attestation=y,o&&(g.ttl=o),a&&(g.id=a),this.client.core.history.set(s,p),f){const b=gs(l,s,d);await B.Linking.openURL(b,this.client.name)}else{const b=ue[r].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=Pe(ee({},u),{correlationId:p.id}),h?(b.internal=Pe(ee({},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=Us(s,n);let l;const u=c&&typeof(B==null?void 0:B.Linking)<"u";try{const f=u?Pt:Qe;l=await this.client.core.crypto.encode(r,h,Pe(ee({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),f}let p,d;try{p=await this.client.core.history.get(r,s);const f=p.request;try{this.shouldSetTVF(f.method,f.params)&&(d=this.getTVFParams(s,f.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),f}if(u){const f=gs(c,r,l);await B.Linking.openURL(f,this.client.name)}else{const f=p.request.method,y=ue[f].res;y.tvf=Pe(ee({},d),{correlationId:s}),o?(y.internal=Pe(ee({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,y)):this.client.core.relayer.publish(r,l,y).catch(g=>this.client.logger.error(g))}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=Sa(s,n);let l;const u=c&&typeof(B==null?void 0:B.Linking)<"u";try{const d=u?Pt:Qe;l=await this.client.core.crypto.encode(r,h,Pe(ee({},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=gs(c,r,l);await B.Linking.openURL(d,this.client.name)}else{const d=p.request.method,f=a||ue[d].res;this.client.core.relayer.publish(r,l,f)}await this.client.core.history.resolve(h)}),S(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;_t(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=>{_t(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===it.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=it.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=it.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}=R("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==null||h.setError(ft.proposal_listener_not_found)),this.isValidConnect(ee({},r.params));const l=a.expiryTimestamp||he(ue.wc_sessionPropose.req.ttl),u=ee({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:nt(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h==null||h.addTrace(st.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:ue.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),S(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(dt(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(rt(s)){await this.client.proposal.delete(n,Y("USER_DISCONNECTED"));const o=Q("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(g=>g.sessionTopic===t);if(!d)return this.client.logger.error(`Pending session not found for topic ${t}`);const f=this.client.proposal.get(d.proposalId),y=Pe(ee(ee(ee({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.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:ie.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(Q("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;dt(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(Q("session_approve",r),{})):rt(s)&&(await this.client.session.delete(t,Y("USER_DISCONNECTED")),this.events.emit(Q("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=ji.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:Y("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ee({topic:t},r));try{ji.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 ji.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=Q("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);dt(s)?this.events.emit(Q("session_update",r),{}):rt(s)&&this.events.emit(Q("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,he(Yt)),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=Q("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);dt(s)?this.events.emit(Q("session_extend",r),{}):rt(s)&&this.events.emit(Q("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=Q("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);dt(s)?this.events.emit(Q("session_ping",r),{}):rt(s)&&this.events.emit(Q("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(fe.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:Y("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(ee({topic:o},p));const d=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:nt(JSON.stringify(Lt("wc_sessionRequest",p,u))),encryptedId:h,metadata:d.peer.metadata,transportType:l}),y={id:u,topic:o,params:p,verifyContext:f};await this.setPendingSessionRequest(y),l===ie.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=Q("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);dt(s)?this.events.emit(Q("session_request",r),{result:s.result}):rt(s)&&this.events.emit(Q("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=ji.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(ee({topic:t},n)),this.client.events.emit("session_event",{id:r,topic:t,params:n}),ji.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}),dt(s)?this.events.emit(Q("session_request",r),{result:s.result}):rt(s)&&this.events.emit(Q("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:nt(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===ie.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:wt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:d,rpcOpts:ue.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=it.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=Q("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Q("session_request",n.request.id),{error:s})})}),S(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===it.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=it.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:Lt("wc_sessionPropose",Pe(ee({},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(!Ae(t)){const{message:h}=R("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(ve(s)||await this.isValidPairingTopic(s),!qd(c)){const{message:h}=R("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!ve(r)&&Ot(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(!ve(n)&&Ot(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),ve(o)||this.validateSessionProps(o,"sessionProperties"),!ve(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=jd(t,"connect()",s);if(r)throw new Error(r.message)}),S(this,"isValidApprove",async t=>{if(!Ae(t))throw new Error(R("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=lr(r,"approve()");if(h)throw new Error(h.message);const l=_o(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!oe(n,!0)){const{message:u}=R("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(ve(o)||this.validateSessionProps(o,"sessionProperties"),!ve(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(!Ae(t)){const{message:n}=R("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!Dd(r)){const{message:n}=R("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),S(this,"isValidSessionSettleRequest",t=>{if(!Ae(t)){const{message:h}=R("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!Oc(s)){const{message:h}=R("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=xd(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=lr(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(_t(o)){const{message:h}=R("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),S(this,"isValidUpdate",async t=>{if(!Ae(t)){const{message:c}=R("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=lr(r,"update()");if(o)throw new Error(o.message);const a=_o(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),S(this,"isValidExtend",async t=>{if(!Ae(t)){const{message:r}=R("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(!Ae(t)){const{message:c}=R("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(!Io(a,n)){const{message:c}=R("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Ld(r)){const{message:c}=R("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!zd(a,n,r.method)){const{message:c}=R("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Hd(o,br)){const{message:c}=R("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${br.min} and ${br.max}`);throw new Error(c)}}),S(this,"isValidRespond",async t=>{var s;if(!Ae(t)){const{message:o}=R("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==null?void 0:t.response)!=null&&s.id&&this.cleanupAfterResponse(t),o}if(!Md(n)){const{message:o}=R("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),S(this,"isValidPing",async t=>{if(!Ae(t)){const{message:r}=R("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),S(this,"isValidEmit",async t=>{if(!Ae(t)){const{message:a}=R("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(!Io(o,n)){const{message:a}=R("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!Ud(r)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Bd(o,n,r.name)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),S(this,"isValidDisconnect",async t=>{if(!Ae(t)){const{message:r}=R("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(!oe(r,!1))throw new Error("uri is required parameter");if(!oe(n,!1))throw new Error("domain is required parameter");if(!oe(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||Hi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ie.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}=R("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}=R("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!==ie.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==null?void 0:t.redirect)==null?void 0:l.universal)!==void 0&&((u=t==null?void 0:t.redirect)==null?void 0:u.universal)!==""&&((p=t==null?void 0:t.redirect)==null?void 0:p.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(B==null?void 0:B.Linking)<"u"}),S(this,"getAppLinkIfEnabled",(t,s)=>{var r;return this.isLinkModeEnabled(t,s)?(r=t==null?void 0: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=Dn(t,"topic")||"",r=decodeURIComponent(Dn(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:ie.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),S(this,"registerLinkModeListeners",async()=>{var t;if(an()||At()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const s=B==null?void 0:B.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(aa).includes(r.method)}),S(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return Pe(ee({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==null?void 0:t.data)||((s=t==null?void 0: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=aa[t];if(typeof s=="string")return[s];const n=s[r.key];if(Ye(n))return t==="solana_signAllTransactions"?n.map(o=>uu(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}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(fe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(xs)?this.client.auth.authKeys.get(xs):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===ie.link_mode?Pt:Qe});rn(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:nt(s)})):nn(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(Be.expired,async e=>{const{topic:t,id:s}=Fa(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,R("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,R("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(kt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(kt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!oe(e,!1)){const{message:t}=R("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}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(_t(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=R("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!oe(e,!1)){const{message:t}=R("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}=R("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(_t(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=R("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=R("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(oe(e,!1)){const{message:t}=R("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=R("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!kd(e)){const{message:t}=R("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=R("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(_t(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=R("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class nb extends Ht{constructor(e,t){super(e,t,Kw,mn),this.core=e,this.logger=t}}let ob=class extends Ht{constructor(e,t){super(e,t,Vw,mn),this.core=e,this.logger=t}};class ab extends Ht{constructor(e,t){super(e,t,Fw,mn,s=>s.id),this.core=e,this.logger=t}}class cb extends Ht{constructor(e,t){super(e,t,Qw,Qs,()=>xs),this.core=e,this.logger=t}}class hb extends Ht{constructor(e,t){super(e,t,Yw,Qs),this.core=e,this.logger=t}}class lb extends Ht{constructor(e,t){super(e,t,Zw,Qs,s=>s.id),this.core=e,this.logger=t}}var ub=Object.defineProperty,pb=(i,e,t)=>e in i?ub(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vr=(i,e,t)=>pb(i,typeof e!="symbol"?e+"":e,t);class db{constructor(e,t){this.core=e,this.logger=t,vr(this,"authKeys"),vr(this,"pairingTopics"),vr(this,"requests"),this.authKeys=new cb(this.core,this.logger),this.pairingTopics=new hb(this.core,this.logger),this.requests=new lb(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var fb=Object.defineProperty,gb=(i,e,t)=>e in i?fb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,V=(i,e,t)=>gb(i,typeof e!="symbol"?e+"":e,t);let mb=class Wc extends rg{constructor(e){super(e),V(this,"protocol",Hc),V(this,"version",Fc),V(this,"name",wr.name),V(this,"metadata"),V(this,"core"),V(this,"logger"),V(this,"events",new xt.EventEmitter),V(this,"engine"),V(this,"session"),V(this,"proposal"),V(this,"pendingRequest"),V(this,"auth"),V(this,"signConfig"),V(this,"on",(s,r)=>this.events.on(s,r)),V(this,"once",(s,r)=>this.events.once(s,r)),V(this,"off",(s,r)=>this.events.off(s,r)),V(this,"removeListener",(s,r)=>this.events.removeListener(s,r)),V(this,"removeAllListeners",s=>this.events.removeAllListeners(s)),V(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"pair",async s=>{try{return await this.engine.pair(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"approve",async s=>{try{return await this.engine.approve(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"reject",async s=>{try{return await this.engine.reject(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"update",async s=>{try{return await this.engine.update(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"extend",async s=>{try{return await this.engine.extend(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"request",async s=>{try{return await this.engine.request(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"respond",async s=>{try{return await this.engine.respond(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"ping",async s=>{try{return await this.engine.ping(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"emit",async s=>{try{return await this.engine.emit(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"find",s=>{try{return this.engine.find(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(s){throw this.logger.error(s.message),s}}),V(this,"authenticate",async(s,r)=>{try{return await this.engine.authenticate(s,r)}catch(n){throw this.logger.error(n.message),n}}),V(this,"formatAuthMessage",s=>{try{return this.engine.formatAuthMessage(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"approveSessionAuthenticate",async s=>{try{return await this.engine.approveSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),V(this,"rejectSessionAuthenticate",async s=>{try{return await this.engine.rejectSessionAuthenticate(s)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||wr.name,this.metadata=Pl(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:os(Ws({level:(e==null?void 0:e.logger)||wr.logger}));this.core=(e==null?void 0:e.core)||new Bw(e),this.logger=Se(t,this.name),this.session=new ob(this.core,this.logger),this.proposal=new nb(this.core,this.logger),this.pendingRequest=new ab(this.core,this.logger),this.engine=new rb(this),this.auth=new db(this.core,this.logger)}static async init(e){const t=new Wc(e);return await t.initialize(),t}get context(){return Ne(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 ha="error",yb="wss://relay.walletconnect.org",wb="wc",bb="universal_provider",ws=`${wb}@2:${bb}:`,Jc="https://rpc.walletconnect.org/v1/",li="generic",vb=`${Jc}bundler`,He={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function Eb(){}function yn(i){return i==null||typeof i!="object"&&typeof i!="function"}function wn(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Ib(i){if(yn(i))return i;if(Array.isArray(i)||wn(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 la(i){return typeof i=="object"&&i!==null}function Qc(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Yc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const _b="[object RegExp]",Zc="[object String]",Xc="[object Number]",eh="[object Boolean]",th="[object Arguments]",Pb="[object Symbol]",$b="[object Date]",Sb="[object Map]",Ob="[object Set]",xb="[object Array]",Ab="[object ArrayBuffer]",Cb="[object Object]",Tb="[object DataView]",Nb="[object Uint8Array]",Rb="[object Uint8ClampedArray]",jb="[object Uint16Array]",qb="[object Uint32Array]",kb="[object Int8Array]",Db="[object Int16Array]",Lb="[object Int32Array]",Mb="[object Float32Array]",Ub="[object Float64Array]";function zb(i,e){return fi(i,void 0,i,new Map,e)}function fi(i,e,t,s=new Map,r=void 0){const n=r==null?void 0:r(i,e,t,s);if(n!=null)return n;if(yn(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]=fi(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,fi(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(fi(a,void 0,t,s,r));return o}if(typeof me<"u"&&me.isBuffer(i))return i.subarray();if(wn(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=fi(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),Dt(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),Dt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),Dt(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,Dt(o,i,t,s,r),o}if(typeof i=="object"&&Bb(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),Dt(o,i,t,s,r),o}return i}function Dt(i,e,t=i,s,r){const n=[...Object.keys(e),...Qc(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=fi(e[a],a,t,s,r))}}function Bb(i){switch(Yc(i)){case th:case xb:case Ab:case Tb:case eh:case $b:case Mb:case Ub:case kb:case Db:case Lb:case Sb:case Xc:case Cb:case _b:case Ob:case Zc:case Pb:case Nb:case Rb:case jb:case qb:return!0;default:return!1}}function Kb(i,e){return zb(i,(t,s,r,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case Xc:case Zc:case eh:{const o=new i.constructor(i==null?void 0:i.valueOf());return Dt(o,i),o}case th:{const o={};return Dt(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function ua(i){return Kb(i)}function pa(i){return i!==null&&typeof i=="object"&&Yc(i)==="[object Arguments]"}function Vb(i){return wn(i)}function Hb(i){var t;if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const s=i[Symbol.toStringTag];return s==null||!((t=Object.getOwnPropertyDescriptor(i,Symbol.toStringTag))!=null&&t.writable)?!1:i.toString()===`[object ${s}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function Fb(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=Zr(r,o,s,new Map)}return r}function Zr(i,e,t,s){if(yn(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(s.has(e))return Ib(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),...Qc(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(pa(a)&&(a={...a}),pa(c)&&(c={...c}),typeof me<"u"&&me.isBuffer(a)&&(a=ua(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)||la(c)&&la(a)?i[o]=Zr(c,a,t,s):c==null&&Hb(a)?i[o]=Zr({},a,t,s):c==null&&Vb(a)?i[o]=ua(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Gb(i,...e){return Fb(i,...e,Eb)}var Wb=Object.defineProperty,Jb=Object.defineProperties,Qb=Object.getOwnPropertyDescriptors,da=Object.getOwnPropertySymbols,Yb=Object.prototype.hasOwnProperty,Zb=Object.prototype.propertyIsEnumerable,fa=(i,e,t)=>e in i?Wb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bs=(i,e)=>{for(var t in e||(e={}))Yb.call(e,t)&&fa(i,t,e[t]);if(da)for(var t of da(e))Zb.call(e,t)&&fa(i,t,e[t]);return i},Xb=(i,e)=>Jb(i,Qb(e));function Me(i,e,t){var s;const r=gi(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Jc}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Ft(i){return i.includes(":")?i.split(":")[1]:i}function ih(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function ev(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 vs(i={},e={}){const t=ga(i),s=ga(e);return Gb(t,s)}function ga(i){var e,t,s,r,n;const o={};if(!Ot(i))return o;for(const[a,c]of Object.entries(i)){const h=Gs(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},d=di(a);o[d]=Xb(bs(bs({},o[d]),c),{chains:ot(h,(e=o[d])==null?void 0:e.chains),methods:ot(l,(t=o[d])==null?void 0:t.methods),events:ot(u,(s=o[d])==null?void 0:s.events)}),(Ot(p)||Ot(((r=o[d])==null?void 0:r.rpcMap)||{}))&&(o[d].rpcMap=bs(bs({},p),(n=o[d])==null?void 0:n.rpcMap))}return o}function ma(i){return i.includes(":")?i.split(":")[2]:i}function ya(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Gs(t)?[t]:s.chains?s.chains:ih(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function Er(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 sh={},W=i=>sh[i],Ir=(i,e)=>{sh[i]=e};var tv=Object.defineProperty,iv=(i,e,t)=>e in i?tv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Zt=(i,e,t)=>iv(i,typeof e!="symbol"?e+"":e,t);class sv{constructor(e){Zt(this,"name","polkadot"),Zt(this,"client"),Zt(this,"httpProviders"),Zt(this,"events"),Zt(this,"namespace"),Zt(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var rv=Object.defineProperty,nv=Object.defineProperties,ov=Object.getOwnPropertyDescriptors,wa=Object.getOwnPropertySymbols,av=Object.prototype.hasOwnProperty,cv=Object.prototype.propertyIsEnumerable,Xr=(i,e,t)=>e in i?rv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ba=(i,e)=>{for(var t in e||(e={}))av.call(e,t)&&Xr(i,t,e[t]);if(wa)for(var t of wa(e))cv.call(e,t)&&Xr(i,t,e[t]);return i},va=(i,e)=>nv(i,ov(e)),Xt=(i,e,t)=>Xr(i,typeof e!="symbol"?e+"":e,t);class hv{constructor(e){Xt(this,"name","eip155"),Xt(this,"client"),Xt(this,"chainId"),Xt(this,"namespace"),Xt(this,"httpProviders"),Xt(this,"events"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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||Me(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("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(Ft(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==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u==null?void 0:u[h];const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:va(ba({},l.sessionProperties||{}),{capabilities:va(ba({},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(Lt("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`${vb}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var lv=Object.defineProperty,uv=(i,e,t)=>e in i?lv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ei=(i,e,t)=>uv(i,typeof e!="symbol"?e+"":e,t);class pv{constructor(e){ei(this,"name","solana"),ei(this,"client"),ei(this,"httpProviders"),ei(this,"events"),ei(this,"namespace"),ei(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var dv=Object.defineProperty,fv=(i,e,t)=>e in i?dv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ti=(i,e,t)=>fv(i,typeof e!="symbol"?e+"":e,t);class gv{constructor(e){ti(this,"name","cosmos"),ti(this,"client"),ti(this,"httpProviders"),ti(this,"events"),ti(this,"namespace"),ti(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var mv=Object.defineProperty,yv=(i,e,t)=>e in i?mv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ii=(i,e,t)=>yv(i,typeof e!="symbol"?e+"":e,t);class wv{constructor(e){ii(this,"name","algorand"),ii(this,"client"),ii(this,"httpProviders"),ii(this,"events"),ii(this,"namespace"),ii(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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||Me(`${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(He.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||Me(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new Ve(new Ze(s,W("disableProviderPing")))}}var bv=Object.defineProperty,vv=(i,e,t)=>e in i?bv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,si=(i,e,t)=>vv(i,typeof e!="symbol"?e+"":e,t);class Ev{constructor(e){si(this,"name","cip34"),si(this,"client"),si(this,"httpProviders"),si(this,"events"),si(this,"namespace"),si(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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 Ve(new Ze(s,W("disableProviderPing")))}}var Iv=Object.defineProperty,_v=(i,e,t)=>e in i?Iv(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 Pv{constructor(e){ri(this,"name","elrond"),ri(this,"client"),ri(this,"httpProviders"),ri(this,"events"),ri(this,"namespace"),ri(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var $v=Object.defineProperty,Sv=(i,e,t)=>e in i?$v(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ni=(i,e,t)=>Sv(i,typeof e!="symbol"?e+"":e,t);class Ov{constructor(e){ni(this,"name","multiversx"),ni(this,"client"),ni(this,"httpProviders"),ni(this,"events"),ni(this,"namespace"),ni(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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=Ft(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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var xv=Object.defineProperty,Av=(i,e,t)=>e in i?xv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oi=(i,e,t)=>Av(i,typeof e!="symbol"?e+"":e,t);class Cv{constructor(e){oi(this,"name","near"),oi(this,"client"),oi(this,"httpProviders"),oi(this,"events"),oi(this,"namespace"),oi(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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||Me(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(He.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||Me(e,this.namespace);return typeof s>"u"?void 0:new Ve(new Ze(s,W("disableProviderPing")))}}var Tv=Object.defineProperty,Nv=(i,e,t)=>e in i?Tv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ai=(i,e,t)=>Nv(i,typeof e!="symbol"?e+"":e,t);class Rv{constructor(e){ai(this,"name","tezos"),ai(this,"client"),ai(this,"httpProviders"),ai(this,"events"),ai(this,"namespace"),ai(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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||Me(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(He.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||Me(e,this.namespace);return typeof s>"u"?void 0:new Ve(new Ze(s))}}var jv=Object.defineProperty,qv=(i,e,t)=>e in i?jv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ci=(i,e,t)=>qv(i,typeof e!="symbol"?e+"":e,t);class kv{constructor(e){ci(this,"name",li),ci(this,"client"),ci(this,"httpProviders"),ci(this,"events"),ci(this,"namespace"),ci(this,"chainId"),this.namespace=e.namespace,this.events=W("events"),this.client=W("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(He.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||Me(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ve(new Ze(s,W("disableProviderPing")))}}var Dv=Object.defineProperty,Lv=Object.defineProperties,Mv=Object.getOwnPropertyDescriptors,Ea=Object.getOwnPropertySymbols,Uv=Object.prototype.hasOwnProperty,zv=Object.prototype.propertyIsEnumerable,en=(i,e,t)=>e in i?Dv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Es=(i,e)=>{for(var t in e||(e={}))Uv.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},_r=(i,e)=>Lv(i,Mv(e)),ze=(i,e,t)=>en(i,typeof e!="symbol"?e+"":e,t);let Bv=class rh{constructor(e){ze(this,"client"),ze(this,"namespaces"),ze(this,"optionalNamespaces"),ze(this,"sessionProperties"),ze(this,"scopedProperties"),ze(this,"events",new sn),ze(this,"rpcProviders",{}),ze(this,"session"),ze(this,"providerOpts"),ze(this,"logger"),ze(this,"uri"),ze(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:os(Ws({level:(e==null?void 0:e.logger)||ha})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new rh(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:Es({},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,Us(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:Y("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=ya(this.session.namespaces);this.namespaces=vs(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=ya(r.namespaces);return this.namespaces=vs(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===li?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(Ye(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 mb.init({core:this.providerOpts.core,logger:this.providerOpts.logger||ha,relayUrl:this.providerOpts.relayUrl||yb,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=>di(t)))];Ir("client",this.client),Ir("events",this.events),Ir("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=ev(t,this.session),r=ih(s),n=vs(this.namespaces,this.optionalNamespaces),o=_r(Es({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new hv({namespace:o});break;case"algorand":this.rpcProviders[t]=new wv({namespace:o});break;case"solana":this.rpcProviders[t]=new pv({namespace:o});break;case"cosmos":this.rpcProviders[t]=new gv({namespace:o});break;case"polkadot":this.rpcProviders[t]=new sv({namespace:o});break;case"cip34":this.rpcProviders[t]=new Ev({namespace:o});break;case"elrond":this.rpcProviders[t]=new Pv({namespace:o});break;case"multiversx":this.rpcProviders[t]=new Ov({namespace:o});break;case"near":this.rpcProviders[t]=new Cv({namespace:o});break;case"tezos":this.rpcProviders[t]=new Rv({namespace:o});break;default:this.rpcProviders[li]?this.rpcProviders[li].updateNamespace(o):this.rpcProviders[li]=new kv({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&&Ye(o)&&this.events.emit("accountsChanged",o.map(ma))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=di(o),h=Er(o)!==Er(a)?`${c}:${Er(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=_r(Es({},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",_r(Es({},Y("USER_DISCONNECTED")),{data:e.topic})))}),this.on(He.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[li]}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=vs(t,s),this.sessionProperties=r,this.scopedProperties=n}validateChain(e){const[t,s]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,s];if(t&&!Object.keys(this.namespaces||{}).map(o=>di(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=di(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(ma);if(!Ye(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(`${ws}/${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(`${ws}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${ws}/${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(ws)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const Kv=Bv,Vv="wc",Hv="ethereum_provider",Fv=`${Vv}@2:${Hv}:`,Gv="https://rpc.walletconnect.org/v1/",Ds=["eth_sendTransaction","personal_sign"],nh=["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"],Ls=["chainChanged","accountsChanged"],oh=["chainChanged","accountsChanged","message","disconnect","connect"],Wv=async()=>{const{createAppKit:i}=await $a(()=>import("./core-C_RCjMc6.js").then(e=>e.u),__vite__mapDeps([12,1,2,3,4,5,6,7,10,11,13,14,15]));return i};var Jv=Object.defineProperty,Qv=Object.defineProperties,Yv=Object.getOwnPropertyDescriptors,Ia=Object.getOwnPropertySymbols,Zv=Object.prototype.hasOwnProperty,Xv=Object.prototype.propertyIsEnumerable,tn=(i,e,t)=>e in i?Jv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,jt=(i,e)=>{for(var t in e||(e={}))Zv.call(e,t)&&tn(i,t,e[t]);if(Ia)for(var t of Ia(e))Xv.call(e,t)&&tn(i,t,e[t]);return i},Mi=(i,e)=>Qv(i,Yv(e)),je=(i,e,t)=>tn(i,typeof e!="symbol"?e+"":e,t);function Ms(i){return Number(i[0].split(":")[1])}function Is(i){return`0x${i.toString(16)}`}function eE(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Ye(e))throw new Error("Invalid chains");const c={chains:e,methods:s||Ds,events:n||Ls,rpcMap:jt({},e.length?{[Ms(e)]:a[Ms(e)]}:{})},h=n==null?void 0:n.filter(d=>!Ls.includes(d)),l=s==null?void 0:s.filter(d=>!Ds.includes(d));if(!t&&!o&&!r&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=(h==null?void 0:h.length)&&(l==null?void 0:l.length)||!t,p={chains:[...new Set(u?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(r!=null&&r.length?r:nh))],events:[...new Set(c.events.concat(o!=null&&o.length?o:oh))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class Ys{constructor(){je(this,"events",new xt.EventEmitter),je(this,"namespace","eip155"),je(this,"accounts",[]),je(this,"signer"),je(this,"chainId",1),je(this,"modal"),je(this,"rpc"),je(this,"STORAGE_KEY",Fv),je(this,"on",(e,t)=>(this.events.on(e,t),this)),je(this,"once",(e,t)=>(this.events.once(e,t),this)),je(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),je(this,"off",(e,t)=>(this.events.off(e,t),this)),je(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new Ys;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}=eE(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(Mi(jt({namespaces:jt({},s&&{[this.namespace]:s})},r&&{optionalNamespaces:{[this.namespace]:r}}),{pairingTopic:e==null?void 0: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=Nn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Is(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==null?void 0: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(Mi(jt({},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=Nn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Is(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",Is(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",Mi(jt({},Y("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",Is(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==null?void 0:e.chains)!=null?t:[],n=(s=e==null?void 0: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==null?void 0:e.methods)||Ds:[],c=r.length?(e==null?void 0:e.events)||Ls:[],h=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],u=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),p=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:r==null?void 0: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?Ms(this.rpc.chains):Ms(this.rpc.optionalChains),this.signer=await Kv.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 Wv(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return uE}),n=r(Mi(jt({},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(Mi(jt({},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&&Ye(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=(r==null?void 0:r[n])||this.getRpcUrl(n)})),s&&Ye(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s==null?void 0:s.map(n=>this.formatChainId(n)),s.forEach(n=>{this.rpc.rpcMap[n]=(r==null?void 0:r[n])||this.getRpcUrl(n)}))}getRpcUrl(e,t){var s;return((s=this.rpc.rpcMap)==null?void 0:s[e])||`${Gv}?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==null?void 0:t.accounts),this.setAccounts(t==null?void 0: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 tE=Ys;var iE=Object.defineProperty,sE=Object.defineProperties,rE=Object.getOwnPropertyDescriptors,_a=Object.getOwnPropertySymbols,nE=Object.prototype.hasOwnProperty,oE=Object.prototype.propertyIsEnumerable,Pa=(i,e,t)=>e in i?iE(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ah=(i,e)=>{for(var t in e||(e={}))nE.call(e,t)&&Pa(i,t,e[t]);if(_a)for(var t of _a(e))oE.call(e,t)&&Pa(i,t,e[t]);return i},aE=(i,e)=>sE(i,rE(e));function cE(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 hE=i=>{const[e,t]=i.split(":");return ch({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function lE(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(hE).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:cE(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:aE(ah({},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(f=>({id:f.id,name:f.name,links:f.links})),...(i.desktopWallets||[]).map(f=>({id:f.id,name:f.name,links:{native:f.links.native,universal:f.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],d=u.filter(f=>!p.includes(f.id));d.length&&(l.customWallets=d)}return l}function ch(i){return ah({formatters:void 0,fees:void 0,serializers:void 0},i)}var uE=Object.freeze({__proto__:null,convertWCMToAppKitOptions:lE,defineChain:ch});const QE=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:tE,OPTIONAL_EVENTS:oh,OPTIONAL_METHODS:nh,REQUIRED_EVENTS:Ls,REQUIRED_METHODS:Ds,default:Ys},Symbol.toStringTag,{value:"Module"}));export{Mf as A,Se as E,Wh as H,os as O,Pn as a,Lh as b,IE as c,EE as d,zs as e,$E as f,PE as g,Ke as h,Te as i,Ki as j,nl as k,Ws as l,_f as m,QE as n,_E as r,ja as t,Jh as w,Ne as y};
|