@dcl/vesting-dashboard 3.7.1-19868070294.commit-e76f047 → 3.8.1-26049798881.commit-a8da177
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/{basic-eeeaaaeb.js → basic-8c6fc222.js} +1 -1
- package/assets/{core-84b3ed1e.js → core-80de04d5.js} +3 -3
- package/assets/{features-21cad012.js → features-ad8879a6.js} +1 -1
- package/assets/{fortmatic-f30106eb.js → fortmatic-41ec166f.js} +1 -1
- package/assets/{index-ec27bc27.js → index-1215067e.js} +1 -1
- package/assets/{index-fec77d48.js → index-3c0257eb.js} +9 -9
- package/assets/{index-91d98a83.css → index-40d93065.css} +7 -7
- package/assets/{index-388893ce.js → index-497ecef2.js} +1 -1
- package/assets/{index-069f2f19.js → index-72fb9c8c.js} +2 -2
- package/assets/{index-516a1ffc.js → index-888e6cca.js} +2 -2
- package/assets/{index-cf405d3f.js → index-e25da697.js} +1 -1
- package/assets/{index-04415554.js → index-ee8fa6c1.js} +1 -1
- package/assets/{index-be0620a9.js → index-f8dafd87.js} +1 -1
- package/assets/{native-bf1092f7.js → native-21ffd7d5.js} +1 -1
- package/assets/{w3m-modal-4a2f6c0b.js → w3m-modal-67a6186f.js} +1 -1
- package/index.html +4 -4
- package/package.json +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as xt,g as $0,a as D0,b as Y,B as ie,e as St,c as pr,x as lc,o as ll,_ as O0}from"./index-
|
|
1
|
+
import{p as xt,g as $0,a as D0,b as Y,B as ie,e as St,c as pr,x as lc,o as ll,_ as O0}from"./index-3c0257eb.js";var ul=globalThis&&globalThis.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))},A0=function(){function t(e,i,r){this.name=e,this.version=i,this.os=r,this.type="browser"}return t}(),P0=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=xt.platform}return t}(),C0=function(){function t(e,i,r,n){this.name=e,this.version=i,this.os=r,this.bot=n,this.type="bot-device"}return t}(),B0=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),T0=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),R0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,F0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,hl=3,N0=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",R0]],fl=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function U0(t){return t?dl(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new T0:typeof navigator<"u"?dl(navigator.userAgent):L0()}function k0(t){return t!==""&&N0.reduce(function(e,i){var r=i[0],n=i[1];if(e)return e;var s=n.exec(t);return!!s&&[r,s]},!1)}function dl(t){var e=k0(t);if(!e)return null;var i=e[0],r=e[1];if(i==="searchbot")return new B0;var n=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);n?n.length<hl&&(n=ul(ul([],n,!0),M0(hl-n.length),!0)):n=[];var s=n.join("."),o=j0(t),a=F0.exec(t);return a&&a[1]?new C0(i,s,o,a[1]):new A0(i,s,o)}function j0(t){for(var e=0,i=fl.length;e<i;e++){var r=fl[e],n=r[0],s=r[1],o=s.exec(t);if(o)return n}return null}function L0(){var t=typeof xt<"u"&&xt.version;return t?new P0(xt.version.slice(1)):null}function M0(t){for(var e=[],i=0;i<t;i++)e.push("0");return e}var L={};/*! *****************************************************************************
|
|
2
2
|
Copyright (c) Microsoft Corporation.
|
|
3
3
|
|
|
4
4
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -23,4 +23,4 @@ ${t.length}`,i=new TextEncoder().encode(e+t);return"0x"+ie.from(rx(i)).toString(
|
|
|
23
23
|
Required: ${o.toString()}
|
|
24
24
|
Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||r)return;const f=qr(e[h].accounts);f.includes(h)||(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${h}
|
|
25
25
|
Required: ${h}
|
|
26
|
-
Approved: ${f.toString()}`))}),o.forEach(h=>{r||(Xi(n[h].methods,s[h].methods)?Xi(n[h].events,s[h].events)||(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${h}`)):r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${h}`))}),r}function d8(t){const e={};return Object.keys(t).forEach(i=>{var r;i.includes(":")?e[i]=t[i]:(r=t[i].chains)==null||r.forEach(n=>{e[n]={methods:t[i].methods,events:t[i].events}})}),e}function ph(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function p8(t){const e={};return Object.keys(t).forEach(i=>{if(i.includes(":"))e[i]=t[i];else{const r=qr(t[i].accounts);r==null||r.forEach(n=>{e[n]={accounts:t[i].accounts.filter(s=>s.includes(`${n}:`)),methods:t[i].methods,events:t[i].events}})}}),e}function g8(t,e){return Hc(t,!1)&&t<=e.max&&t>=e.min}function gh(){const t=Bn();return new Promise(e=>{switch(t){case ft.browser:e(y8());break;case ft.reactNative:e(w8());break;case ft.node:e(m8());break;default:e(!0)}})}function y8(){return Mr()&&(navigator==null?void 0:navigator.onLine)}async function w8(){if(ki()&&typeof Y<"u"&&Y!=null&&Y.NetInfo){const t=await(Y==null?void 0:Y.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function m8(){return!0}function b8(t){switch(Bn()){case ft.browser:v8(t);break;case ft.reactNative:E8(t);break}}function v8(t){!ki()&&Mr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function E8(t){var e;ki()&&typeof Y<"u"&&Y!=null&&Y.NetInfo&&((e=Y)==null||e.NetInfo.addEventListener(i=>t(i==null?void 0:i.isConnected)))}function x8(){var t;return Mr()&&rr()?((t=rr())==null?void 0:t.visibilityState)==="visible":!0}const Xo={};class Qr{static get(e){return Xo[e]}static set(e,i){Xo[e]=i}static delete(e){delete Xo[e]}}function I8(t){const e=An.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function _8({publicKey:t,signature:e,payload:i}){var r;const n=Ka(i.method),s=128|parseInt(((r=i.version)==null?void 0:r.toString())||"4"),o=D8(i.address),a=i.era==="00"?new Uint8Array([0]):Ka(i.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(i.nonce,16),l=new Uint8Array([c&255,c>>8&255]),u=BigInt(`0x${$8(i.tip)}`),h=A8(u),f=new Uint8Array([0,...t,o,...e,...a,...l,...h,...n]),d=O8(f.length+1);return new Uint8Array([...d,s,...f])}function S8(t){const e=Ka(t),i=mE.blake2b(e,void 0,32);return"0x"+ie.from(i).toString("hex")}function Ka(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function $8(t){return t.startsWith("0x")?t.slice(2):t}function D8(t){const e=An.decode(t)[0];return e===42?0:e===60?2:1}function O8(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function A8(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function P8(t){const e=Uint8Array.from(ie.from(t.signature,"hex")),i=I8(t.transaction.address),r=_8({publicKey:i,signature:e,payload:t.transaction}),n=ie.from(r).toString("hex");return S8(n)}function Kc({logger:t,name:e}){const i=typeof t=="string"?Ep({opts:{level:t,name:e}}).logger:t;return i.level=typeof t=="string"?t:t.level,i}class ur{}let C8=class extends ur{constructor(e){super()}};const yh=L.FIVE_SECONDS,hr={pulse:"heartbeat_pulse"};let B8=class Og extends C8{constructor(e){super(e),this.events=new St.EventEmitter,this.interval=yh,this.interval=(e==null?void 0:e.interval)||yh}static async init(e){const i=new Og(e);return await i.init(),i}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),L.toMiliseconds(this.interval))}pulse(){this.events.emit(hr.pulse)}};const T8=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,R8=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,F8=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function N8(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){U8(t);return}return e}function U8(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function rs(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const i=t.trim();if(i.length<=9)switch(i.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!F8.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(T8.test(t)||R8.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,N8)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function k8(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function De(t,...e){try{return k8(t(...e))}catch(i){return Promise.reject(i)}}function j8(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function L8(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ps(t){if(j8(t))return String(t);if(L8(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ps(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Wa="base64:";function M8(t){return typeof t=="string"?t:Wa+V8(t)}function q8(t){return typeof t!="string"||!t.startsWith(Wa)?t:z8(t.slice(Wa.length))}function z8(t){return globalThis.Buffer?ie.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function V8(t){return globalThis.Buffer?ie.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Je(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function H8(...t){return Je(t.join(":"))}function ns(t){return t=Je(t),t?t+":":""}function K8(t,e){if(e===void 0)return!0;let i=0,r=t.indexOf(":");for(;r>-1;)i++,r=t.indexOf(":",r+1);return i<=e}function W8(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const G8="memory",Y8=()=>{const t=new Map;return{name:G8,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,i){t.set(e,i)},setItemRaw(e,i){t.set(e,i)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Z8(t={}){const e={mounts:{"":t.driver||Y8()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},i=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},r=(l,u)=>e.mountpoints.filter(h=>h.startsWith(l)||u&&l.startsWith(h)).map(h=>({relativeBase:l.length>h.length?l.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),n=(l,u)=>{if(e.watching){u=Je(u);for(const h of e.watchListeners)h(l,u)}},s=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await wh(e.mounts[l],n,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,h)=>{const f=new Map,d=p=>{let g=f.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},f.set(p.base,g)),g};for(const p of l){const g=typeof p=="string",w=Je(g?p:p.key),_=g?void 0:p.value,C=g||!p.options?u:{...u,...p.options},b=i(w);d(b).items.push({key:w,value:_,relativeKey:b.relativeKey,options:C})}return Promise.all([...f.values()].map(p=>h(p))).then(p=>p.flat())},c={hasItem(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=i(l);return De(f.hasItem,h,u)},getItem(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=i(l);return De(f.getItem,h,u).then(d=>rs(d))},getItems(l,u={}){return a(l,u,h=>h.driver.getItems?De(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),u).then(f=>f.map(d=>({key:H8(h.base,d.key),value:rs(d.value)}))):Promise.all(h.items.map(f=>De(h.driver.getItem,f.relativeKey,f.options).then(d=>({key:f.key,value:rs(d)})))))},getItemRaw(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=i(l);return f.getItemRaw?De(f.getItemRaw,h,u):De(f.getItem,h,u).then(d=>q8(d))},async setItem(l,u,h={}){if(u===void 0)return c.removeItem(l);l=Je(l);const{relativeKey:f,driver:d}=i(l);d.setItem&&(await De(d.setItem,f,ps(u),h),d.watch||n("update",l))},async setItems(l,u){await a(l,u,async h=>{if(h.driver.setItems)return De(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:ps(f.value),options:f.options})),u);h.driver.setItem&&await Promise.all(h.items.map(f=>De(h.driver.setItem,f.relativeKey,ps(f.value),f.options)))})},async setItemRaw(l,u,h={}){if(u===void 0)return c.removeItem(l,h);l=Je(l);const{relativeKey:f,driver:d}=i(l);if(d.setItemRaw)await De(d.setItemRaw,f,u,h);else if(d.setItem)await De(d.setItem,f,M8(u),h);else return;d.watch||n("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=Je(l);const{relativeKey:h,driver:f}=i(l);f.removeItem&&(await De(f.removeItem,h,u),(u.removeMeta||u.removeMata)&&await De(f.removeItem,h+"$",u),f.watch||n("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=Je(l);const{relativeKey:h,driver:f}=i(l),d=Object.create(null);if(f.getMeta&&Object.assign(d,await De(f.getMeta,h,u)),!u.nativeOnly){const p=await De(f.getItem,h+"$",u).then(g=>rs(g));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(d,p))}return d},setMeta(l,u,h={}){return this.setItem(l+"$",u,h)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){var w;l=ns(l);const h=r(l,!0);let f=[];const d=[];let p=!0;for(const _ of h){(w=_.driver.flags)!=null&&w.maxDepth||(p=!1);const C=await De(_.driver.getKeys,_.relativeBase,u);for(const b of C){const v=_.mountpoint+Je(b);f.some(O=>v.startsWith(O))||d.push(v)}f=[_.mountpoint,...f.filter(b=>!b.startsWith(_.mountpoint))]}const g=u.maxDepth!==void 0&&!p;return d.filter(_=>(!g||K8(_,u.maxDepth))&&W8(_,l))},async clear(l,u={}){l=ns(l),await Promise.all(r(l,!1).map(async h=>{if(h.driver.clear)return De(h.driver.clear,h.relativeBase,u);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",u);return Promise.all(f.map(d=>h.driver.removeItem(d,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>mh(l)))},async watch(l){return await s(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=ns(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[l]=u,e.watching&&Promise.resolve(wh(u,n,l)).then(h=>{e.unwatch[l]=h}).catch(console.error),c},async unmount(l,u=!0){var h,f;l=ns(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&((f=(h=e.unwatch)[l])==null||f.call(h),delete e.unwatch[l]),u&&await mh(e.mounts[l]),e.mountpoints=e.mountpoints.filter(d=>d!==l),delete e.mounts[l])},getMount(l=""){l=Je(l)+":";const u=i(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=Je(l),r(l,u.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,h={})=>c.setItem(l,u,h),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function wh(t,e,i){return t.watch?t.watch((r,n)=>e(r,i+n)):()=>{}}async function mh(t){typeof t.dispose=="function"&&await De(t.dispose)}function fr(t){return new Promise((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error)})}function Ag(t,e){let i;const r=()=>{if(i)return i;const n=indexedDB.open(t);return n.onupgradeneeded=()=>n.result.createObjectStore(e),i=fr(n),i.then(s=>{s.onclose=()=>i=void 0},()=>{}),i};return(n,s)=>r().then(o=>s(o.transaction(e,n).objectStore(e)))}let Qo;function Un(){return Qo||(Qo=Ag("keyval-store","keyval")),Qo}function bh(t,e=Un()){return e("readonly",i=>fr(i.get(t)))}function J8(t,e,i=Un()){return i("readwrite",r=>(r.put(e,t),fr(r.transaction)))}function X8(t,e=Un()){return e("readwrite",i=>(i.delete(t),fr(i.transaction)))}function Q8(t=Un()){return t("readwrite",e=>(e.clear(),fr(e.transaction)))}function eS(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},fr(t.transaction)}function tS(t=Un()){return t("readonly",e=>{if(e.getAllKeys)return fr(e.getAllKeys());const i=[];return eS(e,r=>i.push(r.key)).then(()=>i)})}const iS="idb-keyval";var rS=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",i=n=>e+n;let r;return t.dbName&&t.storeName&&(r=Ag(t.dbName,t.storeName)),{name:iS,options:t,async hasItem(n){return!(typeof await bh(i(n),r)>"u")},async getItem(n){return await bh(i(n),r)??null},setItem(n,s){return J8(i(n),s,r)},removeItem(n){return X8(i(n),r)},getKeys(){return tS(r)},clear(){return Q8(r)}}};const nS="WALLET_CONNECT_V2_INDEXED_DB",sS="keyvaluestorage";let oS=class{constructor(){this.indexedDb=Z8({driver:rS({dbName:nS,storeName:sS})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const i=await this.indexedDb.getItem(e);if(i!==null)return i}async setItem(e,i){await this.indexedDb.setItem(e,ui(i))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ea=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Y<"u"?Y:typeof self<"u"?self:{},gs={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(i){return this.hasOwnProperty(i)?String(this[i]):null},t.prototype.setItem=function(i,r){this[i]=String(r)},t.prototype.removeItem=function(i){delete this[i]},t.prototype.clear=function(){const i=this;Object.keys(i).forEach(function(r){i[r]=void 0,delete i[r]})},t.prototype.key=function(i){return i=i||0,Object.keys(this)[i]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ea<"u"&&ea.localStorage?gs.exports=ea.localStorage:typeof window<"u"&&window.localStorage?gs.exports=window.localStorage:gs.exports=new e})();function aS(t){var e;return[t[0],sr((e=t[1])!=null?e:"")]}let cS=class{constructor(){this.localStorage=gs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(aS)}async getItem(e){const i=this.localStorage.getItem(e);if(i!==null)return sr(i)}async setItem(e,i){this.localStorage.setItem(e,ui(i))}async removeItem(e){this.localStorage.removeItem(e)}};const lS="wc_storage_version",vh=1,uS=async(t,e,i)=>{const r=lS,n=await e.getItem(r);if(n&&n>=vh){i(e);return}const s=await t.getKeys();if(!s.length){i(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(r,vh),i(e),hS(t,o)},hS=async(t,e)=>{e.length&&e.forEach(async i=>{await t.removeItem(i)})};let fS=class{constructor(){this.initialized=!1,this.setInitialized=i=>{this.storage=i,this.initialized=!0};const e=new cS;this.storage=e;try{const i=new oS;uS(e,i,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,i){return await this.initialize(),this.storage.setItem(e,i)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const i=setInterval(()=>{this.initialized&&(clearInterval(i),e())},20)})}};var dS=Object.defineProperty,pS=(t,e,i)=>e in t?dS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Eh=(t,e,i)=>pS(t,typeof e!="symbol"?e+"":e,i);let gS=class extends ur{constructor(e){super(),this.opts=e,Eh(this,"protocol","wc"),Eh(this,"version",2)}};var yS=Object.defineProperty,wS=(t,e,i)=>e in t?yS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,mS=(t,e,i)=>wS(t,typeof e!="symbol"?e+"":e,i);let bS=class extends ur{constructor(e,i){super(),this.core=e,this.logger=i,mS(this,"records",new Map)}},vS=class{constructor(e,i){this.logger=e,this.core=i}},ES=class extends ur{constructor(e,i){super(),this.relayer=e,this.logger=i}},xS=class extends ur{constructor(e){super()}},IS=class{constructor(e,i,r,n){this.core=e,this.logger=i,this.name=r}},_S=class extends ur{constructor(e,i){super(),this.relayer=e,this.logger=i}},SS=class extends ur{constructor(e,i){super(),this.core=e,this.logger=i}},$S=class{constructor(e,i,r){this.core=e,this.logger=i,this.store=r}},DS=class{constructor(e,i){this.projectId=e,this.logger=i}},OS=class{constructor(e,i,r){this.core=e,this.logger=i,this.telemetryEnabled=r}};var AS=Object.defineProperty,PS=(t,e,i)=>e in t?AS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xh=(t,e,i)=>PS(t,typeof e!="symbol"?e+"":e,i);let CS=class{constructor(e){this.opts=e,xh(this,"protocol","wc"),xh(this,"version",2)}},BS=class{constructor(e){this.client=e}};const TS="PARSE_ERROR",RS="INVALID_REQUEST",FS="METHOD_NOT_FOUND",NS="INVALID_PARAMS",Pg="INTERNAL_ERROR",Wc="SERVER_ERROR",US=[-32700,-32600,-32601,-32602,-32603],pn={[TS]:{code:-32700,message:"Parse error"},[RS]:{code:-32600,message:"Invalid Request"},[FS]:{code:-32601,message:"Method not found"},[NS]:{code:-32602,message:"Invalid params"},[Pg]:{code:-32603,message:"Internal error"},[Wc]:{code:-32e3,message:"Server error"}},Cg=Wc;function kS(t){return US.includes(t)}function Ih(t){return Object.keys(pn).includes(t)?pn[t]:pn[Cg]}function jS(t){const e=Object.values(pn).find(i=>i.code===t);return e||pn[Cg]}function Bg(t,e,i){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${i} RPC url at ${e}`):t}var Tg={},Qt={},_h;function LS(){if(_h)return Qt;_h=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.isBrowserCryptoAvailable=Qt.getSubtleCrypto=Qt.getBrowerCrypto=void 0;function t(){return(pr===null||pr===void 0?void 0:pr.crypto)||(pr===null||pr===void 0?void 0:pr.msCrypto)||{}}Qt.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Qt.getSubtleCrypto=e;function i(){return!!t()&&!!e()}return Qt.isBrowserCryptoAvailable=i,Qt}var ei={},Sh;function MS(){if(Sh)return ei;Sh=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.isBrowser=ei.isNode=ei.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ei.isReactNative=t;function e(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}ei.isNode=e;function i(){return!t()&&!e()}return ei.isBrowser=i,ei}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=$n;e.__exportStar(LS(),t),e.__exportStar(MS(),t)})(Tg);function Lt(t=3){const e=Date.now()*Math.pow(10,t),i=Math.floor(Math.random()*Math.pow(10,t));return e+i}function Ri(t=6){return BigInt(Lt(t))}function Ct(t,e,i){return{id:i||Lt(),jsonrpc:"2.0",method:t,params:e}}function Sn(t,e){return{id:t,jsonrpc:"2.0",result:e}}function oo(t,e,i){return{id:t,jsonrpc:"2.0",error:qS(e,i)}}function qS(t,e){return typeof t>"u"?Ih(Pg):(typeof t=="string"&&(t=Object.assign(Object.assign({},Ih(Wc)),{message:t})),typeof e<"u"&&(t.data=e),kS(t.code)&&(t=jS(t.code)),t)}class zS{}class VS extends zS{constructor(){super()}}class HS extends VS{constructor(e){super()}}const KS="^https?:",WS="^wss?:";function GS(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Rg(t,e){const i=GS(t);return typeof i>"u"?!1:new RegExp(e).test(i)}function $h(t){return Rg(t,KS)}function Dh(t){return Rg(t,WS)}function YS(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Fg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Gc(t){return Fg(t)&&"method"in t}function ao(t){return Fg(t)&&(Mt(t)||vt(t))}function Mt(t){return"result"in t}function vt(t){return"error"in t}class Yc extends HS{constructor(e){super(e),this.events=new St.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async request(e,i){return this.requestStrict(Ct(e.method,e.params||[],e.id||Ri().toString()),i)}async requestStrict(e,i){return new Promise(async(r,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{vt(s)?n(s.error):r(s.result)});try{await this.connection.send(e,i)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ao(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const ZS=()=>typeof WebSocket<"u"?WebSocket:typeof Y<"u"&&typeof Y.WebSocket<"u"?Y.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),JS=()=>typeof WebSocket<"u"||typeof Y<"u"&&typeof Y.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Oh=t=>t.split("?")[0],Ah=10,XS=ZS();let QS=class{constructor(e){if(this.url=e,this.events=new St.EventEmitter,this.registering=!1,!Dh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,i)=>{if(typeof this.socket>"u"){i(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ui(e))}catch(i){this.onError(e.id,i)}}register(e=this.url){if(!Dh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const i=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=i||this.events.listenerCount("open")>=i)&&this.events.setMaxListeners(i+1),new Promise((r,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((i,r)=>{const n=Tg.isReactNative()?void 0:{rejectUnauthorized:!YS(e)},s=new XS(e,[],n);JS()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),i(s)}})}onOpen(e){e.onmessage=i=>this.onPayload(i),e.onclose=i=>this.onClose(i),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const i=typeof e.data=="string"?sr(e.data):e.data;this.events.emit("payload",i)}onError(e,i){const r=this.parseError(i),n=r.message||r.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,i=this.url){return Bg(e,Oh(i),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Ah&&this.events.setMaxListeners(Ah)}emitError(e){const i=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Oh(this.url)}`));return this.events.emit("register_error",i),i}};const Ng="wc",Ug=2,Us="core",Kt=`${Ng}@2:${Us}:`,e$={name:Us,logger:"error"},t$={database:":memory:"},i$="crypto",Ph="client_ed25519_seed",r$=L.ONE_DAY,n$="keychain",s$="0.3",o$="messages",a$="0.3",c$=L.SIX_HOURS,l$="publisher",kg="irn",u$="error",jg="wss://relay.walletconnect.org",h$="relayer",me={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"},f$="_subscription",gt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},d$=.1,Ga="2.23.0",he={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},p$="0.3",g$="WALLETCONNECT_CLIENT_ID",Ch="WALLETCONNECT_LINK_MODE_APPS",lt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},y$="subscription",w$="0.3",m$="pairing",b$="0.3",en={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Yi={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Dt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},v$="history",E$="0.3",x$="expirer",wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},I$="0.3",_$="verify-api",S$="https://verify.walletconnect.com",Lg="https://verify.walletconnect.org",gn=Lg,$$=`${gn}/v3`,D$=[S$,Lg],O$="echo",A$="https://echo.walletconnect.com",jt={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"},ii={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"},Ot={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",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},zi={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",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Vi={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"},tn={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"},P$=.1,C$="event-client",B$=86400,T$="https://pulse.walletconnect.org/batch";function R$(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(i[o]!==255)throw new TypeError(s+" is ambiguous");i[o]=n}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,_=0,C=p.length;_!==C&&p[_]===0;)_++,g++;for(var b=(C-_)*u+1>>>0,v=new Uint8Array(b);_!==C;){for(var O=p[_],P=0,T=b-1;(O!==0||P<w)&&T!==-1;T--,P++)O+=256*v[T]>>>0,v[T]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");w=P,_++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,_=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=i[p.charCodeAt(g)];if(v===255)return;for(var O=0,P=C-1;(v!==0||O<_)&&P!==-1;P--,O++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=O,g++}if(p[g]!==" "){for(var T=C-_;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var F$=R$,N$=F$;const Mg=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},U$=t=>new TextEncoder().encode(t),k$=t=>new TextDecoder().decode(t);class j${constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class L${constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}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 qg(this,e)}}class M${constructor(e){this.decoders=e}or(e){return qg(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const qg=(t,e)=>new M$({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class q${constructor(e,i,r,n){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=n,this.encoder=new j$(e,i,r),this.decoder=new L$(e,i,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const co=({name:t,prefix:e,encode:i,decode:r})=>new q$(t,e,i,r),kn=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:n}=N$(i,e);return co({prefix:t,name:e,encode:r,decode:s=>Mg(n(s))})},z$=(t,e,i,r)=>{const n={};for(let u=0;u<e.length;++u)n[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*i/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const h=n[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|h,a+=i,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},V$=(t,e,i)=>{const r=e[e.length-1]==="=",n=(1<<i)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,s+=e[n&a>>o];if(o&&(s+=e[n&a<<i-o]),r)for(;s.length*i&7;)s+="=";return s},Ue=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>co({prefix:e,name:t,encode(n){return V$(n,r,i)},decode(n){return z$(n,r,i,t)}}),H$=co({prefix:"\0",name:"identity",encode:t=>k$(t),decode:t=>U$(t)});var K$=Object.freeze({__proto__:null,identity:H$});const W$=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var G$=Object.freeze({__proto__:null,base2:W$});const Y$=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Z$=Object.freeze({__proto__:null,base8:Y$});const J$=kn({prefix:"9",name:"base10",alphabet:"0123456789"});var X$=Object.freeze({__proto__:null,base10:J$});const Q$=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),e6=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var t6=Object.freeze({__proto__:null,base16:Q$,base16upper:e6});const i6=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),r6=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),n6=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),s6=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),o6=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),a6=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),c6=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),l6=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),u6=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var h6=Object.freeze({__proto__:null,base32:i6,base32upper:r6,base32pad:n6,base32padupper:s6,base32hex:o6,base32hexupper:a6,base32hexpad:c6,base32hexpadupper:l6,base32z:u6});const f6=kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),d6=kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var p6=Object.freeze({__proto__:null,base36:f6,base36upper:d6});const g6=kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),y6=kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var w6=Object.freeze({__proto__:null,base58btc:g6,base58flickr:y6});const m6=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),b6=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),v6=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),E6=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var x6=Object.freeze({__proto__:null,base64:m6,base64pad:b6,base64url:v6,base64urlpad:E6});const zg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),I6=zg.reduce((t,e,i)=>(t[i]=e,t),[]),_6=zg.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function S6(t){return t.reduce((e,i)=>(e+=I6[i],e),"")}function $6(t){const e=[];for(const i of t){const r=_6[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const D6=co({prefix:"🚀",name:"base256emoji",encode:S6,decode:$6});var O6=Object.freeze({__proto__:null,base256emoji:D6}),A6=Vg,Bh=128,P6=127,C6=~P6,B6=Math.pow(2,31);function Vg(t,e,i){e=e||[],i=i||0;for(var r=i;t>=B6;)e[i++]=t&255|Bh,t/=128;for(;t&C6;)e[i++]=t&255|Bh,t>>>=7;return e[i]=t|0,Vg.bytes=i-r+1,e}var T6=Ya,R6=128,Th=127;function Ya(t,r){var i=0,r=r||0,n=0,s=r,o,a=t.length;do{if(s>=a)throw Ya.bytes=0,new RangeError("Could not decode varint");o=t[s++],i+=n<28?(o&Th)<<n:(o&Th)*Math.pow(2,n),n+=7}while(o>=R6);return Ya.bytes=s-r,i}var F6=Math.pow(2,7),N6=Math.pow(2,14),U6=Math.pow(2,21),k6=Math.pow(2,28),j6=Math.pow(2,35),L6=Math.pow(2,42),M6=Math.pow(2,49),q6=Math.pow(2,56),z6=Math.pow(2,63),V6=function(t){return t<F6?1:t<N6?2:t<U6?3:t<k6?4:t<j6?5:t<L6?6:t<M6?7:t<q6?8:t<z6?9:10},H6={encode:A6,decode:T6,encodingLength:V6},Hg=H6;const Rh=(t,e,i=0)=>(Hg.encode(t,e,i),e),Fh=t=>Hg.encodingLength(t),Za=(t,e)=>{const i=e.byteLength,r=Fh(t),n=r+Fh(i),s=new Uint8Array(n+i);return Rh(t,s,0),Rh(i,s,r),s.set(e,n),new K6(t,i,e,s)};class K6{constructor(e,i,r,n){this.code=e,this.size=i,this.digest=r,this.bytes=n}}const Kg=({name:t,code:e,encode:i})=>new W6(t,e,i);class W6{constructor(e,i,r){this.name=e,this.code=i,this.encode=r}digest(e){if(e instanceof Uint8Array){const i=this.encode(e);return i instanceof Uint8Array?Za(this.code,i):i.then(r=>Za(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Wg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),G6=Kg({name:"sha2-256",code:18,encode:Wg("SHA-256")}),Y6=Kg({name:"sha2-512",code:19,encode:Wg("SHA-512")});var Z6=Object.freeze({__proto__:null,sha256:G6,sha512:Y6});const Gg=0,J6="identity",Yg=Mg,X6=t=>Za(Gg,Yg(t)),Q6={code:Gg,name:J6,encode:Yg,digest:X6};var eD=Object.freeze({__proto__:null,identity:Q6});new TextEncoder,new TextDecoder;const Nh={...K$,...G$,...Z$,...X$,...t6,...h6,...p6,...w6,...x6,...O6};({...Z6,...eD});function Zg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function tD(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jg(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const Uh=Jg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ta=Jg("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=tD(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),iD={utf8:Uh,"utf-8":Uh,hex:Nh.base16,latin1:ta,ascii:ta,binary:ta,...Nh};function rD(t,e="utf8"){const i=iD[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zg(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}var nD=Object.defineProperty,sD=(t,e,i)=>e in t?nD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ut=(t,e,i)=>sD(t,typeof e!="symbol"?e+"":e,i);class oD{constructor(e,i){this.core=e,this.logger=i,Ut(this,"keychain",new Map),Ut(this,"name",n$),Ut(this,"version",s$),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Kt),Ut(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Ut(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Ut(this,"set",async(r,n)=>{this.isInitialized(),this.keychain.set(r,n),await this.persist()}),Ut(this,"get",r=>{this.isInitialized();const n=this.keychain.get(r);if(typeof n>"u"){const{message:s}=M("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return n}),Ut(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=dt(i,this.name)}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ta(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ra(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var aD=Object.defineProperty,cD=(t,e,i)=>e in t?aD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Se=(t,e,i)=>cD(t,typeof e!="symbol"?e+"":e,i);class lD{constructor(e,i,r){this.core=e,this.logger=i,Se(this,"name",i$),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Ha()),Se(this,"initialized",!1),Se(this,"clientId"),Se(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Se(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),Se(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const n=await this.getClientSeed(),s=lu(n),o=Xd(s.publicKey);return this.clientId=o,o}),Se(this,"generateKeyPair",()=>{this.isInitialized();const n=d_();return this.setPrivateKey(n.publicKey,n.privateKey)}),Se(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=lu(s),a=this.randomSessionIdentifier;return await l2(a,n,r$,o)}),Se(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=p_(a,s);return this.setSymKey(c,o)}),Se(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||ds(n);return await this.keychain.set(o,n),o}),Se(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"encode",async(n,s,o)=>{this.isInitialized();const a=_g(o),c=ui(s);if(ih(a))return w_(c,o==null?void 0:o.encoding);if(th(a)){const f=a.senderPublicKey,d=a.receiverPublicKey;n=await this.generateSharedKey(f,d)}const l=this.getSymKey(n),{type:u,senderPublicKey:h}=a;return g_({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),Se(this,"decode",async(n,s,o)=>{this.isInitialized();const a=b_(s,o);if(ih(a)){const c=m_(s,o==null?void 0:o.encoding);return sr(c)}if(th(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=y_({symKey:c,encoded:s,encoding:o==null?void 0:o.encoding});return sr(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Se(this,"getPayloadType",(n,s=tt)=>{const o=_n({encoded:n,encoding:s});return ar(o.type)}),Se(this,"getPayloadSenderPublicKey",(n,s=tt)=>{const o=_n({encoded:n,encoding:s});return o.senderPublicKey?nt(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=dt(i,this.name),this.keychain=r||new oD(this.core,this.logger)}get context(){return st(this.logger)}async setPrivateKey(e,i){return await this.keychain.set(e,i),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ph)}catch{e=Ha(),await this.keychain.set(Ph,e)}return rD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var uD=Object.defineProperty,hD=Object.defineProperties,fD=Object.getOwnPropertyDescriptors,kh=Object.getOwnPropertySymbols,dD=Object.prototype.hasOwnProperty,pD=Object.prototype.propertyIsEnumerable,Ja=(t,e,i)=>e in t?uD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,gD=(t,e)=>{for(var i in e||(e={}))dD.call(e,i)&&Ja(t,i,e[i]);if(kh)for(var i of kh(e))pD.call(e,i)&&Ja(t,i,e[i]);return t},yD=(t,e)=>hD(t,fD(e)),ot=(t,e,i)=>Ja(t,typeof e!="symbol"?e+"":e,i);class wD extends vS{constructor(e,i){super(e,i),this.logger=e,this.core=i,ot(this,"messages",new Map),ot(this,"messagesWithoutClientAck",new Map),ot(this,"name",o$),ot(this,"version",a$),ot(this,"initialized",!1),ot(this,"storagePrefix",Kt),ot(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const n=await this.getRelayerMessagesWithoutClientAck();typeof n<"u"&&(this.messagesWithoutClientAck=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),ot(this,"set",async(r,n,s)=>{this.isInitialized();const o=bt(n);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(r,a),s===ys.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,yD(gD({},c),{[o]:n}))}return await this.persist(),o}),ot(this,"get",r=>{this.isInitialized();let n=this.messages.get(r);return typeof n>"u"&&(n={}),n}),ot(this,"getWithoutAck",r=>{this.isInitialized();const n={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),ot(this,"has",(r,n)=>{this.isInitialized();const s=this.get(r),o=bt(n);return typeof s[o]<"u"}),ot(this,"ack",async(r,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=bt(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),ot(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=dt(e,this.name),this.core=i}get context(){return st(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,Ta(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ta(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ra(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Ra(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var mD=Object.defineProperty,bD=Object.defineProperties,vD=Object.getOwnPropertyDescriptors,jh=Object.getOwnPropertySymbols,ED=Object.prototype.hasOwnProperty,xD=Object.prototype.propertyIsEnumerable,Xa=(t,e,i)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,vr=(t,e)=>{for(var i in e||(e={}))ED.call(e,i)&&Xa(t,i,e[i]);if(jh)for(var i of jh(e))xD.call(e,i)&&Xa(t,i,e[i]);return t},Lh=(t,e)=>bD(t,vD(e)),yt=(t,e,i)=>Xa(t,typeof e!="symbol"?e+"":e,i);class ID extends ES{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,yt(this,"events",new St.EventEmitter),yt(this,"name",l$),yt(this,"queue",new Map),yt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),yt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),yt(this,"needsTransportRestart",!1),yt(this,"publish",async(r,n,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:n,opts:s}});const h=(s==null?void 0:s.ttl)||c$,f=(s==null?void 0:s.prompt)||!1,d=(s==null?void 0:s.tag)||0,p=(s==null?void 0:s.id)||Ri().toString(),g=$r(Fs().protocol),w={id:p,method:(s==null?void 0:s.publishMethod)||g.publish,params:vr({topic:r,message:n,ttl:h,prompt:f,tag:d,attestation:s==null?void 0:s.attestation},s==null?void 0:s.tvf)},_=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{Ie((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),Ie((c=w.params)==null?void 0:c.tag)&&((l=w.params)==null||delete l.tag);const C=new Promise(async b=>{const v=({id:P})=>{var T;((T=w.id)==null?void 0:T.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(me.publish,v),b())};this.relayer.events.on(me.publish,v);const O=zt(new Promise((P,T)=>{this.rpcPublish(w,s).then(P).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),T(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${d}`);try{await O,this.events.removeListener(me.publish,v)}catch(P){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(P,P==null?void 0:P.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:n,opts:s}}),await zt(C,this.publishTimeout,_)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(u=s==null?void 0:s.internal)!=null&&u.throwOnFailedPublish)throw C}finally{this.queue.delete(p)}}),yt(this,"publishCustom",async r=>{var n,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:l,opts:u={}}=r,{attestation:h,tvf:f,publishMethod:d,prompt:p,tag:g,ttl:w=L.FIVE_MINUTES}=u,_=u.id||Ri().toString(),C=$r(Fs().protocol),b=d||C.publish,v={id:_,method:b,params:vr(Lh(vr({},l),{ttl:w,prompt:p,tag:g,attestation:h}),f)},O=`Failed to publish custom payload, please try again. id:${_} tag:${g}`;try{Ie((n=v.params)==null?void 0:n.prompt)&&((s=v.params)==null||delete s.prompt),Ie((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const P=new Promise(async T=>{const R=({id:U})=>{var j;((j=v.id)==null?void 0:j.toString())===U.toString()&&(this.removeRequestFromQueue(U),this.relayer.events.removeListener(me.publish,R),T())};this.relayer.events.on(me.publish,R);const A=zt(new Promise((U,j)=>{this.rpcPublish(v,u).then(U).catch(B=>{this.logger.warn(B,B==null?void 0:B.message),j(B)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${_} tag:${g}`);try{await A,this.events.removeListener(me.publish,R)}catch(U){this.queue.set(_,{request:v,opts:u,attempt:1}),this.logger.warn(U,U==null?void 0:U.message)}});this.logger.trace({type:"method",method:"publish",params:{id:_,payload:l,opts:u}}),await zt(P,this.publishTimeout,O)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=u==null?void 0:u.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(_)}}),yt(this,"on",(r,n)=>{this.events.on(r,n)}),yt(this,"once",(r,n)=>{this.events.once(r,n)}),yt(this,"off",(r,n)=>{this.events.off(r,n)}),yt(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),this.relayer=e,this.logger=dt(i,this.name),this.registerEventListeners()}get context(){return st(this.logger)}async rpcPublish(e,i){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(me.publish,vr(vr({},e),i)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,i)=>{var r;const n=e.attempt+1;this.queue.set(i,Lh(vr({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${n}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(hr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(me.connection_stalled);return}this.checkQueue()}),this.relayer.on(me.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var _D=Object.defineProperty,SD=(t,e,i)=>e in t?_D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Er=(t,e,i)=>SD(t,typeof e!="symbol"?e+"":e,i);class $D{constructor(){Er(this,"map",new Map),Er(this,"set",(e,i)=>{const r=this.get(e);this.exists(e,i)||this.map.set(e,[...r,i])}),Er(this,"get",e=>this.map.get(e)||[]),Er(this,"exists",(e,i)=>this.get(e).includes(i)),Er(this,"delete",(e,i)=>{if(typeof i>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,i))return;const n=r.filter(s=>s!==i);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),Er(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var DD=Object.defineProperty,OD=Object.defineProperties,AD=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,PD=Object.prototype.hasOwnProperty,CD=Object.prototype.propertyIsEnumerable,Qa=(t,e,i)=>e in t?DD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,rn=(t,e)=>{for(var i in e||(e={}))PD.call(e,i)&&Qa(t,i,e[i]);if(Mh)for(var i of Mh(e))CD.call(e,i)&&Qa(t,i,e[i]);return t},ia=(t,e)=>OD(t,AD(e)),ce=(t,e,i)=>Qa(t,typeof e!="symbol"?e+"":e,i);class BD extends _S{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,ce(this,"subscriptions",new Map),ce(this,"topicMap",new $D),ce(this,"events",new St.EventEmitter),ce(this,"name",y$),ce(this,"version",w$),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Kt),ce(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ce(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ce(this,"clientId"),ce(this,"batchSubscribeTopicsLimit",500),ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ce(this,"subscribe",async(r,n)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:n}});try{const o=Fs(n),a={topic:r,relay:o,transportType:n==null?void 0:n.transportType};(s=n==null?void 0:n.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,n);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(r,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(r,n.id,n):await this.unsubscribeByTopic(r,n)}),ce(this,"isSubscribed",r=>new Promise(n=>{n(this.topicMap.topics.includes(r))})),ce(this,"isKnownTopic",r=>new Promise(n=>{n(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),ce(this,"on",(r,n)=>{this.events.on(r,n)}),ce(this,"once",(r,n)=>{this.events.once(r,n)}),ce(this,"off",(r,n)=>{this.events.off(r,n)}),ce(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),ce(this,"start",async()=>{await this.onConnect()}),ce(this,"stop",async()=>{await this.onDisconnect()}),ce(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ce(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(n=>{r.push(n)}),await this.batchSubscribe(r)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(hr.pulse,async()=>{await this.checkPending()}),this.events.on(lt.created,async r=>{const n=lt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:r}),await this.persist()}),this.events.on(lt.deleted,async r=>{const n=lt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:r}),await this.persist()})}),this.relayer=e,this.logger=dt(i,this.name),this.clientId=""}get context(){return st(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,i){let r=!1;try{r=this.getSubscription(e).topic===i}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,i){const r=this.topicMap.get(e);await Promise.all(r.map(async n=>await this.unsubscribeById(e,n,i)))}async unsubscribeById(e,i,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}});try{const n=Fs(r);await this.restartToComplete({topic:e,id:i,relay:n}),await this.rpcUnsubscribe(e,i,n);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,i,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,i,r){var n,s;const o=await this.getSubscriptionId(e);if((n=r==null?void 0:r.internal)!=null&&n.skipSubscribe)return o;(!r||(r==null?void 0:r.transportType)===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:i});const a={method:$r(i.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r==null?void 0:r.internal)==null?void 0:s.throwOnFailedPublish;try{if((r==null?void 0:r.transportType)===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},L.toMiliseconds(L.ONE_SECOND)),o;const l=new Promise(async h=>{const f=d=>{d.topic===e&&(this.events.removeListener(lt.created,f),h(d.id))};this.events.on(lt.created,f);try{const d=await zt(new Promise((p,g)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),g(w)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(lt.created,f),h(d)}catch{}}),u=await zt(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(me.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const i=e[0].relay,r={method:$r(i.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await zt(new Promise(n=>{this.relayer.request(r).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const i=e[0].relay,r={method:$r(i.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let n;try{n=await await zt(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}return n}rpcUnsubscribe(e,i,r){const n={method:$r(r.protocol).unsubscribe,params:{topic:e,id:i}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,i){this.setSubscription(e,ia(rn({},i),{id:e})),this.pending.delete(i.topic)}onBatchSubscribe(e){e.length&&e.forEach(i=>{this.setSubscription(i.id,rn({},i)),this.pending.delete(i.topic)})}async onUnsubscribe(e,i,r){this.events.removeAllListeners(i),this.hasSubscription(i,e)&&this.deleteSubscription(i,r),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,i){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:i}),this.addSubscription(e,i)}addSubscription(e,i){this.subscriptions.set(e,rn({},i)),this.topicMap.set(i.topic,e),this.events.emit(lt.created,i)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const i=this.subscriptions.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}deleteSubscription(e,i){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:i});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(lt.deleted,ia(rn({},r),{reason:i}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(lt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],i=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<i;r++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(lt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(i=>{var r;return i.topic===((r=this.subscriptions.get(i.id))==null?void 0:r.topic)})){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(i)}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 i=>ia(rn({},i),{id:await this.getSubscriptionId(i.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const i=await this.rpcBatchFetchMessages(e);i&&i.messages&&(await B3(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(i.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=M("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 bt(e+await this.getClientId())}}var TD=Object.defineProperty,qh=Object.getOwnPropertySymbols,RD=Object.prototype.hasOwnProperty,FD=Object.prototype.propertyIsEnumerable,ec=(t,e,i)=>e in t?TD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,zh=(t,e)=>{for(var i in e||(e={}))RD.call(e,i)&&ec(t,i,e[i]);if(qh)for(var i of qh(e))FD.call(e,i)&&ec(t,i,e[i]);return t},ne=(t,e,i)=>ec(t,typeof e!="symbol"?e+"":e,i);class ND extends xS{constructor(e){var i;super(e),ne(this,"protocol","wc"),ne(this,"version",2),ne(this,"core"),ne(this,"logger"),ne(this,"events",new St.EventEmitter),ne(this,"provider"),ne(this,"messages"),ne(this,"subscriber"),ne(this,"publisher"),ne(this,"name",h$),ne(this,"transportExplicitlyClosed",!1),ne(this,"initialized",!1),ne(this,"connectionAttemptInProgress",!1),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"packageName"),ne(this,"bundleId"),ne(this,"hasExperiencedNetworkDisruption",!1),ne(this,"pingTimeout"),ne(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),ne(this,"reconnectTimeout"),ne(this,"connectPromise"),ne(this,"reconnectInProgress",!1),ne(this,"requestsInFlight",[]),ne(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"request",async r=>{var n,s;this.logger.debug("Publishing Request Payload");const o=r.id||Ri().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const a=`${o}:${((s=r.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),ne(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),ne(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(me.connect)}),ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ne(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(me.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ne(this,"registerProviderListeners",()=>{this.provider.on(gt.payload,this.onPayloadHandler),this.provider.on(gt.connect,this.onConnectHandler),this.provider.on(gt.disconnect,this.onDisconnectHandler),this.provider.on(gt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Kc({logger:(i=e.logger)!=null?i:u$,name:this.name}),this.messages=new wD(this.logger,e.core),this.subscriber=new BD(this,this.logger),this.publisher=new ID(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||jg,y3()?this.packageName=Iu():w3()&&(this.bundleId=Iu()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e==null?void 0:e.message))}get context(){return st(this.logger)}get connected(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,i,r){this.isInitialized(),await this.publisher.publish(e,i,r),await this.recordMessageEvent({topic:e,message:i,publishedAt:Date.now(),transportType:he.relay},ys.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,i){var r,n,s;this.isInitialized(),(!(i!=null&&i.transportType)||(i==null?void 0:i.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(n=i==null?void 0:i.internal)==null?void 0:n.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(lt.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(lt.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,zh({internal:{throwOnFailedPublish:o}},i)).catch(f=>{o&&h(f)})||a,u()})]),a}async unsubscribe(e,i){this.isInitialized(),await this.subscriber.unsubscribe(e,i)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await zt(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.info("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(i,r)=>{await this.connect(e).then(i).catch(r).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 gh())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 i=e.sort((r,n)=>r.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${i.length} message events sorted`);for(const r of i)try{await this.onMessageEvent(r)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${i.length} message events processed`)}async onLinkMessageEvent(e,i){const{topic:r}=e;if(!i.sessionExists){const n=we(L.FIVE_MINUTES),s={topic:r,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(me.message,e),await this.recordMessageEvent(e,ys.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let i=1;for(;i<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${i}...`),await this.createProvider(),await new Promise(async(r,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(gt.disconnect,s),await zt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}).finally(()=>{this.provider.off(gt.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(gt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(gt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const n=r;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${i}`);break}await new Promise(r=>setTimeout(r,L.toMiliseconds(i*1))),i++}}startPingTimeout(){var e,i,r,n,s;if(As())try{(i=(e=this.provider)==null?void 0:e.connection)!=null&&i.socket&&((s=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||s.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 Yc(new QS(x3({sdkVersion:Ga,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,i){const{topic:r,message:n}=e;await this.messages.set(r,n,i)}async shouldIgnoreMessageEvent(e){const{topic:i,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(i))return this.logger.warn(`Ignoring message for unknown topic ${i}`),!0;const n=this.messages.has(i,r);return n&&this.logger.warn(`Ignoring duplicate message: ${r}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Gc(e)){if(!e.method.endsWith(f$))return;const i=e.params,{topic:r,message:n,publishedAt:s,attestation:o}=i.data,a={topic:r,message:n,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(zh({type:"event",event:i.id},a)),this.events.emit(i.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ao(e)&&this.events.emit(me.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ys.inbound),this.events.emit(me.message,e))}async acknowledgePayload(e){const i=Sn(e.id,!0);await this.provider.connection.send(i)}unregisterProviderListeners(){this.provider.off(gt.payload,this.onPayloadHandler),this.provider.off(gt.connect,this.onConnectHandler),this.provider.off(gt.disconnect,this.onDisconnectHandler),this.provider.off(gt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await gh();b8(async i=>{e!==i&&(e=i,i?await this.transportOpen().catch(r=>this.logger.error(r,r==null?void 0:r.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(hr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&x8())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(i){this.logger.warn(i,i==null?void 0:i.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(me.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},L.toMiliseconds(d$)))))}isInitialized(){if(!this.initialized){const{message:e}=M("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 UD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Vh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Hh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const kD="[object RegExp]",jD="[object String]",LD="[object Number]",MD="[object Boolean]",Kh="[object Arguments]",qD="[object Symbol]",zD="[object Date]",VD="[object Map]",HD="[object Set]",KD="[object Array]",WD="[object Function]",GD="[object ArrayBuffer]",ra="[object Object]",YD="[object Error]",ZD="[object DataView]",JD="[object Uint8Array]",XD="[object Uint8ClampedArray]",QD="[object Uint16Array]",eO="[object Uint32Array]",tO="[object BigUint64Array]",iO="[object Int8Array]",rO="[object Int16Array]",nO="[object Int32Array]",sO="[object BigInt64Array]",oO="[object Float32Array]",aO="[object Float64Array]";function cO(){}function Wh(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function lO(t,e,i){return un(t,e,void 0,void 0,void 0,void 0,i)}function un(t,e,i,r,n,s,o){const a=o(t,e,i,r,n,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return yn(t,e,s,o)}return yn(t,e,s,o)}function yn(t,e,i,r){if(Object.is(t,e))return!0;let n=Hh(t),s=Hh(e);if(n===Kh&&(n=ra),s===Kh&&(s=ra),n!==s)return!1;switch(n){case jD:return t.toString()===e.toString();case LD:{const c=t.valueOf(),l=e.valueOf();return UD(c,l)}case MD:case zD:case qD:return Object.is(t.valueOf(),e.valueOf());case kD:return t.source===e.source&&t.flags===e.flags;case WD:return t===e}i=i??new Map;const o=i.get(t),a=i.get(e);if(o!=null&&a!=null)return o===e;i.set(t,e),i.set(e,t);try{switch(n){case VD:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!un(l,e.get(c),c,t,e,i,r))return!1;return!0}case HD:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],f=l.findIndex(d=>un(h,d,void 0,t,e,i,r));if(f===-1)return!1;l.splice(f,1)}return!0}case KD:case JD:case XD:case QD:case eO:case tO:case iO:case rO:case nO:case sO:case oO:case aO:{if(typeof ie<"u"&&ie.isBuffer(t)!==ie.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!un(t[c],e[c],c,t,e,i,r))return!1;return!0}case GD:return t.byteLength!==e.byteLength?!1:yn(new Uint8Array(t),new Uint8Array(e),i,r);case ZD:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:yn(new Uint8Array(t),new Uint8Array(e),i,r);case YD:return t.name===e.name&&t.message===e.message;case ra:{if(!(yn(t.constructor,e.constructor,i,r)||Wh(t)&&Wh(e)))return!1;const c=[...Object.keys(t),...Vh(t)],l=[...Object.keys(e),...Vh(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],f=t[h];if(!Object.hasOwn(e,h))return!1;const d=e[h];if(!un(f,d,h,t,e,i,r))return!1}return!0}default:return!1}}finally{i.delete(t),i.delete(e)}}function uO(t,e){return lO(t,e,cO)}var hO=Object.defineProperty,Gh=Object.getOwnPropertySymbols,fO=Object.prototype.hasOwnProperty,dO=Object.prototype.propertyIsEnumerable,tc=(t,e,i)=>e in t?hO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Yh=(t,e)=>{for(var i in e||(e={}))fO.call(e,i)&&tc(t,i,e[i]);if(Gh)for(var i of Gh(e))dO.call(e,i)&&tc(t,i,e[i]);return t},Ze=(t,e,i)=>tc(t,typeof e!="symbol"?e+"":e,i);class dr extends IS{constructor(e,i,r,n=Kt,s=void 0){super(e,i,r,n),this.core=e,this.logger=i,this.name=r,Ze(this,"map",new Map),Ze(this,"version",p$),Ze(this,"cached",[]),Ze(this,"initialized",!1),Ze(this,"getKey"),Ze(this,"storagePrefix",Kt),Ze(this,"recentlyDeleted",[]),Ze(this,"recentlyDeletedLimit",200),Ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ie(o)?this.map.set(this.getKey(o),o):Z_(o)?this.map.set(o.id,o):J_(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ze(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())}),Ze(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ze(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>uO(a[c],o[c]))):this.values)),Ze(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=Yh(Yh({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ze(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=dt(i,this.name),this.storagePrefix=n,this.getKey=s}get context(){return st(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 i=this.map.get(e);if(!i){if(this.recentlyDeleted.includes(e)){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return i}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:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var pO=Object.defineProperty,gO=(t,e,i)=>e in t?pO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ee=(t,e,i)=>gO(t,typeof e!="symbol"?e+"":e,i);class yO{constructor(e,i){this.core=e,this.logger=i,ee(this,"name",m$),ee(this,"version",b$),ee(this,"events",new lc),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",Kt),ee(this,"ignoredPayloadTypes",[li]),ee(this,"registeredMethods",[]),ee(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ee(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),ee(this,"create",async r=>{this.isInitialized();const n=Ha(),s=await this.core.crypto.setSymKey(n),o=we(L.FIVE_MINUTES),a={protocol:kg},c={topic:s,expiry:o,relay:a,active:!1,methods:r==null?void 0:r.methods},l=oh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:r==null?void 0:r.methods});return this.events.emit(Yi.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r==null?void 0:r.transportType,internal:r==null?void 0:r.internal}),{topic:s,uri:l}}),ee(this,"pair",async r=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:r==null?void 0:r.uri,trace:[jt.pairing_started]}});this.isValidPair(r,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=sh(r.uri);n.props.properties.topic=s,n.addTrace(jt.pairing_uri_validation_success),n.addTrace(jt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),n.addTrace(jt.existing_pairing),u.active)throw n.setError(ii.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(jt.pairing_not_expired)}const h=c||we(L.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(s,h),await this.pairings.set(s,f),n.addTrace(jt.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(Yi.create,f),n.addTrace(jt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(jt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(ii.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw n.setError(ii.subscribe_pairing_topic_failure),d}return n.addTrace(jt.subscribe_pairing_topic_success),f}),ee(this,"activate",async({topic:r})=>{this.isInitialized();const n=we(L.FIVE_MINUTES);this.core.expirer.set(r,n),await this.pairings.update(r,{active:!0,expiry:n})}),ee(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=r;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ki();this.events.once(ae("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),ee(this,"updateExpiry",async({topic:r,expiry:n})=>{this.isInitialized(),await this.pairings.update(r,{expiry:n})}),ee(this,"updateMetadata",async({topic:r,metadata:n})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:n})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(n))}),ee(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(n);return oh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(r,n,s)=>{const o=Ct(n,s),a=await this.core.crypto.encode(r,o),c=en[n].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),ee(this,"sendResult",async(r,n,s)=>{const o=Sn(r,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,r)).request.method,l=en[c].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),ee(this,"sendError",async(r,n,s)=>{const o=oo(r,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,r)).request.method,l=en[c]?en[c].res:en.unregistered_method.res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),ee(this,"deletePairing",async(r,n)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),n?Promise.resolve():this.core.expirer.del(r)])}),ee(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(n=>qt(n.expiry));await Promise.all(r.map(n=>this.deletePairing(n.topic)))}),ee(this,"onRelayEventRequest",async r=>{const{topic:n,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(n,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(n,s);default:return await this.onUnknownRpcMethodRequest(n,s)}}),ee(this,"onRelayEventResponse",async r=>{const{topic:n,payload:s}=r,o=(await this.core.history.get(n,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(o)}}),ee(this,"onPairingPingRequest",async(r,n)=>{const{id:s}=n;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(Yi.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(r,n)=>{const{id:s}=n;setTimeout(()=>{Mt(n)?this.events.emit(ae("pairing_ping",s),{}):vt(n)&&this.events.emit(ae("pairing_ping",s),{error:n.error})},500)}),ee(this,"onPairingDeleteRequest",async(r,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Yi.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(r,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),ee(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",r))}),ee(this,"isValidPair",(r,n)=>{var s;if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${r}`);throw n.setError(ii.malformed_pairing_uri),new Error(a)}if(!Y_(r.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw n.setError(ii.malformed_pairing_uri),new Error(a)}const o=sh(r==null?void 0:r.uri);if(!((s=o==null?void 0:o.relay)!=null&&s.protocol)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(ii.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(ii.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){n.setError(ii.pairing_expired);const{message:a}=M("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ee(this,"isValidPing",async r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:n}=r;await this.isValidPairingTopic(n)}),ee(this,"isValidDisconnect",async r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:n}=r;await this.isValidPairingTopic(n)}),ee(this,"isValidPairingTopic",async r=>{if(!be(r,!1)){const{message:n}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(n)}if(!this.pairings.keys.includes(r)){const{message:n}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(n)}if(qt(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:n}=M("EXPIRED",`pairing topic: ${r}`);throw new Error(n)}}),this.core=e,this.logger=dt(i,this.name),this.pairings=new dr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return st(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(me.message,async e=>{const{topic:i,message:r,transportType:n}=e;if(this.pairings.keys.includes(i)&&n!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(i,r);Gc(s)?(this.core.history.set(i,s),await this.onRelayEventRequest({topic:i,payload:s})):ao(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:i,payload:s}),this.core.history.delete(i,s.id)),await this.core.relayer.messages.ack(i,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(wt.expired,async e=>{const{topic:i}=$p(e.target);i&&this.pairings.keys.includes(i)&&(await this.deletePairing(i,!0),this.events.emit(Yi.expire,{topic:i}))})}}var wO=Object.defineProperty,mO=(t,e,i)=>e in t?wO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Be=(t,e,i)=>mO(t,typeof e!="symbol"?e+"":e,i);class bO extends bS{constructor(e,i){super(e,i),this.core=e,this.logger=i,Be(this,"records",new Map),Be(this,"events",new St.EventEmitter),Be(this,"name",v$),Be(this,"version",E$),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Kt),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Be(this,"set",(r,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:r,request:{method:n.method,params:n.params||null},chainId:s,expiry:we(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Dt.created,o)}),Be(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const n=await this.getRecord(r.id);typeof n.response>"u"&&(n.response=vt(r)?{error:r.error}:{result:r.result},this.records.set(n.id,n),this.persist(),this.events.emit(Dt.updated,n))}),Be(this,"get",async(r,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:n}),await this.getRecord(n))),Be(this,"delete",(r,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===r){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Dt.deleted,s)}}),this.persist()}),Be(this,"exists",async(r,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===r:!1)),Be(this,"on",(r,n)=>{this.events.on(r,n)}),Be(this,"once",(r,n)=>{this.events.once(r,n)}),Be(this,"off",(r,n)=>{this.events.off(r,n)}),Be(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),this.logger=dt(i,this.name)}get context(){return st(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(i=>{if(typeof i.response<"u")return;const r={topic:i.topic,request:Ct(i.request.method,i.request.params,i.id),chainId:i.chainId};return e.push(r)}),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 i=this.records.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Dt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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(Dt.created,e=>{const i=Dt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(Dt.updated,e=>{const i=Dt.updated;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(Dt.deleted,e=>{const i=Dt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.core.heartbeat.on(hr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(i=>{L.toMiliseconds(i.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${i.id}`),this.records.delete(i.id),this.events.emit(Dt.deleted,i,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var vO=Object.defineProperty,EO=(t,e,i)=>e in t?vO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ze=(t,e,i)=>EO(t,typeof e!="symbol"?e+"":e,i);class xO extends SS{constructor(e,i){super(e,i),this.core=e,this.logger=i,ze(this,"expirations",new Map),ze(this,"events",new St.EventEmitter),ze(this,"name",x$),ze(this,"version",I$),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Kt),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"has",r=>{try{const n=this.formatTarget(r);return typeof this.getExpiration(n)<"u"}catch{return!1}}),ze(this,"set",(r,n)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:n};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(wt.created,{target:s,expiration:o})}),ze(this,"get",r=>{this.isInitialized();const n=this.formatTarget(r);return this.getExpiration(n)}),ze(this,"del",r=>{if(this.isInitialized(),this.has(r)){const n=this.formatTarget(r),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(wt.deleted,{target:n,expiration:s})}}),ze(this,"on",(r,n)=>{this.events.on(r,n)}),ze(this,"once",(r,n)=>{this.events.once(r,n)}),ze(this,"off",(r,n)=>{this.events.off(r,n)}),ze(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),this.logger=dt(i,this.name)}get context(){return st(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 I3(e);if(typeof e=="number")return _3(e);const{message:i}=M("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(i)}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(wt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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 i=this.expirations.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return i}checkExpiry(e,i){const{expiry:r}=i;L.toMiliseconds(r)-Date.now()<=0&&this.expire(e,i)}expire(e,i){this.expirations.delete(e),this.events.emit(wt.expired,{target:e,expiration:i})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,i)=>this.checkExpiry(i,e))}registerEventListeners(){this.core.heartbeat.on(hr.pulse,()=>this.checkExpirations()),this.events.on(wt.created,e=>{const i=wt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(wt.expired,e=>{const i=wt.expired;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(wt.deleted,e=>{const i=wt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var IO=Object.defineProperty,_O=(t,e,i)=>e in t?IO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ye=(t,e,i)=>_O(t,typeof e!="symbol"?e+"":e,i);class SO extends $S{constructor(e,i,r){super(e,i,r),this.core=e,this.logger=i,this.store=r,ye(this,"name",_$),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",$$),ye(this,"storagePrefix",Kt),ye(this,"version",Ug),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async n=>{if(!Mr()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=rr(),u=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((f,d)=>{const p=()=>{window.removeEventListener("message",w),l.body.removeChild(g),d("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const w=_=>{if(_.data&&typeof _.data=="string")try{const C=JSON.parse(_.data);if(C.type==="verify_attestation"){if(Aa(C.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),f(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};l.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(l){this.logger.warn(l)}return""}),ye(this,"resolve",async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Aa(s).payload.id!==a)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(n==null?void 0:n.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(L.ONE_SECOND*5),a=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ye(this,"getVerifyUrl",n=>{let s=n||gn;return D$.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${gn}`),s=gn),s}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(L.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}}),ye(this,"persistPublicKey",async n=>{this.logger.debug(n,"persisting public key to local storage"),await this.store.setItem(this.storeKey,n),this.publicKey=n}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(this,"isValidJwtAttestation",async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n}),ye(this,"validateAttestation",(n,s)=>{const o=E_(n,s.publicKey),a={hasExpired:L.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=dt(i,this.name),this.abortController=new AbortController,this.isDevEnv=Fc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return st(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var $O=Object.defineProperty,DO=(t,e,i)=>e in t?$O(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Zh=(t,e,i)=>DO(t,typeof e!="symbol"?e+"":e,i);class OO extends DS{constructor(e,i){super(e,i),this.projectId=e,this.logger=i,Zh(this,"context",O$),Zh(this,"registerDeviceToken",async r=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${A$}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:s,always_raw:a})})}),this.logger=dt(i,this.context)}}var AO=Object.defineProperty,Jh=Object.getOwnPropertySymbols,PO=Object.prototype.hasOwnProperty,CO=Object.prototype.propertyIsEnumerable,ic=(t,e,i)=>e in t?AO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,nn=(t,e)=>{for(var i in e||(e={}))PO.call(e,i)&&ic(t,i,e[i]);if(Jh)for(var i of Jh(e))CO.call(e,i)&&ic(t,i,e[i]);return t},$e=(t,e,i)=>ic(t,typeof e!="symbol"?e+"":e,i);class BO extends OS{constructor(e,i,r=!0){super(e,i,r),this.core=e,this.logger=i,$e(this,"context",C$),$e(this,"storagePrefix",Kt),$e(this,"storageVersion",P$),$e(this,"events",new Map),$e(this,"shouldPersist",!1),$e(this,"init",async()=>{if(!Fc())try{const n={eventId:Su(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:_p(this.core.relayer.protocol,this.core.relayer.version,Ga)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),$e(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,l=Su(),u=this.core.projectId||"",h=Date.now(),f=nn({eventId:l,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,f),this.shouldPersist=!0),f}),$e(this,"getEvent",n=>{const{eventId:s,topic:o}=n;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return nn(nn({},a),this.setMethods(a.eventId))}),$e(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),$e(this,"setEventListeners",()=>{this.core.heartbeat.on(hr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(n.timestamp)>B$&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),$e(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),$e(this,"addTrace",(n,s)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(s),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"setError",(n,s)=>{const o=this.events.get(n);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),$e(this,"restore",async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,nn(nn({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),$e(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),$e(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${T$}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ga}${s}`,{method:"POST",body:JSON.stringify(n)})}),$e(this,"getAppDomain",()=>Ip().url),this.logger=dt(i,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var TO=Object.defineProperty,Xh=Object.getOwnPropertySymbols,RO=Object.prototype.hasOwnProperty,FO=Object.prototype.propertyIsEnumerable,rc=(t,e,i)=>e in t?TO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Qh=(t,e)=>{for(var i in e||(e={}))RO.call(e,i)&&rc(t,i,e[i]);if(Xh)for(var i of Xh(e))FO.call(e,i)&&rc(t,i,e[i]);return t},le=(t,e,i)=>rc(t,typeof e!="symbol"?e+"":e,i);let NO=class Xg extends gS{constructor(e){var i;super(e),le(this,"protocol",Ng),le(this,"version",Ug),le(this,"name",Us),le(this,"relayUrl"),le(this,"projectId"),le(this,"customStoragePrefix"),le(this,"events",new St.EventEmitter),le(this,"logger"),le(this,"heartbeat"),le(this,"relayer"),le(this,"crypto"),le(this,"storage"),le(this,"history"),le(this,"expirer"),le(this,"pairing"),le(this,"verify"),le(this,"echoClient"),le(this,"linkModeSupportedApps"),le(this,"eventClient"),le(this,"initialized",!1),le(this,"logChunkController"),le(this,"on",(a,c)=>this.events.on(a,c)),le(this,"once",(a,c)=>this.events.once(a,c)),le(this,"off",(a,c)=>this.events.off(a,c)),le(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),le(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}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)||jg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=i3({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:e$.logger,name:Us}),{logger:s,chunkLoggerController:o}=Ep({opts:n,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(i=this.logChunkController)!=null&&i.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=dt(s,this.name),this.heartbeat=new B8,this.crypto=new lD(this,this.logger,e==null?void 0:e.keychain),this.history=new bO(this,this.logger),this.expirer=new xO(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new fS(Qh(Qh({},t$),e==null?void 0:e.storageOptions)),this.relayer=new ND({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new yO(this,this.logger),this.verify=new SO(this,this.logger,this.storage),this.echoClient=new OO(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new BO(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const i=new Xg(e);await i.initialize();const r=await i.crypto.getClientId();return await i.storage.setItem(g$,r),i}get context(){return st(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(Ch,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(Ch)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${e}`,r=`${i}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[i]}catch(i){console.warn("Failed to get global WalletConnect core",i);return}}setGlobalCore(e){var i;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((i=e.opts)==null?void 0:i.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof xt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const UO=NO,Qg="wc",e0=2,t0="client",Zc=`${Qg}@${e0}:${t0}:`,na={name:t0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},ef="WALLETCONNECT_DEEPLINK_CHOICE",kO="proposal",tf="Proposal expired",jO="session",xr=L.SEVEN_DAYS,LO="engine",Te={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},sa={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},MO={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},qO="request",zO=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],VO="wc",HO="auth",KO="authKeys",WO="pairingTopics",GO="requests",lo=`${VO}@${1.5}:${HO}:`,ws=`${lo}:PUB_KEY`;var YO=Object.defineProperty,ZO=Object.defineProperties,JO=Object.getOwnPropertyDescriptors,rf=Object.getOwnPropertySymbols,XO=Object.prototype.hasOwnProperty,QO=Object.prototype.propertyIsEnumerable,nc=(t,e,i)=>e in t?YO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,oe=(t,e)=>{for(var i in e||(e={}))XO.call(e,i)&&nc(t,i,e[i]);if(rf)for(var i of rf(e))QO.call(e,i)&&nc(t,i,e[i]);return t},Re=(t,e)=>ZO(t,JO(e)),k=(t,e,i)=>nc(t,typeof e!="symbol"?e+"":e,i);class eA extends BS{constructor(e){super(e),k(this,"name",LO),k(this,"events",new lc),k(this,"initialized",!1),k(this,"requestQueue",{state:kt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),k(this,"emittedSessionRequests",new T3({limit:500})),k(this,"requestQueueDelay",L.ONE_SECOND),k(this,"expectedPairingMethodMap",new Map),k(this,"recentlyDeletedMap",new Map),k(this,"recentlyDeletedLimit",200),k(this,"relayMessageCache",[]),k(this,"pendingSessions",new Map),k(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(Te)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),k(this,"connect",async i=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Re(oe({},i),{requiredNamespaces:i.requiredNamespaces||{},optionalNamespaces:i.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=V_(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:h,walletPay:f}=n,d=((r=h==null?void 0:h[0])==null?void 0:r.ttl)||Te.wc_sessionPropose.req.ttl||L.FIVE_MINUTES;this.validateRequestExpiry(d);let p=s,g,w=!1;try{if(p){const A=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=A.active}}catch(A){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),A}if(!p||!w){const{topic:A,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=A,g=U}if(!p){const{message:A}=M("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(A)}const _=await this.client.core.crypto.generateKeyPair(),C=we(d),b=oe(Re(oe(oe({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:kg}],proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:C,pairingTopic:p},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:Lt()}),(h||f)&&{requests:{authentication:h==null?void 0:h.map(A=>{const{domain:U,chains:j,nonce:B,uri:I,exp:D,nbf:m,type:y,statement:x,requestId:$,resources:E,signatureTypes:S}=A;return{domain:U,chains:j,nonce:B,type:y??"caip122",aud:I,version:"1",iat:new Date().toISOString(),exp:D,nbf:m,statement:x,requestId:$,resources:E,signatureTypes:S}}),walletPay:f}}),v=ae("session_connect",b.id),{reject:O,resolve:P,done:T}=Ki(d,tf),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:tf,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(v,({error:A,session:U})=>{this.client.events.off("proposal_expire",R),A?O(A):U&&P(U)}),await this.setProposal(b.id,b),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:b.id}}}).catch(A=>{throw this.deleteProposal(b.id),A}),{uri:g,approval:T}}),k(this,"pair",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(i)}catch(r){throw this.client.logger.error("pair() failed"),r}}),k(this,"approve",async i=>{var r,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=i==null?void 0:i.id)==null?void 0:r.toString(),trace:[Ot.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw o.setError(zi.no_internet_connection),U}try{await this.isValidProposalId(i==null?void 0:i.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${i==null?void 0:i.id}) failed`),o.setError(zi.proposal_not_found),U}try{await this.isValidApprove(i)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(zi.session_approve_namespace_validation_failure),U}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:_,optionalNamespaces:C}=p;let b=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:g});b||(b=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Ot.session_approve_started,properties:{topic:g,trace:[Ot.session_approve_started,Ot.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),O=w.publicKey,P=await this.client.core.crypto.generateSharedKey(v,O),T=Re(oe(oe(oe({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:we(xr)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=he.relay;b.addTrace(Ot.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:R,internal:{skipSubscribe:!0}})}catch(U){throw b.setError(zi.subscribe_session_topic_failure),U}b.addTrace(Ot.subscribe_session_topic_success);const A=Re(oe({},T),{topic:P,requiredNamespaces:_,optionalNamespaces:C,pairingTopic:g,acknowledged:!1,self:T.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:v,transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(P,A),b.addTrace(Ot.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:v},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:oe({correlationId:a},this.getTVFApproveParams(A))}}),b.addTrace(Ot.session_approve_publish_success)}catch(U){throw this.client.logger.error(U),this.client.session.delete(P,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),U}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:w.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,we(xr)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),k(this,"reject",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(i)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:n}=i;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:n,rpcOpts:Te.wc_sessionPropose.reject}),await this.deleteProposal(r)}),k(this,"update",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(i)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:r,namespaces:n}=i,{done:s,resolve:o,reject:a}=Ki(L.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Lt(),l=Ri().toString(),u=this.client.session.get(r).namespaces;return this.events.once(ae("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(r,{namespaces:n}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(r,{namespaces:u}),a(h)}),{acknowledged:s}}),k(this,"extend",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(i)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=i,n=Lt(),{done:s,resolve:o,reject:a}=Ki(L.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ae("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,we(xr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async i=>{this.isInitialized();try{await this.isValidRequest(i)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:r,request:n,topic:s,expiry:o=Te.wc_sessionRequest.req.ttl}=i,a=this.client.session.get(s);(a==null?void 0:a.transportType)===he.relay&&await this.confirmOnlineStateOrThrow();const c=Lt(),l=Ri().toString(),{done:u,resolve:h,reject:f}=Ki(o,"Request expired. Please try again.");this.events.once(ae("session_request",c),({error:w,result:_})=>{w?f(w):h(_)});const d="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:d,params:{request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:r,id:c}),await u();const g={request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:r};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:d,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(_=>f(_)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:r,id:c}),w()}),new Promise(async w=>{var _;if(!((_=a.sessionConfig)!=null&&_.disableDeepLink)){const C=await O3(this.client.core.storage,ef);await S3({id:c,topic:s,wcDeepLink:C})}w()}),u()]).then(w=>w[2])}),k(this,"respond",async i=>{var r,n;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:(i==null?void 0:i.topic)||((n=(r=i==null?void 0:i.response)==null?void 0:r.id)==null?void 0:n.toString()),trace:[Ot.session_request_response_started]}});try{await this.isValidRespond(i)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zi.session_request_response_validation_failure),h}s.addTrace(Ot.session_request_response_validation_success);const{topic:o,response:a}=i,{id:c}=a,l=this.client.session.get(o);l.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{s.addTrace(Ot.session_request_response_publish_started),Mt(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):vt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(i)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zi.session_request_response_publish_failure),h}}),k(this,"ping",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(i)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:r}=i;if(this.client.session.keys.includes(r)){const n=Lt(),s=Ri().toString(),{done:o,resolve:a,reject:c}=Ki(L.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ae("session_ping",n),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(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:r}))}),k(this,"emit",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(i);const{topic:r,event:n,chainId:s}=i,o=Ri().toString(),a=Lt();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(i);const{topic:r}=i;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:n}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(n)}}),k(this,"find",i=>(this.isInitialized(),this.client.session.getAll().filter(r=>W_(r,i)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(i,r)=>{var n;this.isInitialized(),this.isValidAuthenticate(i);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),o=s?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:f,exp:d,nbf:p,methods:g=[],expiry:w}=i,_=[...i.resources||[]],{topic:C,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:C,uri:b}});const v=await this.client.core.crypto.generateKeyPair(),O=ds(v);if(await Promise.all([this.client.auth.authKeys.set(ws,{responseTopic:O,publicKey:v}),this.client.auth.pairingTopics.set(O,{topic:O,pairingTopic:C})]),await this.client.core.relayer.subscribe(O,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),g.length>0){const{namespace:E}=ci(a[0]);let S=Kx(E,"request",g);fs(_)&&(S=Gx(S,_.pop())),_.push(S)}const P=w&&w>Te.wc_sessionAuthenticate.req.ttl?w:Te.wc_sessionAuthenticate.req.ttl,T={authPayload:{type:f??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:p,resources:_},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(P)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},A={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(Te.wc_sessionPropose.req.ttl),id:Lt()},{done:U,resolve:j,reject:B}=Ki(P,"Request expired"),I=Lt(),D=ae("session_connect",A.id),m=ae("session_request",I),y=async({error:E,session:S})=>{this.events.off(m,x),E?B(E):S&&j({session:S})},x=async E=>{var S,F,N;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),E.error){const W=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return E.error.code===W.code?void 0:(this.events.off(D,y),B(E.error.message))}await this.deleteProposal(A.id),this.events.off(D,y);const{cacaos:H,responder:z}=E.result,q=[],K=[];for(const W of H){await Nu({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Q}=W,pe=fs(Q.resources),ve=[Fa(Q.iss)],_e=Cs(Q.iss);if(pe){const He=Uu(pe),Wt=ku(pe);q.push(...He),ve.push(...Wt)}for(const He of ve)K.push(`${He}:${_e}`)}const G=await this.client.core.crypto.generateSharedKey(v,z.publicKey);let X;q.length>0&&(X={topic:G,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:z,controller:z.publicKey,expiry:we(xr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:uh([...new Set(q)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(G,{transportType:o}),await this.client.session.set(G,X),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:z.metadata}),X=this.client.session.get(G)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(F=z.metadata.redirect)!=null&&F.linkMode&&(N=z.metadata.redirect)!=null&&N.universal&&r&&(this.client.core.addLinkModeSupportedApp(z.metadata.redirect.universal),this.client.session.update(G,{transportType:he.link_mode})),j({auths:H,session:X})};this.events.once(D,y),this.events.once(m,x);let $;try{if(s){const E=Ct("wc_sessionAuthenticate",T,I);this.client.core.history.set(C,E);const S=await this.client.core.crypto.encode("",E,{type:Nn,encoding:Bi});$=is(r,C,S)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:i.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:A,expiry:Te.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:A.id})])}catch(E){throw this.events.off(D,y),this.events.off(m,x),E}return await this.setProposal(A.id,A),await this.setAuthRequest(I,{request:Re(oe({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:$??b,response:U}}),k(this,"approveSessionAuthenticate",async i=>{const{id:r,auths:n}=i,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Vi.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(tn.no_internet_connection),w}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=ds(c),h={type:li,receiverPublicKey:c,senderPublicKey:l},f=[],d=[];for(const w of n){if(!await Nu({cacao:w,projectId:this.client.core.projectId})){s.setError(tn.invalid_cacao);const O=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:O,encodeOpts:h}),new Error(O.message)}s.addTrace(Vi.cacaos_verified);const{p:_}=w,C=fs(_.resources),b=[Fa(_.iss)],v=Cs(_.iss);if(C){const O=Uu(C),P=ku(C);f.push(...O),b.push(...P)}for(const O of b)d.push(`${O}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Vi.create_authenticated_session_topic);let g;if((f==null?void 0:f.length)>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:we(xr),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:uh([...new Set(f)],[...new Set(d)]),transportType:a},s.addTrace(Vi.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw s.setError(tn.subscribe_authenticated_session_topic_failure),w}s.addTrace(Vi.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Vi.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Vi.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(tn.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),k(this,"rejectSessionAuthenticate",async i=>{this.isInitialized();const{id:r,reason:n}=i,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ds(o),l={type:li,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:n,encodeOpts:l,rpcOpts:Te.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),k(this,"formatAuthMessage",i=>{this.isInitialized();const{request:r,iss:n}=i;return zp(r,n)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const i=this.relayMessageCache.shift();i&&await this.onRelayMessage(i)}catch(i){this.client.logger.error(i)}},50)}),k(this,"cleanupDuplicatePairings",async i=>{if(i.pairingTopic)try{const r=this.client.core.pairing.pairings.get(i.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===i.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),k(this,"deleteSession",async i=>{var r;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=i,{self:c}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(ef).catch(l=>this.client.logger.warn(l)),n===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=kt.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===n).map(l=>this.deletePendingSessionRequest(l.id,fe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),k(this,"deleteProposal",async(i,r)=>{if(r)try{const n=this.client.proposal.get(i),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s==null||s.setError(zi.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(i,fe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"proposal")}),k(this,"deletePendingSessionRequest",async(i,r,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(i,r),n?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==i),n&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:i}))}),k(this,"deletePendingAuthRequest",async(i,r,n=!1)=>{await Promise.all([this.client.auth.requests.delete(i,r),n?Promise.resolve():this.client.core.expirer.del(i)])}),k(this,"setExpiry",async(i,r)=>{this.client.session.keys.includes(i)&&(this.client.core.expirer.set(i,r),await this.client.session.update(i,{expiry:r}))}),k(this,"setProposal",async(i,r)=>{this.client.core.expirer.set(i,we(Te.wc_sessionPropose.req.ttl)),await this.client.proposal.set(i,r)}),k(this,"setAuthRequest",async(i,r)=>{const{request:n,pairingTopic:s,transportType:o=he.relay}=r;this.client.core.expirer.set(i,n.expiryTimestamp),await this.client.auth.requests.set(i,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:i,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async i=>{const{id:r,topic:n,params:s,verifyContext:o}=i,a=s.request.expiryTimestamp||we(Te.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:n,params:s,verifyContext:o})}),k(this,"sendRequest",async i=>{const{topic:r,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=i,d=Ct(n,s,c);let p;const g=!!u;try{const C=g?Bi:tt;p=await this.client.core.crypto.encode(r,d,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),C}let w;if(zO.includes(n)){const C=bt(JSON.stringify(d)),b=bt(p);w=await this.client.core.verify.register({id:b,decryptedId:C})}const _=oe(oe({},Te[n].req),f);if(_.attestation=w,o&&(_.ttl=o),a&&(_.id=a),this.client.core.history.set(r,d),g){const C=is(u,r,p);await Y.Linking.openURL(C,this.client.name)}else _.tvf=Re(oe({},h),{correlationId:d.id}),l?(_.internal=Re(oe({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,_)):this.client.core.relayer.publish(r,p,_).catch(C=>this.client.logger.error(C));return d.id}),k(this,"sendProposeSession",async i=>{const{proposal:r,publishOpts:n}=i,s=Ct("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:tt}),a=bt(JSON.stringify(s)),c=bt(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:Re(oe({},n),{publishMethod:"wc_proposeSession",attestation:l})})}),k(this,"sendApproveSession",async i=>{const{sessionTopic:r,pairingProposalResponse:n,proposal:s,sessionSettleRequest:o,publishOpts:a}=i,c=Sn(s.id,n),l=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:tt}),u=Ct("wc_sessionSettle",o,a==null?void 0:a.id),h=await this.client.core.crypto.encode(r,u,{encoding:tt});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:Re(oe({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async i=>{const{id:r,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=i,l=Sn(r,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const p=h?Bi:tt;u=await this.client.core.crypto.encode(n,l,Re(oe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),p}let f,d;try{f=await this.client.core.history.get(n,r);const p=f.request;try{d=this.getTVFParams(r,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g==null?void 0:g.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${r}) failed`),p}if(h){const p=is(c,n,u);await Y.Linking.openURL(p,this.client.name)}else{const p=f.request.method,g=Te[p].res;g.tvf=Re(oe({},d),{correlationId:r}),o?(g.internal=Re(oe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,u,g)):this.client.core.relayer.publish(n,u,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(l)}),k(this,"sendError",async i=>{const{id:r,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=i,l=oo(r,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const d=h?Bi:tt;u=await this.client.core.crypto.encode(n,l,Re(oe({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),d}let f;try{f=await this.client.core.history.get(n,r)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${n}, ${r}) failed`),d}if(h){const d=is(c,n,u);await Y.Linking.openURL(d,this.client.name)}else{const d=f.request.method,p=a||Te[d].res;this.client.core.relayer.publish(n,u,p)}await this.client.core.history.resolve(l)}),k(this,"cleanup",async()=>{const i=[],r=[];this.client.session.getAll().forEach(n=>{let s=!1;qt(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&i.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{qt(n.expiryTimestamp)&&r.push(n.id)}),await Promise.all([...i.map(n=>this.deleteSession({topic:n})),...r.map(n=>this.deleteProposal(n))])}),k(this,"onProviderMessageEvent",async i=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(i):await this.onRelayMessage(i)}),k(this,"onRelayEventRequest",async i=>{this.requestQueue.queue.push(i),await this.processRequestsQueue()}),k(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===kt.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=kt.active;const i=this.requestQueue.queue.shift();if(i)try{await this.processRequest(i)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=kt.idle}),k(this,"processRequest",async i=>{const{topic:r,payload:n,attestation:s,transportType:o,encryptedId:a}=i,c=n.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,n);case"wc_sessionPing":return await this.onSessionPingRequest(r,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n,transportType:s}=i,o=(await this.client.core.history.get(r,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,n);case"wc_sessionExtend":return this.onSessionExtendResponse(r,n);case"wc_sessionPing":return this.onSessionPingResponse(r,n);case"wc_sessionRequest":return this.onSessionRequestResponse(r,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",i=>{const{topic:r}=i,{message:n}=M("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),k(this,"shouldIgnorePairingRequest",i=>{const{topic:r,requestMethod:n}=i,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async i=>{const{topic:r,payload:n,attestation:s,encryptedId:o}=i,{params:a,id:c}=n;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(ii.proposal_listener_not_found)),this.isValidConnect(oe({},n.params));const u=a.expiryTimestamp||we(Te.wc_sessionPropose.req.ttl),h=oe({id:c,pairingTopic:r,expiryTimestamp:u,attestation:s,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:bt(JSON.stringify(n)),encryptedId:o,metadata:h.proposer.metadata});l==null||l.addTrace(jt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Te.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),k(this,"onSessionProposeResponse",async(i,r,n)=>{const{id:s}=r;if(Mt(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:i,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:i})}else if(vt(r)){await this.deleteProposal(s);const o=ae("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),k(this,"onSessionSettleRequest",async(i,r)=>{const{id:n,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r.params,p=[...this.pendingSessions.values()].find(_=>_.sessionTopic===i);if(!p)return this.client.logger.error(`Pending session not found for topic ${i}`);const g=this.client.proposal.get(p.proposalId),w=Re(oe(oe(oe({topic:i,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:w.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:r.id,topic:i,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:w}),this.events.emit(ae("session_connect",p.proposalId),{session:w})}catch(o){await this.sendError({id:n,topic:i,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(i,r)=>{const{id:n}=r;Mt(r)?(await this.client.session.update(i,{acknowledged:!0}),this.events.emit(ae("session_approve",n),{})):vt(r)&&(await this.client.session.delete(i,fe("USER_DISCONNECTED")),this.events.emit(ae("session_approve",n),{error:r.error}))}),k(this,"onSessionUpdateRequest",async(i,r)=>{const{params:n,id:s}=r;try{const o=`${i}_session_update`,a=Qr.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:i,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:i},n));try{Qr.set(o,s),await this.client.session.update(i,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:i,result:!0})}catch(c){throw Qr.delete(o),c}this.client.events.emit("session_update",{id:s,topic:i,params:n})}catch(o){await this.sendError({id:s,topic:i,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(i,r)=>r.toString().slice(0,-3)<i.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(i,r)=>{const{id:n}=r,s=ae("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(r)?this.events.emit(ae("session_update",n),{}):vt(r)&&this.events.emit(ae("session_update",n),{error:r.error})}),k(this,"onSessionExtendRequest",async(i,r)=>{const{id:n}=r;try{this.isValidExtend({topic:i}),await this.setExpiry(i,we(xr)),await this.sendResult({id:n,topic:i,result:!0}),this.client.events.emit("session_extend",{id:n,topic:i})}catch(s){await this.sendError({id:n,topic:i,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(i,r)=>{const{id:n}=r,s=ae("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(r)?this.events.emit(ae("session_extend",n),{}):vt(r)&&this.events.emit(ae("session_extend",n),{error:r.error})}),k(this,"onSessionPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult({id:n,topic:i,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:i})}catch(s){await this.sendError({id:n,topic:i,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(i,r)=>{const{id:n}=r,s=ae("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Mt(r)?this.events.emit(ae("session_ping",n),{}):vt(r)&&this.events.emit(ae("session_ping",n),{error:r.error})},500)}),k(this,"onSessionDeleteRequest",async(i,r)=>{const{id:n}=r;try{await this.isValidDisconnect({topic:i,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:i,error:fe("USER_DISCONNECTED")}),await this.deleteSession({topic:i,id:n})}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async i=>{var r,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=i,{id:h,params:f}=a;try{await this.isValidRequest(oe({topic:o},f));const d=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:bt(JSON.stringify(Ct("wc_sessionRequest",f,h))),encryptedId:l,metadata:d.peer.metadata,transportType:u}),g={id:h,topic:o,params:f,verifyContext:p};await this.setPendingSessionRequest(g),u===he.link_mode&&(r=d.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((n=d.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(d){await this.sendError({id:h,topic:o,error:d}),this.client.logger.error(d)}}),k(this,"onSessionRequestResponse",(i,r)=>{const{id:n}=r,s=ae("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(r)?this.events.emit(ae("session_request",n),{result:r.result}):vt(r)&&this.events.emit(ae("session_request",n),{error:r.error})}),k(this,"onSessionEventRequest",async(i,r)=>{const{id:n,params:s}=r;try{const o=`${i}_session_event_${s.event.name}`,a=Qr.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(oe({topic:i},s)),this.client.events.emit("session_event",{id:n,topic:i,params:s}),Qr.set(o,n)}catch(o){await this.sendError({id:n,topic:i,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(i,r)=>{const{id:n}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:i,payload:r}),Mt(r)?this.events.emit(ae("session_request",n),{result:r.result}):vt(r)&&this.events.emit(ae("session_request",n),{error:r.error})}),k(this,"onSessionAuthenticateRequest",async i=>{var r;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=i;try{const{requester:l,authPayload:u,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:bt(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),d={requester:l,pairingTopic:n,id:s.id,authPayload:u,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:d,pairingTopic:n,transportType:c}),c===he.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:f})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),d={type:li,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:d,rpcOpts:Te.wc_sessionAuthenticate.autoReject,appLink:f})}}),k(this,"addSessionRequestToSessionRequestQueue",i=>{this.sessionRequestQueue.queue.push(i)}),k(this,"cleanupAfterResponse",i=>{this.deletePendingSessionRequest(i.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:i,error:r})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===i&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ae("session_request",s.request.id),{error:r})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.active){this.client.logger.info("session request queue is already active.");return}const i=this.sessionRequestQueue.queue[0];if(!i){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(i)}catch(r){this.client.logger.error(r)}}),k(this,"emitSessionRequest",i=>{if(this.emittedSessionRequests.has(i.id)){this.client.logger.warn({id:i.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${i.id}`);return}this.sessionRequestQueue.state=kt.active,this.emittedSessionRequests.add(i.id),this.client.events.emit("session_request",i)}),k(this,"onPairingCreated",i=>{if(i.methods&&this.expectedPairingMethodMap.set(i.topic,i.methods),i.active)return;const r=this.client.proposal.getAll().find(n=>n.pairingTopic===i.topic);r&&this.onSessionProposeRequest({topic:i.topic,payload:Ct("wc_sessionPropose",Re(oe({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),k(this,"isValidConnect",async i=>{if(!Xe(i)){const{message:l}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(i)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=i;if(Ie(r)||await this.isValidPairingTopic(r),!s8(c,!0)){const{message:l}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(n&&!Ie(n)&&Ht(n)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(n,"requiredNamespaces")}if(s&&!Ie(s)&&Ht(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!Ie(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ie(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(n||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),k(this,"validateNamespaces",(i,r)=>{const n=n8(i,"connect()",r);if(n)throw new Error(n.message)}),k(this,"isValidApprove",async i=>{if(!Xe(i))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${i}`).message);const{id:r,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=i;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=Jo(n,"approve()");if(l)throw new Error(l.message);const u=dh(c.requiredNamespaces,n,"approve()");if(u)throw new Error(u.message);if(!be(s,!0)){const{message:h}=M("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(o&&!Ie(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ie(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(n));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),k(this,"isValidReject",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`reject() params: ${i}`);throw new Error(s)}const{id:r,reason:n}=i;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!a8(n)){const{message:s}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",i=>{if(!Xe(i)){const{message:l}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${i}`);throw new Error(l)}const{relay:r,controller:n,namespaces:s,expiry:o}=i;if(!Dg(r)){const{message:l}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=X_(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Jo(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(qt(o)){const{message:l}=M("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),k(this,"isValidUpdate",async i=>{if(!Xe(i)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${i}`);throw new Error(c)}const{topic:r,namespaces:n}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=Jo(n,"update()");if(o)throw new Error(o.message);const a=dh(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async i=>{if(!Xe(i)){const{message:n}=M("MISSING_OR_INVALID",`extend() params: ${i}`);throw new Error(n)}const{topic:r}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),k(this,"isValidRequest",async i=>{if(!Xe(i)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${i}`);throw new Error(c)}const{topic:r,request:n,chainId:s,expiry:o}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!fh(a,s)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!c8(n)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!h8(a,s,n.method)){const{message:c}=M("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),k(this,"isValidRespond",async i=>{var r;if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`respond() params: ${i}`);throw new Error(a)}const{topic:n,response:s}=i;try{await this.isValidSessionTopic(n)}catch(a){throw(r=i==null?void 0:i.response)!=null&&r.id&&this.cleanupAfterResponse(i),a}if(!l8(s)){const{message:a}=M("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==n){const{message:a}=M("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${n}`);throw new Error(a)}}),k(this,"isValidPing",async i=>{if(!Xe(i)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidEmit",async i=>{if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${i}`);throw new Error(a)}const{topic:r,event:n,chainId:s}=i;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!fh(o,s)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!u8(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!f8(o,s,n.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async i=>{if(!Xe(i)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidAuthenticate",i=>{const{chains:r,uri:n,domain:s,nonce:o}=i;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!be(n,!1))throw new Error("uri is required parameter");if(!be(s,!1))throw new Error("domain is required parameter");if(!be(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>ci(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ci(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),k(this,"getVerifyContext",async i=>{const{attestationId:r,hash:n,encryptedId:s,metadata:o,transportType:a}=i,c={verified:{verifyUrl:o.verifyUrl||gn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:n,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),k(this,"validateSessionProps",(i,r)=>{Object.values(i).forEach((n,s)=>{if(n==null){const{message:o}=M("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${n} for key ${Object.keys(i)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",i=>{const r=this.client.auth.requests.get(i);return typeof r=="object"?r:void 0}),k(this,"addToRecentlyDeleted",(i,r)=>{if(this.recentlyDeletedMap.set(i,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(o)}}}),k(this,"checkRecentlyDeleted",i=>{const r=this.recentlyDeletedMap.get(i);if(r){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${i}`);throw new Error(n)}}),k(this,"isLinkModeEnabled",(i,r)=>{var n,s,o,a,c,l,u,h,f;return!i||r!==he.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=i==null?void 0:i.redirect)==null?void 0:u.universal)!==void 0&&((h=i==null?void 0:i.redirect)==null?void 0:h.universal)!==""&&((f=i==null?void 0:i.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(i.redirect.universal)&&typeof(Y==null?void 0:Y.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(i,r)=>{var n;return this.isLinkModeEnabled(i,r)?(n=i==null?void 0:i.redirect)==null?void 0:n.universal:void 0}),k(this,"handleLinkModeMessage",({url:i})=>{if(!i||!i.includes("wc_ev")||!i.includes("topic"))return;const r=_u(i,"topic")||"",n=decodeURIComponent(_u(i,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:n,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var i;if(Fc()||ki()&&(i=this.client.metadata.redirect)!=null&&i.linkMode){const r=Y==null?void 0:Y.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await r.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),k(this,"getTVFApproveParams",i=>{try{const r=Sg(i.namespaces),n=j_(i.namespaces),s=L_(i.namespaces),o=i.sessionProperties,a=i.scopedProperties;return{approvedChains:r,approvedMethods:n,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}}),k(this,"getTVFParams",(i,r,n)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:i,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,n);c.txHashes=l,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),k(this,"isValidContractData",i=>{var r;if(!i)return!1;try{const n=(i==null?void 0:i.data)||((r=i==null?void 0:i[0])==null?void 0:r.data);if(!n.startsWith("0x"))return!1;const s=n.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),k(this,"extractTxHashesFromResult",(i,r)=>{var n;try{if(!r)return[];const s=i.method,o=MO[s];if(s==="sui_signTransaction")return[Dx(r.transactionBytes)];if(s==="near_signTransaction")return[Bu(r)];if(s==="near_signTransactions")return r.map(c=>Bu(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(n=r.tx_json)==null?void 0:n.hash];if(s==="polkadot_signTransaction")return[P8({transaction:i.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return It(r)?r.map(c=>Tu(c)):[Tu(r)];if(s==="cosmos_signDirect")return[Ax(r)];if(s==="wallet_sendCalls")return Px(r);if(typeof r=="string")return[r];const a=r[o.key];if(It(a))return s==="solana_signAllTransactions"?a.map(c=>$x(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,i=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,n]of Object.entries(i))for(const s of n)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(me.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:i,message:r,attestation:n,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ws)?this.client.auth.authKeys.get(ws):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(i,r,{receiverPublicKey:o,encoding:s===he.link_mode?Bi:tt});Gc(a)?(this.client.core.history.set(i,a),await this.onRelayEventRequest({topic:i,payload:a,attestation:n,transportType:s,encryptedId:bt(r)})):ao(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:i,payload:a,transportType:s}),this.client.core.history.delete(i,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:i,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(i,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(wt.expired,async e=>{const{topic:i,id:r}=$p(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,M("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,M("EXPIRED"),!0);i?this.client.session.keys.includes(i)&&(await this.deleteSession({topic:i,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:i})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(Yi.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Yi.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!be(e,!1)){const{message:i}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(i)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(i)}if(qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:i}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(i)}}async isValidSessionTopic(e){if(!be(e,!1)){const{message:i}=M("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(i)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(i)}if(qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:i}=M("EXPIRED",`session topic: ${e}`);throw new Error(i)}if(!this.client.core.crypto.keychain.has(e)){const{message:i}=M("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(i)}}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(be(e,!1)){const{message:i}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(i)}else{const{message:i}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(i)}}async isValidProposalId(e){if(!o8(e)){const{message:i}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(i)}if(!this.client.proposal.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(i)}if(qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:i}=M("EXPIRED",`proposal id: ${e}`);throw new Error(i)}}validateRequestExpiry(e){if(e&&!g8(e,sa)){const{message:i}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${sa.min} and ${sa.max}`);throw new Error(i)}}}class tA extends dr{constructor(e,i){super(e,i,kO,Zc),this.core=e,this.logger=i}}let iA=class extends dr{constructor(e,i){super(e,i,jO,Zc),this.core=e,this.logger=i}};class rA extends dr{constructor(e,i){super(e,i,qO,Zc,r=>r.id),this.core=e,this.logger=i}}class nA extends dr{constructor(e,i){super(e,i,KO,lo,()=>ws),this.core=e,this.logger=i}}class sA extends dr{constructor(e,i){super(e,i,WO,lo),this.core=e,this.logger=i}}class oA extends dr{constructor(e,i){super(e,i,GO,lo,r=>r.id),this.core=e,this.logger=i}}var aA=Object.defineProperty,cA=(t,e,i)=>e in t?aA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,oa=(t,e,i)=>cA(t,typeof e!="symbol"?e+"":e,i);class lA{constructor(e,i){this.core=e,this.logger=i,oa(this,"authKeys"),oa(this,"pairingTopics"),oa(this,"requests"),this.authKeys=new nA(this.core,this.logger),this.pairingTopics=new sA(this.core,this.logger),this.requests=new oA(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var uA=Object.defineProperty,hA=(t,e,i)=>e in t?uA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,te=(t,e,i)=>hA(t,typeof e!="symbol"?e+"":e,i);class Jc extends CS{constructor(e){super(e),te(this,"protocol",Qg),te(this,"version",e0),te(this,"name",na.name),te(this,"metadata"),te(this,"core"),te(this,"logger"),te(this,"events",new St.EventEmitter),te(this,"engine"),te(this,"session"),te(this,"proposal"),te(this,"pendingRequest"),te(this,"auth"),te(this,"signConfig"),te(this,"on",(r,n)=>this.events.on(r,n)),te(this,"once",(r,n)=>this.events.once(r,n)),te(this,"off",(r,n)=>this.events.off(r,n)),te(this,"removeListener",(r,n)=>this.events.removeListener(r,n)),te(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),te(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"update",async r=>{try{return await this.engine.update(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"request",async r=>{try{return await this.engine.request(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"find",r=>{try{return this.engine.find(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),te(this,"authenticate",async(r,n)=>{try{return await this.engine.authenticate(r,n)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(n){throw this.logger.error(n.message),n}}),this.name=(e==null?void 0:e.name)||na.name,this.metadata=b3(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const i=Kc({logger:(e==null?void 0:e.logger)||na.logger,name:this.name});this.logger=i,this.core=(e==null?void 0:e.core)||new UO(e),this.session=new iA(this.core,this.logger),this.proposal=new tA(this.core,this.logger),this.pendingRequest=new rA(this.core,this.logger),this.engine=new eA(this),this.auth=new lA(this.core,this.logger)}static async init(e){const i=new Jc(e);return await i.initialize(),i}get context(){return st(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")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const fA=Jc;var dA=Object.defineProperty,pA=Object.defineProperties,gA=Object.getOwnPropertyDescriptors,nf=Object.getOwnPropertySymbols,yA=Object.prototype.hasOwnProperty,wA=Object.prototype.propertyIsEnumerable,sf=(t,e,i)=>e in t?dA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,of=(t,e)=>{for(var i in e||(e={}))yA.call(e,i)&&sf(t,i,e[i]);if(nf)for(var i of nf(e))wA.call(e,i)&&sf(t,i,e[i]);return t},af=(t,e)=>pA(t,gA(e));const mA={Accept:"application/json","Content-Type":"application/json"},bA="POST",cf={headers:mA,method:bA},lf=10;let i0=class{constructor(e,i=!1){if(this.url=e,this.disableProviderPing=i,this.events=new St.EventEmitter,this.isAvailable=!1,this.registering=!1,!$h(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=i}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const i=ui(e),r=await(await ll(this.url,af(of({},cf),{body:i}))).json();this.onPayload({data:r})}catch(i){this.onError(e.id,i)}}async register(e=this.url){if(!$h(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const i=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=i||this.events.listenerCount("open")>=i)&&this.events.setMaxListeners(i+1),new Promise((r,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));r()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const i=ui({id:1,jsonrpc:"2.0",method:"test",params:[]});await ll(e,af(of({},cf),{body:i}))}this.onOpen()}catch(i){const r=this.parseError(i);throw this.events.emit("register_error",r),this.onClose(),r}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const i=typeof e.data=="string"?sr(e.data):e.data;this.events.emit("payload",i)}onError(e,i){const r=this.parseError(i),n=r.message||r.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,i=this.url){return Bg(e,i,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>lf&&this.events.setMaxListeners(lf)}};function Xc(t){return t==null||typeof t!="object"&&typeof t!="function"}function r0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function n0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const vA="[object RegExp]",s0="[object String]",o0="[object Number]",a0="[object Boolean]",c0="[object Arguments]",EA="[object Symbol]",xA="[object Date]",IA="[object Map]",_A="[object Set]",SA="[object Array]",$A="[object ArrayBuffer]",DA="[object Object]",OA="[object DataView]",AA="[object Uint8Array]",PA="[object Uint8ClampedArray]",CA="[object Uint16Array]",BA="[object Uint32Array]",TA="[object Int8Array]",RA="[object Int16Array]",FA="[object Int32Array]",NA="[object Float32Array]",UA="[object Float64Array]";function Qc(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function kA(t,e){return Or(t,void 0,t,new Map,e)}function Or(t,e,i,r=new Map,n=void 0){const s=n==null?void 0:n(t,e,i,r);if(s!=null)return s;if(Xc(t))return t;if(r.has(t))return r.get(t);if(Array.isArray(t)){const o=new Array(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Or(t[a],a,i,r,n);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;r.set(t,o);for(const[a,c]of t)o.set(a,Or(c,a,i,r,n));return o}if(t instanceof Set){const o=new Set;r.set(t,o);for(const a of t)o.add(Or(a,void 0,i,r,n));return o}if(typeof ie<"u"&&ie.isBuffer(t))return t.subarray();if(Qc(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Or(t[a],a,i,r,n);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return r.set(t,o),Zi(o,t,i,r,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return r.set(t,o),Zi(o,t,i,r,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return r.set(t,o),Zi(o,t,i,r,n),o}if(t instanceof Error){const o=new t.constructor;return r.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Zi(o,t,i,r,n),o}if(typeof t=="object"&&jA(t)){const o=Object.create(Object.getPrototypeOf(t));return r.set(t,o),Zi(o,t,i,r,n),o}return t}function Zi(t,e,i=t,r,n){const s=[...Object.keys(e),...r0(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Or(e[a],a,i,r,n))}}function jA(t){switch(n0(t)){case c0:case SA:case $A:case OA:case a0:case xA:case NA:case UA:case TA:case RA:case FA:case IA:case o0:case DA:case vA:case _A:case s0:case EA:case AA:case PA:case CA:case BA:return!0;default:return!1}}function LA(t,e){return kA(t,(i,r,n,s)=>{const o=e==null?void 0:e(i,r,n,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case o0:case s0:case a0:{const a=new t.constructor(t==null?void 0:t.valueOf());return Zi(a,t),a}case c0:{const a={};return Zi(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function uf(t){return LA(t)}function hf(t){return t!==null&&typeof t=="object"&&n0(t)==="[object Arguments]"}function ff(t){return typeof t=="object"&&t!==null}function MA(){}function qA(t){return Qc(t)}function zA(t){var i;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const r=t[Symbol.toStringTag];return r==null||!((i=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&i.writable)?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function VA(t){if(Xc(t))return t;if(Array.isArray(t)||Qc(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),i=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new i(t);if(t instanceof RegExp){const r=new i(t);return r.lastIndex=t.lastIndex,r}if(t instanceof DataView)return new i(t.buffer.slice(0));if(t instanceof Error){const r=new i(t.message);return r.stack=t.stack,r.name=t.name,r.cause=t.cause,r}if(typeof File<"u"&&t instanceof File)return new i([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const r=Object.create(e);return Object.assign(r,t)}return t}function HA(t,...e){const i=e.slice(0,-1),r=e[e.length-1];let n=t;for(let s=0;s<i.length;s++){const o=i[s];n=sc(n,o,r,new Map)}return n}function sc(t,e,i,r){if(Xc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(r.has(e))return VA(r.get(e));if(r.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const n=[...Object.keys(e),...r0(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(hf(a)&&(a={...a}),hf(c)&&(c={...c}),typeof ie<"u"&&ie.isBuffer(a)&&(a=uf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const d=h[f];u[d]=c[d]}c=u}else c=[];const l=i(c,a,o,t,e,r);l!=null?t[o]=l:Array.isArray(a)||ff(c)&&ff(a)?t[o]=sc(c,a,i,r):c==null&&zA(a)?t[o]=sc({},a,i,r):c==null&&qA(a)?t[o]=uf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function KA(t,...e){return HA(t,...e,MA)}const df="error",WA="wss://relay.walletconnect.org",GA="wc",l0="universal_provider",ss=`${GA}@2:${l0}:`,u0="https://rpc.walletconnect.org/v1/",h0="generic",YA=`${u0}bundler`,Tr="call_status",ZA=86400,el={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var JA=Object.defineProperty,XA=Object.defineProperties,QA=Object.getOwnPropertyDescriptors,pf=Object.getOwnPropertySymbols,e4=Object.prototype.hasOwnProperty,t4=Object.prototype.propertyIsEnumerable,gf=(t,e,i)=>e in t?JA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,os=(t,e)=>{for(var i in e||(e={}))e4.call(e,i)&&gf(t,i,e[i]);if(pf)for(var i of pf(e))t4.call(e,i)&&gf(t,i,e[i]);return t},i4=(t,e)=>XA(t,QA(e));function f0(t,e,i){var r;const n=ci(t);return((r=e.rpcMap)==null?void 0:r[n.reference])||`${u0}?chainId=${n.namespace}:${n.reference}&projectId=${i}`}function r4(t){return t.includes(":")?t.split(":")[1]:t}function d0(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function n4(t,e){const i=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!i.length)return[];const r=[];return i.forEach(n=>{const s=e.namespaces[n].accounts;r.push(...s)}),r}function yf(t){return Object.fromEntries(Object.entries(t).filter(([e,i])=>{var r,n;return((r=i==null?void 0:i.chains)==null?void 0:r.length)&&((n=i==null?void 0:i.chains)==null?void 0:n.length)>0}))}function as(t={},e={}){const i=yf(wf(t)),r=yf(wf(e));return KA(i,r)}function wf(t){var e,i,r,n,s;const o={};if(!Ht(t))return o;for(const[a,c]of Object.entries(t)){const l=so(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],f=c.rpcMap||{},d=Dr(a);o[d]=i4(os(os({},o[d]),c),{chains:Vt(l,(e=o[d])==null?void 0:e.chains),methods:Vt(u,(i=o[d])==null?void 0:i.methods),events:Vt(h,(r=o[d])==null?void 0:r.events)}),(Ht(f)||Ht(((n=o[d])==null?void 0:n.rpcMap)||{}))&&(o[d].rpcMap=os(os({},f),(s=o[d])==null?void 0:s.rpcMap))}return o}function mf(t){return t.includes(":")?t.split(":")[2]:t}function bf(t){const e={};for(const[i,r]of Object.entries(t)){const n=r.methods||[],s=r.events||[],o=r.accounts||[],a=so(i)?[i]:r.chains?r.chains:d0(r.accounts);e[i]={chains:a,methods:n,events:s,accounts:o}}return e}function aa(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function s4(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const p0={},Rr=t=>p0[t],ca=(t,e)=>{p0[t]=e};var o4=Object.defineProperty,vf=Object.getOwnPropertySymbols,a4=Object.prototype.hasOwnProperty,c4=Object.prototype.propertyIsEnumerable,Ef=(t,e,i)=>e in t?o4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xf=(t,e)=>{for(var i in e||(e={}))a4.call(e,i)&&Ef(t,i,e[i]);if(vf)for(var i of vf(e))c4.call(e,i)&&Ef(t,i,e[i]);return t};const If="eip155",l4=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],u4=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,la=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,_f=t=>Object.keys(t).filter(e=>l4.includes(e)).reduce((e,i)=>(e[i]=h4(t[i]),e),{}),h4=t=>typeof t=="string"&&s4(t)?JSON.parse(t):t,f4=(t,e,i)=>{const{sessionProperties:r={},scopedProperties:n={}}=t,s={};if(!Ht(n)&&!Ht(r))return;const o=_f(r);for(const a of i){const c=u4(a);if(!c)continue;s[la(c)]=o;const l=n==null?void 0:n[`${If}:${c}`];if(l){const u=l==null?void 0:l[`${If}:${c}:${e}`];s[la(c)]=xf(xf({},s[la(c)]),_f(u||l))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var d4=Object.defineProperty,p4=(t,e,i)=>e in t?d4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,g4=(t,e,i)=>p4(t,typeof e!="symbol"?e+"":e,i);let ua,y4=class g0{constructor(e){g4(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,i){return await this.storage.setItem(e,i)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return ua||(ua=new g0(e)),ua}};var w4=Object.defineProperty,m4=Object.defineProperties,b4=Object.getOwnPropertyDescriptors,Sf=Object.getOwnPropertySymbols,v4=Object.prototype.hasOwnProperty,E4=Object.prototype.propertyIsEnumerable,$f=(t,e,i)=>e in t?w4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,x4=(t,e)=>{for(var i in e||(e={}))v4.call(e,i)&&$f(t,i,e[i]);if(Sf)for(var i of Sf(e))E4.call(e,i)&&$f(t,i,e[i]);return t},I4=(t,e)=>m4(t,b4(e));async function _4(t,e){const i=ci(t.result.capabilities.caip345.caip2),r=t.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(r.map(h=>S4(i.reference,h,e))),s=n.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);n.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!s.length||s.some(h=>!h),a=s.every(h=>(h==null?void 0:h.status)==="0x1"),c=s.every(h=>(h==null?void 0:h.status)==="0x0"),l=s.some(h=>(h==null?void 0:h.status)==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:s,status:u}}async function S4(t,e,i){return await i(parseInt(t)).request(Ct("eth_getTransactionReceipt",[e]))}async function $4({sendCalls:t,storage:e}){const i=await e.getItem(Tr);await e.setItem(Tr,I4(x4({},i),{[t.result.id]:{request:t.request,result:t.result,expiry:we(ZA)}}))}async function D4({resultId:t,storage:e}){const i=await e.getItem(Tr);if(i){delete i[t],await e.setItem(Tr,i);for(const r in i)qt(i[r].expiry)&&delete i[r];await e.setItem(Tr,i)}}async function O4({resultId:t,storage:e}){const i=await e.getItem(Tr),r=i==null?void 0:i[t];if(r&&!qt(r.expiry))return r;await D4({resultId:t,storage:e})}var A4=Object.defineProperty,P4=Object.defineProperties,C4=Object.getOwnPropertyDescriptors,Df=Object.getOwnPropertySymbols,B4=Object.prototype.hasOwnProperty,T4=Object.prototype.propertyIsEnumerable,oc=(t,e,i)=>e in t?A4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ha=(t,e)=>{for(var i in e||(e={}))B4.call(e,i)&&oc(t,i,e[i]);if(Df)for(var i of Df(e))T4.call(e,i)&&oc(t,i,e[i]);return t},fa=(t,e)=>P4(t,C4(e)),Hi=(t,e,i)=>oc(t,typeof e!="symbol"?e+"":e,i);class R4{constructor(e){Hi(this,"name","eip155"),Hi(this,"client"),Hi(this,"chainId"),Hi(this,"namespace"),Hi(this,"httpProviders"),Hi(this,"events"),Hi(this,"storage"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=y4.getStorage(this.client.core.storage)}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);case"wallet_sendCalls":return await this.sendCalls(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,i){this.httpProviders[e]||this.setHttpProvider(parseInt(e),i);const r=this.chainId;this.chainId=parseInt(e),this.events.emit(el.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${r}`})}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,i){const r=i||f0(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Yc(new i0(r,Rr("disableProviderPing")))}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;const n=parseInt(r4(i));e[n]=this.createHttpProvider(n,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}getHttpProvider(e){const i=e||this.chainId;return this.httpProviders[i]||(this.httpProviders=fa(ha({},this.httpProviders),{[i]:this.createHttpProvider(i)}),this.httpProviders[i])}async handleSwitchChain(e){var i,r;let n=e.request.params?(i=e.request.params[0])==null?void 0:i.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. 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 i,r,n,s,o;const a=(r=(i=e.request)==null?void 0:i.params)==null?void 0:r[0],c=((s=(n=e.request)==null?void 0:n.params)==null?void 0:s[1])||[];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)||{},h=`${a}${c.join(",")}`,f=u==null?void 0:u[h];if(f)return f;let d;try{d=f4(l,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(d)return d;const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:fa(ha({},l.sessionProperties||{}),{capabilities:fa(ha({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var i,r,n;const s=this.client.session.get(e.topic),o=(i=s.sessionProperties)==null?void 0:i.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(r=s.sessionProperties)==null?void 0:r.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await O4({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(c)try{return await _4(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}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,i){var r;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct("eth_getUserOperationReceipt",[(r=i.request.params)==null?void 0:r[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,i){return`${YA}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${i}`}async sendCalls(e){var i,r,n;const s=await this.client.request(e),o=(i=e.request.params)==null?void 0:i[0],a=s==null?void 0:s.id,c=(s==null?void 0:s.capabilities)||{},l=(r=c==null?void 0:c.caip345)==null?void 0:r.caip2,u=(n=c==null?void 0:c.caip345)==null?void 0:n.transactionHashes;return!a||!l||!(u!=null&&u.length)||await $4({sendCalls:{request:o,result:s},storage:this.storage}),s}}var F4=Object.defineProperty,N4=(t,e,i)=>e in t?F4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ir=(t,e,i)=>N4(t,typeof e!="symbol"?e+"":e,i);class U4{constructor(e){Ir(this,"name",h0),Ir(this,"client"),Ir(this,"httpProviders"),Ir(this,"events"),Ir(this,"namespace"),Ir(this,"chainId"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),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,i){this.httpProviders[e]||this.setHttpProvider(e,i);const r=this.chainId;this.chainId=e,this.events.emit(el.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${r}`})}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]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return ci(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){var e,i;const r={};return(i=(e=this.namespace)==null?void 0:e.accounts)==null||i.forEach(n=>{var s,o;const a=ci(n),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];r[a.reference]=this.createHttpProvider(n,c)}),r}getHttpProvider(e){const i=ci(e).reference,r=this.httpProviders[i];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||f0(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Yc(new i0(r,Rr("disableProviderPing")))}}var k4=Object.defineProperty,j4=Object.defineProperties,L4=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,M4=Object.prototype.hasOwnProperty,q4=Object.prototype.propertyIsEnumerable,ac=(t,e,i)=>e in t?k4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,sn=(t,e)=>{for(var i in e||(e={}))M4.call(e,i)&&ac(t,i,e[i]);if(Of)for(var i of Of(e))q4.call(e,i)&&ac(t,i,e[i]);return t},cs=(t,e)=>j4(t,L4(e)),at=(t,e,i)=>ac(t,typeof e!="symbol"?e+"":e,i);class tl{constructor(e){at(this,"client"),at(this,"namespaces"),at(this,"optionalNamespaces"),at(this,"sessionProperties"),at(this,"scopedProperties"),at(this,"events",new lc),at(this,"rpcProviders",{}),at(this,"session"),at(this,"providerOpts"),at(this,"logger"),at(this,"uri"),at(this,"disableProviderPing",!1),at(this,"connectParams");var i,r;this.providerOpts=e,this.logger=Kc({logger:(i=e.logger)!=null?i:df,name:(r=this.providerOpts.name)!=null?r:l0}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const i=new tl(e);return await i.initialize(),i}async request(e,i,r){const[n,s]=this.validateChain(i);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:sn({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:r})}sendAsync(e,i,r,n){const s=new Date().getTime();this.request(e,r,n).then(o=>i(null,Sn(s,o))).catch(o=>i(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:fe("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,i){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:n}=await this.client.authenticate(e,i);r&&(this.uri=r,this.events.emit("display_uri",r));const s=await n();if(this.session=s.session,this.session){const o=bf(this.session.namespaces);this.namespaces=as(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}removeListener(e,i){this.events.removeListener(e,i)}off(e,i){this.events.off(e,i)}get isWalletConnect(){return!0}async pair(e){var i,r;const{uri:n,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(i=this.connectParams)==null?void 0:i.authentication,walletPay:(r=this.connectParams)==null?void 0:r.walletPay});n&&(this.uri=n,this.events.emit("display_uri",n));const o=await s();this.session=o;const a=bf(o.namespaces);return this.namespaces=as(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,i){try{if(!this.session)return;const[r,n]=this.validateChain(e);this.getProvider(r).setDefaultChain(n,i)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const i=this.client.pairing.getAll();if(!It(i))return;for(const r of i)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${i.length}`)}catch(i){this.logger.warn(i,"Failed to cleanup pending pairings")}}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,i;if(this.client=this.providerOpts.client||await fA.init({core:this.providerOpts.core,logger:this.providerOpts.logger||df,relayUrl:this.providerOpts.relayUrl||WA,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(r){throw this.logger.error(r,"Failed to get session"),new Error(`The provided session: ${(i=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:i.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[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(i=>Dr(i)))];ca("client",this.client),ca("events",this.events),ca("disableProviderPing",this.disableProviderPing),e.forEach(i=>{if(!this.session)return;const r=n4(i,this.session);if((r==null?void 0:r.length)===0)return;const n=d0(r),s=as(this.namespaces,this.optionalNamespaces),o=cs(sn({},s[i]),{accounts:r,chains:n});switch(i){case"eip155":this.rpcProviders[i]=new R4({namespace:o});break;default:this.rpcProviders[i]=new U4({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var i;const{topic:r}=e;r===((i=this.session)==null?void 0:i.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var i;const{params:r,topic:n}=e;if(n!==((i=this.session)==null?void 0:i.topic))return;const{event:s}=r;if(s.name==="accountsChanged"){const o=s.data;o&&It(o)&&this.events.emit("accountsChanged",o.map(mf))}else if(s.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=Dr(o),l=aa(o)!==aa(a)?`${c}:${aa(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:i})=>{var r,n;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:s}=i,o=(n=this.client)==null?void 0:n.session.get(e);this.session=cs(sn({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:i})}),this.client.on("session_delete",async e=>{var i;e.topic===((i=this.session)==null?void 0:i.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",cs(sn({},fe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(el.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(cs(sn({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[h0]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var i;this.getProvider(e).updateNamespace((i=this.session)==null?void 0:i.namespaces[e])})}setNamespaces(e){const{namespaces:i={},optionalNamespaces:r={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=as(i,r),this.sessionProperties=n,this.scopedProperties=s}validateChain(e){const[i,r]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[i,r];if(i&&!Object.keys(this.namespaces||{}).map(o=>Dr(o)).includes(i))throw new Error(`Namespace '${i}' is not configured. Please call connect() first with namespace config.`);if(i&&r)return[i,r];const n=Dr(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:i,internal:r=!1}){if(!this.namespaces)return;const[n,s]=this.validateChain(e);s&&(this.updateNamespaceChain(n,s),r?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:i})):this.getProvider(n).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:i,previousCaipChainId:r}){var n,s;try{if(r===i)return;const o=(s=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(mf);if(!It(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,i){if(!this.namespaces)return;const r=this.namespaces[e]?e:`${e}:${i}`,n={chains:[],methods:[],events:[],defaultChain:i};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=i):this.namespaces[r]=n}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,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,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,i){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${ss}/${e}${n}`,i)}async getFromStore(e){var i;const r=((i=this.session)==null?void 0:i.topic)||"";return await this.client.core.storage.getItem(`${ss}/${e}${r}`)}async deleteFromStore(e){var i;const r=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.removeItem(`${ss}/${e}${r}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const i=await this.client.core.storage.getKeys();for(const r of i)r.startsWith(ss)&&await this.client.core.storage.removeItem(r)}catch(i){this.logger.warn(i,"Failed to cleanup storage")}}}const z4=tl,V4="wc",H4="ethereum_provider",K4=`${V4}@2:${H4}:`,W4="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],y0=["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"],js=["chainChanged","accountsChanged"],w0=["chainChanged","accountsChanged","message","disconnect","connect"],G4=async()=>{const{createAppKit:t}=await O0(()=>import("./core-84b3ed1e.js").then(e=>e.bK),["assets/core-84b3ed1e.js","assets/index-fec77d48.js","assets/index-91d98a83.css"]);return t};var Y4=Object.defineProperty,Z4=Object.defineProperties,J4=Object.getOwnPropertyDescriptors,Af=Object.getOwnPropertySymbols,X4=Object.prototype.hasOwnProperty,Q4=Object.prototype.propertyIsEnumerable,cc=(t,e,i)=>e in t?Y4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Wi=(t,e)=>{for(var i in e||(e={}))X4.call(e,i)&&cc(t,i,e[i]);if(Af)for(var i of Af(e))Q4.call(e,i)&&cc(t,i,e[i]);return t},on=(t,e)=>Z4(t,J4(e)),ct=(t,e,i)=>cc(t,typeof e!="symbol"?e+"":e,i);function Ls(t){return Number(t[0].split(":")[1])}function ls(t){return`0x${t.toString(16)}`}function e5(t){const{chains:e,optionalChains:i,methods:r,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!It(e))throw new Error("Invalid chains");const c={chains:e,methods:r||ks,events:s||js,rpcMap:Wi({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},l=s==null?void 0:s.filter(d=>!js.includes(d)),u=r==null?void 0:r.filter(d=>!ks.includes(d));if(!i&&!o&&!n&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const h=(l==null?void 0:l.length)&&(u==null?void 0:u.length)||!i,f={chains:[...new Set(h?c.chains.concat(i||[]):i)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:y0))],events:[...new Set(c.events.concat(o!=null&&o.length?o:w0))],rpcMap:a};return{required:e.length?c:void 0,optional:i.length?f:void 0}}class uo{constructor(){ct(this,"events",new St.EventEmitter),ct(this,"namespace","eip155"),ct(this,"accounts",[]),ct(this,"signer"),ct(this,"chainId",1),ct(this,"modal"),ct(this,"rpc"),ct(this,"STORAGE_KEY",K4),ct(this,"on",(e,i)=>(this.events.on(e,i),this)),ct(this,"once",(e,i)=>(this.events.once(e,i),this)),ct(this,"removeListener",(e,i)=>(this.events.removeListener(e,i),this)),ct(this,"off",(e,i)=>(this.events.off(e,i),this)),ct(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const i=new uo;return await i.initialize(e),i}async request(e,i){return await this.signer.request(e,this.formatChainId(this.chainId),i)}sendAsync(e,i,r){this.signer.sendAsync(e,i,this.formatChainId(this.chainId),r)}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 i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=e5(this.rpc);try{const s=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(on(Wi({namespaces:Wi({},r&&{[this.namespace]:r})},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!s)return;const o=bu(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async authenticate(e,i){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const n=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(on(Wi({},e),{chains:this.rpc.chains}),i).then(u=>{o(u)}).catch(u=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),s=n.session;if(s){const o=bu(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.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:i}=e,{event:r}=i;r.name==="accountsChanged"?(this.accounts=this.parseAccounts(r.data),this.events.emit("accountsChanged",this.accounts)):r.name==="chainChanged"?this.setChainId(this.formatChainId(r.data)):this.events.emit(r.name,r.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 i=parseInt(e);this.chainId=i,this.events.emit("chainChanged",ls(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",on(Wi({},fe("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 i=e.filter(r=>this.isCompatibleChainId(r)).map(r=>this.parseChainId(r));i.length&&(this.chainId=i[0],this.events.emit("chainChanged",ls(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const i=this.parseChainId(e);this.chainId=i,this.switchEthereumChain(i)}}parseAccountId(e){const[i,r,n]=e.split(":");return{chainId:`${i}:${r}`,address:n}}setAccounts(e){this.accounts=e.filter(i=>this.parseChainId(this.parseAccountId(i).chainId)===this.chainId).map(i=>this.parseAccountId(i).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var i,r;const n=(i=e==null?void 0:e.chains)!=null?i:[],s=(r=e==null?void 0:e.optionalChains)!=null?r:[],o=n.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=n.length?(e==null?void 0:e.methods)||ks:[],c=n.length?(e==null?void 0:e.events)||js:[],l=(e==null?void 0:e.optionalMethods)||[],u=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),f=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:n==null?void 0:n.map(d=>this.formatChainId(d)),optionalChains:s.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,i){const r={};return e.forEach(n=>{r[n]=this.getRpcUrl(n,i)}),r}async initialize(e){var i;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await z4.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 r;try{const n=await G4(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return h5}),o=s(on(Wi({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");r=n(on(Wi({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((i=this.rpc.qrModalOptions)==null?void 0:i.enableMobileFullScreen)===!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:i,optionalChains:r,rpcMap:n}=e;i&&It(i)&&(this.rpc.chains=i.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)})),r&&It(r)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=r==null?void 0:r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)}))}getRpcUrl(e,i){var r;return((r=this.rpc.rpcMap)==null?void 0:r[e])||`${W4}?chainId=eip155:${e}&projectId=${i||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),i=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:i==null?void 0:i.accounts),this.setAccounts(i==null?void 0:i.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(i=>this.signer.logger.warn(i))}}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(i=>this.parseAccount(i))}}const t5=uo;var i5=Object.defineProperty,r5=Object.defineProperties,n5=Object.getOwnPropertyDescriptors,Pf=Object.getOwnPropertySymbols,s5=Object.prototype.hasOwnProperty,o5=Object.prototype.propertyIsEnumerable,Cf=(t,e,i)=>e in t?i5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,m0=(t,e)=>{for(var i in e||(e={}))s5.call(e,i)&&Cf(t,i,e[i]);if(Pf)for(var i of Pf(e))o5.call(e,i)&&Cf(t,i,e[i]);return t},a5=(t,e)=>r5(t,n5(e));function c5(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const l5=t=>{const[e,i]=t.split(":");return b0({id:i,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function u5(t){var e,i,r,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(l5).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),u={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:c5(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:a5(m0({},t.metadata),{name:((i=t.metadata)==null?void 0:i.name)||"WalletConnect",description:((r=t.metadata)==null?void 0:r.description)||"Connect to WalletConnect-compatible wallets",url:((n=t.metadata)==null?void 0:n.url)||"https://walletconnect.org",icons:((s=t.metadata)==null?void 0:s.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],f=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],d=h.filter(p=>!f.includes(p.id));d.length&&(u.customWallets=d)}return u}function b0(t){return m0({formatters:void 0,fees:void 0,serializers:void 0},t)}var h5=Object.freeze({__proto__:null,convertWCMToAppKitOptions:u5,defineChain:b0});const tP=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:t5,OPTIONAL_EVENTS:w0,OPTIONAL_METHODS:y0,REQUIRED_EVENTS:js,REQUIRED_METHODS:ks,default:uo},Symbol.toStringTag,{value:"Module"}));export{B8 as A,Yc as B,oE as C,i3 as D,QS as E,Gc as F,ao as G,Sn as H,ur as I,hr as J,Ct as K,l2 as L,Ri as M,oo as N,Mt as O,lu as P,Xd as Q,vt as R,Lt as S,i0 as T,tP as U,dt as X,Ep as Y,J8 as a,X8 as b,Ag as c,rs as d,Q8 as e,sr as f,bh as g,Ff as h,L as i,Et as j,tS as k,rr as l,uc as m,An as n,c1 as o,Qm as p,mm as q,Im as r,ui as s,nt as t,mE as u,U0 as v,Rf as w,fn as x,Aa as y,st as z};
|
|
26
|
+
Approved: ${f.toString()}`))}),o.forEach(h=>{r||(Xi(n[h].methods,s[h].methods)?Xi(n[h].events,s[h].events)||(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${h}`)):r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${h}`))}),r}function d8(t){const e={};return Object.keys(t).forEach(i=>{var r;i.includes(":")?e[i]=t[i]:(r=t[i].chains)==null||r.forEach(n=>{e[n]={methods:t[i].methods,events:t[i].events}})}),e}function ph(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function p8(t){const e={};return Object.keys(t).forEach(i=>{if(i.includes(":"))e[i]=t[i];else{const r=qr(t[i].accounts);r==null||r.forEach(n=>{e[n]={accounts:t[i].accounts.filter(s=>s.includes(`${n}:`)),methods:t[i].methods,events:t[i].events}})}}),e}function g8(t,e){return Hc(t,!1)&&t<=e.max&&t>=e.min}function gh(){const t=Bn();return new Promise(e=>{switch(t){case ft.browser:e(y8());break;case ft.reactNative:e(w8());break;case ft.node:e(m8());break;default:e(!0)}})}function y8(){return Mr()&&(navigator==null?void 0:navigator.onLine)}async function w8(){if(ki()&&typeof Y<"u"&&Y!=null&&Y.NetInfo){const t=await(Y==null?void 0:Y.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function m8(){return!0}function b8(t){switch(Bn()){case ft.browser:v8(t);break;case ft.reactNative:E8(t);break}}function v8(t){!ki()&&Mr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function E8(t){var e;ki()&&typeof Y<"u"&&Y!=null&&Y.NetInfo&&((e=Y)==null||e.NetInfo.addEventListener(i=>t(i==null?void 0:i.isConnected)))}function x8(){var t;return Mr()&&rr()?((t=rr())==null?void 0:t.visibilityState)==="visible":!0}const Xo={};class Qr{static get(e){return Xo[e]}static set(e,i){Xo[e]=i}static delete(e){delete Xo[e]}}function I8(t){const e=An.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function _8({publicKey:t,signature:e,payload:i}){var r;const n=Ka(i.method),s=128|parseInt(((r=i.version)==null?void 0:r.toString())||"4"),o=D8(i.address),a=i.era==="00"?new Uint8Array([0]):Ka(i.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(i.nonce,16),l=new Uint8Array([c&255,c>>8&255]),u=BigInt(`0x${$8(i.tip)}`),h=A8(u),f=new Uint8Array([0,...t,o,...e,...a,...l,...h,...n]),d=O8(f.length+1);return new Uint8Array([...d,s,...f])}function S8(t){const e=Ka(t),i=mE.blake2b(e,void 0,32);return"0x"+ie.from(i).toString("hex")}function Ka(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function $8(t){return t.startsWith("0x")?t.slice(2):t}function D8(t){const e=An.decode(t)[0];return e===42?0:e===60?2:1}function O8(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function A8(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function P8(t){const e=Uint8Array.from(ie.from(t.signature,"hex")),i=I8(t.transaction.address),r=_8({publicKey:i,signature:e,payload:t.transaction}),n=ie.from(r).toString("hex");return S8(n)}function Kc({logger:t,name:e}){const i=typeof t=="string"?Ep({opts:{level:t,name:e}}).logger:t;return i.level=typeof t=="string"?t:t.level,i}class ur{}let C8=class extends ur{constructor(e){super()}};const yh=L.FIVE_SECONDS,hr={pulse:"heartbeat_pulse"};let B8=class Og extends C8{constructor(e){super(e),this.events=new St.EventEmitter,this.interval=yh,this.interval=(e==null?void 0:e.interval)||yh}static async init(e){const i=new Og(e);return await i.init(),i}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),L.toMiliseconds(this.interval))}pulse(){this.events.emit(hr.pulse)}};const T8=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,R8=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,F8=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function N8(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){U8(t);return}return e}function U8(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function rs(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const i=t.trim();if(i.length<=9)switch(i.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!F8.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(T8.test(t)||R8.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,N8)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function k8(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function De(t,...e){try{return k8(t(...e))}catch(i){return Promise.reject(i)}}function j8(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function L8(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ps(t){if(j8(t))return String(t);if(L8(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ps(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Wa="base64:";function M8(t){return typeof t=="string"?t:Wa+V8(t)}function q8(t){return typeof t!="string"||!t.startsWith(Wa)?t:z8(t.slice(Wa.length))}function z8(t){return globalThis.Buffer?ie.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function V8(t){return globalThis.Buffer?ie.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Je(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function H8(...t){return Je(t.join(":"))}function ns(t){return t=Je(t),t?t+":":""}function K8(t,e){if(e===void 0)return!0;let i=0,r=t.indexOf(":");for(;r>-1;)i++,r=t.indexOf(":",r+1);return i<=e}function W8(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const G8="memory",Y8=()=>{const t=new Map;return{name:G8,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,i){t.set(e,i)},setItemRaw(e,i){t.set(e,i)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Z8(t={}){const e={mounts:{"":t.driver||Y8()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},i=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},r=(l,u)=>e.mountpoints.filter(h=>h.startsWith(l)||u&&l.startsWith(h)).map(h=>({relativeBase:l.length>h.length?l.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),n=(l,u)=>{if(e.watching){u=Je(u);for(const h of e.watchListeners)h(l,u)}},s=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await wh(e.mounts[l],n,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,h)=>{const f=new Map,d=p=>{let g=f.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},f.set(p.base,g)),g};for(const p of l){const g=typeof p=="string",w=Je(g?p:p.key),_=g?void 0:p.value,C=g||!p.options?u:{...u,...p.options},b=i(w);d(b).items.push({key:w,value:_,relativeKey:b.relativeKey,options:C})}return Promise.all([...f.values()].map(p=>h(p))).then(p=>p.flat())},c={hasItem(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=i(l);return De(f.hasItem,h,u)},getItem(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=i(l);return De(f.getItem,h,u).then(d=>rs(d))},getItems(l,u={}){return a(l,u,h=>h.driver.getItems?De(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),u).then(f=>f.map(d=>({key:H8(h.base,d.key),value:rs(d.value)}))):Promise.all(h.items.map(f=>De(h.driver.getItem,f.relativeKey,f.options).then(d=>({key:f.key,value:rs(d)})))))},getItemRaw(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=i(l);return f.getItemRaw?De(f.getItemRaw,h,u):De(f.getItem,h,u).then(d=>q8(d))},async setItem(l,u,h={}){if(u===void 0)return c.removeItem(l);l=Je(l);const{relativeKey:f,driver:d}=i(l);d.setItem&&(await De(d.setItem,f,ps(u),h),d.watch||n("update",l))},async setItems(l,u){await a(l,u,async h=>{if(h.driver.setItems)return De(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:ps(f.value),options:f.options})),u);h.driver.setItem&&await Promise.all(h.items.map(f=>De(h.driver.setItem,f.relativeKey,ps(f.value),f.options)))})},async setItemRaw(l,u,h={}){if(u===void 0)return c.removeItem(l,h);l=Je(l);const{relativeKey:f,driver:d}=i(l);if(d.setItemRaw)await De(d.setItemRaw,f,u,h);else if(d.setItem)await De(d.setItem,f,M8(u),h);else return;d.watch||n("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=Je(l);const{relativeKey:h,driver:f}=i(l);f.removeItem&&(await De(f.removeItem,h,u),(u.removeMeta||u.removeMata)&&await De(f.removeItem,h+"$",u),f.watch||n("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=Je(l);const{relativeKey:h,driver:f}=i(l),d=Object.create(null);if(f.getMeta&&Object.assign(d,await De(f.getMeta,h,u)),!u.nativeOnly){const p=await De(f.getItem,h+"$",u).then(g=>rs(g));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(d,p))}return d},setMeta(l,u,h={}){return this.setItem(l+"$",u,h)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){var w;l=ns(l);const h=r(l,!0);let f=[];const d=[];let p=!0;for(const _ of h){(w=_.driver.flags)!=null&&w.maxDepth||(p=!1);const C=await De(_.driver.getKeys,_.relativeBase,u);for(const b of C){const v=_.mountpoint+Je(b);f.some(O=>v.startsWith(O))||d.push(v)}f=[_.mountpoint,...f.filter(b=>!b.startsWith(_.mountpoint))]}const g=u.maxDepth!==void 0&&!p;return d.filter(_=>(!g||K8(_,u.maxDepth))&&W8(_,l))},async clear(l,u={}){l=ns(l),await Promise.all(r(l,!1).map(async h=>{if(h.driver.clear)return De(h.driver.clear,h.relativeBase,u);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",u);return Promise.all(f.map(d=>h.driver.removeItem(d,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>mh(l)))},async watch(l){return await s(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=ns(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[l]=u,e.watching&&Promise.resolve(wh(u,n,l)).then(h=>{e.unwatch[l]=h}).catch(console.error),c},async unmount(l,u=!0){var h,f;l=ns(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&((f=(h=e.unwatch)[l])==null||f.call(h),delete e.unwatch[l]),u&&await mh(e.mounts[l]),e.mountpoints=e.mountpoints.filter(d=>d!==l),delete e.mounts[l])},getMount(l=""){l=Je(l)+":";const u=i(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=Je(l),r(l,u.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,h={})=>c.setItem(l,u,h),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function wh(t,e,i){return t.watch?t.watch((r,n)=>e(r,i+n)):()=>{}}async function mh(t){typeof t.dispose=="function"&&await De(t.dispose)}function fr(t){return new Promise((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error)})}function Ag(t,e){let i;const r=()=>{if(i)return i;const n=indexedDB.open(t);return n.onupgradeneeded=()=>n.result.createObjectStore(e),i=fr(n),i.then(s=>{s.onclose=()=>i=void 0},()=>{}),i};return(n,s)=>r().then(o=>s(o.transaction(e,n).objectStore(e)))}let Qo;function Un(){return Qo||(Qo=Ag("keyval-store","keyval")),Qo}function bh(t,e=Un()){return e("readonly",i=>fr(i.get(t)))}function J8(t,e,i=Un()){return i("readwrite",r=>(r.put(e,t),fr(r.transaction)))}function X8(t,e=Un()){return e("readwrite",i=>(i.delete(t),fr(i.transaction)))}function Q8(t=Un()){return t("readwrite",e=>(e.clear(),fr(e.transaction)))}function eS(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},fr(t.transaction)}function tS(t=Un()){return t("readonly",e=>{if(e.getAllKeys)return fr(e.getAllKeys());const i=[];return eS(e,r=>i.push(r.key)).then(()=>i)})}const iS="idb-keyval";var rS=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",i=n=>e+n;let r;return t.dbName&&t.storeName&&(r=Ag(t.dbName,t.storeName)),{name:iS,options:t,async hasItem(n){return!(typeof await bh(i(n),r)>"u")},async getItem(n){return await bh(i(n),r)??null},setItem(n,s){return J8(i(n),s,r)},removeItem(n){return X8(i(n),r)},getKeys(){return tS(r)},clear(){return Q8(r)}}};const nS="WALLET_CONNECT_V2_INDEXED_DB",sS="keyvaluestorage";let oS=class{constructor(){this.indexedDb=Z8({driver:rS({dbName:nS,storeName:sS})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const i=await this.indexedDb.getItem(e);if(i!==null)return i}async setItem(e,i){await this.indexedDb.setItem(e,ui(i))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ea=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Y<"u"?Y:typeof self<"u"?self:{},gs={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(i){return this.hasOwnProperty(i)?String(this[i]):null},t.prototype.setItem=function(i,r){this[i]=String(r)},t.prototype.removeItem=function(i){delete this[i]},t.prototype.clear=function(){const i=this;Object.keys(i).forEach(function(r){i[r]=void 0,delete i[r]})},t.prototype.key=function(i){return i=i||0,Object.keys(this)[i]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ea<"u"&&ea.localStorage?gs.exports=ea.localStorage:typeof window<"u"&&window.localStorage?gs.exports=window.localStorage:gs.exports=new e})();function aS(t){var e;return[t[0],sr((e=t[1])!=null?e:"")]}let cS=class{constructor(){this.localStorage=gs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(aS)}async getItem(e){const i=this.localStorage.getItem(e);if(i!==null)return sr(i)}async setItem(e,i){this.localStorage.setItem(e,ui(i))}async removeItem(e){this.localStorage.removeItem(e)}};const lS="wc_storage_version",vh=1,uS=async(t,e,i)=>{const r=lS,n=await e.getItem(r);if(n&&n>=vh){i(e);return}const s=await t.getKeys();if(!s.length){i(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(r,vh),i(e),hS(t,o)},hS=async(t,e)=>{e.length&&e.forEach(async i=>{await t.removeItem(i)})};let fS=class{constructor(){this.initialized=!1,this.setInitialized=i=>{this.storage=i,this.initialized=!0};const e=new cS;this.storage=e;try{const i=new oS;uS(e,i,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,i){return await this.initialize(),this.storage.setItem(e,i)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const i=setInterval(()=>{this.initialized&&(clearInterval(i),e())},20)})}};var dS=Object.defineProperty,pS=(t,e,i)=>e in t?dS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Eh=(t,e,i)=>pS(t,typeof e!="symbol"?e+"":e,i);let gS=class extends ur{constructor(e){super(),this.opts=e,Eh(this,"protocol","wc"),Eh(this,"version",2)}};var yS=Object.defineProperty,wS=(t,e,i)=>e in t?yS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,mS=(t,e,i)=>wS(t,typeof e!="symbol"?e+"":e,i);let bS=class extends ur{constructor(e,i){super(),this.core=e,this.logger=i,mS(this,"records",new Map)}},vS=class{constructor(e,i){this.logger=e,this.core=i}},ES=class extends ur{constructor(e,i){super(),this.relayer=e,this.logger=i}},xS=class extends ur{constructor(e){super()}},IS=class{constructor(e,i,r,n){this.core=e,this.logger=i,this.name=r}},_S=class extends ur{constructor(e,i){super(),this.relayer=e,this.logger=i}},SS=class extends ur{constructor(e,i){super(),this.core=e,this.logger=i}},$S=class{constructor(e,i,r){this.core=e,this.logger=i,this.store=r}},DS=class{constructor(e,i){this.projectId=e,this.logger=i}},OS=class{constructor(e,i,r){this.core=e,this.logger=i,this.telemetryEnabled=r}};var AS=Object.defineProperty,PS=(t,e,i)=>e in t?AS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xh=(t,e,i)=>PS(t,typeof e!="symbol"?e+"":e,i);let CS=class{constructor(e){this.opts=e,xh(this,"protocol","wc"),xh(this,"version",2)}},BS=class{constructor(e){this.client=e}};const TS="PARSE_ERROR",RS="INVALID_REQUEST",FS="METHOD_NOT_FOUND",NS="INVALID_PARAMS",Pg="INTERNAL_ERROR",Wc="SERVER_ERROR",US=[-32700,-32600,-32601,-32602,-32603],pn={[TS]:{code:-32700,message:"Parse error"},[RS]:{code:-32600,message:"Invalid Request"},[FS]:{code:-32601,message:"Method not found"},[NS]:{code:-32602,message:"Invalid params"},[Pg]:{code:-32603,message:"Internal error"},[Wc]:{code:-32e3,message:"Server error"}},Cg=Wc;function kS(t){return US.includes(t)}function Ih(t){return Object.keys(pn).includes(t)?pn[t]:pn[Cg]}function jS(t){const e=Object.values(pn).find(i=>i.code===t);return e||pn[Cg]}function Bg(t,e,i){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${i} RPC url at ${e}`):t}var Tg={},Qt={},_h;function LS(){if(_h)return Qt;_h=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.isBrowserCryptoAvailable=Qt.getSubtleCrypto=Qt.getBrowerCrypto=void 0;function t(){return(pr===null||pr===void 0?void 0:pr.crypto)||(pr===null||pr===void 0?void 0:pr.msCrypto)||{}}Qt.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Qt.getSubtleCrypto=e;function i(){return!!t()&&!!e()}return Qt.isBrowserCryptoAvailable=i,Qt}var ei={},Sh;function MS(){if(Sh)return ei;Sh=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.isBrowser=ei.isNode=ei.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ei.isReactNative=t;function e(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}ei.isNode=e;function i(){return!t()&&!e()}return ei.isBrowser=i,ei}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=$n;e.__exportStar(LS(),t),e.__exportStar(MS(),t)})(Tg);function Lt(t=3){const e=Date.now()*Math.pow(10,t),i=Math.floor(Math.random()*Math.pow(10,t));return e+i}function Ri(t=6){return BigInt(Lt(t))}function Ct(t,e,i){return{id:i||Lt(),jsonrpc:"2.0",method:t,params:e}}function Sn(t,e){return{id:t,jsonrpc:"2.0",result:e}}function oo(t,e,i){return{id:t,jsonrpc:"2.0",error:qS(e,i)}}function qS(t,e){return typeof t>"u"?Ih(Pg):(typeof t=="string"&&(t=Object.assign(Object.assign({},Ih(Wc)),{message:t})),typeof e<"u"&&(t.data=e),kS(t.code)&&(t=jS(t.code)),t)}class zS{}class VS extends zS{constructor(){super()}}class HS extends VS{constructor(e){super()}}const KS="^https?:",WS="^wss?:";function GS(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Rg(t,e){const i=GS(t);return typeof i>"u"?!1:new RegExp(e).test(i)}function $h(t){return Rg(t,KS)}function Dh(t){return Rg(t,WS)}function YS(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Fg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Gc(t){return Fg(t)&&"method"in t}function ao(t){return Fg(t)&&(Mt(t)||vt(t))}function Mt(t){return"result"in t}function vt(t){return"error"in t}class Yc extends HS{constructor(e){super(e),this.events=new St.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async request(e,i){return this.requestStrict(Ct(e.method,e.params||[],e.id||Ri().toString()),i)}async requestStrict(e,i){return new Promise(async(r,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{vt(s)?n(s.error):r(s.result)});try{await this.connection.send(e,i)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ao(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const ZS=()=>typeof WebSocket<"u"?WebSocket:typeof Y<"u"&&typeof Y.WebSocket<"u"?Y.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),JS=()=>typeof WebSocket<"u"||typeof Y<"u"&&typeof Y.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Oh=t=>t.split("?")[0],Ah=10,XS=ZS();let QS=class{constructor(e){if(this.url=e,this.events=new St.EventEmitter,this.registering=!1,!Dh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,i)=>{if(typeof this.socket>"u"){i(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ui(e))}catch(i){this.onError(e.id,i)}}register(e=this.url){if(!Dh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const i=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=i||this.events.listenerCount("open")>=i)&&this.events.setMaxListeners(i+1),new Promise((r,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((i,r)=>{const n=Tg.isReactNative()?void 0:{rejectUnauthorized:!YS(e)},s=new XS(e,[],n);JS()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),i(s)}})}onOpen(e){e.onmessage=i=>this.onPayload(i),e.onclose=i=>this.onClose(i),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const i=typeof e.data=="string"?sr(e.data):e.data;this.events.emit("payload",i)}onError(e,i){const r=this.parseError(i),n=r.message||r.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,i=this.url){return Bg(e,Oh(i),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Ah&&this.events.setMaxListeners(Ah)}emitError(e){const i=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Oh(this.url)}`));return this.events.emit("register_error",i),i}};const Ng="wc",Ug=2,Us="core",Kt=`${Ng}@2:${Us}:`,e$={name:Us,logger:"error"},t$={database:":memory:"},i$="crypto",Ph="client_ed25519_seed",r$=L.ONE_DAY,n$="keychain",s$="0.3",o$="messages",a$="0.3",c$=L.SIX_HOURS,l$="publisher",kg="irn",u$="error",jg="wss://relay.walletconnect.org",h$="relayer",me={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"},f$="_subscription",gt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},d$=.1,Ga="2.23.0",he={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},p$="0.3",g$="WALLETCONNECT_CLIENT_ID",Ch="WALLETCONNECT_LINK_MODE_APPS",lt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},y$="subscription",w$="0.3",m$="pairing",b$="0.3",en={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Yi={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Dt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},v$="history",E$="0.3",x$="expirer",wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},I$="0.3",_$="verify-api",S$="https://verify.walletconnect.com",Lg="https://verify.walletconnect.org",gn=Lg,$$=`${gn}/v3`,D$=[S$,Lg],O$="echo",A$="https://echo.walletconnect.com",jt={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"},ii={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"},Ot={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",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},zi={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",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Vi={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"},tn={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"},P$=.1,C$="event-client",B$=86400,T$="https://pulse.walletconnect.org/batch";function R$(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(i[o]!==255)throw new TypeError(s+" is ambiguous");i[o]=n}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,_=0,C=p.length;_!==C&&p[_]===0;)_++,g++;for(var b=(C-_)*u+1>>>0,v=new Uint8Array(b);_!==C;){for(var O=p[_],P=0,T=b-1;(O!==0||P<w)&&T!==-1;T--,P++)O+=256*v[T]>>>0,v[T]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");w=P,_++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,_=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=i[p.charCodeAt(g)];if(v===255)return;for(var O=0,P=C-1;(v!==0||O<_)&&P!==-1;P--,O++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=O,g++}if(p[g]!==" "){for(var T=C-_;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var F$=R$,N$=F$;const Mg=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},U$=t=>new TextEncoder().encode(t),k$=t=>new TextDecoder().decode(t);class j${constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class L${constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}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 qg(this,e)}}class M${constructor(e){this.decoders=e}or(e){return qg(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const qg=(t,e)=>new M$({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class q${constructor(e,i,r,n){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=n,this.encoder=new j$(e,i,r),this.decoder=new L$(e,i,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const co=({name:t,prefix:e,encode:i,decode:r})=>new q$(t,e,i,r),kn=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:n}=N$(i,e);return co({prefix:t,name:e,encode:r,decode:s=>Mg(n(s))})},z$=(t,e,i,r)=>{const n={};for(let u=0;u<e.length;++u)n[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*i/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const h=n[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|h,a+=i,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},V$=(t,e,i)=>{const r=e[e.length-1]==="=",n=(1<<i)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,s+=e[n&a>>o];if(o&&(s+=e[n&a<<i-o]),r)for(;s.length*i&7;)s+="=";return s},Ue=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>co({prefix:e,name:t,encode(n){return V$(n,r,i)},decode(n){return z$(n,r,i,t)}}),H$=co({prefix:"\0",name:"identity",encode:t=>k$(t),decode:t=>U$(t)});var K$=Object.freeze({__proto__:null,identity:H$});const W$=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var G$=Object.freeze({__proto__:null,base2:W$});const Y$=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Z$=Object.freeze({__proto__:null,base8:Y$});const J$=kn({prefix:"9",name:"base10",alphabet:"0123456789"});var X$=Object.freeze({__proto__:null,base10:J$});const Q$=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),e6=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var t6=Object.freeze({__proto__:null,base16:Q$,base16upper:e6});const i6=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),r6=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),n6=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),s6=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),o6=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),a6=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),c6=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),l6=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),u6=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var h6=Object.freeze({__proto__:null,base32:i6,base32upper:r6,base32pad:n6,base32padupper:s6,base32hex:o6,base32hexupper:a6,base32hexpad:c6,base32hexpadupper:l6,base32z:u6});const f6=kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),d6=kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var p6=Object.freeze({__proto__:null,base36:f6,base36upper:d6});const g6=kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),y6=kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var w6=Object.freeze({__proto__:null,base58btc:g6,base58flickr:y6});const m6=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),b6=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),v6=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),E6=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var x6=Object.freeze({__proto__:null,base64:m6,base64pad:b6,base64url:v6,base64urlpad:E6});const zg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),I6=zg.reduce((t,e,i)=>(t[i]=e,t),[]),_6=zg.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function S6(t){return t.reduce((e,i)=>(e+=I6[i],e),"")}function $6(t){const e=[];for(const i of t){const r=_6[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const D6=co({prefix:"🚀",name:"base256emoji",encode:S6,decode:$6});var O6=Object.freeze({__proto__:null,base256emoji:D6}),A6=Vg,Bh=128,P6=127,C6=~P6,B6=Math.pow(2,31);function Vg(t,e,i){e=e||[],i=i||0;for(var r=i;t>=B6;)e[i++]=t&255|Bh,t/=128;for(;t&C6;)e[i++]=t&255|Bh,t>>>=7;return e[i]=t|0,Vg.bytes=i-r+1,e}var T6=Ya,R6=128,Th=127;function Ya(t,r){var i=0,r=r||0,n=0,s=r,o,a=t.length;do{if(s>=a)throw Ya.bytes=0,new RangeError("Could not decode varint");o=t[s++],i+=n<28?(o&Th)<<n:(o&Th)*Math.pow(2,n),n+=7}while(o>=R6);return Ya.bytes=s-r,i}var F6=Math.pow(2,7),N6=Math.pow(2,14),U6=Math.pow(2,21),k6=Math.pow(2,28),j6=Math.pow(2,35),L6=Math.pow(2,42),M6=Math.pow(2,49),q6=Math.pow(2,56),z6=Math.pow(2,63),V6=function(t){return t<F6?1:t<N6?2:t<U6?3:t<k6?4:t<j6?5:t<L6?6:t<M6?7:t<q6?8:t<z6?9:10},H6={encode:A6,decode:T6,encodingLength:V6},Hg=H6;const Rh=(t,e,i=0)=>(Hg.encode(t,e,i),e),Fh=t=>Hg.encodingLength(t),Za=(t,e)=>{const i=e.byteLength,r=Fh(t),n=r+Fh(i),s=new Uint8Array(n+i);return Rh(t,s,0),Rh(i,s,r),s.set(e,n),new K6(t,i,e,s)};class K6{constructor(e,i,r,n){this.code=e,this.size=i,this.digest=r,this.bytes=n}}const Kg=({name:t,code:e,encode:i})=>new W6(t,e,i);class W6{constructor(e,i,r){this.name=e,this.code=i,this.encode=r}digest(e){if(e instanceof Uint8Array){const i=this.encode(e);return i instanceof Uint8Array?Za(this.code,i):i.then(r=>Za(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Wg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),G6=Kg({name:"sha2-256",code:18,encode:Wg("SHA-256")}),Y6=Kg({name:"sha2-512",code:19,encode:Wg("SHA-512")});var Z6=Object.freeze({__proto__:null,sha256:G6,sha512:Y6});const Gg=0,J6="identity",Yg=Mg,X6=t=>Za(Gg,Yg(t)),Q6={code:Gg,name:J6,encode:Yg,digest:X6};var eD=Object.freeze({__proto__:null,identity:Q6});new TextEncoder,new TextDecoder;const Nh={...K$,...G$,...Z$,...X$,...t6,...h6,...p6,...w6,...x6,...O6};({...Z6,...eD});function Zg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function tD(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jg(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const Uh=Jg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ta=Jg("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=tD(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),iD={utf8:Uh,"utf-8":Uh,hex:Nh.base16,latin1:ta,ascii:ta,binary:ta,...Nh};function rD(t,e="utf8"){const i=iD[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zg(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}var nD=Object.defineProperty,sD=(t,e,i)=>e in t?nD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ut=(t,e,i)=>sD(t,typeof e!="symbol"?e+"":e,i);class oD{constructor(e,i){this.core=e,this.logger=i,Ut(this,"keychain",new Map),Ut(this,"name",n$),Ut(this,"version",s$),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Kt),Ut(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Ut(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Ut(this,"set",async(r,n)=>{this.isInitialized(),this.keychain.set(r,n),await this.persist()}),Ut(this,"get",r=>{this.isInitialized();const n=this.keychain.get(r);if(typeof n>"u"){const{message:s}=M("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return n}),Ut(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=dt(i,this.name)}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ta(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ra(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var aD=Object.defineProperty,cD=(t,e,i)=>e in t?aD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Se=(t,e,i)=>cD(t,typeof e!="symbol"?e+"":e,i);class lD{constructor(e,i,r){this.core=e,this.logger=i,Se(this,"name",i$),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Ha()),Se(this,"initialized",!1),Se(this,"clientId"),Se(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Se(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),Se(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const n=await this.getClientSeed(),s=lu(n),o=Xd(s.publicKey);return this.clientId=o,o}),Se(this,"generateKeyPair",()=>{this.isInitialized();const n=d_();return this.setPrivateKey(n.publicKey,n.privateKey)}),Se(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=lu(s),a=this.randomSessionIdentifier;return await l2(a,n,r$,o)}),Se(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=p_(a,s);return this.setSymKey(c,o)}),Se(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||ds(n);return await this.keychain.set(o,n),o}),Se(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"encode",async(n,s,o)=>{this.isInitialized();const a=_g(o),c=ui(s);if(ih(a))return w_(c,o==null?void 0:o.encoding);if(th(a)){const f=a.senderPublicKey,d=a.receiverPublicKey;n=await this.generateSharedKey(f,d)}const l=this.getSymKey(n),{type:u,senderPublicKey:h}=a;return g_({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),Se(this,"decode",async(n,s,o)=>{this.isInitialized();const a=b_(s,o);if(ih(a)){const c=m_(s,o==null?void 0:o.encoding);return sr(c)}if(th(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=y_({symKey:c,encoded:s,encoding:o==null?void 0:o.encoding});return sr(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Se(this,"getPayloadType",(n,s=tt)=>{const o=_n({encoded:n,encoding:s});return ar(o.type)}),Se(this,"getPayloadSenderPublicKey",(n,s=tt)=>{const o=_n({encoded:n,encoding:s});return o.senderPublicKey?nt(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=dt(i,this.name),this.keychain=r||new oD(this.core,this.logger)}get context(){return st(this.logger)}async setPrivateKey(e,i){return await this.keychain.set(e,i),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ph)}catch{e=Ha(),await this.keychain.set(Ph,e)}return rD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var uD=Object.defineProperty,hD=Object.defineProperties,fD=Object.getOwnPropertyDescriptors,kh=Object.getOwnPropertySymbols,dD=Object.prototype.hasOwnProperty,pD=Object.prototype.propertyIsEnumerable,Ja=(t,e,i)=>e in t?uD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,gD=(t,e)=>{for(var i in e||(e={}))dD.call(e,i)&&Ja(t,i,e[i]);if(kh)for(var i of kh(e))pD.call(e,i)&&Ja(t,i,e[i]);return t},yD=(t,e)=>hD(t,fD(e)),ot=(t,e,i)=>Ja(t,typeof e!="symbol"?e+"":e,i);class wD extends vS{constructor(e,i){super(e,i),this.logger=e,this.core=i,ot(this,"messages",new Map),ot(this,"messagesWithoutClientAck",new Map),ot(this,"name",o$),ot(this,"version",a$),ot(this,"initialized",!1),ot(this,"storagePrefix",Kt),ot(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const n=await this.getRelayerMessagesWithoutClientAck();typeof n<"u"&&(this.messagesWithoutClientAck=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),ot(this,"set",async(r,n,s)=>{this.isInitialized();const o=bt(n);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(r,a),s===ys.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,yD(gD({},c),{[o]:n}))}return await this.persist(),o}),ot(this,"get",r=>{this.isInitialized();let n=this.messages.get(r);return typeof n>"u"&&(n={}),n}),ot(this,"getWithoutAck",r=>{this.isInitialized();const n={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),ot(this,"has",(r,n)=>{this.isInitialized();const s=this.get(r),o=bt(n);return typeof s[o]<"u"}),ot(this,"ack",async(r,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=bt(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),ot(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=dt(e,this.name),this.core=i}get context(){return st(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,Ta(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ta(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ra(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Ra(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var mD=Object.defineProperty,bD=Object.defineProperties,vD=Object.getOwnPropertyDescriptors,jh=Object.getOwnPropertySymbols,ED=Object.prototype.hasOwnProperty,xD=Object.prototype.propertyIsEnumerable,Xa=(t,e,i)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,vr=(t,e)=>{for(var i in e||(e={}))ED.call(e,i)&&Xa(t,i,e[i]);if(jh)for(var i of jh(e))xD.call(e,i)&&Xa(t,i,e[i]);return t},Lh=(t,e)=>bD(t,vD(e)),yt=(t,e,i)=>Xa(t,typeof e!="symbol"?e+"":e,i);class ID extends ES{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,yt(this,"events",new St.EventEmitter),yt(this,"name",l$),yt(this,"queue",new Map),yt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),yt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),yt(this,"needsTransportRestart",!1),yt(this,"publish",async(r,n,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:n,opts:s}});const h=(s==null?void 0:s.ttl)||c$,f=(s==null?void 0:s.prompt)||!1,d=(s==null?void 0:s.tag)||0,p=(s==null?void 0:s.id)||Ri().toString(),g=$r(Fs().protocol),w={id:p,method:(s==null?void 0:s.publishMethod)||g.publish,params:vr({topic:r,message:n,ttl:h,prompt:f,tag:d,attestation:s==null?void 0:s.attestation},s==null?void 0:s.tvf)},_=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{Ie((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),Ie((c=w.params)==null?void 0:c.tag)&&((l=w.params)==null||delete l.tag);const C=new Promise(async b=>{const v=({id:P})=>{var T;((T=w.id)==null?void 0:T.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(me.publish,v),b())};this.relayer.events.on(me.publish,v);const O=zt(new Promise((P,T)=>{this.rpcPublish(w,s).then(P).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),T(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${d}`);try{await O,this.events.removeListener(me.publish,v)}catch(P){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(P,P==null?void 0:P.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:n,opts:s}}),await zt(C,this.publishTimeout,_)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(u=s==null?void 0:s.internal)!=null&&u.throwOnFailedPublish)throw C}finally{this.queue.delete(p)}}),yt(this,"publishCustom",async r=>{var n,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:l,opts:u={}}=r,{attestation:h,tvf:f,publishMethod:d,prompt:p,tag:g,ttl:w=L.FIVE_MINUTES}=u,_=u.id||Ri().toString(),C=$r(Fs().protocol),b=d||C.publish,v={id:_,method:b,params:vr(Lh(vr({},l),{ttl:w,prompt:p,tag:g,attestation:h}),f)},O=`Failed to publish custom payload, please try again. id:${_} tag:${g}`;try{Ie((n=v.params)==null?void 0:n.prompt)&&((s=v.params)==null||delete s.prompt),Ie((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const P=new Promise(async T=>{const R=({id:U})=>{var j;((j=v.id)==null?void 0:j.toString())===U.toString()&&(this.removeRequestFromQueue(U),this.relayer.events.removeListener(me.publish,R),T())};this.relayer.events.on(me.publish,R);const A=zt(new Promise((U,j)=>{this.rpcPublish(v,u).then(U).catch(B=>{this.logger.warn(B,B==null?void 0:B.message),j(B)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${_} tag:${g}`);try{await A,this.events.removeListener(me.publish,R)}catch(U){this.queue.set(_,{request:v,opts:u,attempt:1}),this.logger.warn(U,U==null?void 0:U.message)}});this.logger.trace({type:"method",method:"publish",params:{id:_,payload:l,opts:u}}),await zt(P,this.publishTimeout,O)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=u==null?void 0:u.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(_)}}),yt(this,"on",(r,n)=>{this.events.on(r,n)}),yt(this,"once",(r,n)=>{this.events.once(r,n)}),yt(this,"off",(r,n)=>{this.events.off(r,n)}),yt(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),this.relayer=e,this.logger=dt(i,this.name),this.registerEventListeners()}get context(){return st(this.logger)}async rpcPublish(e,i){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(me.publish,vr(vr({},e),i)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,i)=>{var r;const n=e.attempt+1;this.queue.set(i,Lh(vr({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${n}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(hr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(me.connection_stalled);return}this.checkQueue()}),this.relayer.on(me.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var _D=Object.defineProperty,SD=(t,e,i)=>e in t?_D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Er=(t,e,i)=>SD(t,typeof e!="symbol"?e+"":e,i);class $D{constructor(){Er(this,"map",new Map),Er(this,"set",(e,i)=>{const r=this.get(e);this.exists(e,i)||this.map.set(e,[...r,i])}),Er(this,"get",e=>this.map.get(e)||[]),Er(this,"exists",(e,i)=>this.get(e).includes(i)),Er(this,"delete",(e,i)=>{if(typeof i>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,i))return;const n=r.filter(s=>s!==i);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),Er(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var DD=Object.defineProperty,OD=Object.defineProperties,AD=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,PD=Object.prototype.hasOwnProperty,CD=Object.prototype.propertyIsEnumerable,Qa=(t,e,i)=>e in t?DD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,rn=(t,e)=>{for(var i in e||(e={}))PD.call(e,i)&&Qa(t,i,e[i]);if(Mh)for(var i of Mh(e))CD.call(e,i)&&Qa(t,i,e[i]);return t},ia=(t,e)=>OD(t,AD(e)),ce=(t,e,i)=>Qa(t,typeof e!="symbol"?e+"":e,i);class BD extends _S{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,ce(this,"subscriptions",new Map),ce(this,"topicMap",new $D),ce(this,"events",new St.EventEmitter),ce(this,"name",y$),ce(this,"version",w$),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Kt),ce(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ce(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ce(this,"clientId"),ce(this,"batchSubscribeTopicsLimit",500),ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ce(this,"subscribe",async(r,n)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:n}});try{const o=Fs(n),a={topic:r,relay:o,transportType:n==null?void 0:n.transportType};(s=n==null?void 0:n.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,n);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(r,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(r,n.id,n):await this.unsubscribeByTopic(r,n)}),ce(this,"isSubscribed",r=>new Promise(n=>{n(this.topicMap.topics.includes(r))})),ce(this,"isKnownTopic",r=>new Promise(n=>{n(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),ce(this,"on",(r,n)=>{this.events.on(r,n)}),ce(this,"once",(r,n)=>{this.events.once(r,n)}),ce(this,"off",(r,n)=>{this.events.off(r,n)}),ce(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),ce(this,"start",async()=>{await this.onConnect()}),ce(this,"stop",async()=>{await this.onDisconnect()}),ce(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ce(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(n=>{r.push(n)}),await this.batchSubscribe(r)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(hr.pulse,async()=>{await this.checkPending()}),this.events.on(lt.created,async r=>{const n=lt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:r}),await this.persist()}),this.events.on(lt.deleted,async r=>{const n=lt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:r}),await this.persist()})}),this.relayer=e,this.logger=dt(i,this.name),this.clientId=""}get context(){return st(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,i){let r=!1;try{r=this.getSubscription(e).topic===i}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,i){const r=this.topicMap.get(e);await Promise.all(r.map(async n=>await this.unsubscribeById(e,n,i)))}async unsubscribeById(e,i,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}});try{const n=Fs(r);await this.restartToComplete({topic:e,id:i,relay:n}),await this.rpcUnsubscribe(e,i,n);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,i,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,i,r){var n,s;const o=await this.getSubscriptionId(e);if((n=r==null?void 0:r.internal)!=null&&n.skipSubscribe)return o;(!r||(r==null?void 0:r.transportType)===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:i});const a={method:$r(i.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r==null?void 0:r.internal)==null?void 0:s.throwOnFailedPublish;try{if((r==null?void 0:r.transportType)===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},L.toMiliseconds(L.ONE_SECOND)),o;const l=new Promise(async h=>{const f=d=>{d.topic===e&&(this.events.removeListener(lt.created,f),h(d.id))};this.events.on(lt.created,f);try{const d=await zt(new Promise((p,g)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),g(w)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(lt.created,f),h(d)}catch{}}),u=await zt(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(me.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const i=e[0].relay,r={method:$r(i.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await zt(new Promise(n=>{this.relayer.request(r).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const i=e[0].relay,r={method:$r(i.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let n;try{n=await await zt(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}return n}rpcUnsubscribe(e,i,r){const n={method:$r(r.protocol).unsubscribe,params:{topic:e,id:i}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,i){this.setSubscription(e,ia(rn({},i),{id:e})),this.pending.delete(i.topic)}onBatchSubscribe(e){e.length&&e.forEach(i=>{this.setSubscription(i.id,rn({},i)),this.pending.delete(i.topic)})}async onUnsubscribe(e,i,r){this.events.removeAllListeners(i),this.hasSubscription(i,e)&&this.deleteSubscription(i,r),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,i){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:i}),this.addSubscription(e,i)}addSubscription(e,i){this.subscriptions.set(e,rn({},i)),this.topicMap.set(i.topic,e),this.events.emit(lt.created,i)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const i=this.subscriptions.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}deleteSubscription(e,i){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:i});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(lt.deleted,ia(rn({},r),{reason:i}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(lt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],i=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<i;r++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(lt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(i=>{var r;return i.topic===((r=this.subscriptions.get(i.id))==null?void 0:r.topic)})){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(i)}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 i=>ia(rn({},i),{id:await this.getSubscriptionId(i.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const i=await this.rpcBatchFetchMessages(e);i&&i.messages&&(await B3(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(i.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=M("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 bt(e+await this.getClientId())}}var TD=Object.defineProperty,qh=Object.getOwnPropertySymbols,RD=Object.prototype.hasOwnProperty,FD=Object.prototype.propertyIsEnumerable,ec=(t,e,i)=>e in t?TD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,zh=(t,e)=>{for(var i in e||(e={}))RD.call(e,i)&&ec(t,i,e[i]);if(qh)for(var i of qh(e))FD.call(e,i)&&ec(t,i,e[i]);return t},ne=(t,e,i)=>ec(t,typeof e!="symbol"?e+"":e,i);class ND extends xS{constructor(e){var i;super(e),ne(this,"protocol","wc"),ne(this,"version",2),ne(this,"core"),ne(this,"logger"),ne(this,"events",new St.EventEmitter),ne(this,"provider"),ne(this,"messages"),ne(this,"subscriber"),ne(this,"publisher"),ne(this,"name",h$),ne(this,"transportExplicitlyClosed",!1),ne(this,"initialized",!1),ne(this,"connectionAttemptInProgress",!1),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"packageName"),ne(this,"bundleId"),ne(this,"hasExperiencedNetworkDisruption",!1),ne(this,"pingTimeout"),ne(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),ne(this,"reconnectTimeout"),ne(this,"connectPromise"),ne(this,"reconnectInProgress",!1),ne(this,"requestsInFlight",[]),ne(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"request",async r=>{var n,s;this.logger.debug("Publishing Request Payload");const o=r.id||Ri().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const a=`${o}:${((s=r.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),ne(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),ne(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(me.connect)}),ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ne(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(me.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ne(this,"registerProviderListeners",()=>{this.provider.on(gt.payload,this.onPayloadHandler),this.provider.on(gt.connect,this.onConnectHandler),this.provider.on(gt.disconnect,this.onDisconnectHandler),this.provider.on(gt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Kc({logger:(i=e.logger)!=null?i:u$,name:this.name}),this.messages=new wD(this.logger,e.core),this.subscriber=new BD(this,this.logger),this.publisher=new ID(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||jg,y3()?this.packageName=Iu():w3()&&(this.bundleId=Iu()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e==null?void 0:e.message))}get context(){return st(this.logger)}get connected(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,i,r){this.isInitialized(),await this.publisher.publish(e,i,r),await this.recordMessageEvent({topic:e,message:i,publishedAt:Date.now(),transportType:he.relay},ys.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,i){var r,n,s;this.isInitialized(),(!(i!=null&&i.transportType)||(i==null?void 0:i.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(n=i==null?void 0:i.internal)==null?void 0:n.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(lt.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(lt.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,zh({internal:{throwOnFailedPublish:o}},i)).catch(f=>{o&&h(f)})||a,u()})]),a}async unsubscribe(e,i){this.isInitialized(),await this.subscriber.unsubscribe(e,i)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await zt(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.info("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(i,r)=>{await this.connect(e).then(i).catch(r).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 gh())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 i=e.sort((r,n)=>r.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${i.length} message events sorted`);for(const r of i)try{await this.onMessageEvent(r)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${i.length} message events processed`)}async onLinkMessageEvent(e,i){const{topic:r}=e;if(!i.sessionExists){const n=we(L.FIVE_MINUTES),s={topic:r,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(me.message,e),await this.recordMessageEvent(e,ys.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let i=1;for(;i<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${i}...`),await this.createProvider(),await new Promise(async(r,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(gt.disconnect,s),await zt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}).finally(()=>{this.provider.off(gt.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(gt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(gt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const n=r;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${i}`);break}await new Promise(r=>setTimeout(r,L.toMiliseconds(i*1))),i++}}startPingTimeout(){var e,i,r,n,s;if(As())try{(i=(e=this.provider)==null?void 0:e.connection)!=null&&i.socket&&((s=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||s.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 Yc(new QS(x3({sdkVersion:Ga,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,i){const{topic:r,message:n}=e;await this.messages.set(r,n,i)}async shouldIgnoreMessageEvent(e){const{topic:i,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(i))return this.logger.warn(`Ignoring message for unknown topic ${i}`),!0;const n=this.messages.has(i,r);return n&&this.logger.warn(`Ignoring duplicate message: ${r}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Gc(e)){if(!e.method.endsWith(f$))return;const i=e.params,{topic:r,message:n,publishedAt:s,attestation:o}=i.data,a={topic:r,message:n,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(zh({type:"event",event:i.id},a)),this.events.emit(i.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ao(e)&&this.events.emit(me.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ys.inbound),this.events.emit(me.message,e))}async acknowledgePayload(e){const i=Sn(e.id,!0);await this.provider.connection.send(i)}unregisterProviderListeners(){this.provider.off(gt.payload,this.onPayloadHandler),this.provider.off(gt.connect,this.onConnectHandler),this.provider.off(gt.disconnect,this.onDisconnectHandler),this.provider.off(gt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await gh();b8(async i=>{e!==i&&(e=i,i?await this.transportOpen().catch(r=>this.logger.error(r,r==null?void 0:r.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(hr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&x8())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(i){this.logger.warn(i,i==null?void 0:i.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(me.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},L.toMiliseconds(d$)))))}isInitialized(){if(!this.initialized){const{message:e}=M("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 UD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Vh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Hh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const kD="[object RegExp]",jD="[object String]",LD="[object Number]",MD="[object Boolean]",Kh="[object Arguments]",qD="[object Symbol]",zD="[object Date]",VD="[object Map]",HD="[object Set]",KD="[object Array]",WD="[object Function]",GD="[object ArrayBuffer]",ra="[object Object]",YD="[object Error]",ZD="[object DataView]",JD="[object Uint8Array]",XD="[object Uint8ClampedArray]",QD="[object Uint16Array]",eO="[object Uint32Array]",tO="[object BigUint64Array]",iO="[object Int8Array]",rO="[object Int16Array]",nO="[object Int32Array]",sO="[object BigInt64Array]",oO="[object Float32Array]",aO="[object Float64Array]";function cO(){}function Wh(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function lO(t,e,i){return un(t,e,void 0,void 0,void 0,void 0,i)}function un(t,e,i,r,n,s,o){const a=o(t,e,i,r,n,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return yn(t,e,s,o)}return yn(t,e,s,o)}function yn(t,e,i,r){if(Object.is(t,e))return!0;let n=Hh(t),s=Hh(e);if(n===Kh&&(n=ra),s===Kh&&(s=ra),n!==s)return!1;switch(n){case jD:return t.toString()===e.toString();case LD:{const c=t.valueOf(),l=e.valueOf();return UD(c,l)}case MD:case zD:case qD:return Object.is(t.valueOf(),e.valueOf());case kD:return t.source===e.source&&t.flags===e.flags;case WD:return t===e}i=i??new Map;const o=i.get(t),a=i.get(e);if(o!=null&&a!=null)return o===e;i.set(t,e),i.set(e,t);try{switch(n){case VD:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!un(l,e.get(c),c,t,e,i,r))return!1;return!0}case HD:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],f=l.findIndex(d=>un(h,d,void 0,t,e,i,r));if(f===-1)return!1;l.splice(f,1)}return!0}case KD:case JD:case XD:case QD:case eO:case tO:case iO:case rO:case nO:case sO:case oO:case aO:{if(typeof ie<"u"&&ie.isBuffer(t)!==ie.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!un(t[c],e[c],c,t,e,i,r))return!1;return!0}case GD:return t.byteLength!==e.byteLength?!1:yn(new Uint8Array(t),new Uint8Array(e),i,r);case ZD:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:yn(new Uint8Array(t),new Uint8Array(e),i,r);case YD:return t.name===e.name&&t.message===e.message;case ra:{if(!(yn(t.constructor,e.constructor,i,r)||Wh(t)&&Wh(e)))return!1;const c=[...Object.keys(t),...Vh(t)],l=[...Object.keys(e),...Vh(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],f=t[h];if(!Object.hasOwn(e,h))return!1;const d=e[h];if(!un(f,d,h,t,e,i,r))return!1}return!0}default:return!1}}finally{i.delete(t),i.delete(e)}}function uO(t,e){return lO(t,e,cO)}var hO=Object.defineProperty,Gh=Object.getOwnPropertySymbols,fO=Object.prototype.hasOwnProperty,dO=Object.prototype.propertyIsEnumerable,tc=(t,e,i)=>e in t?hO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Yh=(t,e)=>{for(var i in e||(e={}))fO.call(e,i)&&tc(t,i,e[i]);if(Gh)for(var i of Gh(e))dO.call(e,i)&&tc(t,i,e[i]);return t},Ze=(t,e,i)=>tc(t,typeof e!="symbol"?e+"":e,i);class dr extends IS{constructor(e,i,r,n=Kt,s=void 0){super(e,i,r,n),this.core=e,this.logger=i,this.name=r,Ze(this,"map",new Map),Ze(this,"version",p$),Ze(this,"cached",[]),Ze(this,"initialized",!1),Ze(this,"getKey"),Ze(this,"storagePrefix",Kt),Ze(this,"recentlyDeleted",[]),Ze(this,"recentlyDeletedLimit",200),Ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ie(o)?this.map.set(this.getKey(o),o):Z_(o)?this.map.set(o.id,o):J_(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ze(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())}),Ze(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ze(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>uO(a[c],o[c]))):this.values)),Ze(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=Yh(Yh({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ze(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=dt(i,this.name),this.storagePrefix=n,this.getKey=s}get context(){return st(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 i=this.map.get(e);if(!i){if(this.recentlyDeleted.includes(e)){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return i}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:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var pO=Object.defineProperty,gO=(t,e,i)=>e in t?pO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ee=(t,e,i)=>gO(t,typeof e!="symbol"?e+"":e,i);class yO{constructor(e,i){this.core=e,this.logger=i,ee(this,"name",m$),ee(this,"version",b$),ee(this,"events",new lc),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",Kt),ee(this,"ignoredPayloadTypes",[li]),ee(this,"registeredMethods",[]),ee(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ee(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),ee(this,"create",async r=>{this.isInitialized();const n=Ha(),s=await this.core.crypto.setSymKey(n),o=we(L.FIVE_MINUTES),a={protocol:kg},c={topic:s,expiry:o,relay:a,active:!1,methods:r==null?void 0:r.methods},l=oh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:r==null?void 0:r.methods});return this.events.emit(Yi.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r==null?void 0:r.transportType,internal:r==null?void 0:r.internal}),{topic:s,uri:l}}),ee(this,"pair",async r=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:r==null?void 0:r.uri,trace:[jt.pairing_started]}});this.isValidPair(r,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=sh(r.uri);n.props.properties.topic=s,n.addTrace(jt.pairing_uri_validation_success),n.addTrace(jt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),n.addTrace(jt.existing_pairing),u.active)throw n.setError(ii.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(jt.pairing_not_expired)}const h=c||we(L.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(s,h),await this.pairings.set(s,f),n.addTrace(jt.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(Yi.create,f),n.addTrace(jt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(jt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(ii.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw n.setError(ii.subscribe_pairing_topic_failure),d}return n.addTrace(jt.subscribe_pairing_topic_success),f}),ee(this,"activate",async({topic:r})=>{this.isInitialized();const n=we(L.FIVE_MINUTES);this.core.expirer.set(r,n),await this.pairings.update(r,{active:!0,expiry:n})}),ee(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=r;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ki();this.events.once(ae("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),ee(this,"updateExpiry",async({topic:r,expiry:n})=>{this.isInitialized(),await this.pairings.update(r,{expiry:n})}),ee(this,"updateMetadata",async({topic:r,metadata:n})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:n})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(n))}),ee(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(n);return oh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(r,n,s)=>{const o=Ct(n,s),a=await this.core.crypto.encode(r,o),c=en[n].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),ee(this,"sendResult",async(r,n,s)=>{const o=Sn(r,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,r)).request.method,l=en[c].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),ee(this,"sendError",async(r,n,s)=>{const o=oo(r,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,r)).request.method,l=en[c]?en[c].res:en.unregistered_method.res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),ee(this,"deletePairing",async(r,n)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),n?Promise.resolve():this.core.expirer.del(r)])}),ee(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(n=>qt(n.expiry));await Promise.all(r.map(n=>this.deletePairing(n.topic)))}),ee(this,"onRelayEventRequest",async r=>{const{topic:n,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(n,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(n,s);default:return await this.onUnknownRpcMethodRequest(n,s)}}),ee(this,"onRelayEventResponse",async r=>{const{topic:n,payload:s}=r,o=(await this.core.history.get(n,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(o)}}),ee(this,"onPairingPingRequest",async(r,n)=>{const{id:s}=n;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(Yi.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(r,n)=>{const{id:s}=n;setTimeout(()=>{Mt(n)?this.events.emit(ae("pairing_ping",s),{}):vt(n)&&this.events.emit(ae("pairing_ping",s),{error:n.error})},500)}),ee(this,"onPairingDeleteRequest",async(r,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Yi.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(r,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),ee(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",r))}),ee(this,"isValidPair",(r,n)=>{var s;if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${r}`);throw n.setError(ii.malformed_pairing_uri),new Error(a)}if(!Y_(r.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw n.setError(ii.malformed_pairing_uri),new Error(a)}const o=sh(r==null?void 0:r.uri);if(!((s=o==null?void 0:o.relay)!=null&&s.protocol)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(ii.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(ii.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){n.setError(ii.pairing_expired);const{message:a}=M("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ee(this,"isValidPing",async r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:n}=r;await this.isValidPairingTopic(n)}),ee(this,"isValidDisconnect",async r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:n}=r;await this.isValidPairingTopic(n)}),ee(this,"isValidPairingTopic",async r=>{if(!be(r,!1)){const{message:n}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(n)}if(!this.pairings.keys.includes(r)){const{message:n}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(n)}if(qt(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:n}=M("EXPIRED",`pairing topic: ${r}`);throw new Error(n)}}),this.core=e,this.logger=dt(i,this.name),this.pairings=new dr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return st(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(me.message,async e=>{const{topic:i,message:r,transportType:n}=e;if(this.pairings.keys.includes(i)&&n!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(i,r);Gc(s)?(this.core.history.set(i,s),await this.onRelayEventRequest({topic:i,payload:s})):ao(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:i,payload:s}),this.core.history.delete(i,s.id)),await this.core.relayer.messages.ack(i,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(wt.expired,async e=>{const{topic:i}=$p(e.target);i&&this.pairings.keys.includes(i)&&(await this.deletePairing(i,!0),this.events.emit(Yi.expire,{topic:i}))})}}var wO=Object.defineProperty,mO=(t,e,i)=>e in t?wO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Be=(t,e,i)=>mO(t,typeof e!="symbol"?e+"":e,i);class bO extends bS{constructor(e,i){super(e,i),this.core=e,this.logger=i,Be(this,"records",new Map),Be(this,"events",new St.EventEmitter),Be(this,"name",v$),Be(this,"version",E$),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Kt),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Be(this,"set",(r,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:r,request:{method:n.method,params:n.params||null},chainId:s,expiry:we(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Dt.created,o)}),Be(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const n=await this.getRecord(r.id);typeof n.response>"u"&&(n.response=vt(r)?{error:r.error}:{result:r.result},this.records.set(n.id,n),this.persist(),this.events.emit(Dt.updated,n))}),Be(this,"get",async(r,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:n}),await this.getRecord(n))),Be(this,"delete",(r,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===r){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Dt.deleted,s)}}),this.persist()}),Be(this,"exists",async(r,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===r:!1)),Be(this,"on",(r,n)=>{this.events.on(r,n)}),Be(this,"once",(r,n)=>{this.events.once(r,n)}),Be(this,"off",(r,n)=>{this.events.off(r,n)}),Be(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),this.logger=dt(i,this.name)}get context(){return st(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(i=>{if(typeof i.response<"u")return;const r={topic:i.topic,request:Ct(i.request.method,i.request.params,i.id),chainId:i.chainId};return e.push(r)}),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 i=this.records.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Dt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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(Dt.created,e=>{const i=Dt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(Dt.updated,e=>{const i=Dt.updated;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(Dt.deleted,e=>{const i=Dt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.core.heartbeat.on(hr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(i=>{L.toMiliseconds(i.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${i.id}`),this.records.delete(i.id),this.events.emit(Dt.deleted,i,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var vO=Object.defineProperty,EO=(t,e,i)=>e in t?vO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ze=(t,e,i)=>EO(t,typeof e!="symbol"?e+"":e,i);class xO extends SS{constructor(e,i){super(e,i),this.core=e,this.logger=i,ze(this,"expirations",new Map),ze(this,"events",new St.EventEmitter),ze(this,"name",x$),ze(this,"version",I$),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Kt),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"has",r=>{try{const n=this.formatTarget(r);return typeof this.getExpiration(n)<"u"}catch{return!1}}),ze(this,"set",(r,n)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:n};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(wt.created,{target:s,expiration:o})}),ze(this,"get",r=>{this.isInitialized();const n=this.formatTarget(r);return this.getExpiration(n)}),ze(this,"del",r=>{if(this.isInitialized(),this.has(r)){const n=this.formatTarget(r),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(wt.deleted,{target:n,expiration:s})}}),ze(this,"on",(r,n)=>{this.events.on(r,n)}),ze(this,"once",(r,n)=>{this.events.once(r,n)}),ze(this,"off",(r,n)=>{this.events.off(r,n)}),ze(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),this.logger=dt(i,this.name)}get context(){return st(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 I3(e);if(typeof e=="number")return _3(e);const{message:i}=M("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(i)}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(wt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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 i=this.expirations.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return i}checkExpiry(e,i){const{expiry:r}=i;L.toMiliseconds(r)-Date.now()<=0&&this.expire(e,i)}expire(e,i){this.expirations.delete(e),this.events.emit(wt.expired,{target:e,expiration:i})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,i)=>this.checkExpiry(i,e))}registerEventListeners(){this.core.heartbeat.on(hr.pulse,()=>this.checkExpirations()),this.events.on(wt.created,e=>{const i=wt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(wt.expired,e=>{const i=wt.expired;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(wt.deleted,e=>{const i=wt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var IO=Object.defineProperty,_O=(t,e,i)=>e in t?IO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ye=(t,e,i)=>_O(t,typeof e!="symbol"?e+"":e,i);class SO extends $S{constructor(e,i,r){super(e,i,r),this.core=e,this.logger=i,this.store=r,ye(this,"name",_$),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",$$),ye(this,"storagePrefix",Kt),ye(this,"version",Ug),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async n=>{if(!Mr()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=rr(),u=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((f,d)=>{const p=()=>{window.removeEventListener("message",w),l.body.removeChild(g),d("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const w=_=>{if(_.data&&typeof _.data=="string")try{const C=JSON.parse(_.data);if(C.type==="verify_attestation"){if(Aa(C.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),f(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};l.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(l){this.logger.warn(l)}return""}),ye(this,"resolve",async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Aa(s).payload.id!==a)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(n==null?void 0:n.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(L.ONE_SECOND*5),a=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ye(this,"getVerifyUrl",n=>{let s=n||gn;return D$.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${gn}`),s=gn),s}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(L.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}}),ye(this,"persistPublicKey",async n=>{this.logger.debug(n,"persisting public key to local storage"),await this.store.setItem(this.storeKey,n),this.publicKey=n}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(this,"isValidJwtAttestation",async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n}),ye(this,"validateAttestation",(n,s)=>{const o=E_(n,s.publicKey),a={hasExpired:L.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=dt(i,this.name),this.abortController=new AbortController,this.isDevEnv=Fc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return st(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var $O=Object.defineProperty,DO=(t,e,i)=>e in t?$O(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Zh=(t,e,i)=>DO(t,typeof e!="symbol"?e+"":e,i);class OO extends DS{constructor(e,i){super(e,i),this.projectId=e,this.logger=i,Zh(this,"context",O$),Zh(this,"registerDeviceToken",async r=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${A$}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:s,always_raw:a})})}),this.logger=dt(i,this.context)}}var AO=Object.defineProperty,Jh=Object.getOwnPropertySymbols,PO=Object.prototype.hasOwnProperty,CO=Object.prototype.propertyIsEnumerable,ic=(t,e,i)=>e in t?AO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,nn=(t,e)=>{for(var i in e||(e={}))PO.call(e,i)&&ic(t,i,e[i]);if(Jh)for(var i of Jh(e))CO.call(e,i)&&ic(t,i,e[i]);return t},$e=(t,e,i)=>ic(t,typeof e!="symbol"?e+"":e,i);class BO extends OS{constructor(e,i,r=!0){super(e,i,r),this.core=e,this.logger=i,$e(this,"context",C$),$e(this,"storagePrefix",Kt),$e(this,"storageVersion",P$),$e(this,"events",new Map),$e(this,"shouldPersist",!1),$e(this,"init",async()=>{if(!Fc())try{const n={eventId:Su(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:_p(this.core.relayer.protocol,this.core.relayer.version,Ga)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),$e(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,l=Su(),u=this.core.projectId||"",h=Date.now(),f=nn({eventId:l,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,f),this.shouldPersist=!0),f}),$e(this,"getEvent",n=>{const{eventId:s,topic:o}=n;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return nn(nn({},a),this.setMethods(a.eventId))}),$e(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),$e(this,"setEventListeners",()=>{this.core.heartbeat.on(hr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(n.timestamp)>B$&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),$e(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),$e(this,"addTrace",(n,s)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(s),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"setError",(n,s)=>{const o=this.events.get(n);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),$e(this,"restore",async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,nn(nn({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),$e(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),$e(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${T$}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ga}${s}`,{method:"POST",body:JSON.stringify(n)})}),$e(this,"getAppDomain",()=>Ip().url),this.logger=dt(i,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var TO=Object.defineProperty,Xh=Object.getOwnPropertySymbols,RO=Object.prototype.hasOwnProperty,FO=Object.prototype.propertyIsEnumerable,rc=(t,e,i)=>e in t?TO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Qh=(t,e)=>{for(var i in e||(e={}))RO.call(e,i)&&rc(t,i,e[i]);if(Xh)for(var i of Xh(e))FO.call(e,i)&&rc(t,i,e[i]);return t},le=(t,e,i)=>rc(t,typeof e!="symbol"?e+"":e,i);let NO=class Xg extends gS{constructor(e){var i;super(e),le(this,"protocol",Ng),le(this,"version",Ug),le(this,"name",Us),le(this,"relayUrl"),le(this,"projectId"),le(this,"customStoragePrefix"),le(this,"events",new St.EventEmitter),le(this,"logger"),le(this,"heartbeat"),le(this,"relayer"),le(this,"crypto"),le(this,"storage"),le(this,"history"),le(this,"expirer"),le(this,"pairing"),le(this,"verify"),le(this,"echoClient"),le(this,"linkModeSupportedApps"),le(this,"eventClient"),le(this,"initialized",!1),le(this,"logChunkController"),le(this,"on",(a,c)=>this.events.on(a,c)),le(this,"once",(a,c)=>this.events.once(a,c)),le(this,"off",(a,c)=>this.events.off(a,c)),le(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),le(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}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)||jg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=i3({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:e$.logger,name:Us}),{logger:s,chunkLoggerController:o}=Ep({opts:n,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(i=this.logChunkController)!=null&&i.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=dt(s,this.name),this.heartbeat=new B8,this.crypto=new lD(this,this.logger,e==null?void 0:e.keychain),this.history=new bO(this,this.logger),this.expirer=new xO(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new fS(Qh(Qh({},t$),e==null?void 0:e.storageOptions)),this.relayer=new ND({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new yO(this,this.logger),this.verify=new SO(this,this.logger,this.storage),this.echoClient=new OO(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new BO(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const i=new Xg(e);await i.initialize();const r=await i.crypto.getClientId();return await i.storage.setItem(g$,r),i}get context(){return st(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(Ch,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(Ch)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${e}`,r=`${i}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[i]}catch(i){console.warn("Failed to get global WalletConnect core",i);return}}setGlobalCore(e){var i;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((i=e.opts)==null?void 0:i.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof xt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const UO=NO,Qg="wc",e0=2,t0="client",Zc=`${Qg}@${e0}:${t0}:`,na={name:t0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},ef="WALLETCONNECT_DEEPLINK_CHOICE",kO="proposal",tf="Proposal expired",jO="session",xr=L.SEVEN_DAYS,LO="engine",Te={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},sa={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},MO={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},qO="request",zO=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],VO="wc",HO="auth",KO="authKeys",WO="pairingTopics",GO="requests",lo=`${VO}@${1.5}:${HO}:`,ws=`${lo}:PUB_KEY`;var YO=Object.defineProperty,ZO=Object.defineProperties,JO=Object.getOwnPropertyDescriptors,rf=Object.getOwnPropertySymbols,XO=Object.prototype.hasOwnProperty,QO=Object.prototype.propertyIsEnumerable,nc=(t,e,i)=>e in t?YO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,oe=(t,e)=>{for(var i in e||(e={}))XO.call(e,i)&&nc(t,i,e[i]);if(rf)for(var i of rf(e))QO.call(e,i)&&nc(t,i,e[i]);return t},Re=(t,e)=>ZO(t,JO(e)),k=(t,e,i)=>nc(t,typeof e!="symbol"?e+"":e,i);class eA extends BS{constructor(e){super(e),k(this,"name",LO),k(this,"events",new lc),k(this,"initialized",!1),k(this,"requestQueue",{state:kt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),k(this,"emittedSessionRequests",new T3({limit:500})),k(this,"requestQueueDelay",L.ONE_SECOND),k(this,"expectedPairingMethodMap",new Map),k(this,"recentlyDeletedMap",new Map),k(this,"recentlyDeletedLimit",200),k(this,"relayMessageCache",[]),k(this,"pendingSessions",new Map),k(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(Te)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),k(this,"connect",async i=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Re(oe({},i),{requiredNamespaces:i.requiredNamespaces||{},optionalNamespaces:i.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=V_(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:h,walletPay:f}=n,d=((r=h==null?void 0:h[0])==null?void 0:r.ttl)||Te.wc_sessionPropose.req.ttl||L.FIVE_MINUTES;this.validateRequestExpiry(d);let p=s,g,w=!1;try{if(p){const A=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=A.active}}catch(A){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),A}if(!p||!w){const{topic:A,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=A,g=U}if(!p){const{message:A}=M("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(A)}const _=await this.client.core.crypto.generateKeyPair(),C=we(d),b=oe(Re(oe(oe({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:kg}],proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:C,pairingTopic:p},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:Lt()}),(h||f)&&{requests:{authentication:h==null?void 0:h.map(A=>{const{domain:U,chains:j,nonce:B,uri:I,exp:D,nbf:m,type:y,statement:x,requestId:$,resources:E,signatureTypes:S}=A;return{domain:U,chains:j,nonce:B,type:y??"caip122",aud:I,version:"1",iat:new Date().toISOString(),exp:D,nbf:m,statement:x,requestId:$,resources:E,signatureTypes:S}}),walletPay:f}}),v=ae("session_connect",b.id),{reject:O,resolve:P,done:T}=Ki(d,tf),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:tf,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(v,({error:A,session:U})=>{this.client.events.off("proposal_expire",R),A?O(A):U&&P(U)}),await this.setProposal(b.id,b),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:b.id}}}).catch(A=>{throw this.deleteProposal(b.id),A}),{uri:g,approval:T}}),k(this,"pair",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(i)}catch(r){throw this.client.logger.error("pair() failed"),r}}),k(this,"approve",async i=>{var r,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=i==null?void 0:i.id)==null?void 0:r.toString(),trace:[Ot.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw o.setError(zi.no_internet_connection),U}try{await this.isValidProposalId(i==null?void 0:i.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${i==null?void 0:i.id}) failed`),o.setError(zi.proposal_not_found),U}try{await this.isValidApprove(i)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(zi.session_approve_namespace_validation_failure),U}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:_,optionalNamespaces:C}=p;let b=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:g});b||(b=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Ot.session_approve_started,properties:{topic:g,trace:[Ot.session_approve_started,Ot.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),O=w.publicKey,P=await this.client.core.crypto.generateSharedKey(v,O),T=Re(oe(oe(oe({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:we(xr)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=he.relay;b.addTrace(Ot.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:R,internal:{skipSubscribe:!0}})}catch(U){throw b.setError(zi.subscribe_session_topic_failure),U}b.addTrace(Ot.subscribe_session_topic_success);const A=Re(oe({},T),{topic:P,requiredNamespaces:_,optionalNamespaces:C,pairingTopic:g,acknowledged:!1,self:T.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:v,transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(P,A),b.addTrace(Ot.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:v},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:oe({correlationId:a},this.getTVFApproveParams(A))}}),b.addTrace(Ot.session_approve_publish_success)}catch(U){throw this.client.logger.error(U),this.client.session.delete(P,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),U}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:w.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,we(xr)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),k(this,"reject",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(i)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:n}=i;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:n,rpcOpts:Te.wc_sessionPropose.reject}),await this.deleteProposal(r)}),k(this,"update",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(i)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:r,namespaces:n}=i,{done:s,resolve:o,reject:a}=Ki(L.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Lt(),l=Ri().toString(),u=this.client.session.get(r).namespaces;return this.events.once(ae("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(r,{namespaces:n}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(r,{namespaces:u}),a(h)}),{acknowledged:s}}),k(this,"extend",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(i)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=i,n=Lt(),{done:s,resolve:o,reject:a}=Ki(L.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ae("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,we(xr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async i=>{this.isInitialized();try{await this.isValidRequest(i)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:r,request:n,topic:s,expiry:o=Te.wc_sessionRequest.req.ttl}=i,a=this.client.session.get(s);(a==null?void 0:a.transportType)===he.relay&&await this.confirmOnlineStateOrThrow();const c=Lt(),l=Ri().toString(),{done:u,resolve:h,reject:f}=Ki(o,"Request expired. Please try again.");this.events.once(ae("session_request",c),({error:w,result:_})=>{w?f(w):h(_)});const d="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:d,params:{request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:r,id:c}),await u();const g={request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:r};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:d,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(_=>f(_)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:r,id:c}),w()}),new Promise(async w=>{var _;if(!((_=a.sessionConfig)!=null&&_.disableDeepLink)){const C=await O3(this.client.core.storage,ef);await S3({id:c,topic:s,wcDeepLink:C})}w()}),u()]).then(w=>w[2])}),k(this,"respond",async i=>{var r,n;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:(i==null?void 0:i.topic)||((n=(r=i==null?void 0:i.response)==null?void 0:r.id)==null?void 0:n.toString()),trace:[Ot.session_request_response_started]}});try{await this.isValidRespond(i)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zi.session_request_response_validation_failure),h}s.addTrace(Ot.session_request_response_validation_success);const{topic:o,response:a}=i,{id:c}=a,l=this.client.session.get(o);l.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{s.addTrace(Ot.session_request_response_publish_started),Mt(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):vt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(i)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zi.session_request_response_publish_failure),h}}),k(this,"ping",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(i)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:r}=i;if(this.client.session.keys.includes(r)){const n=Lt(),s=Ri().toString(),{done:o,resolve:a,reject:c}=Ki(L.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ae("session_ping",n),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(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:r}))}),k(this,"emit",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(i);const{topic:r,event:n,chainId:s}=i,o=Ri().toString(),a=Lt();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(i);const{topic:r}=i;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:n}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(n)}}),k(this,"find",i=>(this.isInitialized(),this.client.session.getAll().filter(r=>W_(r,i)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(i,r)=>{var n;this.isInitialized(),this.isValidAuthenticate(i);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),o=s?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:f,exp:d,nbf:p,methods:g=[],expiry:w}=i,_=[...i.resources||[]],{topic:C,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:C,uri:b}});const v=await this.client.core.crypto.generateKeyPair(),O=ds(v);if(await Promise.all([this.client.auth.authKeys.set(ws,{responseTopic:O,publicKey:v}),this.client.auth.pairingTopics.set(O,{topic:O,pairingTopic:C})]),await this.client.core.relayer.subscribe(O,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),g.length>0){const{namespace:E}=ci(a[0]);let S=Kx(E,"request",g);fs(_)&&(S=Gx(S,_.pop())),_.push(S)}const P=w&&w>Te.wc_sessionAuthenticate.req.ttl?w:Te.wc_sessionAuthenticate.req.ttl,T={authPayload:{type:f??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:p,resources:_},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(P)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},A={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(Te.wc_sessionPropose.req.ttl),id:Lt()},{done:U,resolve:j,reject:B}=Ki(P,"Request expired"),I=Lt(),D=ae("session_connect",A.id),m=ae("session_request",I),y=async({error:E,session:S})=>{this.events.off(m,x),E?B(E):S&&j({session:S})},x=async E=>{var S,F,N;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),E.error){const W=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return E.error.code===W.code?void 0:(this.events.off(D,y),B(E.error.message))}await this.deleteProposal(A.id),this.events.off(D,y);const{cacaos:H,responder:z}=E.result,q=[],K=[];for(const W of H){await Nu({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Q}=W,pe=fs(Q.resources),ve=[Fa(Q.iss)],_e=Cs(Q.iss);if(pe){const He=Uu(pe),Wt=ku(pe);q.push(...He),ve.push(...Wt)}for(const He of ve)K.push(`${He}:${_e}`)}const G=await this.client.core.crypto.generateSharedKey(v,z.publicKey);let X;q.length>0&&(X={topic:G,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:z,controller:z.publicKey,expiry:we(xr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:uh([...new Set(q)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(G,{transportType:o}),await this.client.session.set(G,X),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:z.metadata}),X=this.client.session.get(G)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(F=z.metadata.redirect)!=null&&F.linkMode&&(N=z.metadata.redirect)!=null&&N.universal&&r&&(this.client.core.addLinkModeSupportedApp(z.metadata.redirect.universal),this.client.session.update(G,{transportType:he.link_mode})),j({auths:H,session:X})};this.events.once(D,y),this.events.once(m,x);let $;try{if(s){const E=Ct("wc_sessionAuthenticate",T,I);this.client.core.history.set(C,E);const S=await this.client.core.crypto.encode("",E,{type:Nn,encoding:Bi});$=is(r,C,S)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:i.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:A,expiry:Te.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:A.id})])}catch(E){throw this.events.off(D,y),this.events.off(m,x),E}return await this.setProposal(A.id,A),await this.setAuthRequest(I,{request:Re(oe({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:$??b,response:U}}),k(this,"approveSessionAuthenticate",async i=>{const{id:r,auths:n}=i,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Vi.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(tn.no_internet_connection),w}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=ds(c),h={type:li,receiverPublicKey:c,senderPublicKey:l},f=[],d=[];for(const w of n){if(!await Nu({cacao:w,projectId:this.client.core.projectId})){s.setError(tn.invalid_cacao);const O=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:O,encodeOpts:h}),new Error(O.message)}s.addTrace(Vi.cacaos_verified);const{p:_}=w,C=fs(_.resources),b=[Fa(_.iss)],v=Cs(_.iss);if(C){const O=Uu(C),P=ku(C);f.push(...O),b.push(...P)}for(const O of b)d.push(`${O}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Vi.create_authenticated_session_topic);let g;if((f==null?void 0:f.length)>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:we(xr),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:uh([...new Set(f)],[...new Set(d)]),transportType:a},s.addTrace(Vi.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw s.setError(tn.subscribe_authenticated_session_topic_failure),w}s.addTrace(Vi.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Vi.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Vi.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(tn.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),k(this,"rejectSessionAuthenticate",async i=>{this.isInitialized();const{id:r,reason:n}=i,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ds(o),l={type:li,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:n,encodeOpts:l,rpcOpts:Te.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),k(this,"formatAuthMessage",i=>{this.isInitialized();const{request:r,iss:n}=i;return zp(r,n)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const i=this.relayMessageCache.shift();i&&await this.onRelayMessage(i)}catch(i){this.client.logger.error(i)}},50)}),k(this,"cleanupDuplicatePairings",async i=>{if(i.pairingTopic)try{const r=this.client.core.pairing.pairings.get(i.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===i.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),k(this,"deleteSession",async i=>{var r;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=i,{self:c}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(ef).catch(l=>this.client.logger.warn(l)),n===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=kt.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===n).map(l=>this.deletePendingSessionRequest(l.id,fe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),k(this,"deleteProposal",async(i,r)=>{if(r)try{const n=this.client.proposal.get(i),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s==null||s.setError(zi.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(i,fe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"proposal")}),k(this,"deletePendingSessionRequest",async(i,r,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(i,r),n?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==i),n&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:i}))}),k(this,"deletePendingAuthRequest",async(i,r,n=!1)=>{await Promise.all([this.client.auth.requests.delete(i,r),n?Promise.resolve():this.client.core.expirer.del(i)])}),k(this,"setExpiry",async(i,r)=>{this.client.session.keys.includes(i)&&(this.client.core.expirer.set(i,r),await this.client.session.update(i,{expiry:r}))}),k(this,"setProposal",async(i,r)=>{this.client.core.expirer.set(i,we(Te.wc_sessionPropose.req.ttl)),await this.client.proposal.set(i,r)}),k(this,"setAuthRequest",async(i,r)=>{const{request:n,pairingTopic:s,transportType:o=he.relay}=r;this.client.core.expirer.set(i,n.expiryTimestamp),await this.client.auth.requests.set(i,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:i,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async i=>{const{id:r,topic:n,params:s,verifyContext:o}=i,a=s.request.expiryTimestamp||we(Te.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:n,params:s,verifyContext:o})}),k(this,"sendRequest",async i=>{const{topic:r,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=i,d=Ct(n,s,c);let p;const g=!!u;try{const C=g?Bi:tt;p=await this.client.core.crypto.encode(r,d,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),C}let w;if(zO.includes(n)){const C=bt(JSON.stringify(d)),b=bt(p);w=await this.client.core.verify.register({id:b,decryptedId:C})}const _=oe(oe({},Te[n].req),f);if(_.attestation=w,o&&(_.ttl=o),a&&(_.id=a),this.client.core.history.set(r,d),g){const C=is(u,r,p);await Y.Linking.openURL(C,this.client.name)}else _.tvf=Re(oe({},h),{correlationId:d.id}),l?(_.internal=Re(oe({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,_)):this.client.core.relayer.publish(r,p,_).catch(C=>this.client.logger.error(C));return d.id}),k(this,"sendProposeSession",async i=>{const{proposal:r,publishOpts:n}=i,s=Ct("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:tt}),a=bt(JSON.stringify(s)),c=bt(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:Re(oe({},n),{publishMethod:"wc_proposeSession",attestation:l})})}),k(this,"sendApproveSession",async i=>{const{sessionTopic:r,pairingProposalResponse:n,proposal:s,sessionSettleRequest:o,publishOpts:a}=i,c=Sn(s.id,n),l=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:tt}),u=Ct("wc_sessionSettle",o,a==null?void 0:a.id),h=await this.client.core.crypto.encode(r,u,{encoding:tt});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:Re(oe({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async i=>{const{id:r,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=i,l=Sn(r,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const p=h?Bi:tt;u=await this.client.core.crypto.encode(n,l,Re(oe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),p}let f,d;try{f=await this.client.core.history.get(n,r);const p=f.request;try{d=this.getTVFParams(r,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g==null?void 0:g.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${r}) failed`),p}if(h){const p=is(c,n,u);await Y.Linking.openURL(p,this.client.name)}else{const p=f.request.method,g=Te[p].res;g.tvf=Re(oe({},d),{correlationId:r}),o?(g.internal=Re(oe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,u,g)):this.client.core.relayer.publish(n,u,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(l)}),k(this,"sendError",async i=>{const{id:r,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=i,l=oo(r,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const d=h?Bi:tt;u=await this.client.core.crypto.encode(n,l,Re(oe({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),d}let f;try{f=await this.client.core.history.get(n,r)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${n}, ${r}) failed`),d}if(h){const d=is(c,n,u);await Y.Linking.openURL(d,this.client.name)}else{const d=f.request.method,p=a||Te[d].res;this.client.core.relayer.publish(n,u,p)}await this.client.core.history.resolve(l)}),k(this,"cleanup",async()=>{const i=[],r=[];this.client.session.getAll().forEach(n=>{let s=!1;qt(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&i.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{qt(n.expiryTimestamp)&&r.push(n.id)}),await Promise.all([...i.map(n=>this.deleteSession({topic:n})),...r.map(n=>this.deleteProposal(n))])}),k(this,"onProviderMessageEvent",async i=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(i):await this.onRelayMessage(i)}),k(this,"onRelayEventRequest",async i=>{this.requestQueue.queue.push(i),await this.processRequestsQueue()}),k(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===kt.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=kt.active;const i=this.requestQueue.queue.shift();if(i)try{await this.processRequest(i)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=kt.idle}),k(this,"processRequest",async i=>{const{topic:r,payload:n,attestation:s,transportType:o,encryptedId:a}=i,c=n.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,n);case"wc_sessionPing":return await this.onSessionPingRequest(r,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n,transportType:s}=i,o=(await this.client.core.history.get(r,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,n);case"wc_sessionExtend":return this.onSessionExtendResponse(r,n);case"wc_sessionPing":return this.onSessionPingResponse(r,n);case"wc_sessionRequest":return this.onSessionRequestResponse(r,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",i=>{const{topic:r}=i,{message:n}=M("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),k(this,"shouldIgnorePairingRequest",i=>{const{topic:r,requestMethod:n}=i,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async i=>{const{topic:r,payload:n,attestation:s,encryptedId:o}=i,{params:a,id:c}=n;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(ii.proposal_listener_not_found)),this.isValidConnect(oe({},n.params));const u=a.expiryTimestamp||we(Te.wc_sessionPropose.req.ttl),h=oe({id:c,pairingTopic:r,expiryTimestamp:u,attestation:s,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:bt(JSON.stringify(n)),encryptedId:o,metadata:h.proposer.metadata});l==null||l.addTrace(jt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Te.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),k(this,"onSessionProposeResponse",async(i,r,n)=>{const{id:s}=r;if(Mt(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:i,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:i})}else if(vt(r)){await this.deleteProposal(s);const o=ae("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),k(this,"onSessionSettleRequest",async(i,r)=>{const{id:n,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r.params,p=[...this.pendingSessions.values()].find(_=>_.sessionTopic===i);if(!p)return this.client.logger.error(`Pending session not found for topic ${i}`);const g=this.client.proposal.get(p.proposalId),w=Re(oe(oe(oe({topic:i,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:w.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:r.id,topic:i,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:w}),this.events.emit(ae("session_connect",p.proposalId),{session:w})}catch(o){await this.sendError({id:n,topic:i,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(i,r)=>{const{id:n}=r;Mt(r)?(await this.client.session.update(i,{acknowledged:!0}),this.events.emit(ae("session_approve",n),{})):vt(r)&&(await this.client.session.delete(i,fe("USER_DISCONNECTED")),this.events.emit(ae("session_approve",n),{error:r.error}))}),k(this,"onSessionUpdateRequest",async(i,r)=>{const{params:n,id:s}=r;try{const o=`${i}_session_update`,a=Qr.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:i,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:i},n));try{Qr.set(o,s),await this.client.session.update(i,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:i,result:!0})}catch(c){throw Qr.delete(o),c}this.client.events.emit("session_update",{id:s,topic:i,params:n})}catch(o){await this.sendError({id:s,topic:i,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(i,r)=>r.toString().slice(0,-3)<i.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(i,r)=>{const{id:n}=r,s=ae("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(r)?this.events.emit(ae("session_update",n),{}):vt(r)&&this.events.emit(ae("session_update",n),{error:r.error})}),k(this,"onSessionExtendRequest",async(i,r)=>{const{id:n}=r;try{this.isValidExtend({topic:i}),await this.setExpiry(i,we(xr)),await this.sendResult({id:n,topic:i,result:!0}),this.client.events.emit("session_extend",{id:n,topic:i})}catch(s){await this.sendError({id:n,topic:i,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(i,r)=>{const{id:n}=r,s=ae("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(r)?this.events.emit(ae("session_extend",n),{}):vt(r)&&this.events.emit(ae("session_extend",n),{error:r.error})}),k(this,"onSessionPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult({id:n,topic:i,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:i})}catch(s){await this.sendError({id:n,topic:i,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(i,r)=>{const{id:n}=r,s=ae("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Mt(r)?this.events.emit(ae("session_ping",n),{}):vt(r)&&this.events.emit(ae("session_ping",n),{error:r.error})},500)}),k(this,"onSessionDeleteRequest",async(i,r)=>{const{id:n}=r;try{await this.isValidDisconnect({topic:i,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:i,error:fe("USER_DISCONNECTED")}),await this.deleteSession({topic:i,id:n})}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async i=>{var r,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=i,{id:h,params:f}=a;try{await this.isValidRequest(oe({topic:o},f));const d=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:bt(JSON.stringify(Ct("wc_sessionRequest",f,h))),encryptedId:l,metadata:d.peer.metadata,transportType:u}),g={id:h,topic:o,params:f,verifyContext:p};await this.setPendingSessionRequest(g),u===he.link_mode&&(r=d.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((n=d.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(d){await this.sendError({id:h,topic:o,error:d}),this.client.logger.error(d)}}),k(this,"onSessionRequestResponse",(i,r)=>{const{id:n}=r,s=ae("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(r)?this.events.emit(ae("session_request",n),{result:r.result}):vt(r)&&this.events.emit(ae("session_request",n),{error:r.error})}),k(this,"onSessionEventRequest",async(i,r)=>{const{id:n,params:s}=r;try{const o=`${i}_session_event_${s.event.name}`,a=Qr.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(oe({topic:i},s)),this.client.events.emit("session_event",{id:n,topic:i,params:s}),Qr.set(o,n)}catch(o){await this.sendError({id:n,topic:i,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(i,r)=>{const{id:n}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:i,payload:r}),Mt(r)?this.events.emit(ae("session_request",n),{result:r.result}):vt(r)&&this.events.emit(ae("session_request",n),{error:r.error})}),k(this,"onSessionAuthenticateRequest",async i=>{var r;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=i;try{const{requester:l,authPayload:u,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:bt(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),d={requester:l,pairingTopic:n,id:s.id,authPayload:u,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:d,pairingTopic:n,transportType:c}),c===he.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:f})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),d={type:li,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:d,rpcOpts:Te.wc_sessionAuthenticate.autoReject,appLink:f})}}),k(this,"addSessionRequestToSessionRequestQueue",i=>{this.sessionRequestQueue.queue.push(i)}),k(this,"cleanupAfterResponse",i=>{this.deletePendingSessionRequest(i.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:i,error:r})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===i&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ae("session_request",s.request.id),{error:r})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.active){this.client.logger.info("session request queue is already active.");return}const i=this.sessionRequestQueue.queue[0];if(!i){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(i)}catch(r){this.client.logger.error(r)}}),k(this,"emitSessionRequest",i=>{if(this.emittedSessionRequests.has(i.id)){this.client.logger.warn({id:i.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${i.id}`);return}this.sessionRequestQueue.state=kt.active,this.emittedSessionRequests.add(i.id),this.client.events.emit("session_request",i)}),k(this,"onPairingCreated",i=>{if(i.methods&&this.expectedPairingMethodMap.set(i.topic,i.methods),i.active)return;const r=this.client.proposal.getAll().find(n=>n.pairingTopic===i.topic);r&&this.onSessionProposeRequest({topic:i.topic,payload:Ct("wc_sessionPropose",Re(oe({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),k(this,"isValidConnect",async i=>{if(!Xe(i)){const{message:l}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(i)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=i;if(Ie(r)||await this.isValidPairingTopic(r),!s8(c,!0)){const{message:l}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(n&&!Ie(n)&&Ht(n)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(n,"requiredNamespaces")}if(s&&!Ie(s)&&Ht(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!Ie(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ie(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(n||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),k(this,"validateNamespaces",(i,r)=>{const n=n8(i,"connect()",r);if(n)throw new Error(n.message)}),k(this,"isValidApprove",async i=>{if(!Xe(i))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${i}`).message);const{id:r,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=i;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=Jo(n,"approve()");if(l)throw new Error(l.message);const u=dh(c.requiredNamespaces,n,"approve()");if(u)throw new Error(u.message);if(!be(s,!0)){const{message:h}=M("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(o&&!Ie(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ie(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(n));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),k(this,"isValidReject",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`reject() params: ${i}`);throw new Error(s)}const{id:r,reason:n}=i;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!a8(n)){const{message:s}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",i=>{if(!Xe(i)){const{message:l}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${i}`);throw new Error(l)}const{relay:r,controller:n,namespaces:s,expiry:o}=i;if(!Dg(r)){const{message:l}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=X_(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Jo(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(qt(o)){const{message:l}=M("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),k(this,"isValidUpdate",async i=>{if(!Xe(i)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${i}`);throw new Error(c)}const{topic:r,namespaces:n}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=Jo(n,"update()");if(o)throw new Error(o.message);const a=dh(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async i=>{if(!Xe(i)){const{message:n}=M("MISSING_OR_INVALID",`extend() params: ${i}`);throw new Error(n)}const{topic:r}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),k(this,"isValidRequest",async i=>{if(!Xe(i)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${i}`);throw new Error(c)}const{topic:r,request:n,chainId:s,expiry:o}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!fh(a,s)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!c8(n)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!h8(a,s,n.method)){const{message:c}=M("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),k(this,"isValidRespond",async i=>{var r;if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`respond() params: ${i}`);throw new Error(a)}const{topic:n,response:s}=i;try{await this.isValidSessionTopic(n)}catch(a){throw(r=i==null?void 0:i.response)!=null&&r.id&&this.cleanupAfterResponse(i),a}if(!l8(s)){const{message:a}=M("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==n){const{message:a}=M("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${n}`);throw new Error(a)}}),k(this,"isValidPing",async i=>{if(!Xe(i)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidEmit",async i=>{if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${i}`);throw new Error(a)}const{topic:r,event:n,chainId:s}=i;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!fh(o,s)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!u8(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!f8(o,s,n.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async i=>{if(!Xe(i)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidAuthenticate",i=>{const{chains:r,uri:n,domain:s,nonce:o}=i;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!be(n,!1))throw new Error("uri is required parameter");if(!be(s,!1))throw new Error("domain is required parameter");if(!be(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>ci(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ci(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),k(this,"getVerifyContext",async i=>{const{attestationId:r,hash:n,encryptedId:s,metadata:o,transportType:a}=i,c={verified:{verifyUrl:o.verifyUrl||gn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:n,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),k(this,"validateSessionProps",(i,r)=>{Object.values(i).forEach((n,s)=>{if(n==null){const{message:o}=M("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${n} for key ${Object.keys(i)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",i=>{const r=this.client.auth.requests.get(i);return typeof r=="object"?r:void 0}),k(this,"addToRecentlyDeleted",(i,r)=>{if(this.recentlyDeletedMap.set(i,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(o)}}}),k(this,"checkRecentlyDeleted",i=>{const r=this.recentlyDeletedMap.get(i);if(r){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${i}`);throw new Error(n)}}),k(this,"isLinkModeEnabled",(i,r)=>{var n,s,o,a,c,l,u,h,f;return!i||r!==he.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=i==null?void 0:i.redirect)==null?void 0:u.universal)!==void 0&&((h=i==null?void 0:i.redirect)==null?void 0:h.universal)!==""&&((f=i==null?void 0:i.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(i.redirect.universal)&&typeof(Y==null?void 0:Y.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(i,r)=>{var n;return this.isLinkModeEnabled(i,r)?(n=i==null?void 0:i.redirect)==null?void 0:n.universal:void 0}),k(this,"handleLinkModeMessage",({url:i})=>{if(!i||!i.includes("wc_ev")||!i.includes("topic"))return;const r=_u(i,"topic")||"",n=decodeURIComponent(_u(i,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:n,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var i;if(Fc()||ki()&&(i=this.client.metadata.redirect)!=null&&i.linkMode){const r=Y==null?void 0:Y.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await r.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),k(this,"getTVFApproveParams",i=>{try{const r=Sg(i.namespaces),n=j_(i.namespaces),s=L_(i.namespaces),o=i.sessionProperties,a=i.scopedProperties;return{approvedChains:r,approvedMethods:n,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}}),k(this,"getTVFParams",(i,r,n)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:i,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,n);c.txHashes=l,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),k(this,"isValidContractData",i=>{var r;if(!i)return!1;try{const n=(i==null?void 0:i.data)||((r=i==null?void 0:i[0])==null?void 0:r.data);if(!n.startsWith("0x"))return!1;const s=n.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),k(this,"extractTxHashesFromResult",(i,r)=>{var n;try{if(!r)return[];const s=i.method,o=MO[s];if(s==="sui_signTransaction")return[Dx(r.transactionBytes)];if(s==="near_signTransaction")return[Bu(r)];if(s==="near_signTransactions")return r.map(c=>Bu(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(n=r.tx_json)==null?void 0:n.hash];if(s==="polkadot_signTransaction")return[P8({transaction:i.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return It(r)?r.map(c=>Tu(c)):[Tu(r)];if(s==="cosmos_signDirect")return[Ax(r)];if(s==="wallet_sendCalls")return Px(r);if(typeof r=="string")return[r];const a=r[o.key];if(It(a))return s==="solana_signAllTransactions"?a.map(c=>$x(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,i=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,n]of Object.entries(i))for(const s of n)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(me.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:i,message:r,attestation:n,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ws)?this.client.auth.authKeys.get(ws):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(i,r,{receiverPublicKey:o,encoding:s===he.link_mode?Bi:tt});Gc(a)?(this.client.core.history.set(i,a),await this.onRelayEventRequest({topic:i,payload:a,attestation:n,transportType:s,encryptedId:bt(r)})):ao(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:i,payload:a,transportType:s}),this.client.core.history.delete(i,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:i,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(i,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(wt.expired,async e=>{const{topic:i,id:r}=$p(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,M("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,M("EXPIRED"),!0);i?this.client.session.keys.includes(i)&&(await this.deleteSession({topic:i,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:i})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(Yi.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Yi.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!be(e,!1)){const{message:i}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(i)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(i)}if(qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:i}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(i)}}async isValidSessionTopic(e){if(!be(e,!1)){const{message:i}=M("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(i)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(i)}if(qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:i}=M("EXPIRED",`session topic: ${e}`);throw new Error(i)}if(!this.client.core.crypto.keychain.has(e)){const{message:i}=M("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(i)}}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(be(e,!1)){const{message:i}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(i)}else{const{message:i}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(i)}}async isValidProposalId(e){if(!o8(e)){const{message:i}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(i)}if(!this.client.proposal.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(i)}if(qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:i}=M("EXPIRED",`proposal id: ${e}`);throw new Error(i)}}validateRequestExpiry(e){if(e&&!g8(e,sa)){const{message:i}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${sa.min} and ${sa.max}`);throw new Error(i)}}}class tA extends dr{constructor(e,i){super(e,i,kO,Zc),this.core=e,this.logger=i}}let iA=class extends dr{constructor(e,i){super(e,i,jO,Zc),this.core=e,this.logger=i}};class rA extends dr{constructor(e,i){super(e,i,qO,Zc,r=>r.id),this.core=e,this.logger=i}}class nA extends dr{constructor(e,i){super(e,i,KO,lo,()=>ws),this.core=e,this.logger=i}}class sA extends dr{constructor(e,i){super(e,i,WO,lo),this.core=e,this.logger=i}}class oA extends dr{constructor(e,i){super(e,i,GO,lo,r=>r.id),this.core=e,this.logger=i}}var aA=Object.defineProperty,cA=(t,e,i)=>e in t?aA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,oa=(t,e,i)=>cA(t,typeof e!="symbol"?e+"":e,i);class lA{constructor(e,i){this.core=e,this.logger=i,oa(this,"authKeys"),oa(this,"pairingTopics"),oa(this,"requests"),this.authKeys=new nA(this.core,this.logger),this.pairingTopics=new sA(this.core,this.logger),this.requests=new oA(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var uA=Object.defineProperty,hA=(t,e,i)=>e in t?uA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,te=(t,e,i)=>hA(t,typeof e!="symbol"?e+"":e,i);class Jc extends CS{constructor(e){super(e),te(this,"protocol",Qg),te(this,"version",e0),te(this,"name",na.name),te(this,"metadata"),te(this,"core"),te(this,"logger"),te(this,"events",new St.EventEmitter),te(this,"engine"),te(this,"session"),te(this,"proposal"),te(this,"pendingRequest"),te(this,"auth"),te(this,"signConfig"),te(this,"on",(r,n)=>this.events.on(r,n)),te(this,"once",(r,n)=>this.events.once(r,n)),te(this,"off",(r,n)=>this.events.off(r,n)),te(this,"removeListener",(r,n)=>this.events.removeListener(r,n)),te(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),te(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"update",async r=>{try{return await this.engine.update(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"request",async r=>{try{return await this.engine.request(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"find",r=>{try{return this.engine.find(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),te(this,"authenticate",async(r,n)=>{try{return await this.engine.authenticate(r,n)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(n){throw this.logger.error(n.message),n}}),this.name=(e==null?void 0:e.name)||na.name,this.metadata=b3(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const i=Kc({logger:(e==null?void 0:e.logger)||na.logger,name:this.name});this.logger=i,this.core=(e==null?void 0:e.core)||new UO(e),this.session=new iA(this.core,this.logger),this.proposal=new tA(this.core,this.logger),this.pendingRequest=new rA(this.core,this.logger),this.engine=new eA(this),this.auth=new lA(this.core,this.logger)}static async init(e){const i=new Jc(e);return await i.initialize(),i}get context(){return st(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")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const fA=Jc;var dA=Object.defineProperty,pA=Object.defineProperties,gA=Object.getOwnPropertyDescriptors,nf=Object.getOwnPropertySymbols,yA=Object.prototype.hasOwnProperty,wA=Object.prototype.propertyIsEnumerable,sf=(t,e,i)=>e in t?dA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,of=(t,e)=>{for(var i in e||(e={}))yA.call(e,i)&&sf(t,i,e[i]);if(nf)for(var i of nf(e))wA.call(e,i)&&sf(t,i,e[i]);return t},af=(t,e)=>pA(t,gA(e));const mA={Accept:"application/json","Content-Type":"application/json"},bA="POST",cf={headers:mA,method:bA},lf=10;let i0=class{constructor(e,i=!1){if(this.url=e,this.disableProviderPing=i,this.events=new St.EventEmitter,this.isAvailable=!1,this.registering=!1,!$h(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=i}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const i=ui(e),r=await(await ll(this.url,af(of({},cf),{body:i}))).json();this.onPayload({data:r})}catch(i){this.onError(e.id,i)}}async register(e=this.url){if(!$h(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const i=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=i||this.events.listenerCount("open")>=i)&&this.events.setMaxListeners(i+1),new Promise((r,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));r()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const i=ui({id:1,jsonrpc:"2.0",method:"test",params:[]});await ll(e,af(of({},cf),{body:i}))}this.onOpen()}catch(i){const r=this.parseError(i);throw this.events.emit("register_error",r),this.onClose(),r}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const i=typeof e.data=="string"?sr(e.data):e.data;this.events.emit("payload",i)}onError(e,i){const r=this.parseError(i),n=r.message||r.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,i=this.url){return Bg(e,i,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>lf&&this.events.setMaxListeners(lf)}};function Xc(t){return t==null||typeof t!="object"&&typeof t!="function"}function r0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function n0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const vA="[object RegExp]",s0="[object String]",o0="[object Number]",a0="[object Boolean]",c0="[object Arguments]",EA="[object Symbol]",xA="[object Date]",IA="[object Map]",_A="[object Set]",SA="[object Array]",$A="[object ArrayBuffer]",DA="[object Object]",OA="[object DataView]",AA="[object Uint8Array]",PA="[object Uint8ClampedArray]",CA="[object Uint16Array]",BA="[object Uint32Array]",TA="[object Int8Array]",RA="[object Int16Array]",FA="[object Int32Array]",NA="[object Float32Array]",UA="[object Float64Array]";function Qc(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function kA(t,e){return Or(t,void 0,t,new Map,e)}function Or(t,e,i,r=new Map,n=void 0){const s=n==null?void 0:n(t,e,i,r);if(s!=null)return s;if(Xc(t))return t;if(r.has(t))return r.get(t);if(Array.isArray(t)){const o=new Array(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Or(t[a],a,i,r,n);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;r.set(t,o);for(const[a,c]of t)o.set(a,Or(c,a,i,r,n));return o}if(t instanceof Set){const o=new Set;r.set(t,o);for(const a of t)o.add(Or(a,void 0,i,r,n));return o}if(typeof ie<"u"&&ie.isBuffer(t))return t.subarray();if(Qc(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Or(t[a],a,i,r,n);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return r.set(t,o),Zi(o,t,i,r,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return r.set(t,o),Zi(o,t,i,r,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return r.set(t,o),Zi(o,t,i,r,n),o}if(t instanceof Error){const o=new t.constructor;return r.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Zi(o,t,i,r,n),o}if(typeof t=="object"&&jA(t)){const o=Object.create(Object.getPrototypeOf(t));return r.set(t,o),Zi(o,t,i,r,n),o}return t}function Zi(t,e,i=t,r,n){const s=[...Object.keys(e),...r0(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Or(e[a],a,i,r,n))}}function jA(t){switch(n0(t)){case c0:case SA:case $A:case OA:case a0:case xA:case NA:case UA:case TA:case RA:case FA:case IA:case o0:case DA:case vA:case _A:case s0:case EA:case AA:case PA:case CA:case BA:return!0;default:return!1}}function LA(t,e){return kA(t,(i,r,n,s)=>{const o=e==null?void 0:e(i,r,n,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case o0:case s0:case a0:{const a=new t.constructor(t==null?void 0:t.valueOf());return Zi(a,t),a}case c0:{const a={};return Zi(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function uf(t){return LA(t)}function hf(t){return t!==null&&typeof t=="object"&&n0(t)==="[object Arguments]"}function ff(t){return typeof t=="object"&&t!==null}function MA(){}function qA(t){return Qc(t)}function zA(t){var i;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const r=t[Symbol.toStringTag];return r==null||!((i=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&i.writable)?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function VA(t){if(Xc(t))return t;if(Array.isArray(t)||Qc(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),i=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new i(t);if(t instanceof RegExp){const r=new i(t);return r.lastIndex=t.lastIndex,r}if(t instanceof DataView)return new i(t.buffer.slice(0));if(t instanceof Error){const r=new i(t.message);return r.stack=t.stack,r.name=t.name,r.cause=t.cause,r}if(typeof File<"u"&&t instanceof File)return new i([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const r=Object.create(e);return Object.assign(r,t)}return t}function HA(t,...e){const i=e.slice(0,-1),r=e[e.length-1];let n=t;for(let s=0;s<i.length;s++){const o=i[s];n=sc(n,o,r,new Map)}return n}function sc(t,e,i,r){if(Xc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(r.has(e))return VA(r.get(e));if(r.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const n=[...Object.keys(e),...r0(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(hf(a)&&(a={...a}),hf(c)&&(c={...c}),typeof ie<"u"&&ie.isBuffer(a)&&(a=uf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const d=h[f];u[d]=c[d]}c=u}else c=[];const l=i(c,a,o,t,e,r);l!=null?t[o]=l:Array.isArray(a)||ff(c)&&ff(a)?t[o]=sc(c,a,i,r):c==null&&zA(a)?t[o]=sc({},a,i,r):c==null&&qA(a)?t[o]=uf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function KA(t,...e){return HA(t,...e,MA)}const df="error",WA="wss://relay.walletconnect.org",GA="wc",l0="universal_provider",ss=`${GA}@2:${l0}:`,u0="https://rpc.walletconnect.org/v1/",h0="generic",YA=`${u0}bundler`,Tr="call_status",ZA=86400,el={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var JA=Object.defineProperty,XA=Object.defineProperties,QA=Object.getOwnPropertyDescriptors,pf=Object.getOwnPropertySymbols,e4=Object.prototype.hasOwnProperty,t4=Object.prototype.propertyIsEnumerable,gf=(t,e,i)=>e in t?JA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,os=(t,e)=>{for(var i in e||(e={}))e4.call(e,i)&&gf(t,i,e[i]);if(pf)for(var i of pf(e))t4.call(e,i)&&gf(t,i,e[i]);return t},i4=(t,e)=>XA(t,QA(e));function f0(t,e,i){var r;const n=ci(t);return((r=e.rpcMap)==null?void 0:r[n.reference])||`${u0}?chainId=${n.namespace}:${n.reference}&projectId=${i}`}function r4(t){return t.includes(":")?t.split(":")[1]:t}function d0(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function n4(t,e){const i=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!i.length)return[];const r=[];return i.forEach(n=>{const s=e.namespaces[n].accounts;r.push(...s)}),r}function yf(t){return Object.fromEntries(Object.entries(t).filter(([e,i])=>{var r,n;return((r=i==null?void 0:i.chains)==null?void 0:r.length)&&((n=i==null?void 0:i.chains)==null?void 0:n.length)>0}))}function as(t={},e={}){const i=yf(wf(t)),r=yf(wf(e));return KA(i,r)}function wf(t){var e,i,r,n,s;const o={};if(!Ht(t))return o;for(const[a,c]of Object.entries(t)){const l=so(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],f=c.rpcMap||{},d=Dr(a);o[d]=i4(os(os({},o[d]),c),{chains:Vt(l,(e=o[d])==null?void 0:e.chains),methods:Vt(u,(i=o[d])==null?void 0:i.methods),events:Vt(h,(r=o[d])==null?void 0:r.events)}),(Ht(f)||Ht(((n=o[d])==null?void 0:n.rpcMap)||{}))&&(o[d].rpcMap=os(os({},f),(s=o[d])==null?void 0:s.rpcMap))}return o}function mf(t){return t.includes(":")?t.split(":")[2]:t}function bf(t){const e={};for(const[i,r]of Object.entries(t)){const n=r.methods||[],s=r.events||[],o=r.accounts||[],a=so(i)?[i]:r.chains?r.chains:d0(r.accounts);e[i]={chains:a,methods:n,events:s,accounts:o}}return e}function aa(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function s4(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const p0={},Rr=t=>p0[t],ca=(t,e)=>{p0[t]=e};var o4=Object.defineProperty,vf=Object.getOwnPropertySymbols,a4=Object.prototype.hasOwnProperty,c4=Object.prototype.propertyIsEnumerable,Ef=(t,e,i)=>e in t?o4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xf=(t,e)=>{for(var i in e||(e={}))a4.call(e,i)&&Ef(t,i,e[i]);if(vf)for(var i of vf(e))c4.call(e,i)&&Ef(t,i,e[i]);return t};const If="eip155",l4=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],u4=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,la=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,_f=t=>Object.keys(t).filter(e=>l4.includes(e)).reduce((e,i)=>(e[i]=h4(t[i]),e),{}),h4=t=>typeof t=="string"&&s4(t)?JSON.parse(t):t,f4=(t,e,i)=>{const{sessionProperties:r={},scopedProperties:n={}}=t,s={};if(!Ht(n)&&!Ht(r))return;const o=_f(r);for(const a of i){const c=u4(a);if(!c)continue;s[la(c)]=o;const l=n==null?void 0:n[`${If}:${c}`];if(l){const u=l==null?void 0:l[`${If}:${c}:${e}`];s[la(c)]=xf(xf({},s[la(c)]),_f(u||l))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var d4=Object.defineProperty,p4=(t,e,i)=>e in t?d4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,g4=(t,e,i)=>p4(t,typeof e!="symbol"?e+"":e,i);let ua,y4=class g0{constructor(e){g4(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,i){return await this.storage.setItem(e,i)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return ua||(ua=new g0(e)),ua}};var w4=Object.defineProperty,m4=Object.defineProperties,b4=Object.getOwnPropertyDescriptors,Sf=Object.getOwnPropertySymbols,v4=Object.prototype.hasOwnProperty,E4=Object.prototype.propertyIsEnumerable,$f=(t,e,i)=>e in t?w4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,x4=(t,e)=>{for(var i in e||(e={}))v4.call(e,i)&&$f(t,i,e[i]);if(Sf)for(var i of Sf(e))E4.call(e,i)&&$f(t,i,e[i]);return t},I4=(t,e)=>m4(t,b4(e));async function _4(t,e){const i=ci(t.result.capabilities.caip345.caip2),r=t.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(r.map(h=>S4(i.reference,h,e))),s=n.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);n.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!s.length||s.some(h=>!h),a=s.every(h=>(h==null?void 0:h.status)==="0x1"),c=s.every(h=>(h==null?void 0:h.status)==="0x0"),l=s.some(h=>(h==null?void 0:h.status)==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:s,status:u}}async function S4(t,e,i){return await i(parseInt(t)).request(Ct("eth_getTransactionReceipt",[e]))}async function $4({sendCalls:t,storage:e}){const i=await e.getItem(Tr);await e.setItem(Tr,I4(x4({},i),{[t.result.id]:{request:t.request,result:t.result,expiry:we(ZA)}}))}async function D4({resultId:t,storage:e}){const i=await e.getItem(Tr);if(i){delete i[t],await e.setItem(Tr,i);for(const r in i)qt(i[r].expiry)&&delete i[r];await e.setItem(Tr,i)}}async function O4({resultId:t,storage:e}){const i=await e.getItem(Tr),r=i==null?void 0:i[t];if(r&&!qt(r.expiry))return r;await D4({resultId:t,storage:e})}var A4=Object.defineProperty,P4=Object.defineProperties,C4=Object.getOwnPropertyDescriptors,Df=Object.getOwnPropertySymbols,B4=Object.prototype.hasOwnProperty,T4=Object.prototype.propertyIsEnumerable,oc=(t,e,i)=>e in t?A4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ha=(t,e)=>{for(var i in e||(e={}))B4.call(e,i)&&oc(t,i,e[i]);if(Df)for(var i of Df(e))T4.call(e,i)&&oc(t,i,e[i]);return t},fa=(t,e)=>P4(t,C4(e)),Hi=(t,e,i)=>oc(t,typeof e!="symbol"?e+"":e,i);class R4{constructor(e){Hi(this,"name","eip155"),Hi(this,"client"),Hi(this,"chainId"),Hi(this,"namespace"),Hi(this,"httpProviders"),Hi(this,"events"),Hi(this,"storage"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=y4.getStorage(this.client.core.storage)}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);case"wallet_sendCalls":return await this.sendCalls(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,i){this.httpProviders[e]||this.setHttpProvider(parseInt(e),i);const r=this.chainId;this.chainId=parseInt(e),this.events.emit(el.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${r}`})}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,i){const r=i||f0(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Yc(new i0(r,Rr("disableProviderPing")))}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;const n=parseInt(r4(i));e[n]=this.createHttpProvider(n,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}getHttpProvider(e){const i=e||this.chainId;return this.httpProviders[i]||(this.httpProviders=fa(ha({},this.httpProviders),{[i]:this.createHttpProvider(i)}),this.httpProviders[i])}async handleSwitchChain(e){var i,r;let n=e.request.params?(i=e.request.params[0])==null?void 0:i.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. 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 i,r,n,s,o;const a=(r=(i=e.request)==null?void 0:i.params)==null?void 0:r[0],c=((s=(n=e.request)==null?void 0:n.params)==null?void 0:s[1])||[];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)||{},h=`${a}${c.join(",")}`,f=u==null?void 0:u[h];if(f)return f;let d;try{d=f4(l,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(d)return d;const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:fa(ha({},l.sessionProperties||{}),{capabilities:fa(ha({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var i,r,n;const s=this.client.session.get(e.topic),o=(i=s.sessionProperties)==null?void 0:i.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(r=s.sessionProperties)==null?void 0:r.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await O4({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(c)try{return await _4(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}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,i){var r;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct("eth_getUserOperationReceipt",[(r=i.request.params)==null?void 0:r[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,i){return`${YA}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${i}`}async sendCalls(e){var i,r,n;const s=await this.client.request(e),o=(i=e.request.params)==null?void 0:i[0],a=s==null?void 0:s.id,c=(s==null?void 0:s.capabilities)||{},l=(r=c==null?void 0:c.caip345)==null?void 0:r.caip2,u=(n=c==null?void 0:c.caip345)==null?void 0:n.transactionHashes;return!a||!l||!(u!=null&&u.length)||await $4({sendCalls:{request:o,result:s},storage:this.storage}),s}}var F4=Object.defineProperty,N4=(t,e,i)=>e in t?F4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ir=(t,e,i)=>N4(t,typeof e!="symbol"?e+"":e,i);class U4{constructor(e){Ir(this,"name",h0),Ir(this,"client"),Ir(this,"httpProviders"),Ir(this,"events"),Ir(this,"namespace"),Ir(this,"chainId"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),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,i){this.httpProviders[e]||this.setHttpProvider(e,i);const r=this.chainId;this.chainId=e,this.events.emit(el.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${r}`})}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]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return ci(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){var e,i;const r={};return(i=(e=this.namespace)==null?void 0:e.accounts)==null||i.forEach(n=>{var s,o;const a=ci(n),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];r[a.reference]=this.createHttpProvider(n,c)}),r}getHttpProvider(e){const i=ci(e).reference,r=this.httpProviders[i];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||f0(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Yc(new i0(r,Rr("disableProviderPing")))}}var k4=Object.defineProperty,j4=Object.defineProperties,L4=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,M4=Object.prototype.hasOwnProperty,q4=Object.prototype.propertyIsEnumerable,ac=(t,e,i)=>e in t?k4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,sn=(t,e)=>{for(var i in e||(e={}))M4.call(e,i)&&ac(t,i,e[i]);if(Of)for(var i of Of(e))q4.call(e,i)&&ac(t,i,e[i]);return t},cs=(t,e)=>j4(t,L4(e)),at=(t,e,i)=>ac(t,typeof e!="symbol"?e+"":e,i);class tl{constructor(e){at(this,"client"),at(this,"namespaces"),at(this,"optionalNamespaces"),at(this,"sessionProperties"),at(this,"scopedProperties"),at(this,"events",new lc),at(this,"rpcProviders",{}),at(this,"session"),at(this,"providerOpts"),at(this,"logger"),at(this,"uri"),at(this,"disableProviderPing",!1),at(this,"connectParams");var i,r;this.providerOpts=e,this.logger=Kc({logger:(i=e.logger)!=null?i:df,name:(r=this.providerOpts.name)!=null?r:l0}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const i=new tl(e);return await i.initialize(),i}async request(e,i,r){const[n,s]=this.validateChain(i);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:sn({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:r})}sendAsync(e,i,r,n){const s=new Date().getTime();this.request(e,r,n).then(o=>i(null,Sn(s,o))).catch(o=>i(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:fe("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,i){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:n}=await this.client.authenticate(e,i);r&&(this.uri=r,this.events.emit("display_uri",r));const s=await n();if(this.session=s.session,this.session){const o=bf(this.session.namespaces);this.namespaces=as(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}removeListener(e,i){this.events.removeListener(e,i)}off(e,i){this.events.off(e,i)}get isWalletConnect(){return!0}async pair(e){var i,r;const{uri:n,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(i=this.connectParams)==null?void 0:i.authentication,walletPay:(r=this.connectParams)==null?void 0:r.walletPay});n&&(this.uri=n,this.events.emit("display_uri",n));const o=await s();this.session=o;const a=bf(o.namespaces);return this.namespaces=as(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,i){try{if(!this.session)return;const[r,n]=this.validateChain(e);this.getProvider(r).setDefaultChain(n,i)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const i=this.client.pairing.getAll();if(!It(i))return;for(const r of i)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${i.length}`)}catch(i){this.logger.warn(i,"Failed to cleanup pending pairings")}}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,i;if(this.client=this.providerOpts.client||await fA.init({core:this.providerOpts.core,logger:this.providerOpts.logger||df,relayUrl:this.providerOpts.relayUrl||WA,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(r){throw this.logger.error(r,"Failed to get session"),new Error(`The provided session: ${(i=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:i.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[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(i=>Dr(i)))];ca("client",this.client),ca("events",this.events),ca("disableProviderPing",this.disableProviderPing),e.forEach(i=>{if(!this.session)return;const r=n4(i,this.session);if((r==null?void 0:r.length)===0)return;const n=d0(r),s=as(this.namespaces,this.optionalNamespaces),o=cs(sn({},s[i]),{accounts:r,chains:n});switch(i){case"eip155":this.rpcProviders[i]=new R4({namespace:o});break;default:this.rpcProviders[i]=new U4({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var i;const{topic:r}=e;r===((i=this.session)==null?void 0:i.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var i;const{params:r,topic:n}=e;if(n!==((i=this.session)==null?void 0:i.topic))return;const{event:s}=r;if(s.name==="accountsChanged"){const o=s.data;o&&It(o)&&this.events.emit("accountsChanged",o.map(mf))}else if(s.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=Dr(o),l=aa(o)!==aa(a)?`${c}:${aa(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:i})=>{var r,n;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:s}=i,o=(n=this.client)==null?void 0:n.session.get(e);this.session=cs(sn({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:i})}),this.client.on("session_delete",async e=>{var i;e.topic===((i=this.session)==null?void 0:i.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",cs(sn({},fe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(el.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(cs(sn({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[h0]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var i;this.getProvider(e).updateNamespace((i=this.session)==null?void 0:i.namespaces[e])})}setNamespaces(e){const{namespaces:i={},optionalNamespaces:r={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=as(i,r),this.sessionProperties=n,this.scopedProperties=s}validateChain(e){const[i,r]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[i,r];if(i&&!Object.keys(this.namespaces||{}).map(o=>Dr(o)).includes(i))throw new Error(`Namespace '${i}' is not configured. Please call connect() first with namespace config.`);if(i&&r)return[i,r];const n=Dr(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:i,internal:r=!1}){if(!this.namespaces)return;const[n,s]=this.validateChain(e);s&&(this.updateNamespaceChain(n,s),r?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:i})):this.getProvider(n).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:i,previousCaipChainId:r}){var n,s;try{if(r===i)return;const o=(s=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(mf);if(!It(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,i){if(!this.namespaces)return;const r=this.namespaces[e]?e:`${e}:${i}`,n={chains:[],methods:[],events:[],defaultChain:i};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=i):this.namespaces[r]=n}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,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,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,i){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${ss}/${e}${n}`,i)}async getFromStore(e){var i;const r=((i=this.session)==null?void 0:i.topic)||"";return await this.client.core.storage.getItem(`${ss}/${e}${r}`)}async deleteFromStore(e){var i;const r=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.removeItem(`${ss}/${e}${r}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const i=await this.client.core.storage.getKeys();for(const r of i)r.startsWith(ss)&&await this.client.core.storage.removeItem(r)}catch(i){this.logger.warn(i,"Failed to cleanup storage")}}}const z4=tl,V4="wc",H4="ethereum_provider",K4=`${V4}@2:${H4}:`,W4="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],y0=["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"],js=["chainChanged","accountsChanged"],w0=["chainChanged","accountsChanged","message","disconnect","connect"],G4=async()=>{const{createAppKit:t}=await O0(()=>import("./core-80de04d5.js").then(e=>e.bK),["assets/core-80de04d5.js","assets/index-3c0257eb.js","assets/index-40d93065.css"]);return t};var Y4=Object.defineProperty,Z4=Object.defineProperties,J4=Object.getOwnPropertyDescriptors,Af=Object.getOwnPropertySymbols,X4=Object.prototype.hasOwnProperty,Q4=Object.prototype.propertyIsEnumerable,cc=(t,e,i)=>e in t?Y4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Wi=(t,e)=>{for(var i in e||(e={}))X4.call(e,i)&&cc(t,i,e[i]);if(Af)for(var i of Af(e))Q4.call(e,i)&&cc(t,i,e[i]);return t},on=(t,e)=>Z4(t,J4(e)),ct=(t,e,i)=>cc(t,typeof e!="symbol"?e+"":e,i);function Ls(t){return Number(t[0].split(":")[1])}function ls(t){return`0x${t.toString(16)}`}function e5(t){const{chains:e,optionalChains:i,methods:r,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!It(e))throw new Error("Invalid chains");const c={chains:e,methods:r||ks,events:s||js,rpcMap:Wi({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},l=s==null?void 0:s.filter(d=>!js.includes(d)),u=r==null?void 0:r.filter(d=>!ks.includes(d));if(!i&&!o&&!n&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const h=(l==null?void 0:l.length)&&(u==null?void 0:u.length)||!i,f={chains:[...new Set(h?c.chains.concat(i||[]):i)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:y0))],events:[...new Set(c.events.concat(o!=null&&o.length?o:w0))],rpcMap:a};return{required:e.length?c:void 0,optional:i.length?f:void 0}}class uo{constructor(){ct(this,"events",new St.EventEmitter),ct(this,"namespace","eip155"),ct(this,"accounts",[]),ct(this,"signer"),ct(this,"chainId",1),ct(this,"modal"),ct(this,"rpc"),ct(this,"STORAGE_KEY",K4),ct(this,"on",(e,i)=>(this.events.on(e,i),this)),ct(this,"once",(e,i)=>(this.events.once(e,i),this)),ct(this,"removeListener",(e,i)=>(this.events.removeListener(e,i),this)),ct(this,"off",(e,i)=>(this.events.off(e,i),this)),ct(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const i=new uo;return await i.initialize(e),i}async request(e,i){return await this.signer.request(e,this.formatChainId(this.chainId),i)}sendAsync(e,i,r){this.signer.sendAsync(e,i,this.formatChainId(this.chainId),r)}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 i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=e5(this.rpc);try{const s=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(on(Wi({namespaces:Wi({},r&&{[this.namespace]:r})},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!s)return;const o=bu(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async authenticate(e,i){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const n=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(on(Wi({},e),{chains:this.rpc.chains}),i).then(u=>{o(u)}).catch(u=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),s=n.session;if(s){const o=bu(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.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:i}=e,{event:r}=i;r.name==="accountsChanged"?(this.accounts=this.parseAccounts(r.data),this.events.emit("accountsChanged",this.accounts)):r.name==="chainChanged"?this.setChainId(this.formatChainId(r.data)):this.events.emit(r.name,r.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 i=parseInt(e);this.chainId=i,this.events.emit("chainChanged",ls(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",on(Wi({},fe("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 i=e.filter(r=>this.isCompatibleChainId(r)).map(r=>this.parseChainId(r));i.length&&(this.chainId=i[0],this.events.emit("chainChanged",ls(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const i=this.parseChainId(e);this.chainId=i,this.switchEthereumChain(i)}}parseAccountId(e){const[i,r,n]=e.split(":");return{chainId:`${i}:${r}`,address:n}}setAccounts(e){this.accounts=e.filter(i=>this.parseChainId(this.parseAccountId(i).chainId)===this.chainId).map(i=>this.parseAccountId(i).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var i,r;const n=(i=e==null?void 0:e.chains)!=null?i:[],s=(r=e==null?void 0:e.optionalChains)!=null?r:[],o=n.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=n.length?(e==null?void 0:e.methods)||ks:[],c=n.length?(e==null?void 0:e.events)||js:[],l=(e==null?void 0:e.optionalMethods)||[],u=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),f=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:n==null?void 0:n.map(d=>this.formatChainId(d)),optionalChains:s.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,i){const r={};return e.forEach(n=>{r[n]=this.getRpcUrl(n,i)}),r}async initialize(e){var i;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await z4.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 r;try{const n=await G4(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return h5}),o=s(on(Wi({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");r=n(on(Wi({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((i=this.rpc.qrModalOptions)==null?void 0:i.enableMobileFullScreen)===!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:i,optionalChains:r,rpcMap:n}=e;i&&It(i)&&(this.rpc.chains=i.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)})),r&&It(r)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=r==null?void 0:r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)}))}getRpcUrl(e,i){var r;return((r=this.rpc.rpcMap)==null?void 0:r[e])||`${W4}?chainId=eip155:${e}&projectId=${i||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),i=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:i==null?void 0:i.accounts),this.setAccounts(i==null?void 0:i.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(i=>this.signer.logger.warn(i))}}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(i=>this.parseAccount(i))}}const t5=uo;var i5=Object.defineProperty,r5=Object.defineProperties,n5=Object.getOwnPropertyDescriptors,Pf=Object.getOwnPropertySymbols,s5=Object.prototype.hasOwnProperty,o5=Object.prototype.propertyIsEnumerable,Cf=(t,e,i)=>e in t?i5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,m0=(t,e)=>{for(var i in e||(e={}))s5.call(e,i)&&Cf(t,i,e[i]);if(Pf)for(var i of Pf(e))o5.call(e,i)&&Cf(t,i,e[i]);return t},a5=(t,e)=>r5(t,n5(e));function c5(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const l5=t=>{const[e,i]=t.split(":");return b0({id:i,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function u5(t){var e,i,r,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(l5).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),u={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:c5(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:a5(m0({},t.metadata),{name:((i=t.metadata)==null?void 0:i.name)||"WalletConnect",description:((r=t.metadata)==null?void 0:r.description)||"Connect to WalletConnect-compatible wallets",url:((n=t.metadata)==null?void 0:n.url)||"https://walletconnect.org",icons:((s=t.metadata)==null?void 0:s.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],f=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],d=h.filter(p=>!f.includes(p.id));d.length&&(u.customWallets=d)}return u}function b0(t){return m0({formatters:void 0,fees:void 0,serializers:void 0},t)}var h5=Object.freeze({__proto__:null,convertWCMToAppKitOptions:u5,defineChain:b0});const tP=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:t5,OPTIONAL_EVENTS:w0,OPTIONAL_METHODS:y0,REQUIRED_EVENTS:js,REQUIRED_METHODS:ks,default:uo},Symbol.toStringTag,{value:"Module"}));export{B8 as A,Yc as B,oE as C,i3 as D,QS as E,Gc as F,ao as G,Sn as H,ur as I,hr as J,Ct as K,l2 as L,Ri as M,oo as N,Mt as O,lu as P,Xd as Q,vt as R,Lt as S,i0 as T,tP as U,dt as X,Ep as Y,J8 as a,X8 as b,Ag as c,rs as d,Q8 as e,sr as f,bh as g,Ff as h,L as i,Et as j,tS as k,rr as l,uc as m,An as n,c1 as o,Qm as p,mm as q,Im as r,ui as s,nt as t,mE as u,U0 as v,Rf as w,fn as x,Aa as y,st as z};
|