@dcl/governance-site 2.5.0 → 2.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/{ConstantsUtil-689989f0.js → ConstantsUtil-c3a75781.js} +1 -1
- package/assets/{ExchangeController-88f78111.js → ExchangeController-de6066de.js} +1 -1
- package/assets/{HelpersUtil-40f31189.js → HelpersUtil-47bce835.js} +1 -1
- package/assets/{NetworkUtil-2fb81493.js → NetworkUtil-cfdab321.js} +1 -1
- package/assets/{ReownAuthentication-e5d1d4cc.js → ReownAuthentication-c1098727.js} +1 -1
- package/assets/{SwapController-f47e6f17.js → SwapController-6f3f28da.js} +1 -1
- package/assets/{UserAvatar-0c19fd64.js → UserAvatar-4217a7be.js} +1 -1
- package/assets/{W3MFrameProviderSingleton-33e9645e.js → W3MFrameProviderSingleton-316899f0.js} +2 -2
- package/assets/{basic-509eb412.js → basic-d9c0f288.js} +1 -1
- package/assets/{biconomy-6fa3eb98.js → biconomy-bc04f7cc.js} +1 -1
- package/assets/{ccip-040f274b.js → ccip-d88eddf3.js} +1 -1
- package/assets/{ccip-6d1e4a15.js → ccip-e509a2bd.js} +1 -1
- package/assets/{chains-bae55e5f.js → chains-12910e1f.js} +1 -1
- package/assets/{common-f2e88a7e.js → common-583dfda9.js} +1 -1
- package/assets/{compat-b432550d.js → compat-000e5801.js} +1 -1
- package/assets/{controller-83cf739b.js → controller-5a843a75.js} +1 -1
- package/assets/{core-71a03396.js → core-1a166f08.js} +3 -3
- package/assets/{custom-7ae31f11.js → custom-3c5e7814.js} +1 -1
- package/assets/{data-capture-f1f485c2.js → data-capture-a27f6e5c.js} +1 -1
- package/assets/decimals-50f9fee1.js +1 -0
- package/assets/{decimals-9d5fec14.js → decimals-bddbc743.js} +1 -1
- package/assets/{email-be31d86e.js → email-0c5024d9.js} +1 -1
- package/assets/{embedded-wallet-41341ab4.js → embedded-wallet-d5992bd8.js} +1 -1
- package/assets/{engine-8d2b111b.js → engine-9b39863f.js} +1 -1
- package/assets/{estimate-l1-fee-8acb8860.js → estimate-l1-fee-69110584.js} +1 -1
- package/assets/eth_estimateGas-945ce595.js +1 -0
- package/assets/{eth_getStorageAt-2d8a4700.js → eth_getStorageAt-125a2bc1.js} +1 -1
- package/assets/{eth_getTransactionCount-273004ec.js → eth_getTransactionCount-6240f912.js} +1 -1
- package/assets/{ethereum-667be7dc.js → ethereum-0d579241.js} +1 -1
- package/assets/{execute-6c88dd5f.js → execute-264a98ed.js} +1 -1
- package/assets/{extractIPFS-640303a3.js → extractIPFS-d48a2b7b.js} +1 -1
- package/assets/features-7c8dc530.js +1 -0
- package/assets/{fetchTokenMetadata-1e138f21.js → fetchTokenMetadata-f32fb87e.js} +1 -1
- package/assets/{fortmatic-d34f42c3.js → fortmatic-5f1bb82e.js} +1 -1
- package/assets/{get-bytecode-8cb4e224.js → get-bytecode-7a8c6215.js} +1 -1
- package/assets/{get-ecosystem-wallet-info-ec712acc.js → get-ecosystem-wallet-info-0a9d1fa7.js} +1 -1
- package/assets/{getBalance-0308f38f.js → getBalance-e2e6d859.js} +1 -1
- package/assets/{getInstalledModules-17fa1a09.js → getInstalledModules-4e23fa8a.js} +1 -1
- package/assets/{getNFT-06eb1406.js → getNFT-5486b2f7.js} +1 -1
- package/assets/{getNFT-30795fe1.js → getNFT-74f5ae81.js} +1 -1
- package/assets/{hashBytecode-a29db705.js → hashBytecode-7a0e56f5.js} +1 -1
- package/assets/{hashTypedData-23a00dc9.js → hashTypedData-03b693eb.js} +1 -1
- package/assets/{hashTypedData-ba8e399b.js → hashTypedData-cc1589a7.js} +1 -1
- package/assets/{in-app-9acc158b.js → in-app-1d212717.js} +1 -1
- package/assets/{in-app-wallet-calls-48ca2694.js → in-app-wallet-calls-7fdb5823.js} +1 -1
- package/assets/{index-89cbc69d.js → index-06d7a58c.js} +1 -1
- package/assets/{index-355751ab.js → index-10c73e9d.js} +245 -245
- package/assets/{index-9ecf773e.js → index-19891b89.js} +1 -1
- package/assets/{index-2ebd7a81.js → index-206ffe7d.js} +1 -1
- package/assets/{index-f4401a12.js → index-20b33848.js} +1 -1
- package/assets/{index-6e64d31e.js → index-23dd6251.js} +2 -2
- package/assets/{index-2124b7cd.js → index-2cab452e.js} +1 -1
- package/assets/{index-9c2f8893.js → index-2f82abe0.js} +1 -1
- package/assets/{index-a5c29e80.js → index-30a8f53e.js} +1 -1
- package/assets/{index-4bc8eee8.js → index-31022e63.js} +1 -1
- package/assets/{index-a5876580.js → index-32a45902.js} +1 -1
- package/assets/{index-b7605561.js → index-3b678484.js} +1 -1
- package/assets/{index-3cdab001.js → index-3bc5c9df.js} +1 -1
- package/assets/{index-d7ed4af8.js → index-3d19d06c.js} +1 -1
- package/assets/{index-1368749b.js → index-401eba13.js} +1 -1
- package/assets/{index-f4841b7d.js → index-5071722a.js} +1 -1
- package/assets/{index-e7f3149f.css → index-59db4a58.css} +4 -4
- package/assets/{index-e6ba4bbe.js → index-5d7b6c51.js} +1 -1
- package/assets/{index-78689969.js → index-5ece9033.js} +1 -1
- package/assets/{index-33bd3c33.js → index-610c7efb.js} +1 -1
- package/assets/{index-a91bb597.js → index-69a0492a.js} +1 -1
- package/assets/{index-76dbec48.js → index-6d8da0b7.js} +1 -1
- package/assets/{index-863b5c53.js → index-6ec6d7c7.js} +1 -1
- package/assets/{index-ec8cf158.js → index-780a2232.js} +1 -1
- package/assets/{index-b40ed19e.js → index-7ad05b06.js} +1 -1
- package/assets/{index-e332724b.js → index-7f01a27a.js} +1 -1
- package/assets/{index-69ac8519.js → index-877ffe4a.js} +1 -1
- package/assets/{index-e6d2ed90.js → index-8aeaab91.js} +1 -1
- package/assets/{index-66d53073.js → index-8cbb4ff7.js} +2 -2
- package/assets/{index-e2d1a06e.js → index-8d81098b.js} +1 -1
- package/assets/{index-3ad96675.js → index-8fa35f13.js} +1 -1
- package/assets/{index-5f847edd.js → index-93724bad.js} +2 -2
- package/assets/index-9bee2cc7.js +77 -0
- package/assets/{index-2e071cd2.js → index-9d37fa54.js} +1 -1
- package/assets/{index-57dbcd5d.js → index-a151f6d7.js} +1 -1
- package/assets/{index-54323fc3.js → index-a22875e4.js} +2 -2
- package/assets/{index-d7bf28d3.js → index-a69ba1cc.js} +1 -1
- package/assets/{index-6c8c5091.js → index-a6a44c61.js} +1 -1
- package/assets/{index-b41b719c.js → index-aae2726c.js} +1 -1
- package/assets/{index-8bdd54b7.js → index-ad63abcf.js} +1 -1
- package/assets/{index-375e28ad.js → index-b3691f6b.js} +1 -1
- package/assets/{index-276c1c99.js → index-b3889ac8.js} +1 -1
- package/assets/{index-2537319c.js → index-bb13bbcd.js} +1 -1
- package/assets/{index-05f3c18a.js → index-bcedc0e6.js} +1 -1
- package/assets/{index-9e3730d4.js → index-c49dee70.js} +1 -1
- package/assets/{index-c7839713.js → index-cafc0996.js} +1 -1
- package/assets/{index-1c9749d2.js → index-d22cfc35.js} +1 -1
- package/assets/{index-9c119afb.js → index-d2f37bee.js} +1 -1
- package/assets/{index-ffdeacb2.js → index-d44b19e2.js} +1 -1
- package/assets/{index-8b5a06dd.js → index-d77a63d3.js} +1 -1
- package/assets/{index-ab687c6f.js → index-e332040b.js} +1 -1
- package/assets/{index-5b4e7208.js → index-e583ff4e.js} +1 -1
- package/assets/{index-5947dd15.js → index-e9ab8876.js} +1 -1
- package/assets/{index-3c50ab3b.js → index-f49c89c1.js} +1 -1
- package/assets/{index-3d2bada3.js → index-fe892b11.js} +1 -1
- package/assets/{index.es-2aacf970.js → index.es-0f7943d8.js} +1 -1
- package/assets/{index.es-ce0aa5fd.js → index.es-30a0ec70.js} +3 -3
- package/assets/{index.es-ac60fff2.js → index.es-4520fb10.js} +1 -1
- package/assets/{index.web-1837e57d.js → index.web-e2526e19.js} +1 -1
- package/assets/{localBatchGatewayRequest-b2e2be89.js → localBatchGatewayRequest-ff5d42f6.js} +1 -1
- package/assets/{native-8dd45a06.js → native-3e8a86bb.js} +1 -1
- package/assets/{networks-2b49f856.js → networks-fc1b1902.js} +1 -1
- package/assets/{onramp-7ba26b97.js → onramp-cf41485f.js} +1 -1
- package/assets/{openzeppelin-56d83a0f.js → openzeppelin-e72c7daa.js} +1 -1
- package/assets/{ownerOf-558180d2.js → ownerOf-c09a8f45.js} +1 -1
- package/assets/parseNft-147a451f.js +1 -0
- package/assets/{parseSignature-16c7c561.js → parseSignature-6b0b4698.js} +2 -2
- package/assets/{parseSignature-7a759338.js → parseSignature-b975d9a6.js} +1 -1
- package/assets/{passkeys-fd92f407.js → passkeys-bb25d43e.js} +1 -1
- package/assets/{pay-with-exchange-542b5282.js → pay-with-exchange-cd96ece6.js} +1 -1
- package/assets/{prepare-contract-call-ac31a985.js → prepare-contract-call-4be4cc68.js} +1 -1
- package/assets/{qr-overlay-548b2074.js → qr-overlay-fd67e1ca.js} +1 -1
- package/assets/{receive-9119a0fc.js → receive-9ddd4e2d.js} +1 -1
- package/assets/{redirect-state-202ec690.js → redirect-state-301cb22c.js} +1 -1
- package/assets/{resolveImplementation-ffd32467.js → resolveImplementation-6b55308f.js} +1 -1
- package/assets/{rpc-4fa5fbde.js → rpc-83ca4b71.js} +1 -1
- package/assets/{secp256k1-61174a68.js → secp256k1-44255658.js} +1 -1
- package/assets/{secp256k1-587b447b.js → secp256k1-4ab38443.js} +1 -1
- package/assets/{secp256k1-2e39eaab.js → secp256k1-ac683ebc.js} +1 -1
- package/assets/{send-5e9549ca.js → send-7e34f1e6.js} +1 -1
- package/assets/{send-batch-transaction-16b5b747.js → send-batch-transaction-429c82ee.js} +1 -1
- package/assets/{send-eip712-transaction-67b51817.js → send-eip712-transaction-20a9b9ed.js} +1 -1
- package/assets/send-gasless-transaction-0435da18.js +1 -0
- package/assets/{send-transaction-5984dc09.js → send-transaction-c3053b90.js} +1 -1
- package/assets/{session-proposal-548687be.js → session-proposal-d1473b74.js} +1 -1
- package/assets/{session-request-543a34de.js → session-request-f0a8f695.js} +1 -1
- package/assets/{sha256-865a5e2e.js → sha256-937f482f.js} +1 -1
- package/assets/{signing-67cb53a5.js → signing-6d6682ec.js} +2 -2
- package/assets/{socials-1c5f45aa.js → socials-d1713bee.js} +1 -1
- package/assets/{swaps-a0b58cae.js → swaps-8bad12fe.js} +1 -1
- package/assets/{thirdweb-d54893e0.js → thirdweb-73096eef.js} +2 -2
- package/assets/{to-serializable-transaction-2ea802ff.js → to-serializable-transaction-9e540f8c.js} +2 -2
- package/assets/{totalSupply-f714505e.js → totalSupply-7e83596b.js} +1 -1
- package/assets/{transaction-e500e7c4.js → transaction-ea614a5a.js} +1 -1
- package/assets/{transactionReceipt-c6fe2381.js → transactionReceipt-1e425ab1.js} +1 -1
- package/assets/{transactions-9a79e8f9.js → transactions-a47e2cb5.js} +1 -1
- package/assets/{tslib.es6-b444c8f1.js → tslib.es6-24024d67.js} +1 -1
- package/assets/{utils-74c631d9.js → utils-dddc86ba.js} +1 -1
- package/assets/{verifyHash-34edded7.js → verifyHash-b21b75c2.js} +1 -1
- package/assets/{w3m-modal-0795c078.js → w3m-modal-e914d462.js} +1 -1
- package/assets/{w3m-modal-906aa735.js → w3m-modal-ff2f112d.js} +1 -1
- package/assets/{wait-for-tx-receipt-dbf6b521.js → wait-for-tx-receipt-50389b4e.js} +1 -1
- package/assets/{wallets-331c410d.js → wallets-4e23dd0f.js} +4 -4
- package/assets/{web-connector-3a1204fd.js → web-connector-351693f5.js} +2 -2
- package/assets/{writeContract-f6b81199.js → writeContract-03e44e49.js} +2 -2
- package/assets/{zora-sepolia-eaf59a0b.js → zora-sepolia-72e60034.js} +1 -1
- package/assets/{zoraTestnet-55836178.js → zoraTestnet-1485f0af.js} +1 -1
- package/index.html +4 -4
- package/package.json +3 -3
- package/assets/decimals-37678a25.js +0 -1
- package/assets/eth_estimateGas-79dc1763.js +0 -1
- package/assets/features-0025dc16.js +0 -1
- package/assets/index-7ee82e4f.js +0 -77
- package/assets/parseNft-93d99682.js +0 -1
- package/assets/send-gasless-transaction-8bdf3649.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{_ as Ea,b as zi,a as B,B as Ie,g as ch,e as St,N as tn}from"./index-
|
|
2
|
-
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Pa}walk(e){return $a(this,e)}}function $a(i,e){return e!=null&&e(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?$a(i.cause,e):e?null:i}class Sa extends Ft{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 Si(i,{dir:e,size:t=32}={}){return typeof i=="string"?vh(i,{dir:e,size:t}):Eh(i,{dir:e,size:t})}function vh(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new Sa({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function Eh(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new Sa({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 Ih extends Ft{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 _h extends Ft{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Oi(i,{size:e}){if(En(i)>e)throw new _h({givenSize:En(i),maxSize:e})}function $r(i,e={}){const{signed:t}=e;e.size&&Oi(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 Ph(i,e={}){return Number($r(i,e))}const $h=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Sr(i,e={}){return typeof i=="number"||typeof i=="bigint"?xa(i,e):typeof i=="string"?xh(i,e):typeof i=="boolean"?Sh(i,e):Oa(i,e)}function Sh(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(Oi(t,{size:e.size}),Si(t,{size:e.size})):t}function Oa(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=$h[i[r]];const s=`0x${t}`;return typeof e.size=="number"?(Oi(s,{size:e.size}),Si(s,{dir:"right",size:e.size})):s}function xa(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 Ih({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?Si(a,{size:s}):a}const Oh=new TextEncoder;function xh(i,e={}){const t=Oh.encode(i);return Oa(t,e)}const Ah=new TextEncoder;function Ch(i,e={}){return typeof i=="number"||typeof i=="bigint"?Nh(i,e):typeof i=="boolean"?Th(i,e):Wi(i)?Aa(i,e):Ca(i,e)}function Th(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(Oi(t,{size:e.size}),Si(t,{size:e.size})):t}const lt={zero:48,nine:57,A:65,F:70,a:97,f:102};function In(i){if(i>=lt.zero&&i<=lt.nine)return i-lt.zero;if(i>=lt.A&&i<=lt.F)return i-(lt.A-10);if(i>=lt.a&&i<=lt.f)return i-(lt.a-10)}function Aa(i,e={}){let t=i;e.size&&(Oi(t,{size:e.size}),t=Si(t,{dir:"right",size:e.size}));let s=t.slice(2);s.length%2&&(s=`0${s}`);const r=s.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=In(s.charCodeAt(a++)),h=In(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new Ft(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function Nh(i,e){const t=xa(i,e);return Aa(t)}function Ca(i,e={}){const t=Ah.encode(i);return typeof e.size=="number"?(Oi(t,{size:e.size}),Si(t,{dir:"right",size:e.size})):t}function xs(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Rh(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Us(i,...e){if(!Rh(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 Yv(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");xs(i.outputLen),xs(i.blockLen)}function _n(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function qh(i,e){Us(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),Pn=BigInt(32);function jh(i,e=!1){return e?{h:Number(i&ps),l:Number(i>>Pn&ps)}:{h:Number(i>>Pn&ps)|0,l:Number(i&ps)|0}}function kh(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}=jh(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Dh=(i,e,t)=>i<<t|e>>>32-t,Lh=(i,e,t)=>e<<t|i>>>32-t,Fh=(i,e,t)=>e<<t-32|i>>>64-t,Uh=(i,e,t)=>i<<t-32|e>>>64-t,Ht=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Mh(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Zv(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Xv(i,e){return i<<32-e|i>>>e}const $n=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Bh(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Sn(i){for(let e=0;e<i.length;e++)i[e]=Bh(i[e])}function zh(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Ta(i){return typeof i=="string"&&(i=zh(i)),Us(i),i}function e1(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Us(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 Vh{clone(){return this._cloneInto()}}function Hh(i){const e=s=>i().update(Ta(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function t1(i=32){if(Ht&&typeof Ht.getRandomValues=="function")return Ht.getRandomValues(new Uint8Array(i));if(Ht&&typeof Ht.randomBytes=="function")return Ht.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Na=[],Ra=[],qa=[],Kh=BigInt(0),Ri=BigInt(1),Gh=BigInt(2),Wh=BigInt(7),Jh=BigInt(256),Qh=BigInt(113);for(let i=0,e=Ri,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Na.push(2*(5*s+t)),Ra.push((i+1)*(i+2)/2%64);let r=Kh;for(let n=0;n<7;n++)e=(e<<Ri^(e>>Wh)*Qh)%Jh,e&Gh&&(r^=Ri<<(Ri<<BigInt(n))-Ri);qa.push(r)}const[Yh,Zh]=kh(qa,!0),On=(i,e,t)=>t>32?Fh(i,e,t):Dh(i,e,t),xn=(i,e,t)=>t>32?Uh(i,e,t):Lh(i,e,t);function Xh(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=On(h,l,1)^t[a],p=xn(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Ra[o],c=On(r,n,a),h=xn(r,n,a),l=Na[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]^=Yh[s],i[1]^=Zh[s]}t.fill(0)}class nn extends Vh{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,xs(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Mh(this.state)}keccak(){$n||Sn(this.state32),Xh(this.state32,this.rounds),$n||Sn(this.state32),this.posOut=0,this.pos=0}update(e){_n(this);const{blockLen:t,state:s}=this;e=Ta(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&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){_n(this,!1),Us(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return xs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(qh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new nn(t,s,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const el=(i,e,t)=>Hh(()=>new nn(e,i,t)),tl=el(1,136,256/8);function ja(i,e){const t=e||"hex",s=tl(Wi(i,{strict:!1})?Ch(i):i);return t==="bytes"?s:Sr(s)}class il 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 il(8192);function sl(i,e){if(Zs.has(`${i}.${e}`))return Zs.get(`${i}.${e}`);const t=e?`${e}${i.toLowerCase()}`:i.substring(2).toLowerCase(),s=ja(Ca(t),"bytes"),r=(e?t.substring(`${e}0x`.length):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 rl(i){const e=ja(`0x${i.substring(4)}`).substring(26);return sl(`0x${e}`)}async function nl({hash:i,signature:e}){const t=Wi(i)?i:Sr(i),{secp256k1:s}=await Ea(()=>import("./secp256k1-2e39eaab.js"),["assets/secp256k1-2e39eaab.js","assets/index-355751ab.js","assets/index-e7f3149f.css","assets/index-276c1c99.js","assets/index-accd8060.js","assets/index-2124b7cd.js","assets/index-6ab757a5.js","assets/index.es-ac60fff2.js"]);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:u,yParity:p}=e,g=Number(p??u),d=An(g);return new s.Signature($r(h),$r(l)).addRecoveryBit(d)}const o=Wi(e)?e:Sr(e),a=Ph(`0x${o.slice(130)}`),c=An(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function An(i){if(i===0||i===1)return i;if(i===27)return 0;if(i===28)return 1;throw new Error("Invalid yParityOrV value")}async function ol({hash:i,signature:e}){return rl(await nl({hash:i,signature:e}))}function ka(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Vi(i,e){e||(e=i.reduce((r,n)=>r+n.length,0));const t=ka(e);let s=0;for(const r of i)t.set(r,s),s+=r.length;return t}function Da(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Cn=Da("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Xs=Da("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=ka(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),La={utf8:Cn,"utf-8":Cn,hex:wn.base16,latin1:Xs,ascii:Xs,binary:Xs,...wn};function Me(i,e="utf8"){const t=La[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 Ae(i,e="utf8"){const t=La[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)}const al=":";function fi(i){const[e,t]=i.split(al);return{namespace:e,reference:t}}function Tn(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 Fa(i,e){return i.includes(":")?[i]:e.chains||[]}var cl=Object.defineProperty,hl=Object.defineProperties,ll=Object.getOwnPropertyDescriptors,Nn=Object.getOwnPropertySymbols,ul=Object.prototype.hasOwnProperty,pl=Object.prototype.propertyIsEnumerable,Rn=(i,e,t)=>e in i?cl(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qn=(i,e)=>{for(var t in e||(e={}))ul.call(e,t)&&Rn(i,t,e[t]);if(Nn)for(var t of Nn(e))pl.call(e,t)&&Rn(i,t,e[t]);return i},dl=(i,e)=>hl(i,ll(e));const gl="ReactNative",ke={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},fl="js";function As(){return typeof zi<"u"&&typeof zi.versions<"u"&&typeof zi.versions.node<"u"}function Ot(){return!yi()&&!!Ia()&&navigator.product===gl}function yl(){return Ot()&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"&&(B==null?void 0:B.Platform.OS)==="android"}function ml(){return Ot()&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"&&(B==null?void 0:B.Platform.OS)==="ios"}function xi(){return!As()&&!!Ia()&&!!yi()}function is(){return Ot()?ke.reactNative:As()?ke.node:xi()?ke.browser:ke.unknown}function jn(){var i;try{return Ot()&&typeof B<"u"&&typeof(B==null?void 0:B.Application)<"u"?(i=B.Application)==null?void 0:i.applicationId:void 0}catch{return}}function wl(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 bl(i){var e,t;const s=Ua();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!=="")),dl(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 Ua(){return hh()||{name:"",description:"",url:"",icons:[""]}}function vl(){if(is()===ke.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 El(){var i;const e=is();return e===ke.browser?[e,((i=ph())==null?void 0:i.host)||"unknown"].join(":"):e}function Ma(i,e,t){const s=vl(),r=El();return[[i,e].join("-"),[fl,t].join("-"),s,r].join("/")}function Il({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Ma(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},p=wl(h[1]||"",u);return h[0]+"?"+p}function Dt(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 Tt(i=C.FIVE_MINUTES,e){const t=C.toMiliseconds(i||C.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 Ba(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 _l(i){return Ba("topic",i)}function Pl(i){return Ba("id",i)}function za(i){const[e,t]=i.split(":"),s={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")s.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))s.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return s}function ce(i,e){return C.fromMiliseconds((e||Date.now())+C.toMiliseconds(i))}function Et(i){return Date.now()>=C.toMiliseconds(i)}function J(i,e){return`${i}${e?`:${e}`:""}`}function rt(i=[],e=[]){return[...new Set([...i,...e])]}async function $l({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=Sl(n,i,e),a=is();if(a===ke.browser){if(!((s=yi())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Ol(o)}else a===ke.reactNative&&typeof(B==null?void 0:B.Linking)<"u"&&await B.Linking.openURL(o)}catch(r){console.error(r)}}function Sl(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}${Tl(s,!0)}`}else r=`${r}/wc?${s}`;return r}function Ol(i){let e="_self";Cl()?e="_top":(Al()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function xl(i,e){let t="";try{if(xi()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function kn(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function Dn(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function on(){return typeof zi<"u"&&{}.IS_VITEST==="true"}function Al(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Cl(){try{return window.self!==window.top}catch{return!1}}function Tl(i,e=!1){const t=Ie.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Va(i){return Ie.from(i,"base64").toString("utf-8")}function Nl(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 Rl(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ss(i,...e){if(!Rl(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function an(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");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 Ha(i,e){ss(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ds=BigInt(2**32-1),Ln=BigInt(32);function ql(i,e=!1){return e?{h:Number(i&ds),l:Number(i>>Ln&ds)}:{h:Number(i>>Ln&ds)|0,l:Number(i&ds)|0}}function jl(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}=ql(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const kl=(i,e,t)=>i<<t|e>>>32-t,Dl=(i,e,t)=>e<<t|i>>>32-t,Ll=(i,e,t)=>e<<t-32|i>>>64-t,Fl=(i,e,t)=>i<<t-32|e>>>64-t,Kt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Ul(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 Ze(i,e){return i<<32-e|i>>>e}const Fn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ml(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Un(i){for(let e=0;e<i.length;e++)i[e]=Ml(i[e])}function Bl(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function wi(i){return typeof i=="string"&&(i=Bl(i)),ss(i),i}function zl(...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}let cn=class{clone(){return this._cloneInto()}};function Ka(i){const e=s=>i().update(wi(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Ai(i=32){if(Kt&&typeof Kt.getRandomValues=="function")return Kt.getRandomValues(new Uint8Array(i));if(Kt&&typeof Kt.randomBytes=="function")return Kt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Ga=[],Wa=[],Ja=[],Vl=BigInt(0),qi=BigInt(1),Hl=BigInt(2),Kl=BigInt(7),Gl=BigInt(256),Wl=BigInt(113);for(let i=0,e=qi,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Ga.push(2*(5*s+t)),Wa.push((i+1)*(i+2)/2%64);let r=Vl;for(let n=0;n<7;n++)e=(e<<qi^(e>>Kl)*Wl)%Gl,e&Hl&&(r^=qi<<(qi<<BigInt(n))-qi);Ja.push(r)}const[Jl,Ql]=jl(Ja,!0),Mn=(i,e,t)=>t>32?Ll(i,e,t):kl(i,e,t),Bn=(i,e,t)=>t>32?Fl(i,e,t):Dl(i,e,t);function Yl(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=Mn(h,l,1)^t[a],p=Bn(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Wa[o],c=Mn(r,n,a),h=Bn(r,n,a),l=Ga[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]^=Jl[s],i[1]^=Ql[s]}t.fill(0)}let Zl=class Qa extends cn{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Ji(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Ul(this.state)}keccak(){Fn||Un(this.state32),Yl(this.state32,this.rounds),Fn||Un(this.state32),this.posOut=0,this.pos=0}update(e){mi(this);const{blockLen:t,state:s}=this;e=wi(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&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){mi(this,!1),ss(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(Ha(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 Qa(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 Xl=(i,e,t)=>Ka(()=>new Zl(e,i,t)),eu=Xl(1,136,256/8),tu="https://rpc.walletconnect.org/v1";function Ya(i){const e=`Ethereum Signed Message:
|
|
1
|
+
import{_ as Ea,b as zi,a as B,B as Ie,g as ch,e as St,N as tn}from"./index-10c73e9d.js";import{d as wn,g as hh,e as C,h as yi,j as Ia,k as lh,l as uh,m as ph,n as _r,C as dh,s as Pr,I as Pi,q as gh,r as fh,o as Be,t as yh,u as sn,v as rn,b as Fs,w as $i,c as kt,P as bn,Q as mh,x as wh,a as vn,y as ui,f as _a,z as pt,A as it,B as wt}from"./index-b3889ac8.js";import{q as bh}from"./index-6ab757a5.js";import"./index-2cab452e.js";import{f as Qe}from"./index.es-4520fb10.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 En(i){return Wi(i,{strict:!1})?Math.ceil((i.length-2)/2):i.length}const Pa="2.23.2";let Ni={getDocsUrl:({docsBaseUrl:i,docsPath:e="",docsSlug:t})=>e?`${i??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${Pa}`};class Ft extends Error{constructor(e,t={}){var a;const s=(()=>{var c;return t.cause instanceof Ft?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),r=(()=>t.cause instanceof Ft&&t.cause.docsPath||t.docsPath)(),n=(a=Ni.getDocsUrl)==null?void 0:a.call(Ni,{...t,docsPath:r}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...s?[`Details: ${s}`]:[],...Ni.version?[`Version: ${Ni.version}`]:[]].join(`
|
|
2
|
+
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Pa}walk(e){return $a(this,e)}}function $a(i,e){return e!=null&&e(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?$a(i.cause,e):e?null:i}class Sa extends Ft{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 Si(i,{dir:e,size:t=32}={}){return typeof i=="string"?vh(i,{dir:e,size:t}):Eh(i,{dir:e,size:t})}function vh(i,{dir:e,size:t=32}={}){if(t===null)return i;const s=i.replace("0x","");if(s.length>t*2)throw new Sa({size:Math.ceil(s.length/2),targetSize:t,type:"hex"});return`0x${s[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function Eh(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new Sa({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 Ih extends Ft{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 _h extends Ft{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Oi(i,{size:e}){if(En(i)>e)throw new _h({givenSize:En(i),maxSize:e})}function $r(i,e={}){const{signed:t}=e;e.size&&Oi(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 Ph(i,e={}){return Number($r(i,e))}const $h=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Sr(i,e={}){return typeof i=="number"||typeof i=="bigint"?xa(i,e):typeof i=="string"?xh(i,e):typeof i=="boolean"?Sh(i,e):Oa(i,e)}function Sh(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(Oi(t,{size:e.size}),Si(t,{size:e.size})):t}function Oa(i,e={}){let t="";for(let r=0;r<i.length;r++)t+=$h[i[r]];const s=`0x${t}`;return typeof e.size=="number"?(Oi(s,{size:e.size}),Si(s,{dir:"right",size:e.size})):s}function xa(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 Ih({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?Si(a,{size:s}):a}const Oh=new TextEncoder;function xh(i,e={}){const t=Oh.encode(i);return Oa(t,e)}const Ah=new TextEncoder;function Ch(i,e={}){return typeof i=="number"||typeof i=="bigint"?Nh(i,e):typeof i=="boolean"?Th(i,e):Wi(i)?Aa(i,e):Ca(i,e)}function Th(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(Oi(t,{size:e.size}),Si(t,{size:e.size})):t}const lt={zero:48,nine:57,A:65,F:70,a:97,f:102};function In(i){if(i>=lt.zero&&i<=lt.nine)return i-lt.zero;if(i>=lt.A&&i<=lt.F)return i-(lt.A-10);if(i>=lt.a&&i<=lt.f)return i-(lt.a-10)}function Aa(i,e={}){let t=i;e.size&&(Oi(t,{size:e.size}),t=Si(t,{dir:"right",size:e.size}));let s=t.slice(2);s.length%2&&(s=`0${s}`);const r=s.length/2,n=new Uint8Array(r);for(let o=0,a=0;o<r;o++){const c=In(s.charCodeAt(a++)),h=In(s.charCodeAt(a++));if(c===void 0||h===void 0)throw new Ft(`Invalid byte sequence ("${s[a-2]}${s[a-1]}" in "${s}").`);n[o]=c*16+h}return n}function Nh(i,e){const t=xa(i,e);return Aa(t)}function Ca(i,e={}){const t=Ah.encode(i);return typeof e.size=="number"?(Oi(t,{size:e.size}),Si(t,{dir:"right",size:e.size})):t}function xs(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Rh(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Us(i,...e){if(!Rh(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 Yv(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");xs(i.outputLen),xs(i.blockLen)}function _n(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function qh(i,e){Us(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),Pn=BigInt(32);function jh(i,e=!1){return e?{h:Number(i&ps),l:Number(i>>Pn&ps)}:{h:Number(i>>Pn&ps)|0,l:Number(i&ps)|0}}function kh(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}=jh(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const Dh=(i,e,t)=>i<<t|e>>>32-t,Lh=(i,e,t)=>e<<t|i>>>32-t,Fh=(i,e,t)=>e<<t-32|i>>>64-t,Uh=(i,e,t)=>i<<t-32|e>>>64-t,Ht=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Mh(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function Zv(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function Xv(i,e){return i<<32-e|i>>>e}const $n=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Bh(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Sn(i){for(let e=0;e<i.length;e++)i[e]=Bh(i[e])}function zh(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Ta(i){return typeof i=="string"&&(i=zh(i)),Us(i),i}function e1(...i){let e=0;for(let s=0;s<i.length;s++){const r=i[s];Us(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 Vh{clone(){return this._cloneInto()}}function Hh(i){const e=s=>i().update(Ta(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function t1(i=32){if(Ht&&typeof Ht.getRandomValues=="function")return Ht.getRandomValues(new Uint8Array(i));if(Ht&&typeof Ht.randomBytes=="function")return Ht.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Na=[],Ra=[],qa=[],Kh=BigInt(0),Ri=BigInt(1),Gh=BigInt(2),Wh=BigInt(7),Jh=BigInt(256),Qh=BigInt(113);for(let i=0,e=Ri,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Na.push(2*(5*s+t)),Ra.push((i+1)*(i+2)/2%64);let r=Kh;for(let n=0;n<7;n++)e=(e<<Ri^(e>>Wh)*Qh)%Jh,e&Gh&&(r^=Ri<<(Ri<<BigInt(n))-Ri);qa.push(r)}const[Yh,Zh]=kh(qa,!0),On=(i,e,t)=>t>32?Fh(i,e,t):Dh(i,e,t),xn=(i,e,t)=>t>32?Uh(i,e,t):Lh(i,e,t);function Xh(i,e=24){const t=new Uint32Array(10);for(let s=24-e;s<24;s++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],l=t[c+1],u=On(h,l,1)^t[a],p=xn(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Ra[o],c=On(r,n,a),h=xn(r,n,a),l=Na[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]^=Yh[s],i[1]^=Zh[s]}t.fill(0)}class nn extends Vh{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,xs(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Mh(this.state)}keccak(){$n||Sn(this.state32),Xh(this.state32,this.rounds),$n||Sn(this.state32),this.posOut=0,this.pos=0}update(e){_n(this);const{blockLen:t,state:s}=this;e=Ta(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&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){_n(this,!1),Us(e),this.finish();const t=this.state,{blockLen:s}=this;for(let r=0,n=e.length;r<n;){this.posOut>=s&&this.keccak();const o=Math.min(s-this.posOut,n-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return xs(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(qh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:s,outputLen:r,rounds:n,enableXOF:o}=this;return e||(e=new nn(t,s,r,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=s,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}const el=(i,e,t)=>Hh(()=>new nn(e,i,t)),tl=el(1,136,256/8);function ja(i,e){const t=e||"hex",s=tl(Wi(i,{strict:!1})?Ch(i):i);return t==="bytes"?s:Sr(s)}class il 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 il(8192);function sl(i,e){if(Zs.has(`${i}.${e}`))return Zs.get(`${i}.${e}`);const t=e?`${e}${i.toLowerCase()}`:i.substring(2).toLowerCase(),s=ja(Ca(t),"bytes"),r=(e?t.substring(`${e}0x`.length):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 rl(i){const e=ja(`0x${i.substring(4)}`).substring(26);return sl(`0x${e}`)}async function nl({hash:i,signature:e}){const t=Wi(i)?i:Sr(i),{secp256k1:s}=await Ea(()=>import("./secp256k1-ac683ebc.js"),["assets/secp256k1-ac683ebc.js","assets/index-10c73e9d.js","assets/index-59db4a58.css","assets/index-b3889ac8.js","assets/index-accd8060.js","assets/index-2cab452e.js","assets/index-6ab757a5.js","assets/index.es-4520fb10.js"]);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:u,yParity:p}=e,g=Number(p??u),d=An(g);return new s.Signature($r(h),$r(l)).addRecoveryBit(d)}const o=Wi(e)?e:Sr(e),a=Ph(`0x${o.slice(130)}`),c=An(a);return s.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function An(i){if(i===0||i===1)return i;if(i===27)return 0;if(i===28)return 1;throw new Error("Invalid yParityOrV value")}async function ol({hash:i,signature:e}){return rl(await nl({hash:i,signature:e}))}function ka(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Vi(i,e){e||(e=i.reduce((r,n)=>r+n.length,0));const t=ka(e);let s=0;for(const r of i)t.set(r,s),s+=r.length;return t}function Da(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Cn=Da("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Xs=Da("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=ka(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),La={utf8:Cn,"utf-8":Cn,hex:wn.base16,latin1:Xs,ascii:Xs,binary:Xs,...wn};function Me(i,e="utf8"){const t=La[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 Ae(i,e="utf8"){const t=La[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)}const al=":";function fi(i){const[e,t]=i.split(al);return{namespace:e,reference:t}}function Tn(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 Fa(i,e){return i.includes(":")?[i]:e.chains||[]}var cl=Object.defineProperty,hl=Object.defineProperties,ll=Object.getOwnPropertyDescriptors,Nn=Object.getOwnPropertySymbols,ul=Object.prototype.hasOwnProperty,pl=Object.prototype.propertyIsEnumerable,Rn=(i,e,t)=>e in i?cl(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,qn=(i,e)=>{for(var t in e||(e={}))ul.call(e,t)&&Rn(i,t,e[t]);if(Nn)for(var t of Nn(e))pl.call(e,t)&&Rn(i,t,e[t]);return i},dl=(i,e)=>hl(i,ll(e));const gl="ReactNative",ke={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},fl="js";function As(){return typeof zi<"u"&&typeof zi.versions<"u"&&typeof zi.versions.node<"u"}function Ot(){return!yi()&&!!Ia()&&navigator.product===gl}function yl(){return Ot()&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"&&(B==null?void 0:B.Platform.OS)==="android"}function ml(){return Ot()&&typeof B<"u"&&typeof(B==null?void 0:B.Platform)<"u"&&(B==null?void 0:B.Platform.OS)==="ios"}function xi(){return!As()&&!!Ia()&&!!yi()}function is(){return Ot()?ke.reactNative:As()?ke.node:xi()?ke.browser:ke.unknown}function jn(){var i;try{return Ot()&&typeof B<"u"&&typeof(B==null?void 0:B.Application)<"u"?(i=B.Application)==null?void 0:i.applicationId:void 0}catch{return}}function wl(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 bl(i){var e,t;const s=Ua();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!=="")),dl(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 Ua(){return hh()||{name:"",description:"",url:"",icons:[""]}}function vl(){if(is()===ke.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 El(){var i;const e=is();return e===ke.browser?[e,((i=ph())==null?void 0:i.host)||"unknown"].join(":"):e}function Ma(i,e,t){const s=vl(),r=El();return[[i,e].join("-"),[fl,t].join("-"),s,r].join("/")}function Il({protocol:i,version:e,relayUrl:t,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),l=Ma(i,e,s),u={auth:r,ua:l,projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},p=wl(h[1]||"",u);return h[0]+"?"+p}function Dt(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 Tt(i=C.FIVE_MINUTES,e){const t=C.toMiliseconds(i||C.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 Ba(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 _l(i){return Ba("topic",i)}function Pl(i){return Ba("id",i)}function za(i){const[e,t]=i.split(":"),s={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")s.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))s.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return s}function ce(i,e){return C.fromMiliseconds((e||Date.now())+C.toMiliseconds(i))}function Et(i){return Date.now()>=C.toMiliseconds(i)}function J(i,e){return`${i}${e?`:${e}`:""}`}function rt(i=[],e=[]){return[...new Set([...i,...e])]}async function $l({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=Sl(n,i,e),a=is();if(a===ke.browser){if(!((s=yi())!=null&&s.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Ol(o)}else a===ke.reactNative&&typeof(B==null?void 0:B.Linking)<"u"&&await B.Linking.openURL(o)}catch(r){console.error(r)}}function Sl(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}${Tl(s,!0)}`}else r=`${r}/wc?${s}`;return r}function Ol(i){let e="_self";Cl()?e="_top":(Al()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function xl(i,e){let t="";try{if(xi()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(s){console.error(s)}return t}function kn(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),s=t.indexOf(e);return t[s+2]}function Dn(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function on(){return typeof zi<"u"&&{}.IS_VITEST==="true"}function Al(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Cl(){try{return window.self!==window.top}catch{return!1}}function Tl(i,e=!1){const t=Ie.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function Va(i){return Ie.from(i,"base64").toString("utf-8")}function Nl(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 Rl(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ss(i,...e){if(!Rl(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function an(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");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 Ha(i,e){ss(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const ds=BigInt(2**32-1),Ln=BigInt(32);function ql(i,e=!1){return e?{h:Number(i&ds),l:Number(i>>Ln&ds)}:{h:Number(i>>Ln&ds)|0,l:Number(i&ds)|0}}function jl(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}=ql(i[r],e);[t[r],s[r]]=[n,o]}return[t,s]}const kl=(i,e,t)=>i<<t|e>>>32-t,Dl=(i,e,t)=>e<<t|i>>>32-t,Ll=(i,e,t)=>e<<t-32|i>>>64-t,Fl=(i,e,t)=>i<<t-32|e>>>64-t,Kt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Ul(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 Ze(i,e){return i<<32-e|i>>>e}const Fn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ml(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Un(i){for(let e=0;e<i.length;e++)i[e]=Ml(i[e])}function Bl(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function wi(i){return typeof i=="string"&&(i=Bl(i)),ss(i),i}function zl(...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}let cn=class{clone(){return this._cloneInto()}};function Ka(i){const e=s=>i().update(wi(s)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Ai(i=32){if(Kt&&typeof Kt.getRandomValues=="function")return Kt.getRandomValues(new Uint8Array(i));if(Kt&&typeof Kt.randomBytes=="function")return Kt.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const Ga=[],Wa=[],Ja=[],Vl=BigInt(0),qi=BigInt(1),Hl=BigInt(2),Kl=BigInt(7),Gl=BigInt(256),Wl=BigInt(113);for(let i=0,e=qi,t=1,s=0;i<24;i++){[t,s]=[s,(2*t+3*s)%5],Ga.push(2*(5*s+t)),Wa.push((i+1)*(i+2)/2%64);let r=Vl;for(let n=0;n<7;n++)e=(e<<qi^(e>>Kl)*Wl)%Gl,e&Hl&&(r^=qi<<(qi<<BigInt(n))-qi);Ja.push(r)}const[Jl,Ql]=jl(Ja,!0),Mn=(i,e,t)=>t>32?Ll(i,e,t):kl(i,e,t),Bn=(i,e,t)=>t>32?Fl(i,e,t):Dl(i,e,t);function Yl(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=Mn(h,l,1)^t[a],p=Bn(h,l,1)^t[a+1];for(let g=0;g<50;g+=10)i[o+g]^=u,i[o+g+1]^=p}let r=i[2],n=i[3];for(let o=0;o<24;o++){const a=Wa[o],c=Mn(r,n,a),h=Bn(r,n,a),l=Ga[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]^=Jl[s],i[1]^=Ql[s]}t.fill(0)}let Zl=class Qa extends cn{constructor(e,t,s,r=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=s,this.enableXOF=r,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Ji(s),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Ul(this.state)}keccak(){Fn||Un(this.state32),Yl(this.state32,this.rounds),Fn||Un(this.state32),this.posOut=0,this.pos=0}update(e){mi(this);const{blockLen:t,state:s}=this;e=wi(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&&s===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){mi(this,!1),ss(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(Ha(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 Qa(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 Xl=(i,e,t)=>Ka(()=>new Zl(e,i,t)),eu=Xl(1,136,256/8),tu="https://rpc.walletconnect.org/v1";function Ya(i){const e=`Ethereum Signed Message:
|
|
3
3
|
${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+Ie.from(eu(t)).toString("hex")}async function iu(i,e,t,s,r,n){switch(t.t){case"eip191":return await su(i,e,t.s);case"eip1271":return await ru(i,e,t.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function su(i,e,t){return(await ol({hash:Ya(e),signature:t})).toLowerCase()===i.toLowerCase()}async function ru(i,e,t,s,r,n){const o=fi(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=Ya(e).substring(2),p=a+u+c+h+l,g=await fetch(`${n||tu}/?chainId=${s}&projectId=${r}`,{method:"POST",body:JSON.stringify({id:nu(),jsonrpc:"2.0",method:"eth_call",params:[{to:i,data:p},"latest"]})}),{result:d}=await g.json();return d?d.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function nu(){return Date.now()+Math.floor(Math.random()*1e3)}function ou(i){const e=atob(i),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const s=t[0];if(s===0)throw new Error("No signatures found");const r=1+s*64;if(t.length<r)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const n=Ie.from(i,"base64").slice(1,65);return lh.encode(n)}var au=Object.defineProperty,cu=Object.defineProperties,hu=Object.getOwnPropertyDescriptors,zn=Object.getOwnPropertySymbols,lu=Object.prototype.hasOwnProperty,uu=Object.prototype.propertyIsEnumerable,Vn=(i,e,t)=>e in i?au(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,pu=(i,e)=>{for(var t in e||(e={}))lu.call(e,t)&&Vn(i,t,e[t]);if(zn)for(var t of zn(e))uu.call(e,t)&&Vn(i,t,e[t]);return i},du=(i,e)=>cu(i,hu(e));const gu="did:pkh:",hn=i=>i==null?void 0:i.split(":"),fu=i=>{const e=i&&hn(i);if(e)return i.includes(gu)?e[3]:e[1]},Ar=i=>{const e=i&&hn(i);if(e)return e[2]+":"+e[3]},Cs=i=>{const e=i&&hn(i);if(e)return e.pop()};async function Hn(i){const{cacao:e,projectId:t}=i,{s,p:r}=e,n=Za(r,r.iss),o=Cs(r.iss);return await iu(o,n,s,Ar(r.iss),t)}const Za=(i,e)=>{const t=`${i.domain} wants you to sign in with your Ethereum account:`,s=Cs(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: ${fu(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,g=i.resources?`Resources:${i.resources.map(m=>`
|
|
4
4
|
- ${m}`).join("")}`:void 0,d=Ps(i.resources);if(d){const m=Qi(d);r=Pu(r,m)}return[t,s,"",r,"",n,o,a,c,h,l,u,p,g].filter(m=>m!=null).join(`
|
|
5
5
|
`)};function yu(i){return Ie.from(JSON.stringify(i)).toString("base64")}function mu(i){return JSON.parse(Ie.from(i,"base64").toString("utf-8"))}function Ut(i){if(!i)throw new Error("No recap provided, value is undefined");if(!i.att)throw new Error("No `att` property found");const e=Object.keys(i.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const s=i.att[t];if(Array.isArray(s))throw new Error(`Resource must be an object: ${t}`);if(typeof s!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(s).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(s).forEach(r=>{const n=s[r];if(!Array.isArray(n))throw new Error(`Ability limits ${r} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function wu(i,e,t,s={}){return t==null||t.sort((r,n)=>r.localeCompare(n)),{att:{[i]:bu(e,t,s)}}}function bu(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 Xa(i){return Ut(i),`urn:recap:${yu(i).replace(/=/g,"")}`}function Qi(i){const e=mu(i.replace("urn:recap:",""));return Ut(e),e}function vu(i,e,t){const s=wu(i,e,t);return Xa(s)}function Eu(i){return i&&i.includes("urn:recap:")}function Iu(i,e){const t=Qi(i),s=Qi(e),r=_u(t,s);return Xa(r)}function _u(i,e){Ut(i),Ut(e);const t=Object.keys(i.att).concat(Object.keys(e.att)).sort((r,n)=>r.localeCompare(n)),s={att:{}};return t.forEach(r=>{var n,o;Object.keys(((n=i.att)==null?void 0:n[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,h;s.att[r]=du(pu({},s.att[r]),{[a]:((c=i.att[r])==null?void 0:c[a])||((h=e.att[r])==null?void 0:h[a])})})}),s}function Pu(i="",e){Ut(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(i.includes(t))return i;const s=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,p)=>u.action.localeCompare(p.action));const h={};c.forEach(u=>{h[u.ability]||(h[u.ability]=[]),h[u.ability].push(u.action)});const l=Object.keys(h).map(u=>(r++,`(${r}) '${u}': '${h[u].join("', '")}' for '${a}'.`));s.push(l.join(", ").replace(".,","."))});const n=s.join(" "),o=`${t}${n}`;return`${i?i+" ":""}${o}`}function Kn(i){var e;const t=Qi(i);Ut(t);const s=(e=t.att)==null?void 0:e.eip155;return s?Object.keys(s).map(r=>r.split("/")[1]):[]}function Gn(i){const e=Qi(i);Ut(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 Ps(i){if(!i)return;const e=i==null?void 0:i[i.length-1];return Eu(e)?e:void 0}function tr(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function ec(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function je(i,...e){if(!ec(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Wn(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function $u(i,e){je(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Jn(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const Pt=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),Su=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Ou=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ou)throw new Error("Non little-endian hardware is not supported");function xu(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=xu(i);else if(ec(i))i=Tr(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function Au(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function Cu(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 Tu=(i,e)=>{function t(s,...r){if(je(s),i.nonceLength!==void 0){const h=r[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?je(h):je(h,i.nonceLength)}const n=i.tagLength;n&&r[1]!==void 0&&je(r[1]);const o=e(s,...r),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");je(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,je(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(je(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(h,l)}}}return Object.assign(t,i),t};function Qn(i,e,t=!0){if(e===void 0)return new Uint8Array(i);if(e.length!==i)throw new Error("invalid output length, expected "+i+", got: "+e.length);if(t&&!Nu(e))throw new Error("invalid output, must be aligned");return e}function Yn(i,e,t,s){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(t>>r&n),a=Number(t&n),c=s?4:0,h=s?0:4;i.setUint32(e+c,o,s),i.setUint32(e+h,a,s)}function Nu(i){return i.byteOffset%4===0}function Tr(i){return Uint8Array.from(i)}function bi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const tc=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),Ru=tc("expand 16-byte k"),qu=tc("expand 32-byte k"),ju=Pt(Ru),ku=Pt(qu);function H(i,e){return i<<e|i>>>32-e}function Nr(i){return i.byteOffset%4===0}const gs=64,Du=16,ic=2**32-1,Zn=new Uint32Array;function Lu(i,e,t,s,r,n,o,a){const c=r.length,h=new Uint8Array(gs),l=Pt(h),u=Nr(r)&&Nr(n),p=u?Pt(r):Zn,g=u?Pt(n):Zn;for(let d=0;d<c;o++){if(i(e,t,s,l,o,a),o>=ic)throw new Error("arx: counter overflow");const m=Math.min(gs,c-d);if(u&&m===gs){const f=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let w=0,y;w<Du;w++)y=f+w,g[y]=p[y]^l[w];d+=gs;continue}for(let f=0,w;f<m;f++)w=d+f,n[w]=r[w]^h[f];d+=m}}function Fu(i,e){const{allowShortKeys:t,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=Au({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),Jn(n),Jn(t),(a,c,h,l,u=0)=>{je(a),je(c),je(h);const p=h.length;if(l===void 0&&(l=new Uint8Array(p)),je(l),tr(u),u<0||u>=ic)throw new Error("arx: counter overflow");if(l.length<p)throw new Error(`arx: output (${l.length}) is shorter than data (${p})`);const g=[];let d=a.length,m,f;if(d===32)g.push(m=Tr(a)),f=ku;else if(d===16&&t)m=new Uint8Array(32),m.set(a),m.set(a,16),f=ju,g.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);Nr(c)||g.push(c=Tr(c));const w=Pt(m);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(f,w,Pt(c.subarray(0,16)),w),c=c.subarray(16)}const y=16-r;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const _=new Uint8Array(12);_.set(c,n?0:12-c.length),c=_,g.push(c)}const I=Pt(c);return Lu(i,f,w,I,h,l,u,o),bi(...g),l}}const fe=(i,e)=>i[e++]&255|(i[e++]&255)<<8;class Uu{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),je(e,32);const t=fe(e,0),s=fe(e,2),r=fe(e,4),n=fe(e,6),o=fe(e,8),a=fe(e,10),c=fe(e,12),h=fe(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>10|r<<6)&7939,this.r[3]=(r>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=fe(e,16+2*l)}process(e,t,s=!1){const r=s?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],u=o[4],p=o[5],g=o[6],d=o[7],m=o[8],f=o[9],w=fe(e,t+0),y=fe(e,t+2),I=fe(e,t+4),_=fe(e,t+6),T=fe(e,t+8),P=fe(e,t+10),S=fe(e,t+12),N=fe(e,t+14);let b=n[0]+(w&8191),D=n[1]+((w>>>13|y<<3)&8191),q=n[2]+((y>>>10|I<<6)&8191),k=n[3]+((I>>>7|_<<9)&8191),F=n[4]+((_>>>4|T<<12)&8191),E=n[5]+(T>>>1&8191),x=n[6]+((T>>>14|P<<2)&8191),O=n[7]+((P>>>11|S<<5)&8191),R=n[8]+((S>>>8|N<<8)&8191),j=n[9]+(N>>>5|r),$=0,L=$+b*a+D*(5*f)+q*(5*m)+k*(5*d)+F*(5*g);$=L>>>13,L&=8191,L+=E*(5*p)+x*(5*u)+O*(5*l)+R*(5*h)+j*(5*c),$+=L>>>13,L&=8191;let U=$+b*c+D*a+q*(5*f)+k*(5*m)+F*(5*d);$=U>>>13,U&=8191,U+=E*(5*g)+x*(5*p)+O*(5*u)+R*(5*l)+j*(5*h),$+=U>>>13,U&=8191;let M=$+b*h+D*c+q*a+k*(5*f)+F*(5*m);$=M>>>13,M&=8191,M+=E*(5*d)+x*(5*g)+O*(5*p)+R*(5*u)+j*(5*l),$+=M>>>13,M&=8191;let X=$+b*l+D*h+q*c+k*a+F*(5*f);$=X>>>13,X&=8191,X+=E*(5*m)+x*(5*d)+O*(5*g)+R*(5*p)+j*(5*u),$+=X>>>13,X&=8191;let W=$+b*u+D*l+q*h+k*c+F*a;$=W>>>13,W&=8191,W+=E*(5*f)+x*(5*m)+O*(5*d)+R*(5*g)+j*(5*p),$+=W>>>13,W&=8191;let se=$+b*p+D*u+q*l+k*h+F*c;$=se>>>13,se&=8191,se+=E*a+x*(5*f)+O*(5*m)+R*(5*d)+j*(5*g),$+=se>>>13,se&=8191;let he=$+b*g+D*p+q*u+k*l+F*h;$=he>>>13,he&=8191,he+=E*c+x*a+O*(5*f)+R*(5*m)+j*(5*d),$+=he>>>13,he&=8191;let ve=$+b*d+D*g+q*p+k*u+F*l;$=ve>>>13,ve&=8191,ve+=E*h+x*c+O*a+R*(5*f)+j*(5*m),$+=ve>>>13,ve&=8191;let oe=$+b*m+D*d+q*g+k*p+F*u;$=oe>>>13,oe&=8191,oe+=E*l+x*h+O*c+R*a+j*(5*f),$+=oe>>>13,oe&=8191;let ae=$+b*f+D*m+q*d+k*g+F*p;$=ae>>>13,ae&=8191,ae+=E*u+x*l+O*h+R*c+j*a,$+=ae>>>13,ae&=8191,$=($<<2)+$|0,$=$+L|0,L=$&8191,$=$>>>13,U+=$,n[0]=L,n[1]=U,n[2]=M,n[3]=X,n[4]=W,n[5]=se,n[6]=he,n[7]=ve,n[8]=oe,n[9]=ae}finalize(){const{h:e,pad:t}=this,s=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,s[0]=e[0]+5,r=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+r,r=s[a]>>>13,s[a]&=8191;s[9]-=8192;let n=(r^1)-1;for(let a=0;a<10;a++)s[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|s[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;bi(s)}update(e){Wn(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(){bi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Wn(this),$u(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 Mu(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 Bu=Mu(i=>new Uu(i));function zu(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],g=e[3],d=e[4],m=e[5],f=e[6],w=e[7],y=r,I=t[0],_=t[1],T=t[2],P=o,S=a,N=c,b=h,D=l,q=u,k=p,F=g,E=d,x=m,O=f,R=w,j=y,$=I,L=_,U=T;for(let X=0;X<n;X+=2)P=P+D|0,j=H(j^P,16),E=E+j|0,D=H(D^E,12),P=P+D|0,j=H(j^P,8),E=E+j|0,D=H(D^E,7),S=S+q|0,$=H($^S,16),x=x+$|0,q=H(q^x,12),S=S+q|0,$=H($^S,8),x=x+$|0,q=H(q^x,7),N=N+k|0,L=H(L^N,16),O=O+L|0,k=H(k^O,12),N=N+k|0,L=H(L^N,8),O=O+L|0,k=H(k^O,7),b=b+F|0,U=H(U^b,16),R=R+U|0,F=H(F^R,12),b=b+F|0,U=H(U^b,8),R=R+U|0,F=H(F^R,7),P=P+q|0,U=H(U^P,16),O=O+U|0,q=H(q^O,12),P=P+q|0,U=H(U^P,8),O=O+U|0,q=H(q^O,7),S=S+k|0,j=H(j^S,16),R=R+j|0,k=H(k^R,12),S=S+k|0,j=H(j^S,8),R=R+j|0,k=H(k^R,7),N=N+F|0,$=H($^N,16),E=E+$|0,F=H(F^E,12),N=N+F|0,$=H($^N,8),E=E+$|0,F=H(F^E,7),b=b+D|0,L=H(L^b,16),x=x+L|0,D=H(D^x,12),b=b+D|0,L=H(L^b,8),x=x+L|0,D=H(D^x,7);let M=0;s[M++]=o+P|0,s[M++]=a+S|0,s[M++]=c+N|0,s[M++]=h+b|0,s[M++]=l+D|0,s[M++]=u+q|0,s[M++]=p+k|0,s[M++]=g+F|0,s[M++]=d+E|0,s[M++]=m+x|0,s[M++]=f+O|0,s[M++]=w+R|0,s[M++]=y+j|0,s[M++]=I+$|0,s[M++]=_+L|0,s[M++]=T+U|0}const Vu=Fu(zu,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Hu=new Uint8Array(16),Xn=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(Hu.subarray(t))},Ku=new Uint8Array(32);function eo(i,e,t,s,r){const n=i(e,t,Ku),o=Bu.create(n);r&&Xn(o,r),Xn(o,s);const a=new Uint8Array(16),c=Su(a);Yn(c,0,BigInt(r?r.length:0),!0),Yn(c,8,BigInt(s.length),!0),o.update(a);const h=o.digest();return bi(n,a),h}const Gu=i=>(e,t,s)=>({encrypt(r,n){const o=r.length;n=Qn(o+16,n,!1),n.set(r);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=eo(i,e,t,a,s);return n.set(c,o),bi(c),n},decrypt(r,n){n=Qn(r.length-16,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=eo(i,e,t,o,s);if(!Cu(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),i(e,t,n,n,1),bi(c),n}}),sc=Tu({blockSize:64,nonceLength:12,tagLength:16},Gu(Vu));let rc=class extends cn{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,an(e);const s=wi(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),ss(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 Ms=(i,e,t)=>new rc(i,e).update(t).digest();Ms.create=(i,e)=>new rc(i,e);function Wu(i,e,t){return an(i),t===void 0&&(t=new Uint8Array(i.outputLen)),Ms(i,wi(t),wi(e))}const ir=new Uint8Array([0]),to=new Uint8Array;function Ju(i,e,t,s=32){if(an(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=to);const n=new Uint8Array(r*i.outputLen),o=Ms.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?to: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 Qu=(i,e,t,s,r)=>Ju(i,Wu(i,e,t),s,r);function Yu(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 Zu(i,e,t){return i&e^~i&t}function Xu(i,e,t){return i&e^i&t^e&t}let ep=class extends cn{constructor(e,t,s,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=er(this.buffer)}update(e){mi(this);const{view:t,buffer:s,blockLen:r}=this;e=wi(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),Ha(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;Yu(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 tp=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),vt=new Uint32Array(64);class ip extends ep{constructor(){super(64,32,8,!1),this.A=bt[0]|0,this.B=bt[1]|0,this.C=bt[2]|0,this.D=bt[3]|0,this.E=bt[4]|0,this.F=bt[5]|0,this.G=bt[6]|0,this.H=bt[7]|0}get(){const{A:e,B:t,C:s,D:r,E:n,F:o,G:a,H:c}=this;return[e,t,s,r,n,o,a,c]}set(e,t,s,r,n,o,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=r|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)vt[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=vt[u-15],g=vt[u-2],d=Ze(p,7)^Ze(p,18)^p>>>3,m=Ze(g,17)^Ze(g,19)^g>>>10;vt[u]=m+vt[u-7]+d+vt[u-16]|0}let{A:s,B:r,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const p=Ze(a,6)^Ze(a,11)^Ze(a,25),g=l+p+Zu(a,c,h)+tp[u]+vt[u]|0,d=(Ze(s,2)^Ze(s,13)^Ze(s,22))+Xu(s,r,n)|0;l=h,h=c,c=a,a=o+g|0,o=n,n=r,r=s,s=g+d|0}s=s+this.A|0,r=r+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(s,r,n,o,a,c,h,l)}roundClean(){vt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const rs=Ka(()=>new ip);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Bs=BigInt(0),zs=BigInt(1),sp=BigInt(2);function Mt(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function ns(i){if(!Mt(i))throw new Error("Uint8Array expected")}function vi(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const rp=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Ei(i){ns(i);let e="";for(let t=0;t<i.length;t++)e+=rp[i[t]];return e}function pi(i){const e=i.toString(16);return e.length&1?"0"+e:e}function ln(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?Bs:BigInt("0x"+i)}const ut={_0:48,_9:57,A:65,F:70,a:97,f:102};function io(i){if(i>=ut._0&&i<=ut._9)return i-ut._0;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 Ii(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const s=new Uint8Array(t);for(let r=0,n=0;r<t;r++,n+=2){const o=io(i.charCodeAt(n)),a=io(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}s[r]=o*16+a}return s}function Lt(i){return ln(Ei(i))}function Yi(i){return ns(i),ln(Ei(Uint8Array.from(i).reverse()))}function _i(i,e){return Ii(i.toString(16).padStart(e*2,"0"))}function Vs(i,e){return _i(i,e).reverse()}function np(i){return Ii(pi(i))}function qe(i,e,t){let s;if(typeof e=="string")try{s=Ii(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(Mt(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];ns(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 op(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 ap(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const sr=i=>typeof i=="bigint"&&Bs<=i;function Hs(i,e,t){return sr(i)&&sr(e)&&sr(t)&&e<=i&&i<t}function yt(i,e,t,s){if(!Hs(e,t,s))throw new Error("expected valid "+i+": "+t+" <= n < "+s+", got "+e)}function nc(i){let e;for(e=0;i>Bs;i>>=zs,e+=1);return e}function cp(i,e){return i>>BigInt(e)&zs}function hp(i,e,t){return i|(t?zs:Bs)<<BigInt(e)}const un=i=>(sp<<BigInt(i-1))-zs,rr=i=>new Uint8Array(i),so=i=>Uint8Array.from(i);function oc(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(so([0]),l),s=a(),l.length!==0&&(r=a(so([1]),l),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const u=[];for(;l<e;){s=a();const p=s.slice();u.push(p),l+=s.length}return Zi(...u)};return(l,u)=>{o(),c(l);let p;for(;!(p=u(h()));)c();return o(),p}}const lp={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"||Mt(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 Ci(i,e,t={}){const s=(r,n,o)=>{const a=lp[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 up=()=>{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 pp=Object.freeze({__proto__:null,isBytes:Mt,abytes:ns,abool:vi,bytesToHex:Ei,numberToHexUnpadded:pi,hexToNumber:ln,hexToBytes:Ii,bytesToNumberBE:Lt,bytesToNumberLE:Yi,numberToBytesBE:_i,numberToBytesLE:Vs,numberToVarBytesBE:np,ensureBytes:qe,concatBytes:Zi,equalBytes:op,utf8ToBytes:ap,inRange:Hs,aInRange:yt,bitLen:nc,bitGet:cp,bitSet:hp,bitMask:un,createHmacDrbg:oc,validateObject:Ci,notImplemented:up,memoized:Rr});const ge=BigInt(0),ie=BigInt(1),Rt=BigInt(2),dp=BigInt(3),qr=BigInt(4),ro=BigInt(5),no=BigInt(8);function xe(i,e){const t=i%e;return t>=ge?t:e+t}function ac(i,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===ie)return ge;let s=ie;for(;e>ge;)e&ie&&(s=s*i%t),i=i*i%t,e>>=ie;return s}function Ge(i,e,t){let s=i;for(;e-- >ge;)s*=s,s%=t;return s}function jr(i,e){if(i===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let t=xe(i,e),s=e,r=ge,n=ie;for(;t!==ge;){const o=s/t,a=s%t,c=r-n*o;s=t,t=a,r=n,n=c}if(s!==ie)throw new Error("invert: does not exist");return xe(r,e)}function gp(i){const e=(i-ie)/Rt;let t,s,r;for(t=i-ie,s=0;t%Rt===ge;t/=Rt,s++);for(r=Rt;r<i&&ac(r,e,i)!==i-ie;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(s===1){const o=(i+ie)/qr;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+ie)/Rt;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=s,h=o.pow(o.mul(o.ONE,r),t),l=o.pow(a,n),u=o.pow(a,t);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let p=1;for(let d=o.sqr(u);p<c&&!o.eql(d,o.ONE);p++)d=o.sqr(d);const g=o.pow(h,ie<<BigInt(c-p-1));h=o.sqr(g),l=o.mul(l,g),u=o.mul(u,h),c=p}return l}}function fp(i){if(i%qr===dp){const e=(i+ie)/qr;return function(t,s){const r=t.pow(s,e);if(!t.eql(t.sqr(r),s))throw new Error("Cannot find square root");return r}}if(i%no===ro){const e=(i-ro)/no;return function(t,s){const r=t.mul(s,Rt),n=t.pow(r,e),o=t.mul(s,n),a=t.mul(t.mul(o,Rt),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),s))throw new Error("Cannot find square root");return c}}return gp(i)}const yp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function mp(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=yp.reduce((s,r)=>(s[r]="function",s),e);return Ci(i,t)}function wp(i,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return i.ONE;if(t===ie)return e;let s=i.ONE,r=e;for(;t>ge;)t&ie&&(s=i.mul(s,r)),r=i.sqr(r),t>>=ie;return s}function bp(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 cc(i,e){const t=e!==void 0?e:i.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function hc(i,e,t=!1,s={}){if(i<=ge)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:r,nByteLength:n}=cc(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:r,BYTES:n,MASK:un(r),ZERO:ge,ONE:ie,create:c=>xe(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&ie)===ie,neg:c=>xe(-c,i),eql:(c,h)=>c===h,sqr:c=>xe(c*c,i),add:(c,h)=>xe(c+h,i),sub:(c,h)=>xe(c-h,i),mul:(c,h)=>xe(c*h,i),pow:(c,h)=>wp(a,c,h),div:(c,h)=>xe(c*jr(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>jr(c,i),sqrt:s.sqrt||(c=>(o||(o=fp(i)),o(a,c))),invertBatch:c=>bp(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>t?Vs(c,n):_i(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Yi(c):Lt(c)}});return Object.freeze(a)}function lc(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 uc(i){const e=lc(i);return e+Math.ceil(e/2)}function vp(i,e,t=!1){const s=i.length,r=lc(e),n=uc(e);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=t?Yi(i):Lt(i),a=xe(o,e-ie)+ie;return t?Vs(a,r):_i(a,r)}const oo=BigInt(0),fs=BigInt(1);function nr(i,e){const t=e.negate();return i?t:e}function pc(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){pc(i,e);const t=Math.ceil(e/i)+1,s=2**(i-1);return{windows:t,windowSize:s}}function Ep(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 Ip(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,dc=new WeakMap;function cr(i){return dc.get(i)||1}function _p(i,e){return{constTimeNegate:nr,hasPrecomputes(t){return cr(t)!==1},unsafeLadder(t,s,r=i.ZERO){let n=t;for(;s>oo;)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 g=p*o;let d=Number(r&h);r>>=u,d>o&&(d-=l,r+=fs);const m=g,f=g+Math.abs(d)-1,w=p%2!==0,y=d<0;d===0?c=c.add(nr(w,s[m])):a=a.add(nr(y,s[f]))}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===oo)break;let g=Number(r&c);if(r>>=l,g>a&&(g-=h,r+=fs),g===0)continue;let d=s[p+Math.abs(g)-1];g<0&&(d=d.negate()),n=n.add(d)}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){pc(s,e),dc.set(t,s),ar.delete(t)}}}function Pp(i,e,t,s){if(Ep(t,i),Ip(s,e),t.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=i.ZERO,n=nc(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 g=0;g<s.length;g++){const d=s[g],m=Number(d>>BigInt(u)&BigInt(a));c[m]=c[m].add(t[g])}let p=r;for(let g=c.length-1,d=r;g>0;g--)d=d.add(c[g]),p=p.add(d);if(l=l.add(p),u!==0)for(let g=0;g<o;g++)l=l.double()}return l}function gc(i){return mp(i.Fp),Ci(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...cc(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Gt=BigInt(0),hr=BigInt(1);function $p(i){return Ci(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function Sp(i){const e=$p(i),{P:t}=e,s=y=>xe(y,t),r=e.montgomeryBits,n=Math.ceil(r/8),o=e.nByteLength,a=e.adjustScalarBytes||(y=>y),c=e.powPminus2||(y=>ac(y,t-BigInt(2),t));function h(y,I,_){const T=s(y*(I-_));return I=s(I-T),_=s(_+T),[I,_]}const l=(e.a-BigInt(2))/BigInt(4);function u(y,I){yt("u",y,Gt,t),yt("scalar",I,Gt,t);const _=I,T=y;let P=hr,S=Gt,N=y,b=hr,D=Gt,q;for(let F=BigInt(r-1);F>=Gt;F--){const E=_>>F&hr;D^=E,q=h(D,P,N),P=q[0],N=q[1],q=h(D,S,b),S=q[0],b=q[1],D=E;const x=P+S,O=s(x*x),R=P-S,j=s(R*R),$=O-j,L=N+b,U=N-b,M=s(U*x),X=s(L*R),W=M+X,se=M-X;N=s(W*W),b=s(T*s(se*se)),P=s(O*j),S=s($*(O+s(l*$)))}q=h(D,P,N),P=q[0],N=q[1],q=h(D,S,b),S=q[0],b=q[1];const k=c(S);return s(P*k)}function p(y){return Vs(s(y),n)}function g(y){const I=qe("u coordinate",y,n);return o===32&&(I[31]&=127),Yi(I)}function d(y){const I=qe("scalar",y),_=I.length;if(_!==n&&_!==o){let T=""+n+" or "+o;throw new Error("invalid scalar, expected "+T+" bytes, got "+_)}return Yi(a(I))}function m(y,I){const _=g(I),T=d(y),P=u(_,T);if(P===Gt)throw new Error("invalid private or public key received");return p(P)}const f=p(e.Gu);function w(y){return m(y,f)}return{scalarMult:m,scalarMultBase:w,getSharedSecret:(y,I)=>m(y,I),getPublicKey:y=>w(y),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:f}}const kr=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Op=BigInt(1),ao=BigInt(2),xp=BigInt(3),Ap=BigInt(5);BigInt(8);function Cp(i){const e=BigInt(10),t=BigInt(20),s=BigInt(40),r=BigInt(80),n=kr,o=i*i%n*i%n,a=Ge(o,ao,n)*o%n,c=Ge(a,Op,n)*i%n,h=Ge(c,Ap,n)*c%n,l=Ge(h,e,n)*h%n,u=Ge(l,t,n)*l%n,p=Ge(u,s,n)*u%n,g=Ge(p,r,n)*p%n,d=Ge(g,r,n)*p%n,m=Ge(d,e,n)*h%n;return{pow_p_5_8:Ge(m,ao,n)*i%n,b2:o}}function Tp(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const Dr=Sp({P:kr,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=kr,{pow_p_5_8:t,b2:s}=Cp(i);return xe(Ge(t,xp,e)*s,e)},adjustScalarBytes:Tp,randomBytes:Ai});function co(i){i.lowS!==void 0&&vi("lowS",i.lowS),i.prehash!==void 0&&vi("prehash",i.prehash)}function Np(i){const e=gc(i);Ci(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:Rp,hexToBytes:qp}=pp;class jp extends Error{constructor(e=""){super(e)}}const gt={Err:jp,_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<ft)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 Rp(i)}},toSig(i){const{Err:e,_int:t,_tlv:s}=gt,r=typeof i=="string"?qp(i):i;ns(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)}},ft=BigInt(0),pe=BigInt(1);BigInt(2);const ho=BigInt(3);BigInt(4);function kp(i){const e=Np(i),{Fp:t}=e,s=hc(e.n,e.nBitLength),r=e.toBytes||((m,f,w)=>{const y=f.toAffine();return Zi(Uint8Array.from([4]),t.toBytes(y.x),t.toBytes(y.y))}),n=e.fromBytes||(m=>{const f=m.subarray(1),w=t.fromBytes(f.subarray(0,t.BYTES)),y=t.fromBytes(f.subarray(t.BYTES,2*t.BYTES));return{x:w,y}});function o(m){const{a:f,b:w}=e,y=t.sqr(m),I=t.mul(y,m);return t.add(t.add(I,t.mul(m,f)),w)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Hs(m,pe,e.n)}function c(m){const{allowedPrivateKeyLengths:f,nByteLength:w,wrapPrivateKey:y,n:I}=e;if(f&&typeof m!="bigint"){if(Mt(m)&&(m=Ei(m)),typeof m!="string"||!f.includes(m.length))throw new Error("invalid private key");m=m.padStart(w*2,"0")}let _;try{_=typeof m=="bigint"?m:Lt(qe("private key",m,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof m)}return y&&(_=xe(_,I)),yt("private key",_,pe,I),_}function h(m){if(!(m instanceof p))throw new Error("ProjectivePoint expected")}const l=Rr((m,f)=>{const{px:w,py:y,pz:I}=m;if(t.eql(I,t.ONE))return{x:w,y};const _=m.is0();f==null&&(f=_?t.ONE:t.inv(I));const T=t.mul(w,f),P=t.mul(y,f),S=t.mul(I,f);if(_)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:T,y:P}}),u=Rr(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}const{x:f,y:w}=m.toAffine();if(!t.isValid(f)||!t.isValid(w))throw new Error("bad point: x or y not FE");const y=t.sqr(w),I=o(f);if(!t.eql(y,I))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(f,w,y){if(this.px=f,this.py=w,this.pz=y,f==null||!t.isValid(f))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(y==null||!t.isValid(y))throw new Error("z required");Object.freeze(this)}static fromAffine(f){const{x:w,y}=f||{};if(!f||!t.isValid(w)||!t.isValid(y))throw new Error("invalid affine point");if(f instanceof p)throw new Error("projective point not allowed");const I=_=>t.eql(_,t.ZERO);return I(w)&&I(y)?p.ZERO:new p(w,y,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const w=t.invertBatch(f.map(y=>y.pz));return f.map((y,I)=>y.toAffine(w[I])).map(p.fromAffine)}static fromHex(f){const w=p.fromAffine(n(qe("pointHex",f)));return w.assertValidity(),w}static fromPrivateKey(f){return p.BASE.multiply(c(f))}static msm(f,w){return Pp(p,s,f,w)}_setWindowSize(f){d.setWindowSize(this,f)}assertValidity(){u(this)}hasEvenY(){const{y:f}=this.toAffine();if(t.isOdd)return!t.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){h(f);const{px:w,py:y,pz:I}=this,{px:_,py:T,pz:P}=f,S=t.eql(t.mul(w,P),t.mul(_,I)),N=t.eql(t.mul(y,P),t.mul(T,I));return S&&N}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:f,b:w}=e,y=t.mul(w,ho),{px:I,py:_,pz:T}=this;let P=t.ZERO,S=t.ZERO,N=t.ZERO,b=t.mul(I,I),D=t.mul(_,_),q=t.mul(T,T),k=t.mul(I,_);return k=t.add(k,k),N=t.mul(I,T),N=t.add(N,N),P=t.mul(f,N),S=t.mul(y,q),S=t.add(P,S),P=t.sub(D,S),S=t.add(D,S),S=t.mul(P,S),P=t.mul(k,P),N=t.mul(y,N),q=t.mul(f,q),k=t.sub(b,q),k=t.mul(f,k),k=t.add(k,N),N=t.add(b,b),b=t.add(N,b),b=t.add(b,q),b=t.mul(b,k),S=t.add(S,b),q=t.mul(_,T),q=t.add(q,q),b=t.mul(q,k),P=t.sub(P,b),N=t.mul(q,D),N=t.add(N,N),N=t.add(N,N),new p(P,S,N)}add(f){h(f);const{px:w,py:y,pz:I}=this,{px:_,py:T,pz:P}=f;let S=t.ZERO,N=t.ZERO,b=t.ZERO;const D=e.a,q=t.mul(e.b,ho);let k=t.mul(w,_),F=t.mul(y,T),E=t.mul(I,P),x=t.add(w,y),O=t.add(_,T);x=t.mul(x,O),O=t.add(k,F),x=t.sub(x,O),O=t.add(w,I);let R=t.add(_,P);return O=t.mul(O,R),R=t.add(k,E),O=t.sub(O,R),R=t.add(y,I),S=t.add(T,P),R=t.mul(R,S),S=t.add(F,E),R=t.sub(R,S),b=t.mul(D,O),S=t.mul(q,E),b=t.add(S,b),S=t.sub(F,b),b=t.add(F,b),N=t.mul(S,b),F=t.add(k,k),F=t.add(F,k),E=t.mul(D,E),O=t.mul(q,O),F=t.add(F,E),E=t.sub(k,E),E=t.mul(D,E),O=t.add(O,E),k=t.mul(F,O),N=t.add(N,k),k=t.mul(R,O),S=t.mul(x,S),S=t.sub(S,k),k=t.mul(x,F),b=t.mul(R,b),b=t.add(b,k),new p(S,N,b)}subtract(f){return this.add(f.negate())}is0(){return this.equals(p.ZERO)}wNAF(f){return d.wNAFCached(this,f,p.normalizeZ)}multiplyUnsafe(f){const{endo:w,n:y}=e;yt("scalar",f,ft,y);const I=p.ZERO;if(f===ft)return I;if(this.is0()||f===pe)return this;if(!w||d.hasPrecomputes(this))return d.wNAFCachedUnsafe(this,f,p.normalizeZ);let{k1neg:_,k1:T,k2neg:P,k2:S}=w.splitScalar(f),N=I,b=I,D=this;for(;T>ft||S>ft;)T&pe&&(N=N.add(D)),S&pe&&(b=b.add(D)),D=D.double(),T>>=pe,S>>=pe;return _&&(N=N.negate()),P&&(b=b.negate()),b=new p(t.mul(b.px,w.beta),b.py,b.pz),N.add(b)}multiply(f){const{endo:w,n:y}=e;yt("scalar",f,pe,y);let I,_;if(w){const{k1neg:T,k1:P,k2neg:S,k2:N}=w.splitScalar(f);let{p:b,f:D}=this.wNAF(P),{p:q,f:k}=this.wNAF(N);b=d.constTimeNegate(T,b),q=d.constTimeNegate(S,q),q=new p(t.mul(q.px,w.beta),q.py,q.pz),I=b.add(q),_=D.add(k)}else{const{p:T,f:P}=this.wNAF(f);I=T,_=P}return p.normalizeZ([I,_])[0]}multiplyAndAddUnsafe(f,w,y){const I=p.BASE,_=(P,S)=>S===ft||S===pe||!P.equals(I)?P.multiplyUnsafe(S):P.multiply(S),T=_(this,w).add(_(f,y));return T.is0()?void 0:T}toAffine(f){return l(this,f)}isTorsionFree(){const{h:f,isTorsionFree:w}=e;if(f===pe)return!0;if(w)return w(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:w}=e;return f===pe?this:w?w(p,this):this.multiplyUnsafe(e.h)}toRawBytes(f=!0){return vi("isCompressed",f),this.assertValidity(),r(p,this,f)}toHex(f=!0){return vi("isCompressed",f),Ei(this.toRawBytes(f))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const g=e.nBitLength,d=_p(p,e.endo?Math.ceil(g/2):g);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Dp(i){const e=gc(i);return Ci(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Lp(i){const e=Dp(i),{Fp:t,n:s}=e,r=t.BYTES+1,n=2*t.BYTES+1;function o(E){return xe(E,s)}function a(E){return jr(E,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=kp({...e,toBytes(E,x,O){const R=x.toAffine(),j=t.toBytes(R.x),$=Zi;return vi("isCompressed",O),O?$(Uint8Array.from([x.hasEvenY()?2:3]),j):$(Uint8Array.from([4]),j,t.toBytes(R.y))},fromBytes(E){const x=E.length,O=E[0],R=E.subarray(1);if(x===r&&(O===2||O===3)){const j=Lt(R);if(!Hs(j,pe,t.ORDER))throw new Error("Point is not on curve");const $=l(j);let L;try{L=t.sqrt($)}catch(M){const X=M instanceof Error?": "+M.message:"";throw new Error("Point is not on curve"+X)}const U=(L&pe)===pe;return(O&1)===1!==U&&(L=t.neg(L)),{x:j,y:L}}else if(x===n&&O===4){const j=t.fromBytes(R.subarray(0,t.BYTES)),$=t.fromBytes(R.subarray(t.BYTES,2*t.BYTES));return{x:j,y:$}}else{const j=r,$=n;throw new Error("invalid Point, expected length of "+j+", or uncompressed "+$+", got "+x)}}}),p=E=>Ei(_i(E,e.nByteLength));function g(E){const x=s>>pe;return E>x}function d(E){return g(E)?o(-E):E}const m=(E,x,O)=>Lt(E.slice(x,O));class f{constructor(x,O,R){this.r=x,this.s=O,this.recovery=R,this.assertValidity()}static fromCompact(x){const O=e.nByteLength;return x=qe("compactSignature",x,O*2),new f(m(x,0,O),m(x,O,2*O))}static fromDER(x){const{r:O,s:R}=gt.toSig(qe("DER",x));return new f(O,R)}assertValidity(){yt("r",this.r,pe,s),yt("s",this.s,pe,s)}addRecoveryBit(x){return new f(this.r,this.s,x)}recoverPublicKey(x){const{r:O,s:R,recovery:j}=this,$=P(qe("msgHash",x));if(j==null||![0,1,2,3].includes(j))throw new Error("recovery id invalid");const L=j===2||j===3?O+e.n:O;if(L>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const U=j&1?"03":"02",M=c.fromHex(U+p(L)),X=a(L),W=o(-$*X),se=o(R*X),he=c.BASE.multiplyAndAddUnsafe(M,W,se);if(!he)throw new Error("point at infinify");return he.assertValidity(),he}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Ii(this.toDERHex())}toDERHex(){return gt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ii(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const w={isValidPrivateKey(E){try{return h(E),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const E=uc(e.n);return vp(e.randomBytes(E),e.n)},precompute(E=8,x=c.BASE){return x._setWindowSize(E),x.multiply(BigInt(3)),x}};function y(E,x=!0){return c.fromPrivateKey(E).toRawBytes(x)}function I(E){const x=Mt(E),O=typeof E=="string",R=(x||O)&&E.length;return x?R===r||R===n:O?R===2*r||R===2*n:E instanceof c}function _(E,x,O=!0){if(I(E))throw new Error("first arg must be private key");if(!I(x))throw new Error("second arg must be public key");return c.fromHex(x).multiply(h(E)).toRawBytes(O)}const T=e.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");const x=Lt(E),O=E.length*8-e.nBitLength;return O>0?x>>BigInt(O):x},P=e.bits2int_modN||function(E){return o(T(E))},S=un(e.nBitLength);function N(E){return yt("num < 2^"+e.nBitLength,E,ft,S),_i(E,e.nByteLength)}function b(E,x,O=D){if(["recovered","canonical"].some(oe=>oe in O))throw new Error("sign() legacy options not supported");const{hash:R,randomBytes:j}=e;let{lowS:$,prehash:L,extraEntropy:U}=O;$==null&&($=!0),E=qe("msgHash",E),co(O),L&&(E=qe("prehashed msgHash",R(E)));const M=P(E),X=h(x),W=[N(X),N(M)];if(U!=null&&U!==!1){const oe=U===!0?j(t.BYTES):U;W.push(qe("extraEntropy",oe))}const se=Zi(...W),he=M;function ve(oe){const ae=T(oe);if(!u(ae))return;const xt=a(ae),at=c.BASE.multiply(ae).toAffine(),Ye=o(at.x);if(Ye===ft)return;const ct=o(xt*o(he+Ye*X));if(ct===ft)return;let ht=(at.x===Ye?0:2)|Number(at.y&pe),us=ct;return $&&g(ct)&&(us=d(ct),ht^=1),new f(Ye,us,ht)}return{seed:se,k2sig:ve}}const D={lowS:e.lowS,prehash:!1},q={lowS:e.lowS,prehash:!1};function k(E,x,O=D){const{seed:R,k2sig:j}=b(E,x,O),$=e;return oc($.hash.outputLen,$.nByteLength,$.hmac)(R,j)}c.BASE._setWindowSize(8);function F(E,x,O,R=q){var ct;const j=E;x=qe("msgHash",x),O=qe("publicKey",O);const{lowS:$,prehash:L,format:U}=R;if(co(R),"strict"in R)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 M=typeof j=="string"||Mt(j),X=!M&&!U&&typeof j=="object"&&j!==null&&typeof j.r=="bigint"&&typeof j.s=="bigint";if(!M&&!X)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let W,se;try{if(X&&(W=new f(j.r,j.s)),M){try{U!=="compact"&&(W=f.fromDER(j))}catch(ht){if(!(ht instanceof gt.Err))throw ht}!W&&U!=="der"&&(W=f.fromCompact(j))}se=c.fromHex(O)}catch{return!1}if(!W||$&&W.hasHighS())return!1;L&&(x=e.hash(x));const{r:he,s:ve}=W,oe=P(x),ae=a(ve),xt=o(oe*ae),at=o(he*ae),Ye=(ct=c.BASE.multiplyAndAddUnsafe(se,xt,at))==null?void 0:ct.toAffine();return Ye?o(Ye.x)===he:!1}return{CURVE:e,getPublicKey:y,getSharedSecret:_,sign:k,verify:F,ProjectivePoint:c,Signature:f,utils:w}}function Fp(i){return{hash:i,hmac:(e,...t)=>Ms(i,e,zl(...t)),randomBytes:Ai}}function Up(i,e){const t=s=>Lp({...i,...Fp(s)});return{...t(e),create:t}}const fc=hc(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Mp=fc.create(BigInt("-3")),Bp=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),zp=Up({a:Mp,b:Bp,Fp:fc,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},rs),yc="base10",Pe="base16",We="base64pad",It="base64url",os="utf8",mc=0,mt=1,as=2,Vp=0,lo=1,Hi=12,pn=32;function Hp(){const i=Dr.utils.randomPrivateKey(),e=Dr.getPublicKey(i);return{privateKey:Ae(i,Pe),publicKey:Ae(e,Pe)}}function Lr(){const i=Ai(pn);return Ae(i,Pe)}function Kp(i,e){const t=Dr.getSharedSecret(Me(i,Pe),Me(e,Pe)),s=Qu(rs,t,void 0,void 0,pn);return Ae(s,Pe)}function $s(i){const e=rs(Me(i,Pe));return Ae(e,Pe)}function st(i){const e=rs(Me(i,os));return Ae(e,Pe)}function wc(i){return Me(`${i}`,yc)}function Bt(i){return Number(Ae(i,yc))}function bc(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function vc(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Gp(i){const e=wc(typeof i.type<"u"?i.type:mc);if(Bt(e)===mt&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?Me(i.senderPublicKey,Pe):void 0,s=typeof i.iv<"u"?Me(i.iv,Pe):Ai(Hi),r=Me(i.symKey,Pe),n=sc(r,s).encrypt(Me(i.message,os)),o=Ec({type:e,sealed:n,iv:s,senderPublicKey:t});return i.encoding===It?bc(o):o}function Wp(i){const e=Me(i.symKey,Pe),{sealed:t,iv:s}=Xi({encoded:i.encoded,encoding:i.encoding}),r=sc(e,s).decrypt(t);if(r===null)throw new Error("Failed to decrypt");return Ae(r,os)}function Jp(i,e){const t=wc(as),s=Ai(Hi),r=Me(i,os),n=Ec({type:t,sealed:r,iv:s});return e===It?bc(n):n}function Qp(i,e){const{sealed:t}=Xi({encoded:i,encoding:e});return Ae(t,os)}function Ec(i){if(Bt(i.type)===as)return Ae(Vi([i.type,i.sealed]),We);if(Bt(i.type)===mt){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ae(Vi([i.type,i.senderPublicKey,i.iv,i.sealed]),We)}return Ae(Vi([i.type,i.iv,i.sealed]),We)}function Xi(i){const e=(i.encoding||We)===It?vc(i.encoded):i.encoded,t=Me(e,We),s=t.slice(Vp,lo),r=lo;if(Bt(s)===mt){const c=r+pn,h=c+Hi,l=t.slice(r,c),u=t.slice(c,h),p=t.slice(h);return{type:s,sealed:p,iv:u,senderPublicKey:l}}if(Bt(s)===as){const c=t.slice(r),h=Ai(Hi);return{type:s,sealed:c,iv:h}}const n=r+Hi,o=t.slice(r,n),a=t.slice(n);return{type:s,sealed:a,iv:o}}function Yp(i,e){const t=Xi({encoded:i,encoding:e==null?void 0:e.encoding});return Ic({type:Bt(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Ae(t.senderPublicKey,Pe):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Ic(i){const e=(i==null?void 0:i.type)||mc;if(e===mt){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 uo(i){return i.type===mt&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function po(i){return i.type===as}function Zp(i){const e=Ie.from(i.x,"base64"),t=Ie.from(i.y,"base64");return Vi([new Uint8Array([4]),e,t])}function Xp(i,e){const[t,s,r]=i.split("."),n=Ie.from(vc(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=rs(c),l=Zp(e);if(!zp.verify(Vi([o,a]),h,l))throw new Error("Invalid signature");return _r(i).payload}const ed="irn";function Ts(i){return(i==null?void 0:i.relay)||{protocol:ed}}function Mi(i){const e=dh[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function td(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=Va(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:id(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:td(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function id(i){return i.startsWith("//")?i.substring(2):i}function sd(i,e="-"){const t="relay",s={};return Object.keys(i).forEach(r=>{const n=r,o=t+e+n;i[n]&&(s[o]=i[n])}),s}function fo(i){const e=new URLSearchParams,t=sd(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 ys(i,e,t){return`${i}?wc_ev=${t}&topic=${e}`}var rd=Object.defineProperty,nd=Object.defineProperties,od=Object.getOwnPropertyDescriptors,yo=Object.getOwnPropertySymbols,ad=Object.prototype.hasOwnProperty,cd=Object.prototype.propertyIsEnumerable,mo=(i,e,t)=>e in i?rd(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,hd=(i,e)=>{for(var t in e||(e={}))ad.call(e,t)&&mo(i,t,e[t]);if(yo)for(var t of yo(e))cd.call(e,t)&&mo(i,t,e[t]);return i},ld=(i,e)=>nd(i,od(e));function Ti(i){const e=[];return i.forEach(t=>{const[s,r]=t.split(":");e.push(`${s}:${r}`)}),e}function ud(i){const e=[];return Object.values(i).forEach(t=>{e.push(...Ti(t.accounts))}),e}function pd(i,e){const t=[];return Object.values(i).forEach(s=>{Ti(s.accounts).includes(e)&&t.push(...s.methods)}),t}function dd(i,e){const t=[];return Object.values(i).forEach(s=>{Ti(s.accounts).includes(e)&&t.push(...s.events)}),t}function Ks(i){return i.includes(":")}function di(i){return Ks(i)?i.split(":")[0]:i}function wo(i){var e,t,s;const r={};if(!$t(i))return r;for(const[n,o]of Object.entries(i)){const a=Ks(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],l=di(n);r[l]=ld(hd({},r[l]),{chains:rt(a,(e=r[l])==null?void 0:e.chains),methods:rt(c,(t=r[l])==null?void 0:t.methods),events:rt(h,(s=r[l])==null?void 0:s.events)})}return r}function gd(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 bo(i,e){e=e.map(s=>s.replace("did:pkh:",""));const t=gd(e);for(const[s,r]of Object.entries(t))r.methods?r.methods=rt(r.methods,i):r.methods=i,r.events=["chainChanged","accountsChanged"];return t}function fd(i,e){var t,s,r,n,o,a;const c=wo(i),h=wo(e),l={},u=Object.keys(c).concat(Object.keys(h));for(const p of u)l[p]={chains:rt((t=c[p])==null?void 0:t.chains,(s=h[p])==null?void 0:s.chains),methods:rt((r=c[p])==null?void 0:r.methods,(n=h[p])==null?void 0:n.methods),events:rt((o=c[p])==null?void 0:o.events,(a=h[p])==null?void 0:a.events)};return l}const yd={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}},md={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 A(i,e){const{message:t,code:s}=md[i];return{message:e?`${t} ${e}`:t,code:s}}function Q(i,e){const{message:t,code:s}=yd[i];return{message:e?`${t} ${e}`:t,code:s}}function Je(i,e){return Array.isArray(i)?typeof e<"u"&&i.length?i.every(e):!0:!1}function $t(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}function we(i){return typeof i>"u"}function ne(i,e){return e&&we(i)?!0:typeof i=="string"&&!!i.trim().length}function dn(i,e){return e&&we(i)?!0:typeof i=="number"&&!isNaN(i)}function wd(i,e){const{requiredNamespaces:t}=e,s=Object.keys(i.namespaces),r=Object.keys(t);let n=!0;return Dt(r,s)?(s.forEach(o=>{const{accounts:a,methods:c,events:h}=i.namespaces[o],l=Ti(a),u=t[o];(!Dt(Fa(o,u),l)||!Dt(u.methods,c)||!Dt(u.events,h))&&(n=!1)}),n):!1}function Ns(i){return ne(i,!1)&&i.includes(":")?i.split(":").length===2:!1}function bd(i){if(ne(i,!1)&&i.includes(":")){const e=i.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&Ns(t)}}return!1}function vd(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(ne(i,!1)){if(e(i))return!0;const t=Va(i);return e(t)}}catch{}return!1}function Ed(i){var e;return(e=i==null?void 0:i.proposer)==null?void 0:e.publicKey}function Id(i){return i==null?void 0:i.topic}function _d(i,e){let t=null;return ne(i==null?void 0:i.publicKey,!1)||(t=A("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function vo(i){let e=!0;return Je(i)?i.length&&(e=i.every(t=>ne(t,!1))):e=!1,e}function Pd(i,e,t){let s=null;return Je(e)&&e.length?e.forEach(r=>{s||Ns(r)||(s=Q("UNSUPPORTED_CHAINS",`${t}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):Ns(i)||(s=Q("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),s}function $d(i,e,t){let s=null;return Object.entries(i).forEach(([r,n])=>{if(s)return;const o=Pd(r,Fa(r,n),`${e} ${t}`);o&&(s=o)}),s}function Sd(i,e){let t=null;return Je(i)?i.forEach(s=>{t||bd(s)||(t=Q("UNSUPPORTED_ACCOUNTS",`${e}, account ${s} should be a string and conform to "namespace:chainId:address" format`))}):t=Q("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function Od(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=Sd(s==null?void 0:s.accounts,`${e} namespace`);r&&(t=r)}),t}function xd(i,e){let t=null;return vo(i==null?void 0:i.methods)?vo(i==null?void 0:i.events)||(t=Q("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=Q("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function _c(i,e){let t=null;return Object.values(i).forEach(s=>{if(t)return;const r=xd(s,`${e}, namespace`);r&&(t=r)}),t}function Ad(i,e,t){let s=null;if(i&&$t(i)){const r=_c(i,e);r&&(s=r);const n=$d(i,e,t);n&&(s=n)}else s=A("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return s}function lr(i,e){let t=null;if(i&&$t(i)){const s=_c(i,e);s&&(t=s);const r=Od(i,e);r&&(t=r)}else t=A("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Pc(i){return ne(i.protocol,!0)}function Cd(i,e){let t=!1;return e&&!i?t=!0:i&&Je(i)&&i.length&&i.forEach(s=>{t=Pc(s)}),t}function Td(i){return typeof i=="number"}function Oe(i){return typeof i<"u"&&typeof i!==null}function Nd(i){return!(!i||typeof i!="object"||!i.code||!dn(i.code,!1)||!i.message||!ne(i.message,!1))}function Rd(i){return!(we(i)||!ne(i.method,!1))}function qd(i){return!(we(i)||we(i.result)&&we(i.error)||!dn(i.id,!1)||!ne(i.jsonrpc,!1))}function jd(i){return!(we(i)||!ne(i.name,!1))}function Eo(i,e){return!(!Ns(e)||!ud(i).includes(e))}function kd(i,e,t){return ne(t,!1)?pd(i,e).includes(t):!1}function Dd(i,e,t){return ne(t,!1)?dd(i,e).includes(t):!1}function Io(i,e,t){let s=null;const r=Ld(i),n=Fd(e),o=Object.keys(r),a=Object.keys(n),c=_o(Object.keys(i)),h=_o(Object.keys(e)),l=c.filter(u=>!h.includes(u));return l.length&&(s=A("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
|
|
@@ -8,4 +8,4 @@ ${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+Ie.from(eu(t)).toString(
|
|
|
8
8
|
Required: ${o.toString()}
|
|
9
9
|
Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||s)return;const p=Ti(e[u].accounts);p.includes(u)||(s=A("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${u}
|
|
10
10
|
Required: ${u}
|
|
11
|
-
Approved: ${p.toString()}`))}),o.forEach(u=>{s||(Dt(r[u].methods,n[u].methods)?Dt(r[u].events,n[u].events)||(s=A("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=A("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function Ld(i){const e={};return Object.keys(i).forEach(t=>{var s;t.includes(":")?e[t]=i[t]:(s=i[t].chains)==null||s.forEach(r=>{e[r]={methods:i[t].methods,events:i[t].events}})}),e}function _o(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Fd(i){const e={};return Object.keys(i).forEach(t=>{if(t.includes(":"))e[t]=i[t];else{const s=Ti(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 Ud(i,e){return dn(i,!1)&&i<=e.max&&i>=e.min}function Po(){const i=is();return new Promise(e=>{switch(i){case ke.browser:e(Md());break;case ke.reactNative:e(Bd());break;case ke.node:e(zd());break;default:e(!0)}})}function Md(){return xi()&&(navigator==null?void 0:navigator.onLine)}async function Bd(){if(Ot()&&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 zd(){return!0}function Vd(i){switch(is()){case ke.browser:Hd(i);break;case ke.reactNative:Kd(i);break}}function Hd(i){!Ot()&&xi()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function Kd(i){var e;Ot()&&typeof B<"u"&&B!=null&&B.NetInfo&&((e=B)==null||e.NetInfo.addEventListener(t=>i(t==null?void 0:t.isConnected)))}function Gd(){var i;return xi()&&yi()?((i=yi())==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]}}const $o=bh;var hi=nt;const es=sg().console||{},Wd={mapHttpRequest:ms,mapHttpResponse:ms,wrapRequestSerializer:pr,wrapResponseSerializer:pr,wrapErrorSerializer:pr,req:ms,res:ms,err:Xd};function Jd(i,e){return Array.isArray(i)?i.filter(function(s){return s!=="!stdSerializers.err"}):i===!0?Object.keys(e):!1}function nt(i){i=i||{},i.browser=i.browser||{};const e=i.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const t=i.browser.write||es;i.browser.write&&(i.browser.asObject=!0);const s=i.serializers||{},r=Jd(i.browser.serialize,s);let n=i.browser.serialize;Array.isArray(i.browser.serialize)&&i.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=["error","fatal","warn","info","debug","trace"];typeof t=="function"&&(t.error=t.fatal=t.warn=t.info=t.debug=t.trace=t),i.enabled===!1&&(i.level="silent");const a=i.level||"info",c=Object.create(t);c.log||(c.log=ts),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:u,set:p});const h={transmit:e,serialize:r,asObject:i.browser.asObject,levels:o,timestamp:eg(i)};c.levels=nt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=ts,c.serializers=s,c._serialize=r,c._stdErrSerialize=n,c.child=g,e&&(c._logEvent=Fr());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function u(){return this._level}function p(d){if(d!=="silent"&&!this.levels.values[d])throw Error("unknown level "+d);this._level=d,Wt(h,c,"error","log"),Wt(h,c,"fatal","error"),Wt(h,c,"warn","error"),Wt(h,c,"info","log"),Wt(h,c,"debug","log"),Wt(h,c,"trace","log")}function g(d,m){if(!d)throw new Error("missing bindings for child Pino");m=m||{},r&&d.serializers&&(m.serializers=d.serializers);const f=m.serializers;if(r&&f){var w=Object.assign({},s,f),y=i.browser.serialize===!0?Object.keys(w):r;delete d.serializers,Gs([d],y,w,this._stdErrSerialize)}function I(_){this._childLevel=(_._childLevel|0)+1,this.error=Jt(_,d,"error"),this.fatal=Jt(_,d,"fatal"),this.warn=Jt(_,d,"warn"),this.info=Jt(_,d,"info"),this.debug=Jt(_,d,"debug"),this.trace=Jt(_,d,"trace"),w&&(this.serializers=w,this._serialize=y),e&&(this._logEvent=Fr([].concat(_._logEvent.bindings,d)))}return I.prototype=this,new I(this)}return c}nt.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"}};nt.stdSerializers=Wd;nt.stdTimeFunctions=Object.assign({},{nullTime:$c,epochTime:Sc,unixTime:tg,isoTime:ig});function Wt(i,e,t,s){const r=Object.getPrototypeOf(e);e[t]=e.levelVal>e.levels.values[t]?ts:r[t]?r[t]:es[t]||es[s]||ts,Qd(i,e,t)}function Qd(i,e,t){!i.transmit&&e[t]===ts||(e[t]=function(s){return function(){const n=i.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===es?es:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(i.serialize&&!i.asObject&&Gs(o,this._serialize,this.serializers,this._stdErrSerialize),i.asObject?s.call(a,Yd(this,t,o,n)):s.apply(a,o),i.transmit){const h=i.transmit.level||e.level,l=nt.levels.values[h],u=nt.levels.values[t];if(u<l)return;Zd(this,{ts:n,methodLevel:t,methodValue:u,transmitLevel:h,transmitValue:nt.levels.values[i.transmit.level||e.level],send:i.transmit.send,val:e.levelVal},o)}}}(e[t]))}function Yd(i,e,t,s){i._serialize&&Gs(t,i._serialize,i.serializers,i._stdErrSerialize);const r=t.slice();let n=r[0];const o={};s&&(o.time=s),o.level=nt.levels.values[e];let a=(i._childLevel|0)+1;if(a<1&&(a=1),n!==null&&typeof n=="object"){for(;a--&&typeof r[0]=="object";)Object.assign(o,r.shift());n=r.length?$o(r.shift(),r):void 0}else typeof n=="string"&&(n=$o(r.shift(),r));return n!==void 0&&(o.msg=n),o}function Gs(i,e,t,s){for(const r in i)if(s&&i[r]instanceof Error)i[r]=nt.stdSerializers.err(i[r]);else if(typeof i[r]=="object"&&!Array.isArray(i[r]))for(const n in i[r])e&&e.indexOf(n)>-1&&n in t&&(i[r][n]=t[n](i[r][n]))}function Jt(i,e,t){return function(){const s=new Array(1+arguments.length);s[0]=e;for(var r=1;r<s.length;r++)s[r]=arguments[r-1];return i[t].apply(this,s)}}function Zd(i,e,t){const s=e.send,r=e.ts,n=e.methodLevel,o=e.methodValue,a=e.val,c=i._logEvent.bindings;Gs(t,i._serialize||Object.keys(i.serializers),i.serializers,i._stdErrSerialize===void 0?!0:i._stdErrSerialize),i._logEvent.ts=r,i._logEvent.messages=t.filter(function(h){return c.indexOf(h)===-1}),i._logEvent.level.label=n,i._logEvent.level.value=o,s(n,i._logEvent,a),i._logEvent=Fr(c)}function Fr(i){return{ts:0,messages:[],bindings:i||[],level:{label:"",value:0}}}function Xd(i){const e={type:i.constructor.name,msg:i.message,stack:i.stack};for(const t in i)e[t]===void 0&&(e[t]=i[t]);return e}function eg(i){return typeof i.timestamp=="function"?i.timestamp:i.timestamp===!1?$c:Sc}function ms(){return{}}function pr(i){return i}function ts(){}function $c(){return!1}function Sc(){return Date.now()}function tg(){return Math.round(Date.now()/1e3)}function ig(){return new Date(Date.now()).toISOString()}function sg(){function i(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 i(self)||i(window)||i(this)||{}}}const cs=ch(hi),rg={level:"info"},hs="custom_context",gn=1e3*1024;let ng=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}},So=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new ng(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;t!==null;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}},Oc=class{constructor(e,t=gn){this.level=e??"error",this.levelValue=hi.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new So(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(Pr({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 So(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(Pr({extraMetadata:e})),new Blob(t,{type:"application/json"})}},og=class{constructor(e,t=gn){this.baseChunkLogger=new Oc(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),s=document.createElement("a");s.href=t,s.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)}},ag=class{constructor(e,t=gn){this.baseChunkLogger=new Oc(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var cg=Object.defineProperty,hg=Object.defineProperties,lg=Object.getOwnPropertyDescriptors,Oo=Object.getOwnPropertySymbols,ug=Object.prototype.hasOwnProperty,pg=Object.prototype.propertyIsEnumerable,xo=(i,e,t)=>e in i?cg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Rs=(i,e)=>{for(var t in e||(e={}))ug.call(e,t)&&xo(i,t,e[t]);if(Oo)for(var t of Oo(e))pg.call(e,t)&&xo(i,t,e[t]);return i},qs=(i,e)=>hg(i,lg(e));function Ws(i){return qs(Rs({},i),{level:(i==null?void 0:i.level)||rg.level})}function dg(i,e=hs){return i[e]||""}function gg(i,e,t=hs){return i[t]=e,i}function Ce(i,e=hs){let t="";return typeof i.bindings>"u"?t=dg(i,e):t=i.bindings().context||"",t}function fg(i,e,t=hs){const s=Ce(i,t);return s.trim()?`${s}/${e}`:e}function $e(i,e,t=hs){const s=fg(i,e,t),r=i.child({context:s});return gg(r,s,t)}function yg(i){var e,t;const s=new og((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:cs(qs(Rs({},i.opts),{level:"trace",browser:qs(Rs({},(t=i.opts)==null?void 0:t.browser),{write:r=>s.write(r)})})),chunkLoggerController:s}}function mg(i){var e;const t=new ag((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:cs(qs(Rs({},i.opts),{level:"trace"}),t),chunkLoggerController:t}}function wg(i){return typeof i.loggerOverride<"u"&&typeof i.loggerOverride!="string"?{logger:i.loggerOverride,chunkLoggerController:null}:typeof window<"u"?yg(i):mg(i)}var bg=Object.defineProperty,vg=(i,e,t)=>e in i?bg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ao=(i,e,t)=>vg(i,typeof e!="symbol"?e+"":e,t);let Eg=class extends Pi{constructor(e){super(),this.opts=e,Ao(this,"protocol","wc"),Ao(this,"version",2)}};var Ig=Object.defineProperty,_g=(i,e,t)=>e in i?Ig(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Pg=(i,e,t)=>_g(i,typeof e!="symbol"?e+"":e,t);let $g=class extends Pi{constructor(e,t){super(),this.core=e,this.logger=t,Pg(this,"records",new Map)}},Sg=class{constructor(e,t){this.logger=e,this.core=t}};class Og extends Pi{constructor(e,t){super(),this.relayer=e,this.logger=t}}let xg=class extends Pi{constructor(e){super()}},Ag=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},Cg=class extends Pi{constructor(e,t){super(),this.relayer=e,this.logger=t}},Tg=class extends Pi{constructor(e,t){super(),this.core=e,this.logger=t}},Ng=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},Rg=class{constructor(e,t){this.projectId=e,this.logger=t}},qg=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var jg=Object.defineProperty,kg=(i,e,t)=>e in i?jg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Co=(i,e,t)=>kg(i,typeof e!="symbol"?e+"":e,t);let Dg=class{constructor(e){this.opts=e,Co(this,"protocol","wc"),Co(this,"version",2)}},Lg=class{constructor(e){this.client=e}};const xc="wc",Ac=2,js="core",ot=`${xc}@2:${js}:`,Fg={name:js,logger:"error"},Ug={database:":memory:"},Mg="crypto",To="client_ed25519_seed",Bg=C.ONE_DAY,zg="keychain",Vg="0.3",Hg="messages",Kg="0.3",No=C.SIX_HOURS,Gg="publisher",Cc="irn",Wg="error",Tc="wss://relay.walletconnect.org",Jg="relayer",de={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},Qg="_subscription",Le={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Yg=.1,Ur="2.21.1",te={link_mode:"link_mode",relay:"relay"},Ss={inbound:"inbound",outbound:"outbound"},Zg="0.3",Xg="WALLETCONNECT_CLIENT_ID",Ro="WALLETCONNECT_LINK_MODE_APPS",Re={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},ef="subscription",tf="0.3",sf="pairing",rf="0.3",ki={wc_pairingDelete:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:C.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:C.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:C.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:C.ONE_DAY,prompt:!1,tag:0},res:{ttl:C.ONE_DAY,prompt:!1,tag:0}}},qt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ve={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},nf="history",of="0.3",af="expirer",Ue={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},cf="0.3",hf="verify-api",lf="https://verify.walletconnect.com",Nc="https://verify.walletconnect.org",Ki=Nc,uf=`${Ki}/v3`,pf=[lf,Nc],df="echo",gf="https://echo.walletconnect.com",tt={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"},dt={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"},He={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},At={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Ct={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Di={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},ff=.1,yf="event-client",mf=86400,wf="https://pulse.walletconnect.org/batch";function bf(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(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,f=0,w=0,y=d.length;w!==y&&d[w]===0;)w++,m++;for(var I=(y-w)*l+1>>>0,_=new Uint8Array(I);w!==y;){for(var T=d[w],P=0,S=I-1;(T!==0||P<f)&&S!==-1;S--,P++)T+=256*_[S]>>>0,_[S]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");f=P,w++}for(var N=I-f;N!==I&&_[N]===0;)N++;for(var b=c.repeat(m);N<I;++N)b+=i.charAt(_[N]);return b}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var f=0,w=0;d[m]===c;)f++,m++;for(var y=(d.length-m)*h+1>>>0,I=new Uint8Array(y);d[m];){var _=t[d.charCodeAt(m)];if(_===255)return;for(var T=0,P=y-1;(_!==0||T<w)&&P!==-1;P--,T++)_+=a*I[P]>>>0,I[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");w=T,m++}if(d[m]!==" "){for(var S=y-w;S!==y&&I[S]===0;)S++;for(var N=new Uint8Array(f+(y-S)),b=f;S!==y;)N[b++]=I[S++];return N}}}function g(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:g}}var vf=bf,Ef=vf;const Rc=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},If=i=>new TextEncoder().encode(i),_f=i=>new TextDecoder().decode(i);class Pf{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 $f{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 Sf{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 Sf({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Of{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Pf(e,t,s),this.decoder=new $f(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 Of(i,e,t,s),ls=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=Ef(t,e);return Js({prefix:i,name:e,encode:s,decode:n=>Rc(r(n))})},xf=(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},Af=(i,e,t)=>{const s=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),s)for(;n.length*t&7;)n+="=";return n},be=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>Js({prefix:e,name:i,encode(r){return Af(r,s,t)},decode(r){return xf(r,s,t,i)}}),Cf=Js({prefix:"\0",name:"identity",encode:i=>_f(i),decode:i=>If(i)});var Tf=Object.freeze({__proto__:null,identity:Cf});const Nf=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Rf=Object.freeze({__proto__:null,base2:Nf});const qf=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var jf=Object.freeze({__proto__:null,base8:qf});const kf=ls({prefix:"9",name:"base10",alphabet:"0123456789"});var Df=Object.freeze({__proto__:null,base10:kf});const Lf=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ff=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Uf=Object.freeze({__proto__:null,base16:Lf,base16upper:Ff});const Mf=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bf=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zf=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Vf=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Hf=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kf=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Gf=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Wf=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jf=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Qf=Object.freeze({__proto__:null,base32:Mf,base32upper:Bf,base32pad:zf,base32padupper:Vf,base32hex:Hf,base32hexupper:Kf,base32hexpad:Gf,base32hexpadupper:Wf,base32z:Jf});const Yf=ls({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zf=ls({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xf=Object.freeze({__proto__:null,base36:Yf,base36upper:Zf});const ey=ls({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ty=ls({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var iy=Object.freeze({__proto__:null,base58btc:ey,base58flickr:ty});const sy=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ry=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ny=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),oy=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ay=Object.freeze({__proto__:null,base64:sy,base64pad:ry,base64url:ny,base64urlpad:oy});const jc=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),cy=jc.reduce((i,e,t)=>(i[t]=e,i),[]),hy=jc.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function ly(i){return i.reduce((e,t)=>(e+=cy[t],e),"")}function uy(i){const e=[];for(const t of i){const s=hy[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const py=Js({prefix:"🚀",name:"base256emoji",encode:ly,decode:uy});var dy=Object.freeze({__proto__:null,base256emoji:py}),gy=kc,qo=128,fy=127,yy=~fy,my=Math.pow(2,31);function kc(i,e,t){e=e||[],t=t||0;for(var s=t;i>=my;)e[t++]=i&255|qo,i/=128;for(;i&yy;)e[t++]=i&255|qo,i>>>=7;return e[t]=i|0,kc.bytes=t-s+1,e}var wy=Mr,by=128,jo=127;function Mr(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw Mr.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&jo)<<r:(o&jo)*Math.pow(2,r),r+=7}while(o>=by);return Mr.bytes=n-s,t}var vy=Math.pow(2,7),Ey=Math.pow(2,14),Iy=Math.pow(2,21),_y=Math.pow(2,28),Py=Math.pow(2,35),$y=Math.pow(2,42),Sy=Math.pow(2,49),Oy=Math.pow(2,56),xy=Math.pow(2,63),Ay=function(i){return i<vy?1:i<Ey?2:i<Iy?3:i<_y?4:i<Py?5:i<$y?6:i<Sy?7:i<Oy?8:i<xy?9:10},Cy={encode:gy,decode:wy,encodingLength:Ay},Dc=Cy;const ko=(i,e,t=0)=>(Dc.encode(i,e,t),e),Do=i=>Dc.encodingLength(i),Br=(i,e)=>{const t=e.byteLength,s=Do(i),r=s+Do(t),n=new Uint8Array(r+t);return ko(i,n,0),ko(t,n,s),n.set(e,r),new Ty(i,t,e,n)};class Ty{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Lc=({name:i,code:e,encode:t})=>new Ny(i,e,t);class Ny{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Br(this.code,t):t.then(s=>Br(this.code,s))}else throw Error("Unknown type, must be binary type")}}const Fc=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Ry=Lc({name:"sha2-256",code:18,encode:Fc("SHA-256")}),qy=Lc({name:"sha2-512",code:19,encode:Fc("SHA-512")});var jy=Object.freeze({__proto__:null,sha256:Ry,sha512:qy});const Uc=0,ky="identity",Mc=Rc,Dy=i=>Br(Uc,Mc(i)),Ly={code:Uc,name:ky,encode:Mc,digest:Dy};var Fy=Object.freeze({__proto__:null,identity:Ly});new TextEncoder,new TextDecoder;const Lo={...Tf,...Rf,...jf,...Df,...Uf,...Qf,...Xf,...iy,...ay,...dy};({...jy,...Fy});function Uy(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Bc(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Fo=Bc("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),dr=Bc("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=Uy(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),My={utf8:Fo,"utf-8":Fo,hex:Lo.base16,latin1:dr,ascii:dr,binary:dr,...Lo};function By(i,e="utf8"){const t=My[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 zy=Object.defineProperty,Vy=(i,e,t)=>e in i?zy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xe=(i,e,t)=>Vy(i,typeof e!="symbol"?e+"":e,t);class Hy{constructor(e,t){this.core=e,this.logger=t,Xe(this,"keychain",new Map),Xe(this,"name",zg),Xe(this,"version",Vg),Xe(this,"initialized",!1),Xe(this,"storagePrefix",ot),Xe(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),Xe(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),Xe(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),Xe(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=A("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),Xe(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,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}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ky=Object.defineProperty,Gy=(i,e,t)=>e in i?Ky(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>Gy(i,typeof e!="symbol"?e+"":e,t);class Wy{constructor(e,t,s){this.core=e,this.logger=t,ye(this,"name",Mg),ye(this,"keychain"),ye(this,"randomSessionIdentifier",Lr()),ye(this,"initialized",!1),ye(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),ye(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),ye(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=bn(r);return mh(n.publicKey)}),ye(this,"generateKeyPair",()=>{this.isInitialized();const r=Hp();return this.setPrivateKey(r.publicKey,r.privateKey)}),ye(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=bn(n),a=this.randomSessionIdentifier;return await wh(a,r,Bg,o)}),ye(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Kp(a,n);return this.setSymKey(c,o)}),ye(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||$s(r);return await this.keychain.set(o,r),o}),ye(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),ye(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),ye(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Ic(o),c=Pr(n);if(po(a))return Jp(c,o==null?void 0:o.encoding);if(uo(a)){const p=a.senderPublicKey,g=a.receiverPublicKey;r=await this.generateSharedKey(p,g)}const h=this.getSymKey(r),{type:l,senderPublicKey:u}=a;return Gp({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),ye(this,"decode",async(r,n,o)=>{this.isInitialized();const a=Yp(n,o);if(po(a)){const c=Qp(n,o==null?void 0:o.encoding);return vn(c)}if(uo(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Wp({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return vn(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),ye(this,"getPayloadType",(r,n=We)=>{const o=Xi({encoded:r,encoding:n});return Bt(o.type)}),ye(this,"getPayloadSenderPublicKey",(r,n=We)=>{const o=Xi({encoded:r,encoding:n});return o.senderPublicKey?Ae(o.senderPublicKey,Pe):void 0}),this.core=e,this.logger=$e(t,this.name),this.keychain=s||new Hy(this.core,this.logger)}get context(){return Ce(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(To)}catch{e=Lr(),await this.keychain.set(To,e)}return By(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Jy=Object.defineProperty,Qy=Object.defineProperties,Yy=Object.getOwnPropertyDescriptors,Uo=Object.getOwnPropertySymbols,Zy=Object.prototype.hasOwnProperty,Xy=Object.prototype.propertyIsEnumerable,zr=(i,e,t)=>e in i?Jy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,em=(i,e)=>{for(var t in e||(e={}))Zy.call(e,t)&&zr(i,t,e[t]);if(Uo)for(var t of Uo(e))Xy.call(e,t)&&zr(i,t,e[t]);return i},tm=(i,e)=>Qy(i,Yy(e)),Te=(i,e,t)=>zr(i,typeof e!="symbol"?e+"":e,t);class im extends Sg{constructor(e,t){super(e,t),this.logger=e,this.core=t,Te(this,"messages",new Map),Te(this,"messagesWithoutClientAck",new Map),Te(this,"name",Hg),Te(this,"version",Kg),Te(this,"initialized",!1),Te(this,"storagePrefix",ot),Te(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}}}),Te(this,"set",async(s,r,n)=>{this.isInitialized();const o=st(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===Ss.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,tm(em({},c),{[o]:r}))}return await this.persist(),o}),Te(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Te(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}),Te(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=st(r);return typeof n[o]<"u"}),Te(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=st(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Te(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=$e(e,this.name),this.core=t}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,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}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var sm=Object.defineProperty,rm=Object.defineProperties,nm=Object.getOwnPropertyDescriptors,Mo=Object.getOwnPropertySymbols,om=Object.prototype.hasOwnProperty,am=Object.prototype.propertyIsEnumerable,Vr=(i,e,t)=>e in i?sm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ws=(i,e)=>{for(var t in e||(e={}))om.call(e,t)&&Vr(i,t,e[t]);if(Mo)for(var t of Mo(e))am.call(e,t)&&Vr(i,t,e[t]);return i},gr=(i,e)=>rm(i,nm(e)),Ke=(i,e,t)=>Vr(i,typeof e!="symbol"?e+"":e,t);class cm extends Og{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Ke(this,"events",new St.EventEmitter),Ke(this,"name",Gg),Ke(this,"queue",new Map),Ke(this,"publishTimeout",C.toMiliseconds(C.ONE_MINUTE)),Ke(this,"initialPublishTimeout",C.toMiliseconds(C.ONE_SECOND*15)),Ke(this,"needsTransportRestart",!1),Ke(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)||No,c=Ts(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}},g=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const d=new Promise(async m=>{const f=({id:y})=>{p.opts.id===y&&(this.removeRequestFromQueue(y),this.relayer.events.removeListener(de.publish,f),m(p))};this.relayer.events.on(de.publish,f);const w=_t(new Promise((y,I)=>{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(y).catch(_=>{this.logger.warn(_,_==null?void 0:_.message),I(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await w,this.events.removeListener(de.publish,f)}catch(y){this.queue.set(u,gr(ws({},p),{attempt:1})),this.logger.warn(y,y==null?void 0:y.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await _t(d,this.publishTimeout,g)}catch(d){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(d),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw d}finally{this.queue.delete(u)}}),Ke(this,"on",(s,r)=>{this.events.on(s,r)}),Ke(this,"once",(s,r)=>{this.events.once(s,r)}),Ke(this,"off",(s,r)=>{this.events.off(s,r)}),Ke(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=$e(t,this.name),this.registerEventListeners()}get context(){return Ce(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=No,prompt:h,tag:l,id:u,attestation:p,tvf:g}=e,d={method:Mi(Ts().protocol).publish,params:ws({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},g),id:u};we((t=d.params)==null?void 0:t.prompt)&&((s=d.params)==null||delete s.prompt),we((r=d.params)==null?void 0:r.tag)&&((n=d.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:d});const m=await this.relayer.request(d);return this.relayer.events.emit(de.publish,e),this.logger.debug("Successfully Published Payload"),m}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,gr(ws({},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(ws({},e),{topic:r,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on($i.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(de.connection_stalled);return}this.checkQueue()}),this.relayer.on(de.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var hm=Object.defineProperty,lm=(i,e,t)=>e in i?hm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qt=(i,e,t)=>lm(i,typeof e!="symbol"?e+"":e,t);class um{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 pm=Object.defineProperty,dm=Object.defineProperties,gm=Object.getOwnPropertyDescriptors,Bo=Object.getOwnPropertySymbols,fm=Object.prototype.hasOwnProperty,ym=Object.prototype.propertyIsEnumerable,Hr=(i,e,t)=>e in i?pm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Li=(i,e)=>{for(var t in e||(e={}))fm.call(e,t)&&Hr(i,t,e[t]);if(Bo)for(var t of Bo(e))ym.call(e,t)&&Hr(i,t,e[t]);return i},fr=(i,e)=>dm(i,gm(e)),Y=(i,e,t)=>Hr(i,typeof e!="symbol"?e+"":e,t);class mm extends Cg{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Y(this,"subscriptions",new Map),Y(this,"topicMap",new um),Y(this,"events",new St.EventEmitter),Y(this,"name",ef),Y(this,"version",tf),Y(this,"pending",new Map),Y(this,"cached",[]),Y(this,"initialized",!1),Y(this,"storagePrefix",ot),Y(this,"subscribeTimeout",C.toMiliseconds(C.ONE_MINUTE)),Y(this,"initialSubscribeTimeout",C.toMiliseconds(C.ONE_SECOND*15)),Y(this,"clientId"),Y(this,"batchSubscribeTopicsLimit",500),Y(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Y(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=Ts(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}}),Y(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)}),Y(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),Y(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),Y(this,"on",(s,r)=>{this.events.on(s,r)}),Y(this,"once",(s,r)=>{this.events.once(s,r)}),Y(this,"off",(s,r)=>{this.events.off(s,r)}),Y(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),Y(this,"start",async()=>{await this.onConnect()}),Y(this,"stop",async()=>{await this.onDisconnect()}),Y(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Y(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)}),Y(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on($i.pulse,async()=>{await this.checkPending()}),this.events.on(Re.created,async s=>{const r=Re.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(Re.deleted,async s=>{const r=Re.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=$e(t,this.name),this.clientId=""}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const r=Ts(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Q("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,s){var r;(!s||(s==null?void 0:s.transportType)===te.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Mi(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)===te.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},C.toMiliseconds(C.ONE_SECOND)),a;const c=new Promise(async l=>{const u=p=>{p.topic===e&&(this.events.removeListener(Re.created,u),l(p.id))};this.events.on(Re.created,u);try{const p=await _t(new Promise((g,d)=>{this.relayer.request(n).catch(m=>{this.logger.warn(m,m==null?void 0:m.message),d(m)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Re.created,u),l(p)}catch{}}),h=await _t(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(de.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Mi(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await _t(new Promise(r=>{this.relayer.request(s).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Mi(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let r;try{r=await await _t(new Promise((n,o)=>{this.relayer.request(s).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Mi(s.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,fr(Li({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Li({},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,Li({},t)),this.topicMap.set(t.topic,e),this.events.emit(Re.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}=A("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(Re.deleted,fr(Li({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Re.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(Re.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=A("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async t=>fr(Li({},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 Nl(C.toMiliseconds(C.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}=A("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 st(e+await this.getClientId())}}var wm=Object.defineProperty,zo=Object.getOwnPropertySymbols,bm=Object.prototype.hasOwnProperty,vm=Object.prototype.propertyIsEnumerable,Kr=(i,e,t)=>e in i?wm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Vo=(i,e)=>{for(var t in e||(e={}))bm.call(e,t)&&Kr(i,t,e[t]);if(zo)for(var t of zo(e))vm.call(e,t)&&Kr(i,t,e[t]);return i},K=(i,e,t)=>Kr(i,typeof e!="symbol"?e+"":e,t);class Em extends xg{constructor(e){super(e),K(this,"protocol","wc"),K(this,"version",2),K(this,"core"),K(this,"logger"),K(this,"events",new St.EventEmitter),K(this,"provider"),K(this,"messages"),K(this,"subscriber"),K(this,"publisher"),K(this,"name",Jg),K(this,"transportExplicitlyClosed",!1),K(this,"initialized",!1),K(this,"connectionAttemptInProgress",!1),K(this,"relayUrl"),K(this,"projectId"),K(this,"packageName"),K(this,"bundleId"),K(this,"hasExperiencedNetworkDisruption",!1),K(this,"pingTimeout"),K(this,"heartBeatTimeout",C.toMiliseconds(C.THIRTY_SECONDS+C.FIVE_SECONDS)),K(this,"reconnectTimeout"),K(this,"connectPromise"),K(this,"reconnectInProgress",!1),K(this,"requestsInFlight",[]),K(this,"connectTimeout",C.toMiliseconds(C.ONE_SECOND*15)),K(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}}),K(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,s,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(s=(t=this.provider)==null?void 0:t.connection)==null?void 0:s.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),K(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),K(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(de.connect)}),K(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),K(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(de.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),K(this,"registerProviderListeners",()=>{this.provider.on(Le.payload,this.onPayloadHandler),this.provider.on(Le.connect,this.onConnectHandler),this.provider.on(Le.disconnect,this.onDisconnectHandler),this.provider.on(Le.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?$e(e.logger,this.name):cs(Ws({level:e.logger||Wg})),this.messages=new im(this.logger,e.core),this.subscriber=new mm(this,this.logger),this.publisher=new cm(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Tc,this.projectId=e.projectId,yl()?this.packageName=jn():ml()&&(this.bundleId=jn()),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 Ce(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1||!1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:te.relay},Ss.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(Re.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Re.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,Vo({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&u(p)})||a,l()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await _t(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,s)=>{await this.connect(e).then(t).catch(s).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Po())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==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=ce(C.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(de.message,e),await this.recordMessageEvent(e,Ss.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(Le.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(Le.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(Le.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Le.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,C.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(As())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(s=this.provider)==null?void 0:s.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Be(new yh(Il({sdkVersion:Ur,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:s,message:r}=e;await this.messages.set(s,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||s.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,s);return r&&this.logger.warn(`Ignoring duplicate message: ${s}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),sn(e)){if(!e.method.endsWith(Qg))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:te.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Vo({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else rn(e)&&this.events.emit(de.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Ss.inbound),this.events.emit(de.message,e))}async acknowledgePayload(e){const t=Fs(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Le.payload,this.onPayloadHandler),this.provider.off(Le.connect,this.onConnectHandler),this.provider.off(Le.disconnect,this.onDisconnectHandler),this.provider.off(Le.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Po();Vd(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($i.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Gd())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(de.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},C.toMiliseconds(Yg)))))}isInitialized(){if(!this.initialized){const{message:e}=A("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 Im(){}function Ho(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 Ko(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Go(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const _m="[object RegExp]",Pm="[object String]",$m="[object Number]",Sm="[object Boolean]",Wo="[object Arguments]",Om="[object Symbol]",xm="[object Date]",Am="[object Map]",Cm="[object Set]",Tm="[object Array]",Nm="[object Function]",Rm="[object ArrayBuffer]",yr="[object Object]",qm="[object Error]",jm="[object DataView]",km="[object Uint8Array]",Dm="[object Uint8ClampedArray]",Lm="[object Uint16Array]",Fm="[object Uint32Array]",Um="[object BigUint64Array]",Mm="[object Int8Array]",Bm="[object Int16Array]",zm="[object Int32Array]",Vm="[object BigInt64Array]",Hm="[object Float32Array]",Km="[object Float64Array]";function Gm(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function Wm(i,e,t){return Bi(i,e,void 0,void 0,void 0,void 0,t)}function Bi(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 Gi(i,e,n,o)}return Gi(i,e,n,o)}function Gi(i,e,t,s){if(Object.is(i,e))return!0;let r=Go(i),n=Go(e);if(r===Wo&&(r=yr),n===Wo&&(n=yr),r!==n)return!1;switch(r){case Pm:return i.toString()===e.toString();case $m:{const c=i.valueOf(),h=e.valueOf();return Gm(c,h)}case Sm:case xm:case Om:return Object.is(i.valueOf(),e.valueOf());case _m:return i.source===e.source&&i.flags===e.flags;case Nm: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 Am:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!Bi(h,e.get(c),c,i,e,t,s))return!1;return!0}case Cm:{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(g=>Bi(u,g,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case Tm:case km:case Dm:case Lm:case Fm:case Um:case Mm:case Bm:case zm:case Vm:case Hm:case Km:{if(typeof Ie<"u"&&Ie.isBuffer(i)!==Ie.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!Bi(i[c],e[c],c,i,e,t,s))return!1;return!0}case Rm:return i.byteLength!==e.byteLength?!1:Gi(new Uint8Array(i),new Uint8Array(e),t,s);case jm:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:Gi(new Uint8Array(i),new Uint8Array(e),t,s);case qm:return i.name===e.name&&i.message===e.message;case yr:{if(!(Gi(i.constructor,e.constructor,t,s)||Ho(i)&&Ho(e)))return!1;const c=[...Object.keys(i),...Ko(i)],h=[...Object.keys(e),...Ko(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 g=e[u];if(!Bi(p,g,u,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function Jm(i,e){return Wm(i,e,Im)}var Qm=Object.defineProperty,Jo=Object.getOwnPropertySymbols,Ym=Object.prototype.hasOwnProperty,Zm=Object.prototype.propertyIsEnumerable,Gr=(i,e,t)=>e in i?Qm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qo=(i,e)=>{for(var t in e||(e={}))Ym.call(e,t)&&Gr(i,t,e[t]);if(Jo)for(var t of Jo(e))Zm.call(e,t)&&Gr(i,t,e[t]);return i},Se=(i,e,t)=>Gr(i,typeof e!="symbol"?e+"":e,t);class zt extends Ag{constructor(e,t,s,r=ot,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,Se(this,"map",new Map),Se(this,"version",Zg),Se(this,"cached",[]),Se(this,"initialized",!1),Se(this,"getKey"),Se(this,"storagePrefix",ot),Se(this,"recentlyDeleted",[]),Se(this,"recentlyDeletedLimit",200),Se(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!we(o)?this.map.set(this.getKey(o),o):Ed(o)?this.map.set(o.id,o):Id(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Se(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Se(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Se(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Jm(a[c],o[c]))):this.values)),Se(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Qo(Qo({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Se(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=$e(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=A("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=A("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}=A("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}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Xm=Object.defineProperty,ew=(i,e,t)=>e in i?Xm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,z=(i,e,t)=>ew(i,typeof e!="symbol"?e+"":e,t);class tw{constructor(e,t){this.core=e,this.logger=t,z(this,"name",sf),z(this,"version",rf),z(this,"events",new tn),z(this,"pairings"),z(this,"initialized",!1),z(this,"storagePrefix",ot),z(this,"ignoredPayloadTypes",[mt]),z(this,"registeredMethods",[]),z(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),z(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),z(this,"create",async s=>{this.isInitialized();const r=Lr(),n=await this.core.crypto.setSymKey(r),o=ce(C.FIVE_MINUTES),a={protocol:Cc},c={topic:n,expiry:o,relay:a,active:!1,methods:s==null?void 0:s.methods},h=fo({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(qt.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}}),z(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s==null?void 0:s.uri,trace:[tt.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(tt.pairing_uri_validation_success),r.addTrace(tt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(tt.existing_pairing),l.active)throw r.setError(dt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(tt.pairing_not_expired)}const u=c||ce(C.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(tt.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(qt.create,p),r.addTrace(tt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(tt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(dt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(g){throw r.setError(dt.subscribe_pairing_topic_failure),g}return r.addTrace(tt.subscribe_pairing_topic_success),p}),z(this,"activate",async({topic:s})=>{this.isInitialized();const r=ce(C.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),z(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}=Tt();this.events.once(J("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),z(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),z(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),z(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),z(this,"disconnect",async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:r}=s;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Q("USER_DISCONNECTED")),await this.deletePairing(r))}),z(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return fo({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),z(this,"sendRequest",async(s,r,n)=>{const o=kt(r,n),a=await this.core.crypto.encode(s,o),c=ki[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),z(this,"sendResult",async(s,r,n)=>{const o=Fs(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=ki[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),z(this,"sendError",async(s,r,n)=>{const o=_a(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=ki[c]?ki[c].res:ki.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),z(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,Q("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),z(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>Et(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),z(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)}}),z(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)}}),z(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(qt.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),z(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{pt(r)?this.events.emit(J("pairing_ping",n),{}):it(r)&&this.events.emit(J("pairing_ping",n),{error:r.error})},500)}),z(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(qt.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),z(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Q("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,s,a),this.logger.error(a)}catch(a){await this.sendError(n,s,a),this.logger.error(a)}}),z(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(Q("WC_METHOD_UNSUPPORTED",s))}),z(this,"isValidPair",(s,r)=>{var n;if(!Oe(s)){const{message:a}=A("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(dt.malformed_pairing_uri),new Error(a)}if(!vd(s.uri)){const{message:a}=A("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(dt.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}=A("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(dt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=A("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(dt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&C.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(dt.pairing_expired);const{message:a}=A("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),z(this,"isValidPing",async s=>{if(!Oe(s)){const{message:n}=A("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),z(this,"isValidDisconnect",async s=>{if(!Oe(s)){const{message:n}=A("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),z(this,"isValidPairingTopic",async s=>{if(!ne(s,!1)){const{message:r}=A("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=A("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(Et(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=A("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=$e(t,this.name),this.pairings=new zt(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ce(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(de.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==te.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);sn(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):rn(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,s)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(Ue.expired,async e=>{const{topic:t}=za(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(qt.expire,{topic:t}))})}}var iw=Object.defineProperty,sw=(i,e,t)=>e in i?iw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,me=(i,e,t)=>sw(i,typeof e!="symbol"?e+"":e,t);class rw extends $g{constructor(e,t){super(e,t),this.core=e,this.logger=t,me(this,"records",new Map),me(this,"events",new St.EventEmitter),me(this,"name",nf),me(this,"version",of),me(this,"cached",[]),me(this,"initialized",!1),me(this,"storagePrefix",ot),me(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)}),me(this,"set",(s,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:s,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:s,request:{method:r.method,params:r.params||null},chainId:n,expiry:ce(C.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ve.created,o)}),me(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=it(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(Ve.updated,r))}),me(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))),me(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(Ve.deleted,n)}}),this.persist()}),me(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),me(this,"on",(s,r)=>{this.events.on(s,r)}),me(this,"once",(s,r)=>{this.events.once(s,r)}),me(this,"off",(s,r)=>{this.events.off(s,r)}),me(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:kt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:s}=A("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ve.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=A("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(Ve.created,e=>{const t=Ve.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ve.updated,e=>{const t=Ve.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ve.deleted,e=>{const t=Ve.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on($i.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{C.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Ve.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var nw=Object.defineProperty,ow=(i,e,t)=>e in i?nw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ee=(i,e,t)=>ow(i,typeof e!="symbol"?e+"":e,t);class aw extends Tg{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ee(this,"expirations",new Map),Ee(this,"events",new St.EventEmitter),Ee(this,"name",af),Ee(this,"version",cf),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",ot),Ee(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ee(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ee(this,"set",(s,r)=>{this.isInitialized();const n=this.formatTarget(s),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Ue.created,{target:n,expiration:o})}),Ee(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),Ee(this,"del",s=>{if(this.isInitialized(),this.has(s)){const r=this.formatTarget(s),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Ue.deleted,{target:r,expiration:n})}}),Ee(this,"on",(s,r)=>{this.events.on(s,r)}),Ee(this,"once",(s,r)=>{this.events.once(s,r)}),Ee(this,"off",(s,r)=>{this.events.off(s,r)}),Ee(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return _l(e);if(typeof e=="number")return Pl(e);const{message:t}=A("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(Ue.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=A("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}=A("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;C.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Ue.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on($i.pulse,()=>this.checkExpirations()),this.events.on(Ue.created,e=>{const t=Ue.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ue.expired,e=>{const t=Ue.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ue.deleted,e=>{const t=Ue.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var cw=Object.defineProperty,hw=(i,e,t)=>e in i?cw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,re=(i,e,t)=>hw(i,typeof e!="symbol"?e+"":e,t);class lw extends Ng{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,re(this,"name",hf),re(this,"abortController"),re(this,"isDevEnv"),re(this,"verifyUrlV3",uf),re(this,"storagePrefix",ot),re(this,"version",Ac),re(this,"publicKey"),re(this,"fetchPromise"),re(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&C.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),re(this,"register",async r=>{if(!xi()||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=yi(),l=this.startAbortTimer(C.ONE_SECOND*5),u=await new Promise((p,g)=>{const d=()=>{window.removeEventListener("message",f),h.body.removeChild(m),g("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const m=h.createElement("iframe");m.src=c,m.style.display="none",m.addEventListener("error",d,{signal:this.abortController.signal});const f=w=>{if(w.data&&typeof w.data=="string")try{const y=JSON.parse(w.data);if(y.type==="verify_attestation"){if(_r(y.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(m),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",f),p(y.attestation===null?"":y.attestation)}}catch(y){this.logger.warn(y)}};h.body.appendChild(m),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),re(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(_r(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),re(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(C.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),re(this,"getVerifyUrl",r=>{let n=r||Ki;return pf.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ki}`),n=Ki),n}),re(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(C.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),re(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),re(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),re(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),re(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),re(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),re(this,"validateAttestation",(r,n)=>{const o=Xp(r,n.publicKey),a={hasExpired:C.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=$e(t,this.name),this.abortController=new AbortController,this.isDevEnv=on(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ce(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),C.toMiliseconds(e))}}var uw=Object.defineProperty,pw=(i,e,t)=>e in i?uw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Yo=(i,e,t)=>pw(i,typeof e!="symbol"?e+"":e,t);class dw extends Rg{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Yo(this,"context",df),Yo(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${gf}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=$e(t,this.context)}}var gw=Object.defineProperty,Zo=Object.getOwnPropertySymbols,fw=Object.prototype.hasOwnProperty,yw=Object.prototype.propertyIsEnumerable,Wr=(i,e,t)=>e in i?gw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Fi=(i,e)=>{for(var t in e||(e={}))fw.call(e,t)&&Wr(i,t,e[t]);if(Zo)for(var t of Zo(e))yw.call(e,t)&&Wr(i,t,e[t]);return i},le=(i,e,t)=>Wr(i,typeof e!="symbol"?e+"":e,t);class mw extends qg{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,le(this,"context",yf),le(this,"storagePrefix",ot),le(this,"storageVersion",ff),le(this,"events",new Map),le(this,"shouldPersist",!1),le(this,"init",async()=>{if(!on())try{const r={eventId:Dn(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ma(this.core.relayer.protocol,this.core.relayer.version,Ur)}}};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=Dn(),l=this.core.projectId||"",u=Date.now(),p=Fi({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 Fi(Fi({},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($i.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{C.fromMiliseconds(Date.now())-C.fromMiliseconds(r.timestamp)>mf&&(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,Fi(Fi({},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(`${wf}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ur}${n}`,{method:"POST",body:JSON.stringify(r)})}),le(this,"getAppDomain",()=>Ua().url),this.logger=$e(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var ww=Object.defineProperty,Xo=Object.getOwnPropertySymbols,bw=Object.prototype.hasOwnProperty,vw=Object.prototype.propertyIsEnumerable,Jr=(i,e,t)=>e in i?ww(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ea=(i,e)=>{for(var t in e||(e={}))bw.call(e,t)&&Jr(i,t,e[t]);if(Xo)for(var t of Xo(e))vw.call(e,t)&&Jr(i,t,e[t]);return i},ee=(i,e,t)=>Jr(i,typeof e!="symbol"?e+"":e,t);let Ew=class zc extends Eg{constructor(e){var t;super(e),ee(this,"protocol",xc),ee(this,"version",Ac),ee(this,"name",js),ee(this,"relayUrl"),ee(this,"projectId"),ee(this,"customStoragePrefix"),ee(this,"events",new St.EventEmitter),ee(this,"logger"),ee(this,"heartbeat"),ee(this,"relayer"),ee(this,"crypto"),ee(this,"storage"),ee(this,"history"),ee(this,"expirer"),ee(this,"pairing"),ee(this,"verify"),ee(this,"echoClient"),ee(this,"linkModeSupportedApps"),ee(this,"eventClient"),ee(this,"initialized",!1),ee(this,"logChunkController"),ee(this,"on",(a,c)=>this.events.on(a,c)),ee(this,"once",(a,c)=>this.events.once(a,c)),ee(this,"off",(a,c)=>this.events.off(a,c)),ee(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ee(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:te.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e==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)||Tc,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Ws({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:Fg.logger,name:js}),{logger:n,chunkLoggerController:o}=wg({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=$e(n,this.name),this.heartbeat=new gh,this.crypto=new Wy(this,this.logger,e==null?void 0:e.keychain),this.history=new rw(this,this.logger),this.expirer=new aw(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new fh(ea(ea({},Ug),e==null?void 0:e.storageOptions)),this.relayer=new Em({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new tw(this,this.logger),this.verify=new lw(this,this.logger,this.storage),this.echoClient=new dw(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new mw(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new zc(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(Xg,s),t}get context(){return Ce(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Ro,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(Ro)||[],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 zi<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const Iw=Ew,Vc="wc",Hc=2,Kc="client",fn=`${Vc}@${Hc}:${Kc}:`,mr={name:Kc,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},ta="WALLETCONNECT_DEEPLINK_CHOICE",_w="proposal",ia="Proposal expired",Pw="session",Yt=C.SEVEN_DAYS,$w="engine",ue={wc_sessionPropose:{req:{ttl:C.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1104},res:{ttl:C.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1106},res:{ttl:C.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:C.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:C.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1112},res:{ttl:C.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1114},res:{ttl:C.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:C.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:C.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1119}}},wr={min:C.FIVE_MINUTES,max:C.SEVEN_DAYS},et={idle:"IDLE",active:"ACTIVE"},sa={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Sw="request",Ow=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],xw="wc",Aw="auth",Cw="authKeys",Tw="pairingTopics",Nw="requests",Qs=`${xw}@${1.5}:${Aw}:`,Os=`${Qs}:PUB_KEY`;var Rw=Object.defineProperty,qw=Object.defineProperties,jw=Object.getOwnPropertyDescriptors,ra=Object.getOwnPropertySymbols,kw=Object.prototype.hasOwnProperty,Dw=Object.prototype.propertyIsEnumerable,Qr=(i,e,t)=>e in i?Rw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Z=(i,e)=>{for(var t in e||(e={}))kw.call(e,t)&&Qr(i,t,e[t]);if(ra)for(var t of ra(e))Dw.call(e,t)&&Qr(i,t,e[t]);return i},_e=(i,e)=>qw(i,jw(e)),v=(i,e,t)=>Qr(i,typeof e!="symbol"?e+"":e,t);class Lw extends Lg{constructor(e){super(e),v(this,"name",$w),v(this,"events",new tn),v(this,"initialized",!1),v(this,"requestQueue",{state:et.idle,queue:[]}),v(this,"sessionRequestQueue",{state:et.idle,queue:[]}),v(this,"requestQueueDelay",C.ONE_SECOND),v(this,"expectedPairingMethodMap",new Map),v(this,"recentlyDeletedMap",new Map),v(this,"recentlyDeletedLimit",200),v(this,"relayMessageCache",[]),v(this,"pendingSessions",new Map),v(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()},C.toMiliseconds(this.requestQueueDelay)))}),v(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=_e(Z({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=fd(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 P=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=P.active}}catch(P){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),P}if(!l||!p){const{topic:P,uri:S}=await this.client.core.pairing.create();l=P,u=S}if(!l){const{message:P}=A("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(P)}const g=await this.client.core.crypto.generateKeyPair(),d=ue.wc_sessionPropose.req.ttl||C.FIVE_MINUTES,m=ce(d),f=_e(Z(Z({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:Cc}],proposer:{publicKey:g,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:wt()}),w=J("session_connect",f.id),{reject:y,resolve:I,done:_}=Tt(d,ia),T=({id:P})=>{P===f.id&&(this.client.events.off("proposal_expire",T),this.pendingSessions.delete(f.id),this.events.emit(w,{error:{message:ia,code:0}}))};return this.client.events.on("proposal_expire",T),this.events.once(w,({error:P,session:S})=>{this.client.events.off("proposal_expire",T),P?y(P):S&&I(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:u,approval:_}}),v(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}}),v(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:[He.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(b){throw o.setError(At.no_internet_connection),b}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(b){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(At.proposal_not_found),b}try{await this.isValidApprove(t)}catch(b){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(At.session_approve_namespace_validation_failure),b}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=t,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:d,proposer:m,requiredNamespaces:f,optionalNamespaces:w}=g;let y=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:d});y||(y=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:He.session_approve_started,properties:{topic:d,trace:[He.session_approve_started,He.session_namespaces_validation_success]}}));const I=await this.client.core.crypto.generateKeyPair(),_=m.publicKey,T=await this.client.core.crypto.generateSharedKey(I,_),P=Z(Z(Z({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:I,metadata:this.client.metadata},expiry:ce(Yt)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),S=te.relay;y.addTrace(He.subscribing_session_topic);try{await this.client.core.relayer.subscribe(T,{transportType:S})}catch(b){throw y.setError(At.subscribe_session_topic_failure),b}y.addTrace(He.subscribe_session_topic_success);const N=_e(Z({},P),{topic:T,requiredNamespaces:f,optionalNamespaces:w,pairingTopic:d,acknowledged:!1,self:P.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:I,transportType:te.relay});await this.client.session.set(T,N),y.addTrace(He.store_session);try{y.addTrace(He.publishing_session_settle),await this.sendRequest({topic:T,method:"wc_sessionSettle",params:P,throwOnFailedPublish:!0}).catch(b=>{throw y==null||y.setError(At.session_settle_publish_failure),b}),y.addTrace(He.session_settle_publish_success),y.addTrace(He.publishing_session_approve),await this.sendResult({id:a,topic:d,result:{relay:{protocol:c??"irn"},responderPublicKey:I},throwOnFailedPublish:!0}).catch(b=>{throw y==null||y.setError(At.session_approve_publish_failure),b}),y.addTrace(He.session_approve_publish_success)}catch(b){throw this.client.logger.error(b),this.client.session.delete(T,Q("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(T),b}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:m.metadata}),await this.client.proposal.delete(a,Q("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(T,ce(Yt)),{topic:T,acknowledged:()=>Promise.resolve(this.client.session.get(T))}}),v(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,Q("USER_DISCONNECTED")))}),v(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}=Tt(),c=wt(),h=ui().toString(),l=this.client.session.get(s).namespaces;return this.events.once(J("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(s,{namespaces:r}),await this.sendRequest({topic:s,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(u=>{this.client.logger.error(u),this.client.session.update(s,{namespaces:l}),a(u)}),{acknowledged:n}}),v(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:s}=t,r=wt(),{done:n,resolve:o,reject:a}=Tt();return this.events.once(J("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ce(Yt)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),v(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}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)===te.relay&&await this.confirmOnlineStateOrThrow();const c=wt(),h=ui().toString(),{done:l,resolve:u,reject:p}=Tt(o,"Request expired. Please try again.");this.events.once(J("session_request",c),({error:w,result:y})=>{w?p(w):u(y)});const g="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:{request:_e(Z({},r),{expiryTimestamp:ce(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(w=>p(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const m={request:_e(Z({},r),{expiryTimestamp:ce(o)}),chainId:s},f=this.shouldSetTVF(g,m);return await Promise.all([new Promise(async w=>{await this.sendRequest(Z({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:m,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,m)})).catch(y=>p(y)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),w()}),new Promise(async w=>{var y;if(!((y=a.sessionConfig)!=null&&y.disableDeepLink)){const I=await xl(this.client.core.storage,ta);await $l({id:c,topic:n,wcDeepLink:I})}w()}),l()]).then(w=>w[2])}),v(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:s,response:r}=t,{id:n}=r,o=this.client.session.get(s);o.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);pt(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):it(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),v(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:s}=t;if(this.client.session.keys.includes(s)){const r=wt(),n=ui().toString(),{done:o,resolve:a,reject:c}=Tt();this.events.once(J("session_ping",r),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:s,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(s)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:s}))}),v(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=wt();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),v(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:s}=t;if(this.client.session.keys.includes(s))await this.sendRequest({topic:s,method:"wc_sessionDelete",params:Q("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:s,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(s))await this.client.core.pairing.disconnect({topic:s});else{const{message:r}=A("MISMATCHED_TOPIC",`Session or pairing topic not found: ${s}`);throw new Error(r)}}),v(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>wd(s,t)))),v(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),v(this,"authenticate",async(t,s)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=s&&this.client.core.linkModeSupportedApps.includes(s)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?te.link_mode:te.relay;o===te.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:g,nbf:d,methods:m=[],expiry:f}=t,w=[...t.resources||[]],{topic:y,uri:I}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:y,uri:I}});const _=await this.client.core.crypto.generateKeyPair(),T=$s(_);if(await Promise.all([this.client.auth.authKeys.set(Os,{responseTopic:T,publicKey:_}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:y})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${y}`),m.length>0){const{namespace:$}=fi(a[0]);let L=vu($,"request",m);Ps(w)&&(L=Iu(L,w.pop())),w.push(L)}const P=f&&f>ue.wc_sessionAuthenticate.req.ttl?f:ue.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:p??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:g,nbf:d,resources:w},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ce(P)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},b={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:y,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ce(ue.wc_sessionPropose.req.ttl),id:wt()},{done:D,resolve:q,reject:k}=Tt(P,"Request expired"),F=wt(),E=J("session_connect",b.id),x=J("session_request",F),O=async({error:$,session:L})=>{this.events.off(x,R),$?k($):L&&q({session:L})},R=async $=>{var L,U,M;if(await this.deletePendingAuthRequest(F,{message:"fulfilled",code:0}),$.error){const ae=Q("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return $.error.code===ae.code?void 0:(this.events.off(E,O),k($.error.message))}await this.deleteProposal(b.id),this.events.off(E,O);const{cacaos:X,responder:W}=$.result,se=[],he=[];for(const ae of X){await Hn({cacao:ae,projectId:this.client.core.projectId})||(this.client.logger.error(ae,"Signature verification failed"),k(Q("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:xt}=ae,at=Ps(xt.resources),Ye=[Ar(xt.iss)],ct=Cs(xt.iss);if(at){const ht=Kn(at),us=Gn(at);se.push(...ht),Ye.push(...us)}for(const ht of Ye)he.push(`${ht}:${ct}`)}const ve=await this.client.core.crypto.generateSharedKey(_,W.publicKey);let oe;se.length>0&&(oe={topic:ve,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:W,controller:W.publicKey,expiry:ce(Yt),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:y,namespaces:bo([...new Set(se)],[...new Set(he)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,oe),y&&await this.client.core.pairing.updateMetadata({topic:y,metadata:W.metadata}),oe=this.client.session.get(ve)),(L=this.client.metadata.redirect)!=null&&L.linkMode&&(U=W.metadata.redirect)!=null&&U.linkMode&&(M=W.metadata.redirect)!=null&&M.universal&&s&&(this.client.core.addLinkModeSupportedApp(W.metadata.redirect.universal),this.client.session.update(ve,{transportType:te.link_mode})),q({auths:X,session:oe})};this.events.once(E,O),this.events.once(x,R);let j;try{if(n){const $=kt("wc_sessionAuthenticate",S,F);this.client.core.history.set(y,$);const L=await this.client.core.crypto.encode("",$,{type:as,encoding:It});j=ys(s,y,L)}else await Promise.all([this.sendRequest({topic:y,method:"wc_sessionAuthenticate",params:S,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:F}),this.sendRequest({topic:y,method:"wc_sessionPropose",params:b,expiry:ue.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:b.id})])}catch($){throw this.events.off(E,O),this.events.off(x,R),$}return await this.setProposal(b.id,b),await this.setAuthRequest(F,{request:_e(Z({},S),{verifyContext:{}}),pairingTopic:y,transportType:o}),{uri:j??I,response:D}}),v(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[Ct.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(Di.no_internet_connection),f}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(Di.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||te.relay;a===te.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=$s(c),u={type:mt,receiverPublicKey:c,senderPublicKey:h},p=[],g=[];for(const f of r){if(!await Hn({cacao:f,projectId:this.client.core.projectId})){n.setError(Di.invalid_cacao);const T=Q("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:T,encodeOpts:u}),new Error(T.message)}n.addTrace(Ct.cacaos_verified);const{p:w}=f,y=Ps(w.resources),I=[Ar(w.iss)],_=Cs(w.iss);if(y){const T=Kn(y),P=Gn(y);p.push(...T),I.push(...P)}for(const T of I)g.push(`${T}:${_}`)}const d=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Ct.create_authenticated_session_topic);let m;if((p==null?void 0:p.length)>0){m={topic:d,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ce(Yt),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:bo([...new Set(p)],[...new Set(g)]),transportType:a},n.addTrace(Ct.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(f){throw n.setError(Di.subscribe_authenticated_session_topic_failure),f}n.addTrace(Ct.subscribe_authenticated_session_topic_success),await this.client.session.set(d,m),n.addTrace(Ct.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Ct.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:s,result:{cacaos:r,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(f){throw n.setError(Di.authenticated_session_approve_publish_failure),f}return await this.client.auth.requests.delete(s,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:m}}),v(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:s,reason:r}=t,n=this.getPendingAuthRequest(s);if(!n)throw new Error(`Could not find pending auth request with id ${s}`);n.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=$s(o),h={type:mt,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,Q("USER_DISCONNECTED"))}),v(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return Za(s,r)}),v(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)}),v(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)}}),v(this,"deleteSession",async t=>{var s;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Q("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(ta).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,Q("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=et.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),v(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(At.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Q("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),v(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=et.idle,this.client.events.emit("session_request_expire",{id:t}))}),v(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)])}),v(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}))}),v(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ce(ue.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),v(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=te.relay}=s;this.client.core.expirer.set(t,r.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:t,pairingTopic:n,verifyContext:r.verifyContext,transportType:o})}),v(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ce(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})}),v(this,"sendRequest",async t=>{const{topic:s,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:u}=t,p=kt(r,n,c);let g;const d=!!l;try{const w=d?It:We;g=await this.client.core.crypto.encode(s,p,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),w}let m;if(Ow.includes(r)){const w=st(JSON.stringify(p)),y=st(g);m=await this.client.core.verify.register({id:y,decryptedId:w})}const f=ue[r].req;if(f.attestation=m,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(s,p),d){const w=ys(l,s,g);await B.Linking.openURL(w,this.client.name)}else{const w=ue[r].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=_e(Z({},u),{correlationId:p.id}),h?(w.internal=_e(Z({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,g,w)):this.client.core.relayer.publish(s,g,w).catch(y=>this.client.logger.error(y))}return p.id}),v(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=Fs(s,n);let l;const u=c&&typeof(B==null?void 0:B.Linking)<"u";try{const d=u?It:We;l=await this.client.core.crypto.encode(r,h,_e(Z({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),d}let p,g;try{p=await this.client.core.history.get(r,s);const d=p.request;try{this.shouldSetTVF(d.method,d.params)&&(g=this.getTVFParams(s,d.params,n))}catch(m){this.client.logger.warn("sendResult() -> getTVFParams() failed",m)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),d}if(u){const d=ys(c,r,l);await B.Linking.openURL(d,this.client.name)}else{const d=p.request.method,m=ue[d].res;m.tvf=_e(Z({},g),{correlationId:s}),o?(m.internal=_e(Z({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,m)):this.client.core.relayer.publish(r,l,m).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(h)}),v(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=_a(s,n);let l;const u=c&&typeof(B==null?void 0:B.Linking)<"u";try{const g=u?It:We;l=await this.client.core.crypto.encode(r,h,_e(Z({},o||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),g}let p;try{p=await this.client.core.history.get(r,s)}catch(g){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),g}if(u){const g=ys(c,r,l);await B.Linking.openURL(g,this.client.name)}else{const g=p.request.method,d=a||ue[g].res;this.client.core.relayer.publish(r,l,d)}await this.client.core.history.resolve(h)}),v(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;Et(r.expiry)&&(n=!0),this.client.core.crypto.keychain.has(r.topic)||(n=!0),n&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Et(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),v(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),v(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),v(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===et.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=et.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=et.idle}),v(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}`)}}),v(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}`)}}),v(this,"onRelayEventUnknownPayload",t=>{const{topic:s}=t,{message:r}=A("MISSING_OR_INVALID",`Decoded payload on topic ${s} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),v(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)}),v(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(dt.proposal_listener_not_found)),this.isValidConnect(Z({},r.params));const l=a.expiryTimestamp||ce(ue.wc_sessionPropose.req.ttl),u=Z({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:st(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h==null||h.addTrace(tt.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)}}),v(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(pt(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(it(s)){await this.client.proposal.delete(n,Q("USER_DISCONNECTED"));const o=J("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:s.error})}}),v(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,g=[...this.pendingSessions.values()].find(f=>f.sessionTopic===t);if(!g)return this.client.logger.error(`Pending session not found for topic ${t}`);const d=this.client.proposal.get(g.proposalId),m=_e(Z(Z(Z({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:d.requiredNamespaces,optionalNamespaces:d.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),{transportType:te.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(J("session_connect",g.proposalId),{session:m}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(m),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)}}),v(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;pt(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(J("session_approve",r),{})):it(s)&&(await this.client.session.delete(t,Q("USER_DISCONNECTED")),this.events.emit(J("session_approve",r),{error:s.error}))}),v(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:Q("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Z({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)}}),v(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),v(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=J("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);pt(s)?this.events.emit(J("session_update",r),{}):it(s)&&this.events.emit(J("session_update",r),{error:s.error})}),v(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ce(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)}}),v(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=J("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);pt(s)?this.events.emit(J("session_extend",r),{}):it(s)&&this.events.emit(J("session_extend",r),{error:s.error})}),v(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)}}),v(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=J("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);pt(s)?this.events.emit(J("session_ping",r),{}):it(s)&&this.events.emit(J("session_ping",r),{error:s.error})},500)}),v(this,"onSessionDeleteRequest",async(t,s)=>{const{id:r}=s;try{this.isValidDisconnect({topic:t,reason:s.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(de.publish,async()=>{n(await this.deleteSession({topic:t,id:r}))})}),this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Q("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),v(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(Z({topic:o},p));const g=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:st(JSON.stringify(kt("wc_sessionRequest",p,u))),encryptedId:h,metadata:g.peer.metadata,transportType:l}),m={id:u,topic:o,params:p,verifyContext:d};await this.setPendingSessionRequest(m),l===te.link_mode&&(s=g.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=g.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(g){await this.sendError({id:u,topic:o,error:g}),this.client.logger.error(g)}}),v(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=J("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);pt(s)?this.events.emit(J("session_request",r),{result:s.result}):it(s)&&this.events.emit(J("session_request",r),{error:s.error})}),v(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(Z({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)}}),v(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),pt(s)?this.events.emit(J("session_request",r),{result:s.result}):it(s)&&this.events.emit(J("session_request",r),{error:s.error})}),v(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:st(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),g={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:p,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:g,pairingTopic:r,transportType:c}),c===te.link_mode&&(s=h.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:p})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),g={type:mt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:g,rpcOpts:ue.wc_sessionAuthenticate.autoReject,appLink:p})}}),v(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),v(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=et.idle,this.processSessionRequestQueue()},C.toMiliseconds(this.requestQueueDelay))}),v(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:s})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=J("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(J("session_request",n.request.id),{error:s})})}),v(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===et.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=et.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),v(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),v(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const s=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);s&&this.onSessionProposeRequest({topic:t.topic,payload:kt("wc_sessionPropose",_e(Z({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),v(this,"isValidConnect",async t=>{if(!Oe(t)){const{message:h}=A("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:s,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(we(s)||await this.isValidPairingTopic(s),!Cd(c,!0)){const{message:h}=A("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!we(r)&&$t(r)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(r,"requiredNamespaces")}if(!we(n)&&$t(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>h.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}}),v(this,"validateNamespaces",(t,s)=>{const r=Ad(t,"connect()",s);if(r)throw new Error(r.message)}),v(this,"isValidApprove",async t=>{if(!Oe(t))throw new Error(A("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=Io(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!ne(n,!0)){const{message:u}=A("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(p=>u.has(p)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),v(this,"isValidReject",async t=>{if(!Oe(t)){const{message:n}=A("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!Nd(r)){const{message:n}=A("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),v(this,"isValidSessionSettleRequest",t=>{if(!Oe(t)){const{message:h}=A("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!Pc(s)){const{message:h}=A("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=_d(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=lr(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Et(o)){const{message:h}=A("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),v(this,"isValidUpdate",async t=>{if(!Oe(t)){const{message:c}=A("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=Io(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),v(this,"isValidExtend",async t=>{if(!Oe(t)){const{message:r}=A("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:s}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s)}),v(this,"isValidRequest",async t=>{if(!Oe(t)){const{message:c}=A("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:s,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const{namespaces:a}=this.client.session.get(s);if(!Eo(a,n)){const{message:c}=A("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Rd(r)){const{message:c}=A("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!kd(a,n,r.method)){const{message:c}=A("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Ud(o,wr)){const{message:c}=A("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${wr.min} and ${wr.max}`);throw new Error(c)}}),v(this,"isValidRespond",async t=>{var s;if(!Oe(t)){const{message:o}=A("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(!qd(n)){const{message:o}=A("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),v(this,"isValidPing",async t=>{if(!Oe(t)){const{message:r}=A("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),v(this,"isValidEmit",async t=>{if(!Oe(t)){const{message:a}=A("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:s,event:r,chainId:n}=t;await this.isValidSessionTopic(s);const{namespaces:o}=this.client.session.get(s);if(!Eo(o,n)){const{message:a}=A("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!jd(r)){const{message:a}=A("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Dd(o,n,r.name)){const{message:a}=A("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),v(this,"isValidDisconnect",async t=>{if(!Oe(t)){const{message:r}=A("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),v(this,"isValidAuthenticate",t=>{const{chains:s,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(s)||s.length===0)throw new Error("chains is required and must be a non-empty array");if(!ne(r,!1))throw new Error("uri is required parameter");if(!ne(n,!1))throw new Error("domain is required parameter");if(!ne(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>fi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=fi(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),v(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||Ki,validation:"UNKNOWN",origin:o.url||""}};try{if(a===te.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:s,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),v(this,"validateSessionProps",(t,s)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=A("MISSING_OR_INVALID",`${s} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),v(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),v(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)}}}),v(this,"checkRecentlyDeleted",t=>{const s=this.recentlyDeletedMap.get(t);if(s){const{message:r}=A("MISSING_OR_INVALID",`Record was recently deleted - ${s}: ${t}`);throw new Error(r)}}),v(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,u,p;return!t||s!==te.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((l=t==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"}),v(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}),v(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=kn(t,"topic")||"",r=decodeURIComponent(kn(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:te.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),v(this,"registerLinkModeListeners",async()=>{var t;if(on()||Ot()&&(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)}}}),v(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(sa).includes(r.method)}),v(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return _e(Z({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{}}),v(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}),v(this,"extractTxHashesFromResult",(t,s)=>{try{const r=sa[t];if(typeof s=="string")return[s];const n=s[r.key];if(Je(n))return t==="solana_signAllTransactions"?n.map(o=>ou(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}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(de.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Os)?this.client.auth.authKeys.get(Os):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===te.link_mode?It:We});sn(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:st(s)})):rn(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,s)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Ue.expired,async e=>{const{topic:t,id:s}=za(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,A("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,A("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(qt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(qt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ne(e,!1)){const{message:t}=A("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}=A("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=A("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ne(e,!1)){const{message:t}=A("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}=A("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=A("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=A("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ne(e,!1)){const{message:t}=A("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=A("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!Td(e)){const{message:t}=A("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=A("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=A("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class Fw extends zt{constructor(e,t){super(e,t,_w,fn),this.core=e,this.logger=t}}let Uw=class extends zt{constructor(e,t){super(e,t,Pw,fn),this.core=e,this.logger=t}};class Mw extends zt{constructor(e,t){super(e,t,Sw,fn,s=>s.id),this.core=e,this.logger=t}}class Bw extends zt{constructor(e,t){super(e,t,Cw,Qs,()=>Os),this.core=e,this.logger=t}}class zw extends zt{constructor(e,t){super(e,t,Tw,Qs),this.core=e,this.logger=t}}class Vw extends zt{constructor(e,t){super(e,t,Nw,Qs,s=>s.id),this.core=e,this.logger=t}}var Hw=Object.defineProperty,Kw=(i,e,t)=>e in i?Hw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,br=(i,e,t)=>Kw(i,typeof e!="symbol"?e+"":e,t);class Gw{constructor(e,t){this.core=e,this.logger=t,br(this,"authKeys"),br(this,"pairingTopics"),br(this,"requests"),this.authKeys=new Bw(this.core,this.logger),this.pairingTopics=new zw(this.core,this.logger),this.requests=new Vw(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Ww=Object.defineProperty,Jw=(i,e,t)=>e in i?Ww(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,V=(i,e,t)=>Jw(i,typeof e!="symbol"?e+"":e,t);let Qw=class Gc extends Dg{constructor(e){super(e),V(this,"protocol",Vc),V(this,"version",Hc),V(this,"name",mr.name),V(this,"metadata"),V(this,"core"),V(this,"logger"),V(this,"events",new St.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)||mr.name,this.metadata=bl(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:cs(Ws({level:(e==null?void 0:e.logger)||mr.logger}));this.core=(e==null?void 0:e.core)||new Iw(e),this.logger=$e(t,this.name),this.session=new Uw(this.core,this.logger),this.proposal=new Fw(this.core,this.logger),this.pendingRequest=new Mw(this.core,this.logger),this.engine=new Lw(this),this.auth=new Gw(this.core,this.logger)}static async init(e){const t=new Gc(e);return await t.initialize(),t}get context(){return Ce(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},C.toMiliseconds(C.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const na="error",Yw="wss://relay.walletconnect.org",Zw="wc",Xw="universal_provider",bs=`${Zw}@2:${Xw}:`,Wc="https://rpc.walletconnect.org/v1/",li="generic",eb=`${Wc}bundler`,ze={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function tb(){}function yn(i){return i==null||typeof i!="object"&&typeof i!="function"}function mn(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function ib(i){if(yn(i))return i;if(Array.isArray(i)||mn(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 oa(i){return typeof i=="object"&&i!==null}function Jc(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Qc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const sb="[object RegExp]",Yc="[object String]",Zc="[object Number]",Xc="[object Boolean]",eh="[object Arguments]",rb="[object Symbol]",nb="[object Date]",ob="[object Map]",ab="[object Set]",cb="[object Array]",hb="[object ArrayBuffer]",lb="[object Object]",ub="[object DataView]",pb="[object Uint8Array]",db="[object Uint8ClampedArray]",gb="[object Uint16Array]",fb="[object Uint32Array]",yb="[object Int8Array]",mb="[object Int16Array]",wb="[object Int32Array]",bb="[object Float32Array]",vb="[object Float64Array]";function Eb(i,e){return gi(i,void 0,i,new Map,e)}function gi(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]=gi(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,gi(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(gi(a,void 0,t,s,r));return o}if(typeof Ie<"u"&&Ie.isBuffer(i))return i.subarray();if(mn(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=gi(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),jt(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),jt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),jt(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,jt(o,i,t,s,r),o}if(typeof i=="object"&&Ib(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),jt(o,i,t,s,r),o}return i}function jt(i,e,t=i,s,r){const n=[...Object.keys(e),...Jc(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=gi(e[a],a,t,s,r))}}function Ib(i){switch(Qc(i)){case eh:case cb:case hb:case ub:case Xc:case nb:case bb:case vb:case yb:case mb:case wb:case ob:case Zc:case lb:case sb:case ab:case Yc:case rb:case pb:case db:case gb:case fb:return!0;default:return!1}}function _b(i,e){return Eb(i,(t,s,r,n)=>{const o=e==null?void 0:e(t,s,r,n);if(o!=null)return o;if(typeof i=="object")switch(Object.prototype.toString.call(i)){case Zc:case Yc:case Xc:{const a=new i.constructor(i==null?void 0:i.valueOf());return jt(a,i),a}case eh:{const a={};return jt(a,i),a.length=i.length,a[Symbol.iterator]=i[Symbol.iterator],a}default:return}})}function aa(i){return _b(i)}function ca(i){return i!==null&&typeof i=="object"&&Qc(i)==="[object Arguments]"}function Pb(i){return mn(i)}function $b(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 Sb(i,...e){const t=e.slice(0,-1),s=e[e.length-1];let r=i;for(let n=0;n<t.length;n++){const o=t[n];r=Yr(r,o,s,new Map)}return r}function Yr(i,e,t,s){if(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),...Jc(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(ca(a)&&(a={...a}),ca(c)&&(c={...c}),typeof Ie<"u"&&Ie.isBuffer(a)&&(a=aa(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 g=u[p];l[g]=c[g]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||oa(c)&&oa(a)?i[o]=Yr(c,a,t,s):c==null&&$b(a)?i[o]=Yr({},a,t,s):c==null&&Pb(a)?i[o]=aa(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Ob(i,...e){return Sb(i,...e,tb)}var xb=Object.defineProperty,Ab=Object.defineProperties,Cb=Object.getOwnPropertyDescriptors,ha=Object.getOwnPropertySymbols,Tb=Object.prototype.hasOwnProperty,Nb=Object.prototype.propertyIsEnumerable,la=(i,e,t)=>e in i?xb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vs=(i,e)=>{for(var t in e||(e={}))Tb.call(e,t)&&la(i,t,e[t]);if(ha)for(var t of ha(e))Nb.call(e,t)&&la(i,t,e[t]);return i},Rb=(i,e)=>Ab(i,Cb(e));function De(i,e,t){var s;const r=fi(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Wc}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Vt(i){return i.includes(":")?i.split(":")[1]:i}function th(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function qb(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 Es(i={},e={}){const t=ua(i),s=ua(e);return Ob(t,s)}function ua(i){var e,t,s,r,n;const o={};if(!$t(i))return o;for(const[a,c]of Object.entries(i)){const h=Ks(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},g=di(a);o[g]=Rb(vs(vs({},o[g]),c),{chains:rt(h,(e=o[g])==null?void 0:e.chains),methods:rt(l,(t=o[g])==null?void 0:t.methods),events:rt(u,(s=o[g])==null?void 0:s.events)}),($t(p)||$t(((r=o[g])==null?void 0:r.rpcMap)||{}))&&(o[g].rpcMap=vs(vs({},p),(n=o[g])==null?void 0:n.rpcMap))}return o}function pa(i){return i.includes(":")?i.split(":")[2]:i}function da(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Ks(t)?[t]:s.chains?s.chains:th(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function vr(i){return typeof i=="number"?i:i.includes("0x")?parseInt(i,16):(i=i.includes(":")?i.split(":")[1]:i,isNaN(Number(i))?i:Number(i))}const ih={},G=i=>ih[i],Er=(i,e)=>{ih[i]=e};var jb=Object.defineProperty,kb=(i,e,t)=>e in i?jb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Zt=(i,e,t)=>kb(i,typeof e!="symbol"?e+"":e,t);class Db{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var Lb=Object.defineProperty,Fb=Object.defineProperties,Ub=Object.getOwnPropertyDescriptors,ga=Object.getOwnPropertySymbols,Mb=Object.prototype.hasOwnProperty,Bb=Object.prototype.propertyIsEnumerable,Zr=(i,e,t)=>e in i?Lb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,fa=(i,e)=>{for(var t in e||(e={}))Mb.call(e,t)&&Zr(i,t,e[t]);if(ga)for(var t of ga(e))Bb.call(e,t)&&Zr(i,t,e[t]);return i},ya=(i,e)=>Fb(i,Ub(e)),Xt=(i,e,t)=>Zr(i,typeof e!="symbol"?e+"":e,t);class zb{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=G("events"),this.client=G("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(ze.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||De(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=parseInt(Vt(t));e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,s;let r=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(s=this.namespace.chains)==null?void 0:s[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,s,r,n,o;const a=(s=(t=e.request)==null?void 0:t.params)==null?void 0:s[0],c=((n=(r=e.request)==null?void 0:r.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l==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:ya(fa({},l.sessionProperties||{}),{capabilities:ya(fa({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var t,s;const r=this.client.session.get(e.topic),n=(t=r.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(s=r.sessionProperties)==null?void 0:s.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var s;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(kt("eth_getUserOperationReceipt",[(s=t.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${eb}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var Vb=Object.defineProperty,Hb=(i,e,t)=>e in i?Vb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ei=(i,e,t)=>Hb(i,typeof e!="symbol"?e+"":e,t);class Kb{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var Gb=Object.defineProperty,Wb=(i,e,t)=>e in i?Gb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ti=(i,e,t)=>Wb(i,typeof e!="symbol"?e+"":e,t);class Jb{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var Qb=Object.defineProperty,Yb=(i,e,t)=>e in i?Qb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ii=(i,e,t)=>Yb(i,typeof e!="symbol"?e+"":e,t);class Zb{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const s=t||De(`${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(ze.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||De(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new Be(new Qe(s,G("disableProviderPing")))}}var Xb=Object.defineProperty,ev=(i,e,t)=>e in i?Xb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,si=(i,e,t)=>ev(i,typeof e!="symbol"?e+"":e,t);class tv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const s=this.getCardanoRPCUrl(t),r=Vt(t);e[r]=this.createHttpProvider(r,s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var iv=Object.defineProperty,sv=(i,e,t)=>e in i?iv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ri=(i,e,t)=>sv(i,typeof e!="symbol"?e+"":e,t);class rv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var nv=Object.defineProperty,ov=(i,e,t)=>e in i?nv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ni=(i,e,t)=>ov(i,typeof e!="symbol"?e+"":e,t);class av{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var cv=Object.defineProperty,hv=(i,e,t)=>e in i?cv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oi=(i,e,t)=>hv(i,typeof e!="symbol"?e+"":e,t);class lv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||De(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(ze.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||De(e,this.namespace);return typeof s>"u"?void 0:new Be(new Qe(s,G("disableProviderPing")))}}var uv=Object.defineProperty,pv=(i,e,t)=>e in i?uv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ai=(i,e,t)=>pv(i,typeof e!="symbol"?e+"":e,t);class dv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||De(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(ze.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||De(e,this.namespace);return typeof s>"u"?void 0:new Be(new Qe(s))}}var gv=Object.defineProperty,fv=(i,e,t)=>e in i?gv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ci=(i,e,t)=>fv(i,typeof e!="symbol"?e+"":e,t);class yv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.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=fi(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var mv=Object.defineProperty,wv=Object.defineProperties,bv=Object.getOwnPropertyDescriptors,ma=Object.getOwnPropertySymbols,vv=Object.prototype.hasOwnProperty,Ev=Object.prototype.propertyIsEnumerable,Xr=(i,e,t)=>e in i?mv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Is=(i,e)=>{for(var t in e||(e={}))vv.call(e,t)&&Xr(i,t,e[t]);if(ma)for(var t of ma(e))Ev.call(e,t)&&Xr(i,t,e[t]);return i},Ir=(i,e)=>wv(i,bv(e)),Fe=(i,e,t)=>Xr(i,typeof e!="symbol"?e+"":e,t);let Iv=class sh{constructor(e){Fe(this,"client"),Fe(this,"namespaces"),Fe(this,"optionalNamespaces"),Fe(this,"sessionProperties"),Fe(this,"scopedProperties"),Fe(this,"events",new tn),Fe(this,"rpcProviders",{}),Fe(this,"session"),Fe(this,"providerOpts"),Fe(this,"logger"),Fe(this,"uri"),Fe(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:cs(Ws({level:(e==null?void 0:e.logger)||na})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new sh(e);return await t.initialize(),t}async request(e,t,s){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Is({},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,Fs(n,o))).catch(o=>t(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Q("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:s,response:r}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const n=await r();if(this.session=n.session,this.session){const o=da(this.session.namespaces);this.namespaces=Es(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=da(r.namespaces);return this.namespaces=Es(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(Je(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 Qw.init({core:this.providerOpts.core,logger:this.providerOpts.logger||na,relayUrl:this.providerOpts.relayUrl||Yw,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)))];Er("client",this.client),Er("events",this.events),Er("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=qb(t,this.session),r=th(s),n=Es(this.namespaces,this.optionalNamespaces),o=Ir(Is({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new zb({namespace:o});break;case"algorand":this.rpcProviders[t]=new Zb({namespace:o});break;case"solana":this.rpcProviders[t]=new Kb({namespace:o});break;case"cosmos":this.rpcProviders[t]=new Jb({namespace:o});break;case"polkadot":this.rpcProviders[t]=new Db({namespace:o});break;case"cip34":this.rpcProviders[t]=new tv({namespace:o});break;case"elrond":this.rpcProviders[t]=new rv({namespace:o});break;case"multiversx":this.rpcProviders[t]=new av({namespace:o});break;case"near":this.rpcProviders[t]=new lv({namespace:o});break;case"tezos":this.rpcProviders[t]=new dv({namespace:o});break;default:this.rpcProviders[li]?this.rpcProviders[li].updateNamespace(o):this.rpcProviders[li]=new yv({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&&Je(o)&&this.events.emit("accountsChanged",o.map(pa))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=di(o),h=vr(o)!==vr(a)?`${c}:${vr(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,r;if(e!==((s=this.session)==null?void 0:s.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Ir(Is({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ir(Is({},Q("USER_DISCONNECTED")),{data:e.topic})))}),this.on(ze.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=Es(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(pa);if(!Je(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(`${bs}/${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(`${bs}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${bs}/${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(bs)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const _v=Iv,Pv="wc",$v="ethereum_provider",Sv=`${Pv}@2:${$v}:`,Ov="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],rh=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Ds=["chainChanged","accountsChanged"],nh=["chainChanged","accountsChanged","message","disconnect","connect"],xv=async()=>{const{createAppKit:i}=await Ea(()=>import("./core-71a03396.js").then(e=>e.u),["assets/core-71a03396.js","assets/index-355751ab.js","assets/index-e7f3149f.css","assets/index-276c1c99.js","assets/index-accd8060.js","assets/index-2124b7cd.js","assets/index.es-ac60fff2.js","assets/http-a4cf4808.js","assets/createBatchScheduler-7c9ada66.js","assets/W3MFrameProviderSingleton-33e9645e.js","assets/NetworkUtil-2fb81493.js","assets/lit-element-0711c853.js"]);return i};var Av=Object.defineProperty,Cv=Object.defineProperties,Tv=Object.getOwnPropertyDescriptors,wa=Object.getOwnPropertySymbols,Nv=Object.prototype.hasOwnProperty,Rv=Object.prototype.propertyIsEnumerable,en=(i,e,t)=>e in i?Av(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Nt=(i,e)=>{for(var t in e||(e={}))Nv.call(e,t)&&en(i,t,e[t]);if(wa)for(var t of wa(e))Rv.call(e,t)&&en(i,t,e[t]);return i},Ui=(i,e)=>Cv(i,Tv(e)),Ne=(i,e,t)=>en(i,typeof e!="symbol"?e+"":e,t);function Ls(i){return Number(i[0].split(":")[1])}function _s(i){return`0x${i.toString(16)}`}function qv(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Je(e))throw new Error("Invalid chains");const c={chains:e,methods:s||ks,events:n||Ds,rpcMap:Nt({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},h=n==null?void 0:n.filter(g=>!Ds.includes(g)),l=s==null?void 0:s.filter(g=>!ks.includes(g));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:rh))],events:[...new Set(c.events.concat(o!=null&&o.length?o:nh))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class Ys{constructor(){Ne(this,"events",new St.EventEmitter),Ne(this,"namespace","eip155"),Ne(this,"accounts",[]),Ne(this,"signer"),Ne(this,"chainId",1),Ne(this,"modal"),Ne(this,"rpc"),Ne(this,"STORAGE_KEY",Sv),Ne(this,"on",(e,t)=>(this.events.on(e,t),this)),Ne(this,"once",(e,t)=>(this.events.once(e,t),this)),Ne(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),Ne(this,"off",(e,t)=>(this.events.off(e,t),this)),Ne(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}=qv(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(Ui(Nt({namespaces:Nt({},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 g;(g=this.modal)==null||g.showErrorMessage("Unable to connect"),c(new Error(p.message))})});if(!n)return;const o=Tn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_s(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(Ui(Nt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=r.session;if(n){const o=Tn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_s(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",_s(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",Ui(Nt({},Q("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",_s(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)||ks:[],c=r.length?(e==null?void 0:e.events)||Ds:[],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(g=>this.formatChainId(g)),optionalChains:n.map(g=>this.formatChainId(g)),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?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await _v.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 xv(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return Hv}),n=r(Ui(Nt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=s(Ui(Nt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:s,rpcMap:r}=e;t&&Je(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&&Je(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])||`${Ov}?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 jv=Ys;var kv=Object.defineProperty,Dv=Object.defineProperties,Lv=Object.getOwnPropertyDescriptors,ba=Object.getOwnPropertySymbols,Fv=Object.prototype.hasOwnProperty,Uv=Object.prototype.propertyIsEnumerable,va=(i,e,t)=>e in i?kv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oh=(i,e)=>{for(var t in e||(e={}))Fv.call(e,t)&&va(i,t,e[t]);if(ba)for(var t of ba(e))Uv.call(e,t)&&va(i,t,e[t]);return i},Mv=(i,e)=>Dv(i,Lv(e));function Bv(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 zv=i=>{const[e,t]=i.split(":");return ah({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function Vv(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(zv).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:Bv(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:Mv(oh({},i.metadata),{name:((t=i.metadata)==null?void 0:t.name)||"WalletConnect",description:((s=i.metadata)==null?void 0:s.description)||"Connect to WalletConnect-compatible wallets",url:((r=i.metadata)==null?void 0:r.url)||"https://walletconnect.org",icons:((n=i.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:i.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(i.explorerRecommendedWalletIds)?i.explorerRecommendedWalletIds:[],excludeWalletIds:i.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(i.explorerExcludedWalletIds)?i.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=i.mobileWallets)!=null&&o.length||(a=i.desktopWallets)!=null&&a.length){const u=[...(i.mobileWallets||[]).map(d=>({id:d.id,name:d.name,links:d.links})),...(i.desktopWallets||[]).map(d=>({id:d.id,name:d.name,links:{native:d.links.native,universal:d.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],g=u.filter(d=>!p.includes(d.id));g.length&&(l.customWallets=g)}return l}function ah(i){return oh({formatters:void 0,fees:void 0,serializers:void 0},i)}var Hv=Object.freeze({__proto__:null,convertWCMToAppKitOptions:Vv,defineChain:ah});const _1=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:jv,OPTIONAL_EVENTS:nh,OPTIONAL_METHODS:rh,REQUIRED_EVENTS:Ds,REQUIRED_METHODS:ks,default:Ys},Symbol.toStringTag,{value:"Module"}));export{wg as A,$e as E,Vh as H,cs as O,_n as a,qh as b,Zv as c,Yv as d,Us as e,e1 as f,t1 as g,Me as h,Ae as i,Vi as j,tl as k,Ws as l,_1 as m,Xv as r,Ta as t,Hh as w,Ce as y};
|
|
11
|
+
Approved: ${p.toString()}`))}),o.forEach(u=>{s||(Dt(r[u].methods,n[u].methods)?Dt(r[u].events,n[u].events)||(s=A("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${u}`)):s=A("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${u}`))}),s}function Ld(i){const e={};return Object.keys(i).forEach(t=>{var s;t.includes(":")?e[t]=i[t]:(s=i[t].chains)==null||s.forEach(r=>{e[r]={methods:i[t].methods,events:i[t].events}})}),e}function _o(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function Fd(i){const e={};return Object.keys(i).forEach(t=>{if(t.includes(":"))e[t]=i[t];else{const s=Ti(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 Ud(i,e){return dn(i,!1)&&i<=e.max&&i>=e.min}function Po(){const i=is();return new Promise(e=>{switch(i){case ke.browser:e(Md());break;case ke.reactNative:e(Bd());break;case ke.node:e(zd());break;default:e(!0)}})}function Md(){return xi()&&(navigator==null?void 0:navigator.onLine)}async function Bd(){if(Ot()&&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 zd(){return!0}function Vd(i){switch(is()){case ke.browser:Hd(i);break;case ke.reactNative:Kd(i);break}}function Hd(i){!Ot()&&xi()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function Kd(i){var e;Ot()&&typeof B<"u"&&B!=null&&B.NetInfo&&((e=B)==null||e.NetInfo.addEventListener(t=>i(t==null?void 0:t.isConnected)))}function Gd(){var i;return xi()&&yi()?((i=yi())==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]}}const $o=bh;var hi=nt;const es=sg().console||{},Wd={mapHttpRequest:ms,mapHttpResponse:ms,wrapRequestSerializer:pr,wrapResponseSerializer:pr,wrapErrorSerializer:pr,req:ms,res:ms,err:Xd};function Jd(i,e){return Array.isArray(i)?i.filter(function(s){return s!=="!stdSerializers.err"}):i===!0?Object.keys(e):!1}function nt(i){i=i||{},i.browser=i.browser||{};const e=i.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const t=i.browser.write||es;i.browser.write&&(i.browser.asObject=!0);const s=i.serializers||{},r=Jd(i.browser.serialize,s);let n=i.browser.serialize;Array.isArray(i.browser.serialize)&&i.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=["error","fatal","warn","info","debug","trace"];typeof t=="function"&&(t.error=t.fatal=t.warn=t.info=t.debug=t.trace=t),i.enabled===!1&&(i.level="silent");const a=i.level||"info",c=Object.create(t);c.log||(c.log=ts),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:u,set:p});const h={transmit:e,serialize:r,asObject:i.browser.asObject,levels:o,timestamp:eg(i)};c.levels=nt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=ts,c.serializers=s,c._serialize=r,c._stdErrSerialize=n,c.child=g,e&&(c._logEvent=Fr());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function u(){return this._level}function p(d){if(d!=="silent"&&!this.levels.values[d])throw Error("unknown level "+d);this._level=d,Wt(h,c,"error","log"),Wt(h,c,"fatal","error"),Wt(h,c,"warn","error"),Wt(h,c,"info","log"),Wt(h,c,"debug","log"),Wt(h,c,"trace","log")}function g(d,m){if(!d)throw new Error("missing bindings for child Pino");m=m||{},r&&d.serializers&&(m.serializers=d.serializers);const f=m.serializers;if(r&&f){var w=Object.assign({},s,f),y=i.browser.serialize===!0?Object.keys(w):r;delete d.serializers,Gs([d],y,w,this._stdErrSerialize)}function I(_){this._childLevel=(_._childLevel|0)+1,this.error=Jt(_,d,"error"),this.fatal=Jt(_,d,"fatal"),this.warn=Jt(_,d,"warn"),this.info=Jt(_,d,"info"),this.debug=Jt(_,d,"debug"),this.trace=Jt(_,d,"trace"),w&&(this.serializers=w,this._serialize=y),e&&(this._logEvent=Fr([].concat(_._logEvent.bindings,d)))}return I.prototype=this,new I(this)}return c}nt.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"}};nt.stdSerializers=Wd;nt.stdTimeFunctions=Object.assign({},{nullTime:$c,epochTime:Sc,unixTime:tg,isoTime:ig});function Wt(i,e,t,s){const r=Object.getPrototypeOf(e);e[t]=e.levelVal>e.levels.values[t]?ts:r[t]?r[t]:es[t]||es[s]||ts,Qd(i,e,t)}function Qd(i,e,t){!i.transmit&&e[t]===ts||(e[t]=function(s){return function(){const n=i.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===es?es:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(i.serialize&&!i.asObject&&Gs(o,this._serialize,this.serializers,this._stdErrSerialize),i.asObject?s.call(a,Yd(this,t,o,n)):s.apply(a,o),i.transmit){const h=i.transmit.level||e.level,l=nt.levels.values[h],u=nt.levels.values[t];if(u<l)return;Zd(this,{ts:n,methodLevel:t,methodValue:u,transmitLevel:h,transmitValue:nt.levels.values[i.transmit.level||e.level],send:i.transmit.send,val:e.levelVal},o)}}}(e[t]))}function Yd(i,e,t,s){i._serialize&&Gs(t,i._serialize,i.serializers,i._stdErrSerialize);const r=t.slice();let n=r[0];const o={};s&&(o.time=s),o.level=nt.levels.values[e];let a=(i._childLevel|0)+1;if(a<1&&(a=1),n!==null&&typeof n=="object"){for(;a--&&typeof r[0]=="object";)Object.assign(o,r.shift());n=r.length?$o(r.shift(),r):void 0}else typeof n=="string"&&(n=$o(r.shift(),r));return n!==void 0&&(o.msg=n),o}function Gs(i,e,t,s){for(const r in i)if(s&&i[r]instanceof Error)i[r]=nt.stdSerializers.err(i[r]);else if(typeof i[r]=="object"&&!Array.isArray(i[r]))for(const n in i[r])e&&e.indexOf(n)>-1&&n in t&&(i[r][n]=t[n](i[r][n]))}function Jt(i,e,t){return function(){const s=new Array(1+arguments.length);s[0]=e;for(var r=1;r<s.length;r++)s[r]=arguments[r-1];return i[t].apply(this,s)}}function Zd(i,e,t){const s=e.send,r=e.ts,n=e.methodLevel,o=e.methodValue,a=e.val,c=i._logEvent.bindings;Gs(t,i._serialize||Object.keys(i.serializers),i.serializers,i._stdErrSerialize===void 0?!0:i._stdErrSerialize),i._logEvent.ts=r,i._logEvent.messages=t.filter(function(h){return c.indexOf(h)===-1}),i._logEvent.level.label=n,i._logEvent.level.value=o,s(n,i._logEvent,a),i._logEvent=Fr(c)}function Fr(i){return{ts:0,messages:[],bindings:i||[],level:{label:"",value:0}}}function Xd(i){const e={type:i.constructor.name,msg:i.message,stack:i.stack};for(const t in i)e[t]===void 0&&(e[t]=i[t]);return e}function eg(i){return typeof i.timestamp=="function"?i.timestamp:i.timestamp===!1?$c:Sc}function ms(){return{}}function pr(i){return i}function ts(){}function $c(){return!1}function Sc(){return Date.now()}function tg(){return Math.round(Date.now()/1e3)}function ig(){return new Date(Date.now()).toISOString()}function sg(){function i(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 i(self)||i(window)||i(this)||{}}}const cs=ch(hi),rg={level:"info"},hs="custom_context",gn=1e3*1024;let ng=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}},So=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new ng(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;t!==null;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}},Oc=class{constructor(e,t=gn){this.level=e??"error",this.levelValue=hi.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new So(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(Pr({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 So(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(Pr({extraMetadata:e})),new Blob(t,{type:"application/json"})}},og=class{constructor(e,t=gn){this.baseChunkLogger=new Oc(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),s=document.createElement("a");s.href=t,s.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(t)}},ag=class{constructor(e,t=gn){this.baseChunkLogger=new Oc(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var cg=Object.defineProperty,hg=Object.defineProperties,lg=Object.getOwnPropertyDescriptors,Oo=Object.getOwnPropertySymbols,ug=Object.prototype.hasOwnProperty,pg=Object.prototype.propertyIsEnumerable,xo=(i,e,t)=>e in i?cg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Rs=(i,e)=>{for(var t in e||(e={}))ug.call(e,t)&&xo(i,t,e[t]);if(Oo)for(var t of Oo(e))pg.call(e,t)&&xo(i,t,e[t]);return i},qs=(i,e)=>hg(i,lg(e));function Ws(i){return qs(Rs({},i),{level:(i==null?void 0:i.level)||rg.level})}function dg(i,e=hs){return i[e]||""}function gg(i,e,t=hs){return i[t]=e,i}function Ce(i,e=hs){let t="";return typeof i.bindings>"u"?t=dg(i,e):t=i.bindings().context||"",t}function fg(i,e,t=hs){const s=Ce(i,t);return s.trim()?`${s}/${e}`:e}function $e(i,e,t=hs){const s=fg(i,e,t),r=i.child({context:s});return gg(r,s,t)}function yg(i){var e,t;const s=new og((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:cs(qs(Rs({},i.opts),{level:"trace",browser:qs(Rs({},(t=i.opts)==null?void 0:t.browser),{write:r=>s.write(r)})})),chunkLoggerController:s}}function mg(i){var e;const t=new ag((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:cs(qs(Rs({},i.opts),{level:"trace"}),t),chunkLoggerController:t}}function wg(i){return typeof i.loggerOverride<"u"&&typeof i.loggerOverride!="string"?{logger:i.loggerOverride,chunkLoggerController:null}:typeof window<"u"?yg(i):mg(i)}var bg=Object.defineProperty,vg=(i,e,t)=>e in i?bg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ao=(i,e,t)=>vg(i,typeof e!="symbol"?e+"":e,t);let Eg=class extends Pi{constructor(e){super(),this.opts=e,Ao(this,"protocol","wc"),Ao(this,"version",2)}};var Ig=Object.defineProperty,_g=(i,e,t)=>e in i?Ig(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Pg=(i,e,t)=>_g(i,typeof e!="symbol"?e+"":e,t);let $g=class extends Pi{constructor(e,t){super(),this.core=e,this.logger=t,Pg(this,"records",new Map)}},Sg=class{constructor(e,t){this.logger=e,this.core=t}};class Og extends Pi{constructor(e,t){super(),this.relayer=e,this.logger=t}}let xg=class extends Pi{constructor(e){super()}},Ag=class{constructor(e,t,s,r){this.core=e,this.logger=t,this.name=s}},Cg=class extends Pi{constructor(e,t){super(),this.relayer=e,this.logger=t}},Tg=class extends Pi{constructor(e,t){super(),this.core=e,this.logger=t}},Ng=class{constructor(e,t,s){this.core=e,this.logger=t,this.store=s}},Rg=class{constructor(e,t){this.projectId=e,this.logger=t}},qg=class{constructor(e,t,s){this.core=e,this.logger=t,this.telemetryEnabled=s}};var jg=Object.defineProperty,kg=(i,e,t)=>e in i?jg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Co=(i,e,t)=>kg(i,typeof e!="symbol"?e+"":e,t);let Dg=class{constructor(e){this.opts=e,Co(this,"protocol","wc"),Co(this,"version",2)}},Lg=class{constructor(e){this.client=e}};const xc="wc",Ac=2,js="core",ot=`${xc}@2:${js}:`,Fg={name:js,logger:"error"},Ug={database:":memory:"},Mg="crypto",To="client_ed25519_seed",Bg=C.ONE_DAY,zg="keychain",Vg="0.3",Hg="messages",Kg="0.3",No=C.SIX_HOURS,Gg="publisher",Cc="irn",Wg="error",Tc="wss://relay.walletconnect.org",Jg="relayer",de={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},Qg="_subscription",Le={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Yg=.1,Ur="2.21.1",te={link_mode:"link_mode",relay:"relay"},Ss={inbound:"inbound",outbound:"outbound"},Zg="0.3",Xg="WALLETCONNECT_CLIENT_ID",Ro="WALLETCONNECT_LINK_MODE_APPS",Re={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},ef="subscription",tf="0.3",sf="pairing",rf="0.3",ki={wc_pairingDelete:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:C.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:C.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:C.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:C.ONE_DAY,prompt:!1,tag:0},res:{ttl:C.ONE_DAY,prompt:!1,tag:0}}},qt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ve={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},nf="history",of="0.3",af="expirer",Ue={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},cf="0.3",hf="verify-api",lf="https://verify.walletconnect.com",Nc="https://verify.walletconnect.org",Ki=Nc,uf=`${Ki}/v3`,pf=[lf,Nc],df="echo",gf="https://echo.walletconnect.com",tt={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"},dt={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"},He={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},At={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Ct={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Di={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},ff=.1,yf="event-client",mf=86400,wf="https://pulse.walletconnect.org/batch";function bf(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(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var m=0,f=0,w=0,y=d.length;w!==y&&d[w]===0;)w++,m++;for(var I=(y-w)*l+1>>>0,_=new Uint8Array(I);w!==y;){for(var T=d[w],P=0,S=I-1;(T!==0||P<f)&&S!==-1;S--,P++)T+=256*_[S]>>>0,_[S]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");f=P,w++}for(var N=I-f;N!==I&&_[N]===0;)N++;for(var b=c.repeat(m);N<I;++N)b+=i.charAt(_[N]);return b}function p(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var m=0;if(d[m]!==" "){for(var f=0,w=0;d[m]===c;)f++,m++;for(var y=(d.length-m)*h+1>>>0,I=new Uint8Array(y);d[m];){var _=t[d.charCodeAt(m)];if(_===255)return;for(var T=0,P=y-1;(_!==0||T<w)&&P!==-1;P--,T++)_+=a*I[P]>>>0,I[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");w=T,m++}if(d[m]!==" "){for(var S=y-w;S!==y&&I[S]===0;)S++;for(var N=new Uint8Array(f+(y-S)),b=f;S!==y;)N[b++]=I[S++];return N}}}function g(d){var m=p(d);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:g}}var vf=bf,Ef=vf;const Rc=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},If=i=>new TextEncoder().encode(i),_f=i=>new TextDecoder().decode(i);class Pf{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 $f{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 Sf{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 Sf({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Of{constructor(e,t,s,r){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=r,this.encoder=new Pf(e,t,s),this.decoder=new $f(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 Of(i,e,t,s),ls=({prefix:i,name:e,alphabet:t})=>{const{encode:s,decode:r}=Ef(t,e);return Js({prefix:i,name:e,encode:s,decode:n=>Rc(r(n))})},xf=(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},Af=(i,e,t)=>{const s=e[e.length-1]==="=",r=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[r&a>>o];if(o&&(n+=e[r&a<<t-o]),s)for(;n.length*t&7;)n+="=";return n},be=({name:i,prefix:e,bitsPerChar:t,alphabet:s})=>Js({prefix:e,name:i,encode(r){return Af(r,s,t)},decode(r){return xf(r,s,t,i)}}),Cf=Js({prefix:"\0",name:"identity",encode:i=>_f(i),decode:i=>If(i)});var Tf=Object.freeze({__proto__:null,identity:Cf});const Nf=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Rf=Object.freeze({__proto__:null,base2:Nf});const qf=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var jf=Object.freeze({__proto__:null,base8:qf});const kf=ls({prefix:"9",name:"base10",alphabet:"0123456789"});var Df=Object.freeze({__proto__:null,base10:kf});const Lf=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ff=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Uf=Object.freeze({__proto__:null,base16:Lf,base16upper:Ff});const Mf=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bf=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zf=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Vf=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Hf=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kf=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Gf=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Wf=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jf=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Qf=Object.freeze({__proto__:null,base32:Mf,base32upper:Bf,base32pad:zf,base32padupper:Vf,base32hex:Hf,base32hexupper:Kf,base32hexpad:Gf,base32hexpadupper:Wf,base32z:Jf});const Yf=ls({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zf=ls({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xf=Object.freeze({__proto__:null,base36:Yf,base36upper:Zf});const ey=ls({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ty=ls({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var iy=Object.freeze({__proto__:null,base58btc:ey,base58flickr:ty});const sy=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ry=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ny=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),oy=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ay=Object.freeze({__proto__:null,base64:sy,base64pad:ry,base64url:ny,base64urlpad:oy});const jc=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),cy=jc.reduce((i,e,t)=>(i[t]=e,i),[]),hy=jc.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function ly(i){return i.reduce((e,t)=>(e+=cy[t],e),"")}function uy(i){const e=[];for(const t of i){const s=hy[t.codePointAt(0)];if(s===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}const py=Js({prefix:"🚀",name:"base256emoji",encode:ly,decode:uy});var dy=Object.freeze({__proto__:null,base256emoji:py}),gy=kc,qo=128,fy=127,yy=~fy,my=Math.pow(2,31);function kc(i,e,t){e=e||[],t=t||0;for(var s=t;i>=my;)e[t++]=i&255|qo,i/=128;for(;i&yy;)e[t++]=i&255|qo,i>>>=7;return e[t]=i|0,kc.bytes=t-s+1,e}var wy=Mr,by=128,jo=127;function Mr(i,s){var t=0,s=s||0,r=0,n=s,o,a=i.length;do{if(n>=a)throw Mr.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=r<28?(o&jo)<<r:(o&jo)*Math.pow(2,r),r+=7}while(o>=by);return Mr.bytes=n-s,t}var vy=Math.pow(2,7),Ey=Math.pow(2,14),Iy=Math.pow(2,21),_y=Math.pow(2,28),Py=Math.pow(2,35),$y=Math.pow(2,42),Sy=Math.pow(2,49),Oy=Math.pow(2,56),xy=Math.pow(2,63),Ay=function(i){return i<vy?1:i<Ey?2:i<Iy?3:i<_y?4:i<Py?5:i<$y?6:i<Sy?7:i<Oy?8:i<xy?9:10},Cy={encode:gy,decode:wy,encodingLength:Ay},Dc=Cy;const ko=(i,e,t=0)=>(Dc.encode(i,e,t),e),Do=i=>Dc.encodingLength(i),Br=(i,e)=>{const t=e.byteLength,s=Do(i),r=s+Do(t),n=new Uint8Array(r+t);return ko(i,n,0),ko(t,n,s),n.set(e,r),new Ty(i,t,e,n)};class Ty{constructor(e,t,s,r){this.code=e,this.size=t,this.digest=s,this.bytes=r}}const Lc=({name:i,code:e,encode:t})=>new Ny(i,e,t);class Ny{constructor(e,t,s){this.name=e,this.code=t,this.encode=s}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Br(this.code,t):t.then(s=>Br(this.code,s))}else throw Error("Unknown type, must be binary type")}}const Fc=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Ry=Lc({name:"sha2-256",code:18,encode:Fc("SHA-256")}),qy=Lc({name:"sha2-512",code:19,encode:Fc("SHA-512")});var jy=Object.freeze({__proto__:null,sha256:Ry,sha512:qy});const Uc=0,ky="identity",Mc=Rc,Dy=i=>Br(Uc,Mc(i)),Ly={code:Uc,name:ky,encode:Mc,digest:Dy};var Fy=Object.freeze({__proto__:null,identity:Ly});new TextEncoder,new TextDecoder;const Lo={...Tf,...Rf,...jf,...Df,...Uf,...Qf,...Xf,...iy,...ay,...dy};({...jy,...Fy});function Uy(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function Bc(i,e,t,s){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:s}}}const Fo=Bc("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),dr=Bc("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=Uy(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),My={utf8:Fo,"utf-8":Fo,hex:Lo.base16,latin1:dr,ascii:dr,binary:dr,...Lo};function By(i,e="utf8"){const t=My[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 zy=Object.defineProperty,Vy=(i,e,t)=>e in i?zy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xe=(i,e,t)=>Vy(i,typeof e!="symbol"?e+"":e,t);class Hy{constructor(e,t){this.core=e,this.logger=t,Xe(this,"keychain",new Map),Xe(this,"name",zg),Xe(this,"version",Vg),Xe(this,"initialized",!1),Xe(this,"storagePrefix",ot),Xe(this,"init",async()=>{if(!this.initialized){const s=await this.getKeyChain();typeof s<"u"&&(this.keychain=s),this.initialized=!0}}),Xe(this,"has",s=>(this.isInitialized(),this.keychain.has(s))),Xe(this,"set",async(s,r)=>{this.isInitialized(),this.keychain.set(s,r),await this.persist()}),Xe(this,"get",s=>{this.isInitialized();const r=this.keychain.get(s);if(typeof r>"u"){const{message:n}=A("NO_MATCHING_KEY",`${this.name}: ${s}`);throw new Error(n)}return r}),Xe(this,"del",async s=>{this.isInitialized(),this.keychain.delete(s),await this.persist()}),this.core=e,this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,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}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Ky=Object.defineProperty,Gy=(i,e,t)=>e in i?Ky(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ye=(i,e,t)=>Gy(i,typeof e!="symbol"?e+"":e,t);class Wy{constructor(e,t,s){this.core=e,this.logger=t,ye(this,"name",Mg),ye(this,"keychain"),ye(this,"randomSessionIdentifier",Lr()),ye(this,"initialized",!1),ye(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),ye(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),ye(this,"getClientId",async()=>{this.isInitialized();const r=await this.getClientSeed(),n=bn(r);return mh(n.publicKey)}),ye(this,"generateKeyPair",()=>{this.isInitialized();const r=Hp();return this.setPrivateKey(r.publicKey,r.privateKey)}),ye(this,"signJWT",async r=>{this.isInitialized();const n=await this.getClientSeed(),o=bn(n),a=this.randomSessionIdentifier;return await wh(a,r,Bg,o)}),ye(this,"generateSharedKey",(r,n,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Kp(a,n);return this.setSymKey(c,o)}),ye(this,"setSymKey",async(r,n)=>{this.isInitialized();const o=n||$s(r);return await this.keychain.set(o,r),o}),ye(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),ye(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),ye(this,"encode",async(r,n,o)=>{this.isInitialized();const a=Ic(o),c=Pr(n);if(po(a))return Jp(c,o==null?void 0:o.encoding);if(uo(a)){const p=a.senderPublicKey,g=a.receiverPublicKey;r=await this.generateSharedKey(p,g)}const h=this.getSymKey(r),{type:l,senderPublicKey:u}=a;return Gp({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),ye(this,"decode",async(r,n,o)=>{this.isInitialized();const a=Yp(n,o);if(po(a)){const c=Qp(n,o==null?void 0:o.encoding);return vn(c)}if(uo(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;r=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(r),h=Wp({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return vn(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),ye(this,"getPayloadType",(r,n=We)=>{const o=Xi({encoded:r,encoding:n});return Bt(o.type)}),ye(this,"getPayloadSenderPublicKey",(r,n=We)=>{const o=Xi({encoded:r,encoding:n});return o.senderPublicKey?Ae(o.senderPublicKey,Pe):void 0}),this.core=e,this.logger=$e(t,this.name),this.keychain=s||new Hy(this.core,this.logger)}get context(){return Ce(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(To)}catch{e=Lr(),await this.keychain.set(To,e)}return By(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Jy=Object.defineProperty,Qy=Object.defineProperties,Yy=Object.getOwnPropertyDescriptors,Uo=Object.getOwnPropertySymbols,Zy=Object.prototype.hasOwnProperty,Xy=Object.prototype.propertyIsEnumerable,zr=(i,e,t)=>e in i?Jy(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,em=(i,e)=>{for(var t in e||(e={}))Zy.call(e,t)&&zr(i,t,e[t]);if(Uo)for(var t of Uo(e))Xy.call(e,t)&&zr(i,t,e[t]);return i},tm=(i,e)=>Qy(i,Yy(e)),Te=(i,e,t)=>zr(i,typeof e!="symbol"?e+"":e,t);class im extends Sg{constructor(e,t){super(e,t),this.logger=e,this.core=t,Te(this,"messages",new Map),Te(this,"messagesWithoutClientAck",new Map),Te(this,"name",Hg),Te(this,"version",Kg),Te(this,"initialized",!1),Te(this,"storagePrefix",ot),Te(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}}}),Te(this,"set",async(s,r,n)=>{this.isInitialized();const o=st(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===Ss.inbound){const c=this.messagesWithoutClientAck.get(s)||{};this.messagesWithoutClientAck.set(s,tm(em({},c),{[o]:r}))}return await this.persist(),o}),Te(this,"get",s=>{this.isInitialized();let r=this.messages.get(s);return typeof r>"u"&&(r={}),r}),Te(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}),Te(this,"has",(s,r)=>{this.isInitialized();const n=this.get(s),o=st(r);return typeof n[o]<"u"}),Te(this,"ack",async(s,r)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(s);if(typeof n>"u")return;const o=st(r);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(s):this.messagesWithoutClientAck.set(s,n),await this.persist()}),Te(this,"del",async s=>{this.isInitialized(),this.messages.delete(s),this.messagesWithoutClientAck.delete(s),await this.persist()}),this.logger=$e(e,this.name),this.core=t}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,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}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var sm=Object.defineProperty,rm=Object.defineProperties,nm=Object.getOwnPropertyDescriptors,Mo=Object.getOwnPropertySymbols,om=Object.prototype.hasOwnProperty,am=Object.prototype.propertyIsEnumerable,Vr=(i,e,t)=>e in i?sm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ws=(i,e)=>{for(var t in e||(e={}))om.call(e,t)&&Vr(i,t,e[t]);if(Mo)for(var t of Mo(e))am.call(e,t)&&Vr(i,t,e[t]);return i},gr=(i,e)=>rm(i,nm(e)),Ke=(i,e,t)=>Vr(i,typeof e!="symbol"?e+"":e,t);class cm extends Og{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Ke(this,"events",new St.EventEmitter),Ke(this,"name",Gg),Ke(this,"queue",new Map),Ke(this,"publishTimeout",C.toMiliseconds(C.ONE_MINUTE)),Ke(this,"initialPublishTimeout",C.toMiliseconds(C.ONE_SECOND*15)),Ke(this,"needsTransportRestart",!1),Ke(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)||No,c=Ts(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}},g=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const d=new Promise(async m=>{const f=({id:y})=>{p.opts.id===y&&(this.removeRequestFromQueue(y),this.relayer.events.removeListener(de.publish,f),m(p))};this.relayer.events.on(de.publish,f);const w=_t(new Promise((y,I)=>{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(y).catch(_=>{this.logger.warn(_,_==null?void 0:_.message),I(_)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await w,this.events.removeListener(de.publish,f)}catch(y){this.queue.set(u,gr(ws({},p),{attempt:1})),this.logger.warn(y,y==null?void 0:y.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:s,message:r,opts:n}}),await _t(d,this.publishTimeout,g)}catch(d){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(d),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw d}finally{this.queue.delete(u)}}),Ke(this,"on",(s,r)=>{this.events.on(s,r)}),Ke(this,"once",(s,r)=>{this.events.once(s,r)}),Ke(this,"off",(s,r)=>{this.events.off(s,r)}),Ke(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.relayer=e,this.logger=$e(t,this.name),this.registerEventListeners()}get context(){return Ce(this.logger)}async rpcPublish(e){var t,s,r,n;const{topic:o,message:a,ttl:c=No,prompt:h,tag:l,id:u,attestation:p,tvf:g}=e,d={method:Mi(Ts().protocol).publish,params:ws({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:p},g),id:u};we((t=d.params)==null?void 0:t.prompt)&&((s=d.params)==null||delete s.prompt),we((r=d.params)==null?void 0:r.tag)&&((n=d.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:d});const m=await this.relayer.request(d);return this.relayer.events.emit(de.publish,e),this.logger.debug("Successfully Published Payload"),m}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const s=e.attempt+1;this.queue.set(t,gr(ws({},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(ws({},e),{topic:r,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on($i.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(de.connection_stalled);return}this.checkQueue()}),this.relayer.on(de.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var hm=Object.defineProperty,lm=(i,e,t)=>e in i?hm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qt=(i,e,t)=>lm(i,typeof e!="symbol"?e+"":e,t);class um{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 pm=Object.defineProperty,dm=Object.defineProperties,gm=Object.getOwnPropertyDescriptors,Bo=Object.getOwnPropertySymbols,fm=Object.prototype.hasOwnProperty,ym=Object.prototype.propertyIsEnumerable,Hr=(i,e,t)=>e in i?pm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Li=(i,e)=>{for(var t in e||(e={}))fm.call(e,t)&&Hr(i,t,e[t]);if(Bo)for(var t of Bo(e))ym.call(e,t)&&Hr(i,t,e[t]);return i},fr=(i,e)=>dm(i,gm(e)),Y=(i,e,t)=>Hr(i,typeof e!="symbol"?e+"":e,t);class mm extends Cg{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,Y(this,"subscriptions",new Map),Y(this,"topicMap",new um),Y(this,"events",new St.EventEmitter),Y(this,"name",ef),Y(this,"version",tf),Y(this,"pending",new Map),Y(this,"cached",[]),Y(this,"initialized",!1),Y(this,"storagePrefix",ot),Y(this,"subscribeTimeout",C.toMiliseconds(C.ONE_MINUTE)),Y(this,"initialSubscribeTimeout",C.toMiliseconds(C.ONE_SECOND*15)),Y(this,"clientId"),Y(this,"batchSubscribeTopicsLimit",500),Y(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Y(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=Ts(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}}),Y(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)}),Y(this,"isSubscribed",s=>new Promise(r=>{r(this.topicMap.topics.includes(s))})),Y(this,"isKnownTopic",s=>new Promise(r=>{r(this.topicMap.topics.includes(s)||this.pending.has(s)||this.cached.some(n=>n.topic===s))})),Y(this,"on",(s,r)=>{this.events.on(s,r)}),Y(this,"once",(s,r)=>{this.events.once(s,r)}),Y(this,"off",(s,r)=>{this.events.off(s,r)}),Y(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),Y(this,"start",async()=>{await this.onConnect()}),Y(this,"stop",async()=>{await this.onDisconnect()}),Y(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Y(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)}),Y(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on($i.pulse,async()=>{await this.checkPending()}),this.events.on(Re.created,async s=>{const r=Re.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()}),this.events.on(Re.deleted,async s=>{const r=Re.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:s}),await this.persist()})}),this.relayer=e,this.logger=$e(t,this.name),this.clientId=""}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let s=!1;try{s=this.getSubscription(e).topic===t}catch{}return s}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const s=this.topicMap.get(e);await Promise.all(s.map(async r=>await this.unsubscribeById(e,r,t)))}async unsubscribeById(e,t,s){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}});try{const r=Ts(s);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r);const n=Q("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:s}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,t,s){var r;(!s||(s==null?void 0:s.transportType)===te.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:Mi(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)===te.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},C.toMiliseconds(C.ONE_SECOND)),a;const c=new Promise(async l=>{const u=p=>{p.topic===e&&(this.events.removeListener(Re.created,u),l(p.id))};this.events.on(Re.created,u);try{const p=await _t(new Promise((g,d)=>{this.relayer.request(n).catch(m=>{this.logger.warn(m,m==null?void 0:m.message),d(m)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Re.created,u),l(p)}catch{}}),h=await _t(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(de.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,s={method:Mi(t.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});try{await await _t(new Promise(r=>{this.relayer.request(s).catch(n=>this.logger.warn(n)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,s={method:Mi(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});let r;try{r=await await _t(new Promise((n,o)=>{this.relayer.request(s).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}return r}rpcUnsubscribe(e,t,s){const r={method:Mi(s.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,t){this.setSubscription(e,fr(Li({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,Li({},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,Li({},t)),this.topicMap.set(t.topic,e),this.events.emit(Re.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}=A("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(Re.deleted,fr(Li({},s),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Re.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(Re.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=A("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async t=>fr(Li({},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 Nl(C.toMiliseconds(C.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}=A("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 st(e+await this.getClientId())}}var wm=Object.defineProperty,zo=Object.getOwnPropertySymbols,bm=Object.prototype.hasOwnProperty,vm=Object.prototype.propertyIsEnumerable,Kr=(i,e,t)=>e in i?wm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Vo=(i,e)=>{for(var t in e||(e={}))bm.call(e,t)&&Kr(i,t,e[t]);if(zo)for(var t of zo(e))vm.call(e,t)&&Kr(i,t,e[t]);return i},K=(i,e,t)=>Kr(i,typeof e!="symbol"?e+"":e,t);class Em extends xg{constructor(e){super(e),K(this,"protocol","wc"),K(this,"version",2),K(this,"core"),K(this,"logger"),K(this,"events",new St.EventEmitter),K(this,"provider"),K(this,"messages"),K(this,"subscriber"),K(this,"publisher"),K(this,"name",Jg),K(this,"transportExplicitlyClosed",!1),K(this,"initialized",!1),K(this,"connectionAttemptInProgress",!1),K(this,"relayUrl"),K(this,"projectId"),K(this,"packageName"),K(this,"bundleId"),K(this,"hasExperiencedNetworkDisruption",!1),K(this,"pingTimeout"),K(this,"heartBeatTimeout",C.toMiliseconds(C.THIRTY_SECONDS+C.FIVE_SECONDS)),K(this,"reconnectTimeout"),K(this,"connectPromise"),K(this,"reconnectInProgress",!1),K(this,"requestsInFlight",[]),K(this,"connectTimeout",C.toMiliseconds(C.ONE_SECOND*15)),K(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}}),K(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,s,r,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(r=(s=(t=this.provider)==null?void 0:t.connection)==null?void 0:s.socket)==null?void 0:r.terminate)==null||n.call(r)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),K(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),K(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(de.connect)}),K(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),K(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(de.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),K(this,"registerProviderListeners",()=>{this.provider.on(Le.payload,this.onPayloadHandler),this.provider.on(Le.connect,this.onConnectHandler),this.provider.on(Le.disconnect,this.onDisconnectHandler),this.provider.on(Le.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?$e(e.logger,this.name):cs(Ws({level:e.logger||Wg})),this.messages=new im(this.logger,e.core),this.subscriber=new mm(this,this.logger),this.publisher=new cm(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Tc,this.projectId=e.projectId,yl()?this.packageName=jn():ml()&&(this.bundleId=jn()),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 Ce(this.logger)}get connected(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===1||!1}get connecting(){var e,t,s;return((s=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:s.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,s){this.isInitialized(),await this.publisher.publish(e,t,s),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:te.relay},Ss.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(Re.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Re.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,Vo({internal:{throwOnFailedPublish:o}},t)).catch(p=>{o&&u(p)})||a,l()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await _t(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,s)=>{await this.connect(e).then(t).catch(s).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Po())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==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=ce(C.FIVE_MINUTES),n={topic:s,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(s,n)}this.events.emit(de.message,e),await this.recordMessageEvent(e,Ss.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(Le.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(Le.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(Le.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Le.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,C.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,s,r,n;if(As())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(r=(s=this.provider)==null?void 0:s.connection)==null?void 0:r.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Be(new yh(Il({sdkVersion:Ur,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:s,message:r}=e;await this.messages.set(s,r,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:s}=e;if(!s||s.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${s}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const r=this.messages.has(t,s);return r&&this.logger.warn(`Ignoring duplicate message: ${s}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),sn(e)){if(!e.method.endsWith(Qg))return;const t=e.params,{topic:s,message:r,publishedAt:n,attestation:o}=t.data,a={topic:s,message:r,publishedAt:n,transportType:te.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Vo({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else rn(e)&&this.events.emit(de.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Ss.inbound),this.events.emit(de.message,e))}async acknowledgePayload(e){const t=Fs(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Le.payload,this.onPayloadHandler),this.provider.off(Le.connect,this.onConnectHandler),this.provider.off(Le.disconnect,this.onDisconnectHandler),this.provider.off(Le.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Po();Vd(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($i.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Gd())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(de.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},C.toMiliseconds(Yg)))))}isInitialized(){if(!this.initialized){const{message:e}=A("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 Im(){}function Ho(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 Ko(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Go(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const _m="[object RegExp]",Pm="[object String]",$m="[object Number]",Sm="[object Boolean]",Wo="[object Arguments]",Om="[object Symbol]",xm="[object Date]",Am="[object Map]",Cm="[object Set]",Tm="[object Array]",Nm="[object Function]",Rm="[object ArrayBuffer]",yr="[object Object]",qm="[object Error]",jm="[object DataView]",km="[object Uint8Array]",Dm="[object Uint8ClampedArray]",Lm="[object Uint16Array]",Fm="[object Uint32Array]",Um="[object BigUint64Array]",Mm="[object Int8Array]",Bm="[object Int16Array]",zm="[object Int32Array]",Vm="[object BigInt64Array]",Hm="[object Float32Array]",Km="[object Float64Array]";function Gm(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function Wm(i,e,t){return Bi(i,e,void 0,void 0,void 0,void 0,t)}function Bi(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 Gi(i,e,n,o)}return Gi(i,e,n,o)}function Gi(i,e,t,s){if(Object.is(i,e))return!0;let r=Go(i),n=Go(e);if(r===Wo&&(r=yr),n===Wo&&(n=yr),r!==n)return!1;switch(r){case Pm:return i.toString()===e.toString();case $m:{const c=i.valueOf(),h=e.valueOf();return Gm(c,h)}case Sm:case xm:case Om:return Object.is(i.valueOf(),e.valueOf());case _m:return i.source===e.source&&i.flags===e.flags;case Nm: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 Am:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!Bi(h,e.get(c),c,i,e,t,s))return!1;return!0}case Cm:{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(g=>Bi(u,g,void 0,i,e,t,s));if(p===-1)return!1;h.splice(p,1)}return!0}case Tm:case km:case Dm:case Lm:case Fm:case Um:case Mm:case Bm:case zm:case Vm:case Hm:case Km:{if(typeof Ie<"u"&&Ie.isBuffer(i)!==Ie.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!Bi(i[c],e[c],c,i,e,t,s))return!1;return!0}case Rm:return i.byteLength!==e.byteLength?!1:Gi(new Uint8Array(i),new Uint8Array(e),t,s);case jm:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:Gi(new Uint8Array(i),new Uint8Array(e),t,s);case qm:return i.name===e.name&&i.message===e.message;case yr:{if(!(Gi(i.constructor,e.constructor,t,s)||Ho(i)&&Ho(e)))return!1;const c=[...Object.keys(i),...Ko(i)],h=[...Object.keys(e),...Ko(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 g=e[u];if(!Bi(p,g,u,i,e,t,s))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function Jm(i,e){return Wm(i,e,Im)}var Qm=Object.defineProperty,Jo=Object.getOwnPropertySymbols,Ym=Object.prototype.hasOwnProperty,Zm=Object.prototype.propertyIsEnumerable,Gr=(i,e,t)=>e in i?Qm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qo=(i,e)=>{for(var t in e||(e={}))Ym.call(e,t)&&Gr(i,t,e[t]);if(Jo)for(var t of Jo(e))Zm.call(e,t)&&Gr(i,t,e[t]);return i},Se=(i,e,t)=>Gr(i,typeof e!="symbol"?e+"":e,t);class zt extends Ag{constructor(e,t,s,r=ot,n=void 0){super(e,t,s,r),this.core=e,this.logger=t,this.name=s,Se(this,"map",new Map),Se(this,"version",Zg),Se(this,"cached",[]),Se(this,"initialized",!1),Se(this,"getKey"),Se(this,"storagePrefix",ot),Se(this,"recentlyDeleted",[]),Se(this,"recentlyDeletedLimit",200),Se(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!we(o)?this.map.set(this.getKey(o),o):Ed(o)?this.map.set(o.id,o):Id(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Se(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Se(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Se(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>Jm(a[c],o[c]))):this.values)),Se(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Qo(Qo({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Se(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=$e(t,this.name),this.storagePrefix=r,this.getKey=n}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:r}=A("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:s}=A("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}=A("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}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Xm=Object.defineProperty,ew=(i,e,t)=>e in i?Xm(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,z=(i,e,t)=>ew(i,typeof e!="symbol"?e+"":e,t);class tw{constructor(e,t){this.core=e,this.logger=t,z(this,"name",sf),z(this,"version",rf),z(this,"events",new tn),z(this,"pairings"),z(this,"initialized",!1),z(this,"storagePrefix",ot),z(this,"ignoredPayloadTypes",[mt]),z(this,"registeredMethods",[]),z(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),z(this,"register",({methods:s})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...s])]}),z(this,"create",async s=>{this.isInitialized();const r=Lr(),n=await this.core.crypto.setSymKey(r),o=ce(C.FIVE_MINUTES),a={protocol:Cc},c={topic:n,expiry:o,relay:a,active:!1,methods:s==null?void 0:s.methods},h=fo({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(qt.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}}),z(this,"pair",async s=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:s==null?void 0:s.uri,trace:[tt.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(tt.pairing_uri_validation_success),r.addTrace(tt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),r.addTrace(tt.existing_pairing),l.active)throw r.setError(dt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);r.addTrace(tt.pairing_not_expired)}const u=c||ce(C.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(tt.store_new_pairing),s.activatePairing&&await this.activate({topic:n}),this.events.emit(qt.create,p),r.addTrace(tt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),r.addTrace(tt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(dt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(g){throw r.setError(dt.subscribe_pairing_topic_failure),g}return r.addTrace(tt.subscribe_pairing_topic_success),p}),z(this,"activate",async({topic:s})=>{this.isInitialized();const r=ce(C.FIVE_MINUTES);this.core.expirer.set(s,r),await this.pairings.update(s,{active:!0,expiry:r})}),z(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}=Tt();this.events.once(J("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),z(this,"updateExpiry",async({topic:s,expiry:r})=>{this.isInitialized(),await this.pairings.update(s,{expiry:r})}),z(this,"updateMetadata",async({topic:s,metadata:r})=>{this.isInitialized(),await this.pairings.update(s,{peerMetadata:r})}),z(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),z(this,"disconnect",async s=>{this.isInitialized(),await this.isValidDisconnect(s);const{topic:r}=s;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Q("USER_DISCONNECTED")),await this.deletePairing(r))}),z(this,"formatUriFromPairing",s=>{this.isInitialized();const{topic:r,relay:n,expiry:o,methods:a}=s,c=this.core.crypto.keychain.get(r);return fo({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),z(this,"sendRequest",async(s,r,n)=>{const o=kt(r,n),a=await this.core.crypto.encode(s,o),c=ki[r].req;return this.core.history.set(s,o),this.core.relayer.publish(s,a,c),o.id}),z(this,"sendResult",async(s,r,n)=>{const o=Fs(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=ki[c].res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),z(this,"sendError",async(s,r,n)=>{const o=_a(s,n),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,s)).request.method,h=ki[c]?ki[c].res:ki.unregistered_method.res;await this.core.relayer.publish(r,a,h),await this.core.history.resolve(o)}),z(this,"deletePairing",async(s,r)=>{await this.core.relayer.unsubscribe(s),await Promise.all([this.pairings.delete(s,Q("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(s),r?Promise.resolve():this.core.expirer.del(s)])}),z(this,"cleanup",async()=>{const s=this.pairings.getAll().filter(r=>Et(r.expiry));await Promise.all(s.map(r=>this.deletePairing(r.topic)))}),z(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)}}),z(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)}}),z(this,"onPairingPingRequest",async(s,r)=>{const{id:n}=r;try{this.isValidPing({topic:s}),await this.sendResult(n,s,!0),this.events.emit(qt.ping,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),z(this,"onPairingPingResponse",(s,r)=>{const{id:n}=r;setTimeout(()=>{pt(r)?this.events.emit(J("pairing_ping",n),{}):it(r)&&this.events.emit(J("pairing_ping",n),{error:r.error})},500)}),z(this,"onPairingDeleteRequest",async(s,r)=>{const{id:n}=r;try{this.isValidDisconnect({topic:s}),await this.deletePairing(s),this.events.emit(qt.delete,{id:n,topic:s})}catch(o){await this.sendError(n,s,o),this.logger.error(o)}}),z(this,"onUnknownRpcMethodRequest",async(s,r)=>{const{id:n,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Q("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,s,a),this.logger.error(a)}catch(a){await this.sendError(n,s,a),this.logger.error(a)}}),z(this,"onUnknownRpcMethodResponse",s=>{this.registeredMethods.includes(s)||this.logger.error(Q("WC_METHOD_UNSUPPORTED",s))}),z(this,"isValidPair",(s,r)=>{var n;if(!Oe(s)){const{message:a}=A("MISSING_OR_INVALID",`pair() params: ${s}`);throw r.setError(dt.malformed_pairing_uri),new Error(a)}if(!vd(s.uri)){const{message:a}=A("MISSING_OR_INVALID",`pair() uri: ${s.uri}`);throw r.setError(dt.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}=A("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(dt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=A("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(dt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&C.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(dt.pairing_expired);const{message:a}=A("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),z(this,"isValidPing",async s=>{if(!Oe(s)){const{message:n}=A("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),z(this,"isValidDisconnect",async s=>{if(!Oe(s)){const{message:n}=A("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(n)}const{topic:r}=s;await this.isValidPairingTopic(r)}),z(this,"isValidPairingTopic",async s=>{if(!ne(s,!1)){const{message:r}=A("MISSING_OR_INVALID",`pairing topic should be a string: ${s}`);throw new Error(r)}if(!this.pairings.keys.includes(s)){const{message:r}=A("NO_MATCHING_KEY",`pairing topic doesn't exist: ${s}`);throw new Error(r)}if(Et(this.pairings.get(s).expiry)){await this.deletePairing(s);const{message:r}=A("EXPIRED",`pairing topic: ${s}`);throw new Error(r)}}),this.core=e,this.logger=$e(t,this.name),this.pairings=new zt(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ce(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(de.message,async e=>{const{topic:t,message:s,transportType:r}=e;if(this.pairings.keys.includes(t)&&r!==te.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s)))try{const n=await this.core.crypto.decode(t,s);sn(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):rn(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,s)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(Ue.expired,async e=>{const{topic:t}=za(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(qt.expire,{topic:t}))})}}var iw=Object.defineProperty,sw=(i,e,t)=>e in i?iw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,me=(i,e,t)=>sw(i,typeof e!="symbol"?e+"":e,t);class rw extends $g{constructor(e,t){super(e,t),this.core=e,this.logger=t,me(this,"records",new Map),me(this,"events",new St.EventEmitter),me(this,"name",nf),me(this,"version",of),me(this,"cached",[]),me(this,"initialized",!1),me(this,"storagePrefix",ot),me(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)}),me(this,"set",(s,r,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:s,request:r,chainId:n}),this.records.has(r.id))return;const o={id:r.id,topic:s,request:{method:r.method,params:r.params||null},chainId:n,expiry:ce(C.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ve.created,o)}),me(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=it(s)?{error:s.error}:{result:s.result},this.records.set(r.id,r),this.persist(),this.events.emit(Ve.updated,r))}),me(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))),me(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(Ve.deleted,n)}}),this.persist()}),me(this,"exists",async(s,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===s:!1)),me(this,"on",(s,r)=>{this.events.on(s,r)}),me(this,"once",(s,r)=>{this.events.once(s,r)}),me(this,"off",(s,r)=>{this.events.off(s,r)}),me(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const s={topic:t.topic,request:kt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(s)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:s}=A("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(s)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ve.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=A("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(Ve.created,e=>{const t=Ve.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ve.updated,e=>{const t=Ve.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(Ve.deleted,e=>{const t=Ve.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on($i.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{C.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(Ve.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var nw=Object.defineProperty,ow=(i,e,t)=>e in i?nw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ee=(i,e,t)=>ow(i,typeof e!="symbol"?e+"":e,t);class aw extends Tg{constructor(e,t){super(e,t),this.core=e,this.logger=t,Ee(this,"expirations",new Map),Ee(this,"events",new St.EventEmitter),Ee(this,"name",af),Ee(this,"version",cf),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",ot),Ee(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(s=>this.expirations.set(s.target,s)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ee(this,"has",s=>{try{const r=this.formatTarget(s);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Ee(this,"set",(s,r)=>{this.isInitialized();const n=this.formatTarget(s),o={target:n,expiry:r};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Ue.created,{target:n,expiration:o})}),Ee(this,"get",s=>{this.isInitialized();const r=this.formatTarget(s);return this.getExpiration(r)}),Ee(this,"del",s=>{if(this.isInitialized(),this.has(s)){const r=this.formatTarget(s),n=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Ue.deleted,{target:r,expiration:n})}}),Ee(this,"on",(s,r)=>{this.events.on(s,r)}),Ee(this,"once",(s,r)=>{this.events.once(s,r)}),Ee(this,"off",(s,r)=>{this.events.off(s,r)}),Ee(this,"removeListener",(s,r)=>{this.events.removeListener(s,r)}),this.logger=$e(t,this.name)}get context(){return Ce(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return _l(e);if(typeof e=="number")return Pl(e);const{message:t}=A("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(Ue.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=A("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}=A("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(s),new Error(s)}return t}checkExpiry(e,t){const{expiry:s}=t;C.toMiliseconds(s)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(Ue.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on($i.pulse,()=>this.checkExpirations()),this.events.on(Ue.created,e=>{const t=Ue.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ue.expired,e=>{const t=Ue.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(Ue.deleted,e=>{const t=Ue.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}}var cw=Object.defineProperty,hw=(i,e,t)=>e in i?cw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,re=(i,e,t)=>hw(i,typeof e!="symbol"?e+"":e,t);class lw extends Ng{constructor(e,t,s){super(e,t,s),this.core=e,this.logger=t,this.store=s,re(this,"name",hf),re(this,"abortController"),re(this,"isDevEnv"),re(this,"verifyUrlV3",uf),re(this,"storagePrefix",ot),re(this,"version",Ac),re(this,"publicKey"),re(this,"fetchPromise"),re(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&C.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),re(this,"register",async r=>{if(!xi()||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=yi(),l=this.startAbortTimer(C.ONE_SECOND*5),u=await new Promise((p,g)=>{const d=()=>{window.removeEventListener("message",f),h.body.removeChild(m),g("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const m=h.createElement("iframe");m.src=c,m.style.display="none",m.addEventListener("error",d,{signal:this.abortController.signal});const f=w=>{if(w.data&&typeof w.data=="string")try{const y=JSON.parse(w.data);if(y.type==="verify_attestation"){if(_r(y.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(m),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",f),p(y.attestation===null?"":y.attestation)}}catch(y){this.logger.warn(y)}};h.body.appendChild(m),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),re(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=r;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(_r(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(r==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),re(this,"fetchAttestation",async(r,n)=>{this.logger.debug(`resolving attestation: ${r} from url: ${n}`);const o=this.startAbortTimer(C.ONE_SECOND*5),a=await fetch(`${n}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),re(this,"getVerifyUrl",r=>{let n=r||Ki;return pf.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ki}`),n=Ki),n}),re(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(C.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await n.json()}catch(r){this.logger.warn(r)}}),re(this,"persistPublicKey",async r=>{this.logger.debug("persisting public key to local storage",r),await this.store.setItem(this.storeKey,r),this.publicKey=r}),re(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),re(this,"isValidJwtAttestation",async r=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(r,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),re(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),re(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),re(this,"validateAttestation",(r,n)=>{const o=Xp(r,n.publicKey),a={hasExpired:C.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=$e(t,this.name),this.abortController=new AbortController,this.isDevEnv=on(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ce(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),C.toMiliseconds(e))}}var uw=Object.defineProperty,pw=(i,e,t)=>e in i?uw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Yo=(i,e,t)=>pw(i,typeof e!="symbol"?e+"":e,t);class dw extends Rg{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,Yo(this,"context",df),Yo(this,"registerDeviceToken",async s=>{const{clientId:r,token:n,notificationType:o,enableEncrypted:a=!1}=s,c=`${gf}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:n,always_raw:a})})}),this.logger=$e(t,this.context)}}var gw=Object.defineProperty,Zo=Object.getOwnPropertySymbols,fw=Object.prototype.hasOwnProperty,yw=Object.prototype.propertyIsEnumerable,Wr=(i,e,t)=>e in i?gw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Fi=(i,e)=>{for(var t in e||(e={}))fw.call(e,t)&&Wr(i,t,e[t]);if(Zo)for(var t of Zo(e))yw.call(e,t)&&Wr(i,t,e[t]);return i},le=(i,e,t)=>Wr(i,typeof e!="symbol"?e+"":e,t);class mw extends qg{constructor(e,t,s=!0){super(e,t,s),this.core=e,this.logger=t,le(this,"context",yf),le(this,"storagePrefix",ot),le(this,"storageVersion",ff),le(this,"events",new Map),le(this,"shouldPersist",!1),le(this,"init",async()=>{if(!on())try{const r={eventId:Dn(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ma(this.core.relayer.protocol,this.core.relayer.version,Ur)}}};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=Dn(),l=this.core.projectId||"",u=Date.now(),p=Fi({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 Fi(Fi({},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($i.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{C.fromMiliseconds(Date.now())-C.fromMiliseconds(r.timestamp)>mf&&(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,Fi(Fi({},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(`${wf}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ur}${n}`,{method:"POST",body:JSON.stringify(r)})}),le(this,"getAppDomain",()=>Ua().url),this.logger=$e(t,this.context),this.telemetryEnabled=s,s?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var ww=Object.defineProperty,Xo=Object.getOwnPropertySymbols,bw=Object.prototype.hasOwnProperty,vw=Object.prototype.propertyIsEnumerable,Jr=(i,e,t)=>e in i?ww(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ea=(i,e)=>{for(var t in e||(e={}))bw.call(e,t)&&Jr(i,t,e[t]);if(Xo)for(var t of Xo(e))vw.call(e,t)&&Jr(i,t,e[t]);return i},ee=(i,e,t)=>Jr(i,typeof e!="symbol"?e+"":e,t);let Ew=class zc extends Eg{constructor(e){var t;super(e),ee(this,"protocol",xc),ee(this,"version",Ac),ee(this,"name",js),ee(this,"relayUrl"),ee(this,"projectId"),ee(this,"customStoragePrefix"),ee(this,"events",new St.EventEmitter),ee(this,"logger"),ee(this,"heartbeat"),ee(this,"relayer"),ee(this,"crypto"),ee(this,"storage"),ee(this,"history"),ee(this,"expirer"),ee(this,"pairing"),ee(this,"verify"),ee(this,"echoClient"),ee(this,"linkModeSupportedApps"),ee(this,"eventClient"),ee(this,"initialized",!1),ee(this,"logChunkController"),ee(this,"on",(a,c)=>this.events.on(a,c)),ee(this,"once",(a,c)=>this.events.once(a,c)),ee(this,"off",(a,c)=>this.events.off(a,c)),ee(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ee(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:te.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const s=this.getGlobalCore(e==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)||Tc,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Ws({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:Fg.logger,name:js}),{logger:n,chunkLoggerController:o}=wg({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=$e(n,this.name),this.heartbeat=new gh,this.crypto=new Wy(this,this.logger,e==null?void 0:e.keychain),this.history=new rw(this,this.logger),this.expirer=new aw(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new fh(ea(ea({},Ug),e==null?void 0:e.storageOptions)),this.relayer=new Em({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new tw(this,this.logger),this.verify=new lw(this,this.logger,this.storage),this.echoClient=new dw(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new mw(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new zc(e);await t.initialize();const s=await t.crypto.getClientId();return await t.storage.setItem(Xg,s),t}get context(){return Ce(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Ro,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(Ro)||[],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 zi<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const Iw=Ew,Vc="wc",Hc=2,Kc="client",fn=`${Vc}@${Hc}:${Kc}:`,mr={name:Kc,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},ta="WALLETCONNECT_DEEPLINK_CHOICE",_w="proposal",ia="Proposal expired",Pw="session",Yt=C.SEVEN_DAYS,$w="engine",ue={wc_sessionPropose:{req:{ttl:C.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1104},res:{ttl:C.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1106},res:{ttl:C.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:C.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:C.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1112},res:{ttl:C.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:C.ONE_DAY,prompt:!1,tag:1114},res:{ttl:C.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:C.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:C.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:C.FIVE_MINUTES,prompt:!1,tag:1119}}},wr={min:C.FIVE_MINUTES,max:C.SEVEN_DAYS},et={idle:"IDLE",active:"ACTIVE"},sa={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Sw="request",Ow=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],xw="wc",Aw="auth",Cw="authKeys",Tw="pairingTopics",Nw="requests",Qs=`${xw}@${1.5}:${Aw}:`,Os=`${Qs}:PUB_KEY`;var Rw=Object.defineProperty,qw=Object.defineProperties,jw=Object.getOwnPropertyDescriptors,ra=Object.getOwnPropertySymbols,kw=Object.prototype.hasOwnProperty,Dw=Object.prototype.propertyIsEnumerable,Qr=(i,e,t)=>e in i?Rw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Z=(i,e)=>{for(var t in e||(e={}))kw.call(e,t)&&Qr(i,t,e[t]);if(ra)for(var t of ra(e))Dw.call(e,t)&&Qr(i,t,e[t]);return i},_e=(i,e)=>qw(i,jw(e)),v=(i,e,t)=>Qr(i,typeof e!="symbol"?e+"":e,t);class Lw extends Lg{constructor(e){super(e),v(this,"name",$w),v(this,"events",new tn),v(this,"initialized",!1),v(this,"requestQueue",{state:et.idle,queue:[]}),v(this,"sessionRequestQueue",{state:et.idle,queue:[]}),v(this,"requestQueueDelay",C.ONE_SECOND),v(this,"expectedPairingMethodMap",new Map),v(this,"recentlyDeletedMap",new Map),v(this,"recentlyDeletedLimit",200),v(this,"relayMessageCache",[]),v(this,"pendingSessions",new Map),v(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()},C.toMiliseconds(this.requestQueueDelay)))}),v(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=_e(Z({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=fd(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 P=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=P.active}}catch(P){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),P}if(!l||!p){const{topic:P,uri:S}=await this.client.core.pairing.create();l=P,u=S}if(!l){const{message:P}=A("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(P)}const g=await this.client.core.crypto.generateKeyPair(),d=ue.wc_sessionPropose.req.ttl||C.FIVE_MINUTES,m=ce(d),f=_e(Z(Z({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:Cc}],proposer:{publicKey:g,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:wt()}),w=J("session_connect",f.id),{reject:y,resolve:I,done:_}=Tt(d,ia),T=({id:P})=>{P===f.id&&(this.client.events.off("proposal_expire",T),this.pendingSessions.delete(f.id),this.events.emit(w,{error:{message:ia,code:0}}))};return this.client.events.on("proposal_expire",T),this.events.once(w,({error:P,session:S})=>{this.client.events.off("proposal_expire",T),P?y(P):S&&I(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:u,approval:_}}),v(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}}),v(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:[He.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(b){throw o.setError(At.no_internet_connection),b}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(b){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(At.proposal_not_found),b}try{await this.isValidApprove(t)}catch(b){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(At.session_approve_namespace_validation_failure),b}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:p}=t,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:d,proposer:m,requiredNamespaces:f,optionalNamespaces:w}=g;let y=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:d});y||(y=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:He.session_approve_started,properties:{topic:d,trace:[He.session_approve_started,He.session_namespaces_validation_success]}}));const I=await this.client.core.crypto.generateKeyPair(),_=m.publicKey,T=await this.client.core.crypto.generateSharedKey(I,_),P=Z(Z(Z({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:I,metadata:this.client.metadata},expiry:ce(Yt)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),S=te.relay;y.addTrace(He.subscribing_session_topic);try{await this.client.core.relayer.subscribe(T,{transportType:S})}catch(b){throw y.setError(At.subscribe_session_topic_failure),b}y.addTrace(He.subscribe_session_topic_success);const N=_e(Z({},P),{topic:T,requiredNamespaces:f,optionalNamespaces:w,pairingTopic:d,acknowledged:!1,self:P.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:I,transportType:te.relay});await this.client.session.set(T,N),y.addTrace(He.store_session);try{y.addTrace(He.publishing_session_settle),await this.sendRequest({topic:T,method:"wc_sessionSettle",params:P,throwOnFailedPublish:!0}).catch(b=>{throw y==null||y.setError(At.session_settle_publish_failure),b}),y.addTrace(He.session_settle_publish_success),y.addTrace(He.publishing_session_approve),await this.sendResult({id:a,topic:d,result:{relay:{protocol:c??"irn"},responderPublicKey:I},throwOnFailedPublish:!0}).catch(b=>{throw y==null||y.setError(At.session_approve_publish_failure),b}),y.addTrace(He.session_approve_publish_success)}catch(b){throw this.client.logger.error(b),this.client.session.delete(T,Q("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(T),b}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:m.metadata}),await this.client.proposal.delete(a,Q("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(T,ce(Yt)),{topic:T,acknowledged:()=>Promise.resolve(this.client.session.get(T))}}),v(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,Q("USER_DISCONNECTED")))}),v(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}=Tt(),c=wt(),h=ui().toString(),l=this.client.session.get(s).namespaces;return this.events.once(J("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(s,{namespaces:r}),await this.sendRequest({topic:s,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(u=>{this.client.logger.error(u),this.client.session.update(s,{namespaces:l}),a(u)}),{acknowledged:n}}),v(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:s}=t,r=wt(),{done:n,resolve:o,reject:a}=Tt();return this.events.once(J("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(s,ce(Yt)),this.sendRequest({topic:s,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),v(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}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)===te.relay&&await this.confirmOnlineStateOrThrow();const c=wt(),h=ui().toString(),{done:l,resolve:u,reject:p}=Tt(o,"Request expired. Please try again.");this.events.once(J("session_request",c),({error:w,result:y})=>{w?p(w):u(y)});const g="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:{request:_e(Z({},r),{expiryTimestamp:ce(o)}),chainId:s},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(w=>p(w)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),await l();const m={request:_e(Z({},r),{expiryTimestamp:ce(o)}),chainId:s},f=this.shouldSetTVF(g,m);return await Promise.all([new Promise(async w=>{await this.sendRequest(Z({clientRpcId:c,relayRpcId:h,topic:n,method:g,params:m,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,m)})).catch(y=>p(y)),this.client.events.emit("session_request_sent",{topic:n,request:r,chainId:s,id:c}),w()}),new Promise(async w=>{var y;if(!((y=a.sessionConfig)!=null&&y.disableDeepLink)){const I=await xl(this.client.core.storage,ta);await $l({id:c,topic:n,wcDeepLink:I})}w()}),l()]).then(w=>w[2])}),v(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:s,response:r}=t,{id:n}=r,o=this.client.session.get(s);o.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);pt(r)?await this.sendResult({id:n,topic:s,result:r.result,throwOnFailedPublish:!0,appLink:a}):it(r)&&await this.sendError({id:n,topic:s,error:r.error,appLink:a}),this.cleanupAfterResponse(t)}),v(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:s}=t;if(this.client.session.keys.includes(s)){const r=wt(),n=ui().toString(),{done:o,resolve:a,reject:c}=Tt();this.events.once(J("session_ping",r),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:s,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(s)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:s}))}),v(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=wt();await this.sendRequest({topic:s,method:"wc_sessionEvent",params:{event:r,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),v(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:s}=t;if(this.client.session.keys.includes(s))await this.sendRequest({topic:s,method:"wc_sessionDelete",params:Q("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:s,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(s))await this.client.core.pairing.disconnect({topic:s});else{const{message:r}=A("MISMATCHED_TOPIC",`Session or pairing topic not found: ${s}`);throw new Error(r)}}),v(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(s=>wd(s,t)))),v(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),v(this,"authenticate",async(t,s)=>{var r;this.isInitialized(),this.isValidAuthenticate(t);const n=s&&this.client.core.linkModeSupportedApps.includes(s)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=n?te.link_mode:te.relay;o===te.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:p,exp:g,nbf:d,methods:m=[],expiry:f}=t,w=[...t.resources||[]],{topic:y,uri:I}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:y,uri:I}});const _=await this.client.core.crypto.generateKeyPair(),T=$s(_);if(await Promise.all([this.client.auth.authKeys.set(Os,{responseTopic:T,publicKey:_}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:y})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${y}`),m.length>0){const{namespace:$}=fi(a[0]);let L=vu($,"request",m);Ps(w)&&(L=Iu(L,w.pop())),w.push(L)}const P=f&&f>ue.wc_sessionAuthenticate.req.ttl?f:ue.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:p??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:g,nbf:d,resources:w},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ce(P)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},b={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:y,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:ce(ue.wc_sessionPropose.req.ttl),id:wt()},{done:D,resolve:q,reject:k}=Tt(P,"Request expired"),F=wt(),E=J("session_connect",b.id),x=J("session_request",F),O=async({error:$,session:L})=>{this.events.off(x,R),$?k($):L&&q({session:L})},R=async $=>{var L,U,M;if(await this.deletePendingAuthRequest(F,{message:"fulfilled",code:0}),$.error){const ae=Q("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return $.error.code===ae.code?void 0:(this.events.off(E,O),k($.error.message))}await this.deleteProposal(b.id),this.events.off(E,O);const{cacaos:X,responder:W}=$.result,se=[],he=[];for(const ae of X){await Hn({cacao:ae,projectId:this.client.core.projectId})||(this.client.logger.error(ae,"Signature verification failed"),k(Q("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:xt}=ae,at=Ps(xt.resources),Ye=[Ar(xt.iss)],ct=Cs(xt.iss);if(at){const ht=Kn(at),us=Gn(at);se.push(...ht),Ye.push(...us)}for(const ht of Ye)he.push(`${ht}:${ct}`)}const ve=await this.client.core.crypto.generateSharedKey(_,W.publicKey);let oe;se.length>0&&(oe={topic:ve,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:W,controller:W.publicKey,expiry:ce(Yt),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:y,namespaces:bo([...new Set(se)],[...new Set(he)]),transportType:o},await this.client.core.relayer.subscribe(ve,{transportType:o}),await this.client.session.set(ve,oe),y&&await this.client.core.pairing.updateMetadata({topic:y,metadata:W.metadata}),oe=this.client.session.get(ve)),(L=this.client.metadata.redirect)!=null&&L.linkMode&&(U=W.metadata.redirect)!=null&&U.linkMode&&(M=W.metadata.redirect)!=null&&M.universal&&s&&(this.client.core.addLinkModeSupportedApp(W.metadata.redirect.universal),this.client.session.update(ve,{transportType:te.link_mode})),q({auths:X,session:oe})};this.events.once(E,O),this.events.once(x,R);let j;try{if(n){const $=kt("wc_sessionAuthenticate",S,F);this.client.core.history.set(y,$);const L=await this.client.core.crypto.encode("",$,{type:as,encoding:It});j=ys(s,y,L)}else await Promise.all([this.sendRequest({topic:y,method:"wc_sessionAuthenticate",params:S,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:F}),this.sendRequest({topic:y,method:"wc_sessionPropose",params:b,expiry:ue.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:b.id})])}catch($){throw this.events.off(E,O),this.events.off(x,R),$}return await this.setProposal(b.id,b),await this.setAuthRequest(F,{request:_e(Z({},S),{verifyContext:{}}),pairingTopic:y,transportType:o}),{uri:j??I,response:D}}),v(this,"approveSessionAuthenticate",async t=>{const{id:s,auths:r}=t,n=this.client.core.eventClient.createEvent({properties:{topic:s.toString(),trace:[Ct.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(Di.no_internet_connection),f}const o=this.getPendingAuthRequest(s);if(!o)throw n.setError(Di.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${s}`);const a=o.transportType||te.relay;a===te.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=$s(c),u={type:mt,receiverPublicKey:c,senderPublicKey:h},p=[],g=[];for(const f of r){if(!await Hn({cacao:f,projectId:this.client.core.projectId})){n.setError(Di.invalid_cacao);const T=Q("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:s,topic:l,error:T,encodeOpts:u}),new Error(T.message)}n.addTrace(Ct.cacaos_verified);const{p:w}=f,y=Ps(w.resources),I=[Ar(w.iss)],_=Cs(w.iss);if(y){const T=Kn(y),P=Gn(y);p.push(...T),I.push(...P)}for(const T of I)g.push(`${T}:${_}`)}const d=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Ct.create_authenticated_session_topic);let m;if((p==null?void 0:p.length)>0){m={topic:d,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ce(Yt),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:bo([...new Set(p)],[...new Set(g)]),transportType:a},n.addTrace(Ct.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(f){throw n.setError(Di.subscribe_authenticated_session_topic_failure),f}n.addTrace(Ct.subscribe_authenticated_session_topic_success),await this.client.session.set(d,m),n.addTrace(Ct.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Ct.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:s,result:{cacaos:r,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(f){throw n.setError(Di.authenticated_session_approve_publish_failure),f}return await this.client.auth.requests.delete(s,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:m}}),v(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:s,reason:r}=t,n=this.getPendingAuthRequest(s);if(!n)throw new Error(`Could not find pending auth request with id ${s}`);n.transportType===te.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=$s(o),h={type:mt,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,Q("USER_DISCONNECTED"))}),v(this,"formatAuthMessage",t=>{this.isInitialized();const{request:s,iss:r}=t;return Za(s,r)}),v(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)}),v(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)}}),v(this,"deleteSession",async t=>{var s;const{topic:r,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Q("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),n||this.client.core.expirer.del(r),this.client.core.storage.removeItem(ta).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===r&&this.deletePendingSessionRequest(h.id,Q("USER_DISCONNECTED"))}),r===((s=this.sessionRequestQueue.queue[0])==null?void 0:s.topic)&&(this.sessionRequestQueue.state=et.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),v(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(At.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,Q("USER_DISCONNECTED")),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),v(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=et.idle,this.client.events.emit("session_request_expire",{id:t}))}),v(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)])}),v(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}))}),v(this,"setProposal",async(t,s)=>{this.client.core.expirer.set(t,ce(ue.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,s)}),v(this,"setAuthRequest",async(t,s)=>{const{request:r,pairingTopic:n,transportType:o=te.relay}=s;this.client.core.expirer.set(t,r.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:t,pairingTopic:n,verifyContext:r.verifyContext,transportType:o})}),v(this,"setPendingSessionRequest",async t=>{const{id:s,topic:r,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||ce(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})}),v(this,"sendRequest",async t=>{const{topic:s,method:r,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:u}=t,p=kt(r,n,c);let g;const d=!!l;try{const w=d?It:We;g=await this.client.core.crypto.encode(s,p,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${s} failed`),w}let m;if(Ow.includes(r)){const w=st(JSON.stringify(p)),y=st(g);m=await this.client.core.verify.register({id:y,decryptedId:w})}const f=ue[r].req;if(f.attestation=m,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(s,p),d){const w=ys(l,s,g);await B.Linking.openURL(w,this.client.name)}else{const w=ue[r].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=_e(Z({},u),{correlationId:p.id}),h?(w.internal=_e(Z({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,g,w)):this.client.core.relayer.publish(s,g,w).catch(y=>this.client.logger.error(y))}return p.id}),v(this,"sendResult",async t=>{const{id:s,topic:r,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=Fs(s,n);let l;const u=c&&typeof(B==null?void 0:B.Linking)<"u";try{const d=u?It:We;l=await this.client.core.crypto.encode(r,h,_e(Z({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),d}let p,g;try{p=await this.client.core.history.get(r,s);const d=p.request;try{this.shouldSetTVF(d.method,d.params)&&(g=this.getTVFParams(s,d.params,n))}catch(m){this.client.logger.warn("sendResult() -> getTVFParams() failed",m)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${s}) failed`),d}if(u){const d=ys(c,r,l);await B.Linking.openURL(d,this.client.name)}else{const d=p.request.method,m=ue[d].res;m.tvf=_e(Z({},g),{correlationId:s}),o?(m.internal=_e(Z({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,l,m)):this.client.core.relayer.publish(r,l,m).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(h)}),v(this,"sendError",async t=>{const{id:s,topic:r,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=_a(s,n);let l;const u=c&&typeof(B==null?void 0:B.Linking)<"u";try{const g=u?It:We;l=await this.client.core.crypto.encode(r,h,_e(Z({},o||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),g}let p;try{p=await this.client.core.history.get(r,s)}catch(g){throw this.client.logger.error(`sendError() -> history.get(${r}, ${s}) failed`),g}if(u){const g=ys(c,r,l);await B.Linking.openURL(g,this.client.name)}else{const g=p.request.method,d=a||ue[g].res;this.client.core.relayer.publish(r,l,d)}await this.client.core.history.resolve(h)}),v(this,"cleanup",async()=>{const t=[],s=[];this.client.session.getAll().forEach(r=>{let n=!1;Et(r.expiry)&&(n=!0),this.client.core.crypto.keychain.has(r.topic)||(n=!0),n&&t.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{Et(r.expiryTimestamp)&&s.push(r.id)}),await Promise.all([...t.map(r=>this.deleteSession({topic:r})),...s.map(r=>this.deleteProposal(r))])}),v(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),v(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),v(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===et.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=et.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(s){this.client.logger.warn(s)}}this.requestQueue.state=et.idle}),v(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}`)}}),v(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}`)}}),v(this,"onRelayEventUnknownPayload",t=>{const{topic:s}=t,{message:r}=A("MISSING_OR_INVALID",`Decoded payload on topic ${s} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),v(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)}),v(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(dt.proposal_listener_not_found)),this.isValidConnect(Z({},r.params));const l=a.expiryTimestamp||ce(ue.wc_sessionPropose.req.ttl),u=Z({id:c,pairingTopic:s,expiryTimestamp:l},a);await this.setProposal(c,u);const p=await this.getVerifyContext({attestationId:n,hash:st(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});h==null||h.addTrace(tt.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)}}),v(this,"onSessionProposeResponse",async(t,s,r)=>{const{id:n}=s;if(pt(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(it(s)){await this.client.proposal.delete(n,Q("USER_DISCONNECTED"));const o=J("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:s.error})}}),v(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,g=[...this.pendingSessions.values()].find(f=>f.sessionTopic===t);if(!g)return this.client.logger.error(`Pending session not found for topic ${t}`);const d=this.client.proposal.get(g.proposalId),m=_e(Z(Z(Z({topic:t,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:d.requiredNamespaces,optionalNamespaces:d.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),u&&{scopedProperties:u}),p&&{sessionConfig:p}),{transportType:te.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(J("session_connect",g.proposalId),{session:m}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(m),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)}}),v(this,"onSessionSettleResponse",async(t,s)=>{const{id:r}=s;pt(s)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(J("session_approve",r),{})):it(s)&&(await this.client.session.delete(t,Q("USER_DISCONNECTED")),this.events.emit(J("session_approve",r),{error:s.error}))}),v(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:Q("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Z({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)}}),v(this,"isRequestOutOfSync",(t,s)=>s.toString().slice(0,-3)<t.toString().slice(0,-3)),v(this,"onSessionUpdateResponse",(t,s)=>{const{id:r}=s,n=J("session_update",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);pt(s)?this.events.emit(J("session_update",r),{}):it(s)&&this.events.emit(J("session_update",r),{error:s.error})}),v(this,"onSessionExtendRequest",async(t,s)=>{const{id:r}=s;try{this.isValidExtend({topic:t}),await this.setExpiry(t,ce(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)}}),v(this,"onSessionExtendResponse",(t,s)=>{const{id:r}=s,n=J("session_extend",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);pt(s)?this.events.emit(J("session_extend",r),{}):it(s)&&this.events.emit(J("session_extend",r),{error:s.error})}),v(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)}}),v(this,"onSessionPingResponse",(t,s)=>{const{id:r}=s,n=J("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);pt(s)?this.events.emit(J("session_ping",r),{}):it(s)&&this.events.emit(J("session_ping",r),{error:s.error})},500)}),v(this,"onSessionDeleteRequest",async(t,s)=>{const{id:r}=s;try{this.isValidDisconnect({topic:t,reason:s.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(de.publish,async()=>{n(await this.deleteSession({topic:t,id:r}))})}),this.sendResult({id:r,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:Q("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),v(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(Z({topic:o},p));const g=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:st(JSON.stringify(kt("wc_sessionRequest",p,u))),encryptedId:h,metadata:g.peer.metadata,transportType:l}),m={id:u,topic:o,params:p,verifyContext:d};await this.setPendingSessionRequest(m),l===te.link_mode&&(s=g.peer.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp((r=g.peer.metadata.redirect)==null?void 0:r.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(g){await this.sendError({id:u,topic:o,error:g}),this.client.logger.error(g)}}),v(this,"onSessionRequestResponse",(t,s)=>{const{id:r}=s,n=J("session_request",r);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);pt(s)?this.events.emit(J("session_request",r),{result:s.result}):it(s)&&this.events.emit(J("session_request",r),{error:s.error})}),v(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(Z({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)}}),v(this,"onSessionAuthenticateResponse",(t,s)=>{const{id:r}=s;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:s}),pt(s)?this.events.emit(J("session_request",r),{result:s.result}):it(s)&&this.events.emit(J("session_request",r),{error:s.error})}),v(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:st(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),g={requester:h,pairingTopic:r,id:n.id,authPayload:l,verifyContext:p,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:g,pairingTopic:r,transportType:c}),c===te.link_mode&&(s=h.metadata.redirect)!=null&&s.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:n.params,id:n.id,verifyContext:p})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),p=this.getAppLinkIfEnabled(n.params.requester.metadata,c),g={type:mt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:r,error:h,encodeOpts:g,rpcOpts:ue.wc_sessionAuthenticate.autoReject,appLink:p})}}),v(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),v(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=et.idle,this.processSessionRequestQueue()},C.toMiliseconds(this.requestQueueDelay))}),v(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:s})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=J("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(J("session_request",n.request.id),{error:s})})}),v(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===et.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=et.active,this.emitSessionRequest(t)}catch(s){this.client.logger.error(s)}}),v(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),v(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const s=this.client.proposal.getAll().find(r=>r.pairingTopic===t.topic);s&&this.onSessionProposeRequest({topic:t.topic,payload:kt("wc_sessionPropose",_e(Z({},s),{requiredNamespaces:s.requiredNamespaces,optionalNamespaces:s.optionalNamespaces,relays:s.relays,proposer:s.proposer,sessionProperties:s.sessionProperties,scopedProperties:s.scopedProperties}),s.id)})}),v(this,"isValidConnect",async t=>{if(!Oe(t)){const{message:h}=A("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:s,requiredNamespaces:r,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(we(s)||await this.isValidPairingTopic(s),!Cd(c,!0)){const{message:h}=A("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!we(r)&&$t(r)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(r,"requiredNamespaces")}if(!we(n)&&$t(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(r||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>h.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}}),v(this,"validateNamespaces",(t,s)=>{const r=Ad(t,"connect()",s);if(r)throw new Error(r.message)}),v(this,"isValidApprove",async t=>{if(!Oe(t))throw new Error(A("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=Io(c.requiredNamespaces,r,"approve()");if(l)throw new Error(l.message);if(!ne(n,!0)){const{message:u}=A("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(we(o)||this.validateSessionProps(o,"sessionProperties"),!we(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(p=>u.has(p)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),v(this,"isValidReject",async t=>{if(!Oe(t)){const{message:n}=A("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:s,reason:r}=t;if(this.checkRecentlyDeleted(s),await this.isValidProposalId(s),!Nd(r)){const{message:n}=A("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(n)}}),v(this,"isValidSessionSettleRequest",t=>{if(!Oe(t)){const{message:h}=A("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:s,controller:r,namespaces:n,expiry:o}=t;if(!Pc(s)){const{message:h}=A("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=_d(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=lr(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Et(o)){const{message:h}=A("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),v(this,"isValidUpdate",async t=>{if(!Oe(t)){const{message:c}=A("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=Io(n.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),v(this,"isValidExtend",async t=>{if(!Oe(t)){const{message:r}=A("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(r)}const{topic:s}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s)}),v(this,"isValidRequest",async t=>{if(!Oe(t)){const{message:c}=A("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:s,request:r,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(s),await this.isValidSessionTopic(s);const{namespaces:a}=this.client.session.get(s);if(!Eo(a,n)){const{message:c}=A("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!Rd(r)){const{message:c}=A("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!kd(a,n,r.method)){const{message:c}=A("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!Ud(o,wr)){const{message:c}=A("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${wr.min} and ${wr.max}`);throw new Error(c)}}),v(this,"isValidRespond",async t=>{var s;if(!Oe(t)){const{message:o}=A("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(!qd(n)){const{message:o}=A("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),v(this,"isValidPing",async t=>{if(!Oe(t)){const{message:r}=A("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),v(this,"isValidEmit",async t=>{if(!Oe(t)){const{message:a}=A("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:s,event:r,chainId:n}=t;await this.isValidSessionTopic(s);const{namespaces:o}=this.client.session.get(s);if(!Eo(o,n)){const{message:a}=A("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!jd(r)){const{message:a}=A("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!Dd(o,n,r.name)){const{message:a}=A("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),v(this,"isValidDisconnect",async t=>{if(!Oe(t)){const{message:r}=A("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(r)}const{topic:s}=t;await this.isValidSessionOrPairingTopic(s)}),v(this,"isValidAuthenticate",t=>{const{chains:s,uri:r,domain:n,nonce:o}=t;if(!Array.isArray(s)||s.length===0)throw new Error("chains is required and must be a non-empty array");if(!ne(r,!1))throw new Error("uri is required parameter");if(!ne(n,!1))throw new Error("domain is required parameter");if(!ne(o,!1))throw new Error("nonce is required parameter");if([...new Set(s.map(c=>fi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=fi(s[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),v(this,"getVerifyContext",async t=>{const{attestationId:s,hash:r,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||Ki,validation:"UNKNOWN",origin:o.url||""}};try{if(a===te.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:s,hash:r,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),v(this,"validateSessionProps",(t,s)=>{Object.values(t).forEach((r,n)=>{if(r==null){const{message:o}=A("MISSING_OR_INVALID",`${s} must contain an existing value for each key. Received: ${r} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),v(this,"getPendingAuthRequest",t=>{const s=this.client.auth.requests.get(t);return typeof s=="object"?s:void 0}),v(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)}}}),v(this,"checkRecentlyDeleted",t=>{const s=this.recentlyDeletedMap.get(t);if(s){const{message:r}=A("MISSING_OR_INVALID",`Record was recently deleted - ${s}: ${t}`);throw new Error(r)}}),v(this,"isLinkModeEnabled",(t,s)=>{var r,n,o,a,c,h,l,u,p;return!t||s!==te.link_mode?!1:((n=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((l=t==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"}),v(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}),v(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const s=kn(t,"topic")||"",r=decodeURIComponent(kn(t,"wc_ev")||""),n=this.client.session.keys.includes(s);n&&this.client.session.update(s,{transportType:te.link_mode}),this.client.core.dispatchEnvelope({topic:s,message:r,sessionExists:n})}),v(this,"registerLinkModeListeners",async()=>{var t;if(on()||Ot()&&(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)}}}),v(this,"shouldSetTVF",(t,s)=>{if(!s||t!=="wc_sessionRequest")return!1;const{request:r}=s;return Object.keys(sa).includes(r.method)}),v(this,"getTVFParams",(t,s,r)=>{var n,o;try{const a=s.request.method,c=this.extractTxHashesFromResult(a,r);return _e(Z({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{}}),v(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}),v(this,"extractTxHashesFromResult",(t,s)=>{try{const r=sa[t];if(typeof s=="string")return[s];const n=s[r.key];if(Je(n))return t==="solana_signAllTransactions"?n.map(o=>ou(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}=A("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(de.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:s,attestation:r,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Os)?this.client.auth.authKeys.get(Os):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,s,{receiverPublicKey:o,encoding:n===te.link_mode?It:We});sn(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:r,transportType:n,encryptedId:st(s)})):rn(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,s)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Ue.expired,async e=>{const{topic:t,id:s}=za(e.target);if(s&&this.client.pendingRequest.keys.includes(s))return await this.deletePendingSessionRequest(s,A("EXPIRED"),!0);if(s&&this.client.auth.requests.keys.includes(s))return await this.deletePendingAuthRequest(s,A("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(qt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(qt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ne(e,!1)){const{message:t}=A("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}=A("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=A("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!ne(e,!1)){const{message:t}=A("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}=A("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=A("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=A("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ne(e,!1)){const{message:t}=A("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=A("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!Td(e)){const{message:t}=A("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=A("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Et(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=A("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class Fw extends zt{constructor(e,t){super(e,t,_w,fn),this.core=e,this.logger=t}}let Uw=class extends zt{constructor(e,t){super(e,t,Pw,fn),this.core=e,this.logger=t}};class Mw extends zt{constructor(e,t){super(e,t,Sw,fn,s=>s.id),this.core=e,this.logger=t}}class Bw extends zt{constructor(e,t){super(e,t,Cw,Qs,()=>Os),this.core=e,this.logger=t}}class zw extends zt{constructor(e,t){super(e,t,Tw,Qs),this.core=e,this.logger=t}}class Vw extends zt{constructor(e,t){super(e,t,Nw,Qs,s=>s.id),this.core=e,this.logger=t}}var Hw=Object.defineProperty,Kw=(i,e,t)=>e in i?Hw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,br=(i,e,t)=>Kw(i,typeof e!="symbol"?e+"":e,t);class Gw{constructor(e,t){this.core=e,this.logger=t,br(this,"authKeys"),br(this,"pairingTopics"),br(this,"requests"),this.authKeys=new Bw(this.core,this.logger),this.pairingTopics=new zw(this.core,this.logger),this.requests=new Vw(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var Ww=Object.defineProperty,Jw=(i,e,t)=>e in i?Ww(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,V=(i,e,t)=>Jw(i,typeof e!="symbol"?e+"":e,t);let Qw=class Gc extends Dg{constructor(e){super(e),V(this,"protocol",Vc),V(this,"version",Hc),V(this,"name",mr.name),V(this,"metadata"),V(this,"core"),V(this,"logger"),V(this,"events",new St.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)||mr.name,this.metadata=bl(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:cs(Ws({level:(e==null?void 0:e.logger)||mr.logger}));this.core=(e==null?void 0:e.core)||new Iw(e),this.logger=$e(t,this.name),this.session=new Uw(this.core,this.logger),this.proposal=new Fw(this.core,this.logger),this.pendingRequest=new Mw(this.core,this.logger),this.engine=new Lw(this),this.auth=new Gw(this.core,this.logger)}static async init(e){const t=new Gc(e);return await t.initialize(),t}get context(){return Ce(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},C.toMiliseconds(C.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const na="error",Yw="wss://relay.walletconnect.org",Zw="wc",Xw="universal_provider",bs=`${Zw}@2:${Xw}:`,Wc="https://rpc.walletconnect.org/v1/",li="generic",eb=`${Wc}bundler`,ze={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function tb(){}function yn(i){return i==null||typeof i!="object"&&typeof i!="function"}function mn(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function ib(i){if(yn(i))return i;if(Array.isArray(i)||mn(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 oa(i){return typeof i=="object"&&i!==null}function Jc(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function Qc(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const sb="[object RegExp]",Yc="[object String]",Zc="[object Number]",Xc="[object Boolean]",eh="[object Arguments]",rb="[object Symbol]",nb="[object Date]",ob="[object Map]",ab="[object Set]",cb="[object Array]",hb="[object ArrayBuffer]",lb="[object Object]",ub="[object DataView]",pb="[object Uint8Array]",db="[object Uint8ClampedArray]",gb="[object Uint16Array]",fb="[object Uint32Array]",yb="[object Int8Array]",mb="[object Int16Array]",wb="[object Int32Array]",bb="[object Float32Array]",vb="[object Float64Array]";function Eb(i,e){return gi(i,void 0,i,new Map,e)}function gi(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]=gi(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,gi(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(gi(a,void 0,t,s,r));return o}if(typeof Ie<"u"&&Ie.isBuffer(i))return i.subarray();if(mn(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);s.set(i,o);for(let a=0;a<i.length;a++)o[a]=gi(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),jt(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),jt(o,i,t,s,r),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return s.set(i,o),jt(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,jt(o,i,t,s,r),o}if(typeof i=="object"&&Ib(i)){const o=Object.create(Object.getPrototypeOf(i));return s.set(i,o),jt(o,i,t,s,r),o}return i}function jt(i,e,t=i,s,r){const n=[...Object.keys(e),...Jc(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=gi(e[a],a,t,s,r))}}function Ib(i){switch(Qc(i)){case eh:case cb:case hb:case ub:case Xc:case nb:case bb:case vb:case yb:case mb:case wb:case ob:case Zc:case lb:case sb:case ab:case Yc:case rb:case pb:case db:case gb:case fb:return!0;default:return!1}}function _b(i,e){return Eb(i,(t,s,r,n)=>{const o=e==null?void 0:e(t,s,r,n);if(o!=null)return o;if(typeof i=="object")switch(Object.prototype.toString.call(i)){case Zc:case Yc:case Xc:{const a=new i.constructor(i==null?void 0:i.valueOf());return jt(a,i),a}case eh:{const a={};return jt(a,i),a.length=i.length,a[Symbol.iterator]=i[Symbol.iterator],a}default:return}})}function aa(i){return _b(i)}function ca(i){return i!==null&&typeof i=="object"&&Qc(i)==="[object Arguments]"}function Pb(i){return mn(i)}function $b(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 Sb(i,...e){const t=e.slice(0,-1),s=e[e.length-1];let r=i;for(let n=0;n<t.length;n++){const o=t[n];r=Yr(r,o,s,new Map)}return r}function Yr(i,e,t,s){if(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),...Jc(e)];for(let n=0;n<r.length;n++){const o=r[n];let a=e[o],c=i[o];if(ca(a)&&(a={...a}),ca(c)&&(c={...c}),typeof Ie<"u"&&Ie.isBuffer(a)&&(a=aa(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 g=u[p];l[g]=c[g]}c=l}else c=[];const h=t(c,a,o,i,e,s);h!=null?i[o]=h:Array.isArray(a)||oa(c)&&oa(a)?i[o]=Yr(c,a,t,s):c==null&&$b(a)?i[o]=Yr({},a,t,s):c==null&&Pb(a)?i[o]=aa(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function Ob(i,...e){return Sb(i,...e,tb)}var xb=Object.defineProperty,Ab=Object.defineProperties,Cb=Object.getOwnPropertyDescriptors,ha=Object.getOwnPropertySymbols,Tb=Object.prototype.hasOwnProperty,Nb=Object.prototype.propertyIsEnumerable,la=(i,e,t)=>e in i?xb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,vs=(i,e)=>{for(var t in e||(e={}))Tb.call(e,t)&&la(i,t,e[t]);if(ha)for(var t of ha(e))Nb.call(e,t)&&la(i,t,e[t]);return i},Rb=(i,e)=>Ab(i,Cb(e));function De(i,e,t){var s;const r=fi(i);return((s=e.rpcMap)==null?void 0:s[r.reference])||`${Wc}?chainId=${r.namespace}:${r.reference}&projectId=${t}`}function Vt(i){return i.includes(":")?i.split(":")[1]:i}function th(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function qb(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 Es(i={},e={}){const t=ua(i),s=ua(e);return Ob(t,s)}function ua(i){var e,t,s,r,n;const o={};if(!$t(i))return o;for(const[a,c]of Object.entries(i)){const h=Ks(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],p=c.rpcMap||{},g=di(a);o[g]=Rb(vs(vs({},o[g]),c),{chains:rt(h,(e=o[g])==null?void 0:e.chains),methods:rt(l,(t=o[g])==null?void 0:t.methods),events:rt(u,(s=o[g])==null?void 0:s.events)}),($t(p)||$t(((r=o[g])==null?void 0:r.rpcMap)||{}))&&(o[g].rpcMap=vs(vs({},p),(n=o[g])==null?void 0:n.rpcMap))}return o}function pa(i){return i.includes(":")?i.split(":")[2]:i}function da(i){const e={};for(const[t,s]of Object.entries(i)){const r=s.methods||[],n=s.events||[],o=s.accounts||[],a=Ks(t)?[t]:s.chains?s.chains:th(s.accounts);e[t]={chains:a,methods:r,events:n,accounts:o}}return e}function vr(i){return typeof i=="number"?i:i.includes("0x")?parseInt(i,16):(i=i.includes(":")?i.split(":")[1]:i,isNaN(Number(i))?i:Number(i))}const ih={},G=i=>ih[i],Er=(i,e)=>{ih[i]=e};var jb=Object.defineProperty,kb=(i,e,t)=>e in i?jb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Zt=(i,e,t)=>kb(i,typeof e!="symbol"?e+"":e,t);class Db{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var Lb=Object.defineProperty,Fb=Object.defineProperties,Ub=Object.getOwnPropertyDescriptors,ga=Object.getOwnPropertySymbols,Mb=Object.prototype.hasOwnProperty,Bb=Object.prototype.propertyIsEnumerable,Zr=(i,e,t)=>e in i?Lb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,fa=(i,e)=>{for(var t in e||(e={}))Mb.call(e,t)&&Zr(i,t,e[t]);if(ga)for(var t of ga(e))Bb.call(e,t)&&Zr(i,t,e[t]);return i},ya=(i,e)=>Fb(i,Ub(e)),Xt=(i,e,t)=>Zr(i,typeof e!="symbol"?e+"":e,t);class zb{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=G("events"),this.client=G("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(ze.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||De(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=parseInt(Vt(t));e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,s;let r=e.request.params?(t=e.request.params[0])==null?void 0:t.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const n=parseInt(r,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(s=this.namespace.chains)==null?void 0:s[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,s,r,n,o;const a=(s=(t=e.request)==null?void 0:t.params)==null?void 0:s[0],c=((n=(r=e.request)==null?void 0:r.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l==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:ya(fa({},l.sessionProperties||{}),{capabilities:ya(fa({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var t,s;const r=this.client.session.get(e.topic),n=(t=r.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(s=r.sessionProperties)==null?void 0:s.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var s;const r=new URL(e),n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(kt("eth_getUserOperationReceipt",[(s=t.request.params)==null?void 0:s[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,t){return`${eb}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var Vb=Object.defineProperty,Hb=(i,e,t)=>e in i?Vb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ei=(i,e,t)=>Hb(i,typeof e!="symbol"?e+"":e,t);class Kb{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var Gb=Object.defineProperty,Wb=(i,e,t)=>e in i?Gb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ti=(i,e,t)=>Wb(i,typeof e!="symbol"?e+"":e,t);class Jb{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var Qb=Object.defineProperty,Yb=(i,e,t)=>e in i?Qb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ii=(i,e,t)=>Yb(i,typeof e!="symbol"?e+"":e,t);class Zb{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const s=t||De(`${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(ze.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||De(e,this.namespace,this.client.core.projectId);return typeof s>"u"?void 0:new Be(new Qe(s,G("disableProviderPing")))}}var Xb=Object.defineProperty,ev=(i,e,t)=>e in i?Xb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,si=(i,e,t)=>ev(i,typeof e!="symbol"?e+"":e,t);class tv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const s=this.getCardanoRPCUrl(t),r=Vt(t);e[r]=this.createHttpProvider(r,s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||this.getCardanoRPCUrl(e);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var iv=Object.defineProperty,sv=(i,e,t)=>e in i?iv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ri=(i,e,t)=>sv(i,typeof e!="symbol"?e+"":e,t);class rv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var nv=Object.defineProperty,ov=(i,e,t)=>e in i?nv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ni=(i,e,t)=>ov(i,typeof e!="symbol"?e+"":e,t);class av{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var s;const r=Vt(t);e[r]=this.createHttpProvider(r,(s=this.namespace.rpcMap)==null?void 0:s[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const s=this.createHttpProvider(e,t);s&&(this.httpProviders[e]=s)}createHttpProvider(e,t){const s=t||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var cv=Object.defineProperty,hv=(i,e,t)=>e in i?cv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oi=(i,e,t)=>hv(i,typeof e!="symbol"?e+"":e,t);class lv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||De(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(ze.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||De(e,this.namespace);return typeof s>"u"?void 0:new Be(new Qe(s,G("disableProviderPing")))}}var uv=Object.defineProperty,pv=(i,e,t)=>e in i?uv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ai=(i,e,t)=>pv(i,typeof e!="symbol"?e+"":e,t);class dv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const s=t||De(`${this.name}:${e}`,this.namespace);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,s)}this.events.emit(ze.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||De(e,this.namespace);return typeof s>"u"?void 0:new Be(new Qe(s))}}var gv=Object.defineProperty,fv=(i,e,t)=>e in i?gv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ci=(i,e,t)=>fv(i,typeof e!="symbol"?e+"":e,t);class yv{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=G("events"),this.client=G("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(ze.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=fi(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||De(e,this.namespace,this.client.core.projectId);if(!s)throw new Error(`No RPC url provided for chainId: ${e}`);return new Be(new Qe(s,G("disableProviderPing")))}}var mv=Object.defineProperty,wv=Object.defineProperties,bv=Object.getOwnPropertyDescriptors,ma=Object.getOwnPropertySymbols,vv=Object.prototype.hasOwnProperty,Ev=Object.prototype.propertyIsEnumerable,Xr=(i,e,t)=>e in i?mv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Is=(i,e)=>{for(var t in e||(e={}))vv.call(e,t)&&Xr(i,t,e[t]);if(ma)for(var t of ma(e))Ev.call(e,t)&&Xr(i,t,e[t]);return i},Ir=(i,e)=>wv(i,bv(e)),Fe=(i,e,t)=>Xr(i,typeof e!="symbol"?e+"":e,t);let Iv=class sh{constructor(e){Fe(this,"client"),Fe(this,"namespaces"),Fe(this,"optionalNamespaces"),Fe(this,"sessionProperties"),Fe(this,"scopedProperties"),Fe(this,"events",new tn),Fe(this,"rpcProviders",{}),Fe(this,"session"),Fe(this,"providerOpts"),Fe(this,"logger"),Fe(this,"uri"),Fe(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:cs(Ws({level:(e==null?void 0:e.logger)||na})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new sh(e);return await t.initialize(),t}async request(e,t,s){const[r,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Is({},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,Fs(n,o))).catch(o=>t(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Q("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:s,response:r}=await this.client.authenticate(e,t);s&&(this.uri=s,this.events.emit("display_uri",s));const n=await r();if(this.session=n.session,this.session){const o=da(this.session.namespaces);this.namespaces=Es(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=da(r.namespaces);return this.namespaces=Es(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(Je(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 Qw.init({core:this.providerOpts.core,logger:this.providerOpts.logger||na,relayUrl:this.providerOpts.relayUrl||Yw,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)))];Er("client",this.client),Er("events",this.events),Er("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const s=qb(t,this.session),r=th(s),n=Es(this.namespaces,this.optionalNamespaces),o=Ir(Is({},n[t]),{accounts:s,chains:r});switch(t){case"eip155":this.rpcProviders[t]=new zb({namespace:o});break;case"algorand":this.rpcProviders[t]=new Zb({namespace:o});break;case"solana":this.rpcProviders[t]=new Kb({namespace:o});break;case"cosmos":this.rpcProviders[t]=new Jb({namespace:o});break;case"polkadot":this.rpcProviders[t]=new Db({namespace:o});break;case"cip34":this.rpcProviders[t]=new tv({namespace:o});break;case"elrond":this.rpcProviders[t]=new rv({namespace:o});break;case"multiversx":this.rpcProviders[t]=new av({namespace:o});break;case"near":this.rpcProviders[t]=new lv({namespace:o});break;case"tezos":this.rpcProviders[t]=new dv({namespace:o});break;default:this.rpcProviders[li]?this.rpcProviders[li].updateNamespace(o):this.rpcProviders[li]=new yv({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&&Je(o)&&this.events.emit("accountsChanged",o.map(pa))}else if(n.name==="chainChanged"){const o=s.chainId,a=s.event.data,c=di(o),h=vr(o)!==vr(a)?`${c}:${vr(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var s,r;if(e!==((s=this.session)==null?void 0:s.topic))return;const{namespaces:n}=t,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Ir(Is({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ir(Is({},Q("USER_DISCONNECTED")),{data:e.topic})))}),this.on(ze.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=Es(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(pa);if(!Je(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(`${bs}/${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(`${bs}/${e}${s}`)}async deleteFromStore(e){var t;const s=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${bs}/${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(bs)&&await this.client.core.storage.removeItem(s)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const _v=Iv,Pv="wc",$v="ethereum_provider",Sv=`${Pv}@2:${$v}:`,Ov="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],rh=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Ds=["chainChanged","accountsChanged"],nh=["chainChanged","accountsChanged","message","disconnect","connect"],xv=async()=>{const{createAppKit:i}=await Ea(()=>import("./core-1a166f08.js").then(e=>e.u),["assets/core-1a166f08.js","assets/index-10c73e9d.js","assets/index-59db4a58.css","assets/index-b3889ac8.js","assets/index-accd8060.js","assets/index-2cab452e.js","assets/index.es-4520fb10.js","assets/http-a4cf4808.js","assets/createBatchScheduler-7c9ada66.js","assets/W3MFrameProviderSingleton-316899f0.js","assets/NetworkUtil-cfdab321.js","assets/lit-element-0711c853.js"]);return i};var Av=Object.defineProperty,Cv=Object.defineProperties,Tv=Object.getOwnPropertyDescriptors,wa=Object.getOwnPropertySymbols,Nv=Object.prototype.hasOwnProperty,Rv=Object.prototype.propertyIsEnumerable,en=(i,e,t)=>e in i?Av(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Nt=(i,e)=>{for(var t in e||(e={}))Nv.call(e,t)&&en(i,t,e[t]);if(wa)for(var t of wa(e))Rv.call(e,t)&&en(i,t,e[t]);return i},Ui=(i,e)=>Cv(i,Tv(e)),Ne=(i,e,t)=>en(i,typeof e!="symbol"?e+"":e,t);function Ls(i){return Number(i[0].split(":")[1])}function _s(i){return`0x${i.toString(16)}`}function qv(i){const{chains:e,optionalChains:t,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=i;if(!Je(e))throw new Error("Invalid chains");const c={chains:e,methods:s||ks,events:n||Ds,rpcMap:Nt({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},h=n==null?void 0:n.filter(g=>!Ds.includes(g)),l=s==null?void 0:s.filter(g=>!ks.includes(g));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:rh))],events:[...new Set(c.events.concat(o!=null&&o.length?o:nh))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?p:void 0}}class Ys{constructor(){Ne(this,"events",new St.EventEmitter),Ne(this,"namespace","eip155"),Ne(this,"accounts",[]),Ne(this,"signer"),Ne(this,"chainId",1),Ne(this,"modal"),Ne(this,"rpc"),Ne(this,"STORAGE_KEY",Sv),Ne(this,"on",(e,t)=>(this.events.on(e,t),this)),Ne(this,"once",(e,t)=>(this.events.once(e,t),this)),Ne(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),Ne(this,"off",(e,t)=>(this.events.off(e,t),this)),Ne(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}=qv(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(Ui(Nt({namespaces:Nt({},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 g;(g=this.modal)==null||g.showErrorMessage("Unable to connect"),c(new Error(p.message))})});if(!n)return;const o=Tn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_s(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(Ui(Nt({},e),{chains:this.rpc.chains}),t).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=r.session;if(n){const o=Tn(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:_s(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",_s(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",Ui(Nt({},Q("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",_s(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)||ks:[],c=r.length?(e==null?void 0:e.events)||Ds:[],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(g=>this.formatChainId(g)),optionalChains:n.map(g=>this.formatChainId(g)),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?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await _v.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 xv(),{convertWCMToAppKitOptions:r}=await Promise.resolve().then(function(){return Hv}),n=r(Ui(Nt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=s(Ui(Nt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:s,rpcMap:r}=e;t&&Je(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&&Je(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])||`${Ov}?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 jv=Ys;var kv=Object.defineProperty,Dv=Object.defineProperties,Lv=Object.getOwnPropertyDescriptors,ba=Object.getOwnPropertySymbols,Fv=Object.prototype.hasOwnProperty,Uv=Object.prototype.propertyIsEnumerable,va=(i,e,t)=>e in i?kv(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,oh=(i,e)=>{for(var t in e||(e={}))Fv.call(e,t)&&va(i,t,e[t]);if(ba)for(var t of ba(e))Uv.call(e,t)&&va(i,t,e[t]);return i},Mv=(i,e)=>Dv(i,Lv(e));function Bv(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 zv=i=>{const[e,t]=i.split(":");return ah({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function Vv(i){var e,t,s,r,n,o,a;const c=(e=i.chains)==null?void 0:e.map(zv).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:Bv(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:Mv(oh({},i.metadata),{name:((t=i.metadata)==null?void 0:t.name)||"WalletConnect",description:((s=i.metadata)==null?void 0:s.description)||"Connect to WalletConnect-compatible wallets",url:((r=i.metadata)==null?void 0:r.url)||"https://walletconnect.org",icons:((n=i.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:i.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(i.explorerRecommendedWalletIds)?i.explorerRecommendedWalletIds:[],excludeWalletIds:i.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(i.explorerExcludedWalletIds)?i.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=i.mobileWallets)!=null&&o.length||(a=i.desktopWallets)!=null&&a.length){const u=[...(i.mobileWallets||[]).map(d=>({id:d.id,name:d.name,links:d.links})),...(i.desktopWallets||[]).map(d=>({id:d.id,name:d.name,links:{native:d.links.native,universal:d.links.universal}}))],p=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],g=u.filter(d=>!p.includes(d.id));g.length&&(l.customWallets=g)}return l}function ah(i){return oh({formatters:void 0,fees:void 0,serializers:void 0},i)}var Hv=Object.freeze({__proto__:null,convertWCMToAppKitOptions:Vv,defineChain:ah});const _1=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:jv,OPTIONAL_EVENTS:nh,OPTIONAL_METHODS:rh,REQUIRED_EVENTS:Ds,REQUIRED_METHODS:ks,default:Ys},Symbol.toStringTag,{value:"Module"}));export{wg as A,$e as E,Vh as H,cs as O,_n as a,qh as b,Zv as c,Yv as d,Us as e,e1 as f,t1 as g,Me as h,Ae as i,Vi as j,tl as k,Ws as l,_1 as m,Xv as r,Ta as t,Hh as w,Ce as y};
|