@dcl/governance-site 1.15.1-20473093943.commit-ad8dc42 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/{UserAvatar-41371133.js → UserAvatar-78751cb5.js} +1 -1
- package/assets/{basic-de12c849.js → basic-ca749c4c.js} +1 -1
- package/assets/{core-0c13d1dd.js → core-806d78ea.js} +7 -7
- package/assets/{features-e842dc9f.js → features-b72c9430.js} +1 -1
- package/assets/{fortmatic-dbae6d9f.js → fortmatic-12e0f2e5.js} +1 -1
- package/assets/{index-2a49049d.js → index-073512a1.js} +1 -1
- package/assets/{index-726bc846.js → index-2ef9f1d1.js} +14 -14
- package/assets/{index-bc60e460.js → index-372705ba.js} +1 -1
- package/assets/{index-6dad6f13.js → index-4be588a0.js} +1 -1
- package/assets/{index-37d53923.js → index-74e34dfb.js} +2 -2
- package/assets/{index-a5cbd387.css → index-a8255d1c.css} +4 -4
- package/assets/{index-16e232ba.js → index-bbb36593.js} +1 -1
- package/assets/{index-c2e969f4.js → index-c1c8440f.js} +1 -1
- package/assets/{tslib.es6-1071ccd0.js → tslib.es6-82b9ba96.js} +1 -1
- package/assets/{w3m-modal-d813356f.js → w3m-modal-26eff9d9.js} +1 -1
- package/index.html +4 -4
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as xt,g as kf,h as Y,B as re,i as St,c as gi,x as dc,o as dl,_ as T0}from"./index-
|
|
1
|
+
import{e as xt,g as kf,h as Y,B as re,i as St,c as gi,x as dc,o as dl,_ as T0}from"./index-2ef9f1d1.js";var pl=globalThis&&globalThis.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var i=0,n=e.length,s;i<n;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return t.concat(s||Array.prototype.slice.call(e))},R0=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),F0=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=xt.platform}return t}(),N0=function(){function t(e,r,i,n){this.name=e,this.version=r,this.os=i,this.bot=n,this.type="bot-device"}return t}(),U0=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),k0=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),j0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,L0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,gl=3,M0=[["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",j0]],yl=[["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 q0(t){return t?wl(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new k0:typeof navigator<"u"?wl(navigator.userAgent):H0()}function z0(t){return t!==""&&M0.reduce(function(e,r){var i=r[0],n=r[1];if(e)return e;var s=n.exec(t);return!!s&&[i,s]},!1)}function wl(t){var e=z0(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new U0;var n=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);n?n.length<gl&&(n=pl(pl([],n,!0),K0(gl-n.length),!0)):n=[];var s=n.join("."),o=V0(t),a=L0.exec(t);return a&&a[1]?new N0(r,s,o,a[1]):new R0(r,s,o)}function V0(t){for(var e=0,r=yl.length;e<r;e++){var i=yl[e],n=i[0],s=i[1],o=s.exec(t);if(o)return n}return null}function H0(){var t=typeof xt<"u"&&xt.version;return t?new F0(xt.version.slice(1)):null}function K0(t){for(var e=[],r=0;r<t;r++)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
|
|
@@ -36,4 +36,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
|
36
36
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
37
37
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
38
38
|
PERFORMANCE OF THIS SOFTWARE.
|
|
39
|
-
***************************************************************************** */var Ya=function(t,e){return Ya=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Ya(t,e)};function KS(t,e){Ya(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Za=function(){return Za=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Za.apply(this,arguments)};function WS(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function GS(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function YS(t,e){return function(r,i){e(r,i,t)}}function ZS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function JS(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):n(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function XS(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=l[0]&2?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,n=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function QS(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function e$(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Ja(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Lg(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function t$(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Lg(arguments[e]));return t}function r$(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function Sn(t){return this instanceof Sn?(this.v=t,this):new Sn(t)}function i$(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(f){i[f]&&(n[f]=function(d){return new Promise(function(p,g){s.push([f,d,p,g])>1||a(f,d)})})}function a(f,d){try{c(i[f](d))}catch(p){h(s[0][3],p)}}function c(f){f.value instanceof Sn?Promise.resolve(f.value.v).then(l,u):h(s[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,d){f(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function n$(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:Sn(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function s$(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Ja=="function"?Ja(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),n(a,c,o.done,o.value)})}}function n(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function o$(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function a$(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function c$(t){return t&&t.__esModule?t:{default:t}}function l$(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function u$(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const h$=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Za},__asyncDelegator:n$,__asyncGenerator:i$,__asyncValues:s$,__await:Sn,__awaiter:JS,__classPrivateFieldGet:l$,__classPrivateFieldSet:u$,__createBinding:QS,__decorate:GS,__exportStar:e$,__extends:KS,__generator:XS,__importDefault:c$,__importStar:a$,__makeTemplateObject:o$,__metadata:ZS,__param:YS,__read:Lg,__rest:WS,__spread:t$,__spreadArrays:r$,__values:Ja},Symbol.toStringTag,{value:"Module"})),f$=kf(h$);var er={},Ah;function d$(){if(Ah)return er;Ah=1,Object.defineProperty(er,"__esModule",{value:!0}),er.isBrowserCryptoAvailable=er.getSubtleCrypto=er.getBrowerCrypto=void 0;function t(){return(gi===null||gi===void 0?void 0:gi.crypto)||(gi===null||gi===void 0?void 0:gi.msCrypto)||{}}er.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}er.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return er.isBrowserCryptoAvailable=r,er}var tr={},Ph;function p$(){if(Ph)return tr;Ph=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.isBrowser=tr.isNode=tr.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}tr.isReactNative=t;function e(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}tr.isNode=e;function r(){return!t()&&!e()}return tr.isBrowser=r,tr}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=f$;e.__exportStar(d$(),t),e.__exportStar(p$(),t)})(jg);function Lt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Rr(t=6){return BigInt(Lt(t))}function Ct(t,e,r){return{id:r||Lt(),jsonrpc:"2.0",method:t,params:e}}function $n(t,e){return{id:t,jsonrpc:"2.0",result:e}}function oo(t,e,r){return{id:t,jsonrpc:"2.0",error:g$(e,r)}}function g$(t,e){return typeof t>"u"?Dh(Ng):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dh(Jc)),{message:t})),typeof e<"u"&&(t.data=e),VS(t.code)&&(t=HS(t.code)),t)}class y${}class w$ extends y${constructor(){super()}}class m$ extends w${constructor(e){super()}}const b$="^https?:",v$="^wss?:";function E$(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Mg(t,e){const r=E$(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ch(t){return Mg(t,b$)}function Bh(t){return Mg(t,v$)}function x$(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function qg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Xc(t){return qg(t)&&"method"in t}function ao(t){return qg(t)&&(Mt(t)||vt(t))}function Mt(t){return"result"in t}function vt(t){return"error"in t}class Qc extends m${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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Ct(e.method,e.params||[],e.id||Rr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{vt(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}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)}}var ta,Th;function _$(){return Th||(Th=1,ta=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),ta}const I$=()=>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:_$(),S$=()=>typeof WebSocket<"u"||typeof Y<"u"&&typeof Y.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Rh=t=>t.split("?")[0],Fh=10,$$=I$();let O$=class{constructor(e){if(this.url=e,this.events=new St.EventEmitter,this.registering=!1,!Bh(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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(oi(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Bh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,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"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=jg.isReactNative()?void 0:{rejectUnauthorized:!x$(e)},s=new $$(e,[],n);S$()?s.onerror=o=>{const a=o;i(this.emitError(a.error))}:s.on("error",o=>{i(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),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 r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return kg(e,Rh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Fh&&this.events.setMaxListeners(Fh)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Rh(this.url)}`));return this.events.emit("register_error",r),r}};const zg="wc",Vg=2,Us="core",Wt=`${zg}@2:${Us}:`,D$={name:Us,logger:"error"},A$={database:":memory:"},P$="crypto",Nh="client_ed25519_seed",C$=L.ONE_DAY,B$="keychain",T$="0.3",R$="messages",F$="0.3",N$=L.SIX_HOURS,U$="publisher",Hg="irn",k$="error",Kg="wss://relay.walletconnect.org",j$="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"},L$="_subscription",gt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},M$=.1,Xa="2.23.1",he={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},q$="0.3",z$="WALLETCONNECT_CLIENT_ID",Uh="WALLETCONNECT_LINK_MODE_APPS",lt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},V$="subscription",H$="0.3",K$="pairing",W$="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}}},Yr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},G$="history",Y$="0.3",Z$="expirer",wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},J$="0.3",X$="verify-api",Q$="https://verify.walletconnect.com",Wg="https://verify.walletconnect.org",gn=Wg,e6=`${gn}/v3`,t6=[Q$,Wg],r6="echo",i6="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"},ir={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"},Dt={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"},zr={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"},Vr={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"},n6=.1,s6="event-client",o6=86400,a6="https://pulse.walletconnect.org/batch";function c6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[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,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*u+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}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,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;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 l6=c6,u6=l6;const Gg=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")},h6=t=>new TextEncoder().encode(t),f6=t=>new TextDecoder().decode(t);class d6{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class p6{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yg(this,e)}}class g6{constructor(e){this.decoders=e}or(e){return Yg(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yg=(t,e)=>new g6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class y6{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new d6(e,r,i),this.decoder=new p6(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const co=({name:t,prefix:e,encode:r,decode:i})=>new y6(t,e,r,i),kn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=u6(r,e);return co({prefix:t,name:e,encode:i,decode:s=>Gg(n(s))})},w6=(t,e,r,i)=>{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*r/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-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},m6=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Ue=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>co({prefix:e,name:t,encode(n){return m6(n,i,r)},decode(n){return w6(n,i,r,t)}}),b6=co({prefix:"\0",name:"identity",encode:t=>f6(t),decode:t=>h6(t)});var v6=Object.freeze({__proto__:null,identity:b6});const E6=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var x6=Object.freeze({__proto__:null,base2:E6});const _6=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var I6=Object.freeze({__proto__:null,base8:_6});const S6=kn({prefix:"9",name:"base10",alphabet:"0123456789"});var $6=Object.freeze({__proto__:null,base10:S6});const O6=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),D6=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var A6=Object.freeze({__proto__:null,base16:O6,base16upper:D6});const P6=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),C6=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),B6=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),T6=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),R6=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),F6=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),N6=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),U6=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),k6=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var j6=Object.freeze({__proto__:null,base32:P6,base32upper:C6,base32pad:B6,base32padupper:T6,base32hex:R6,base32hexupper:F6,base32hexpad:N6,base32hexpadupper:U6,base32z:k6});const L6=kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),M6=kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var q6=Object.freeze({__proto__:null,base36:L6,base36upper:M6});const z6=kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),V6=kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var H6=Object.freeze({__proto__:null,base58btc:z6,base58flickr:V6});const K6=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),W6=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),G6=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Y6=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Z6=Object.freeze({__proto__:null,base64:K6,base64pad:W6,base64url:G6,base64urlpad:Y6});const Zg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),J6=Zg.reduce((t,e,r)=>(t[r]=e,t),[]),X6=Zg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Q6(t){return t.reduce((e,r)=>(e+=J6[r],e),"")}function eO(t){const e=[];for(const r of t){const i=X6[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const tO=co({prefix:"🚀",name:"base256emoji",encode:Q6,decode:eO});var rO=Object.freeze({__proto__:null,base256emoji:tO}),iO=Jg,kh=128,nO=127,sO=~nO,oO=Math.pow(2,31);function Jg(t,e,r){e=e||[],r=r||0;for(var i=r;t>=oO;)e[r++]=t&255|kh,t/=128;for(;t&sO;)e[r++]=t&255|kh,t>>>=7;return e[r]=t|0,Jg.bytes=r-i+1,e}var aO=Qa,cO=128,jh=127;function Qa(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw Qa.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&jh)<<n:(o&jh)*Math.pow(2,n),n+=7}while(o>=cO);return Qa.bytes=s-i,r}var lO=Math.pow(2,7),uO=Math.pow(2,14),hO=Math.pow(2,21),fO=Math.pow(2,28),dO=Math.pow(2,35),pO=Math.pow(2,42),gO=Math.pow(2,49),yO=Math.pow(2,56),wO=Math.pow(2,63),mO=function(t){return t<lO?1:t<uO?2:t<hO?3:t<fO?4:t<dO?5:t<pO?6:t<gO?7:t<yO?8:t<wO?9:10},bO={encode:iO,decode:aO,encodingLength:mO},Xg=bO;const Lh=(t,e,r=0)=>(Xg.encode(t,e,r),e),Mh=t=>Xg.encodingLength(t),ec=(t,e)=>{const r=e.byteLength,i=Mh(t),n=i+Mh(r),s=new Uint8Array(n+r);return Lh(t,s,0),Lh(r,s,i),s.set(e,n),new vO(t,r,e,s)};class vO{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const Qg=({name:t,code:e,encode:r})=>new EO(t,e,r);class EO{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?ec(this.code,r):r.then(i=>ec(this.code,i))}else throw Error("Unknown type, must be binary type")}}const e0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),xO=Qg({name:"sha2-256",code:18,encode:e0("SHA-256")}),_O=Qg({name:"sha2-512",code:19,encode:e0("SHA-512")});var IO=Object.freeze({__proto__:null,sha256:xO,sha512:_O});const t0=0,SO="identity",r0=Gg,$O=t=>ec(t0,r0(t)),OO={code:t0,name:SO,encode:r0,digest:$O};var DO=Object.freeze({__proto__:null,identity:OO});new TextEncoder,new TextDecoder;const qh={...v6,...x6,...I6,...$6,...A6,...j6,...q6,...H6,...Z6,...rO};({...IO,...DO});function i0(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function AO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?i0(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function n0(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const zh=n0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ra=n0("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=AO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),PO={utf8:zh,"utf-8":zh,hex:qh.base16,latin1:ra,ascii:ra,binary:ra,...qh};function CO(t,e="utf8"){const r=PO[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?i0(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var BO=Object.defineProperty,TO=(t,e,r)=>e in t?BO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ut=(t,e,r)=>TO(t,typeof e!="symbol"?e+"":e,r);class RO{constructor(e,r){this.core=e,this.logger=r,Ut(this,"keychain",new Map),Ut(this,"name",B$),Ut(this,"version",T$),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Wt),Ut(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Ut(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Ut(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),Ut(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=M("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),Ut(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=dt(r,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,Ra(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fa(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 FO=Object.defineProperty,NO=(t,e,r)=>e in t?FO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Se=(t,e,r)=>NO(t,typeof e!="symbol"?e+"":e,r);class UO{constructor(e,r,i){this.core=e,this.logger=r,Se(this,"name",P$),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Ka()),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=du(n),o=sp(s.publicKey);return this.clientId=o,o}),Se(this,"generateKeyPair",()=>{this.isInitialized();const n=bI();return this.setPrivateKey(n.publicKey,n.privateKey)}),Se(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=du(s),a=this.randomSessionIdentifier;return await p2(a,n,C$,o)}),Se(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=vI(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=Pg(o),c=oi(s);if(ah(a))return _I(c,o==null?void 0:o.encoding);if(oh(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 EI({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=SI(s,o);if(ah(a)){const c=II(s,o==null?void 0:o.encoding);return si(c)}if(oh(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=xI({symKey:c,encoded:s,encoding:o==null?void 0:o.encoding});return si(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=In({encoded:n,encoding:s});return ci(o.type)}),Se(this,"getPayloadSenderPublicKey",(n,s=tt)=>{const o=In({encoded:n,encoding:s});return o.senderPublicKey?nt(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=dt(r,this.name),this.keychain=i||new RO(this.core,this.logger)}get context(){return st(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Nh)}catch{e=Ka(),await this.keychain.set(Nh,e)}return CO(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 kO=Object.defineProperty,jO=Object.defineProperties,LO=Object.getOwnPropertyDescriptors,Vh=Object.getOwnPropertySymbols,MO=Object.prototype.hasOwnProperty,qO=Object.prototype.propertyIsEnumerable,tc=(t,e,r)=>e in t?kO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zO=(t,e)=>{for(var r in e||(e={}))MO.call(e,r)&&tc(t,r,e[r]);if(Vh)for(var r of Vh(e))qO.call(e,r)&&tc(t,r,e[r]);return t},VO=(t,e)=>jO(t,LO(e)),ot=(t,e,r)=>tc(t,typeof e!="symbol"?e+"":e,r);class HO extends $S{constructor(e,r){super(e,r),this.logger=e,this.core=r,ot(this,"messages",new Map),ot(this,"messagesWithoutClientAck",new Map),ot(this,"name",R$),ot(this,"version",F$),ot(this,"initialized",!1),ot(this,"storagePrefix",Wt),ot(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);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(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ot(this,"set",async(i,n,s)=>{this.isInitialized();const o=bt(n);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(i,a),s===ys.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,VO(zO({},c),{[o]:n}))}return await this.persist(),o}),ot(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),ot(this,"getWithoutAck",i=>{this.isInitialized();const n={};for(const s of i){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),ot(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=bt(n);return typeof s[o]<"u"}),ot(this,"ack",async(i,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(i);if(typeof s>"u")return;const o=bt(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,s),await this.persist()}),ot(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=dt(e,this.name),this.core=r}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,Ra(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ra(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fa(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Fa(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 KO=Object.defineProperty,WO=Object.defineProperties,GO=Object.getOwnPropertyDescriptors,Hh=Object.getOwnPropertySymbols,YO=Object.prototype.hasOwnProperty,ZO=Object.prototype.propertyIsEnumerable,rc=(t,e,r)=>e in t?KO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e)=>{for(var r in e||(e={}))YO.call(e,r)&&rc(t,r,e[r]);if(Hh)for(var r of Hh(e))ZO.call(e,r)&&rc(t,r,e[r]);return t},Kh=(t,e)=>WO(t,GO(e)),yt=(t,e,r)=>rc(t,typeof e!="symbol"?e+"":e,r);class JO extends OS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,yt(this,"events",new St.EventEmitter),yt(this,"name",U$),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(i,n,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const h=(s==null?void 0:s.ttl)||N$,f=(s==null?void 0:s.prompt)||!1,d=(s==null?void 0:s.tag)||0,p=(s==null?void 0:s.id)||Rr().toString(),g=$i(Fs().protocol),w={id:p,method:(s==null?void 0:s.publishMethod)||g.publish,params:Ei({topic:i,message:n,ttl:h,prompt:f,tag:d,attestation:s==null?void 0:s.attestation},s==null?void 0:s.tvf)},I=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{_e((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),_e((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 D=Vt(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 D,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:i,message:n,opts:s}}),await Vt(C,this.publishTimeout,I)}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 i=>{var n,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:l,opts:u={}}=i,{attestation:h,tvf:f,publishMethod:d,prompt:p,tag:g,ttl:w=L.FIVE_MINUTES}=u,I=u.id||Rr().toString(),C=$i(Fs().protocol),b=d||C.publish,v={id:I,method:b,params:Ei(Kh(Ei({},l),{ttl:w,prompt:p,tag:g,attestation:h}),f)},D=`Failed to publish custom payload, please try again. id:${I} tag:${g}`;try{_e((n=v.params)==null?void 0:n.prompt)&&((s=v.params)==null||delete s.prompt),_e((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=Vt(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:${I} tag:${g}`);try{await A,this.events.removeListener(me.publish,R)}catch(U){this.queue.set(I,{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:I,payload:l,opts:u}}),await Vt(P,this.publishTimeout,D)}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(I)}}),yt(this,"on",(i,n)=>{this.events.on(i,n)}),yt(this,"once",(i,n)=>{this.events.once(i,n)}),yt(this,"off",(i,n)=>{this.events.off(i,n)}),yt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=dt(r,this.name),this.registerEventListeners()}get context(){return st(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(me.publish,Ei(Ei({},e),r)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var i;const n=e.attempt+1;this.queue.set(r,Kh(Ei({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.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(fi.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 XO=Object.defineProperty,QO=(t,e,r)=>e in t?XO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xi=(t,e,r)=>QO(t,typeof e!="symbol"?e+"":e,r);class eD{constructor(){xi(this,"map",new Map),xi(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),xi(this,"get",e=>this.map.get(e)||[]),xi(this,"exists",(e,r)=>this.get(e).includes(r)),xi(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),xi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var tD=Object.defineProperty,rD=Object.defineProperties,iD=Object.getOwnPropertyDescriptors,Wh=Object.getOwnPropertySymbols,nD=Object.prototype.hasOwnProperty,sD=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?tD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rn=(t,e)=>{for(var r in e||(e={}))nD.call(e,r)&&ic(t,r,e[r]);if(Wh)for(var r of Wh(e))sD.call(e,r)&&ic(t,r,e[r]);return t},ia=(t,e)=>rD(t,iD(e)),ce=(t,e,r)=>ic(t,typeof e!="symbol"?e+"":e,r);class oD extends PS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ce(this,"subscriptions",new Map),ce(this,"topicMap",new eD),ce(this,"events",new St.EventEmitter),ce(this,"name",V$),ce(this,"version",H$),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Wt),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(i,n)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const o=Fs(n),a={topic:i,relay:o,transportType:n==null?void 0:n.transportType};(s=n==null?void 0:n.internal)!=null&&s.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,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:i,opts:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(i,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),ce(this,"isSubscribed",i=>new Promise(n=>{n(this.topicMap.topics.includes(i))})),ce(this,"isKnownTopic",i=>new Promise(n=>{n(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(s=>s.topic===i))})),ce(this,"on",(i,n)=>{this.events.on(i,n)}),ce(this,"once",(i,n)=>{this.events.once(i,n)}),ce(this,"off",(i,n)=>{this.events.off(i,n)}),ce(this,"removeListener",(i,n)=>{this.events.removeListener(i,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 i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(fi.pulse,async()=>{await this.checkPending()}),this.events.on(lt.created,async i=>{const n=lt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(lt.deleted,async i=>{const n=lt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=dt(r,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,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=Fs(i);await this.restartToComplete({topic:e,id:r,relay:n}),await this.rpcUnsubscribe(e,r,n);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i){var n,s;const o=await this.getSubscriptionId(e);if((n=i==null?void 0:i.internal)!=null&&n.skipSubscribe)return o;(!i||(i==null?void 0:i.transportType)===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:$i(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{if((i==null?void 0:i.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 Vt(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 Vt(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 r=e[0].relay,i={method:$i(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Vt(new Promise(n=>{this.relayer.request(i).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 r=e[0].relay,i={method:$i(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Vt(new Promise((s,o)=>{this.relayer.request(i).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,r,i){const n={method:$i(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,ia(rn({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rn({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rn({},r)),this.topicMap.set(r.topic,e),this.events.emit(lt.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(lt.deleted,ia(rn({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(lt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){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(r=>{var i;return r.topic===((i=this.subscriptions.get(r.id))==null?void 0:i.topic)})){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}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 r=>ia(rn({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await k3(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.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 aD=Object.defineProperty,Gh=Object.getOwnPropertySymbols,cD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,nc=(t,e,r)=>e in t?aD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yh=(t,e)=>{for(var r in e||(e={}))cD.call(e,r)&&nc(t,r,e[r]);if(Gh)for(var r of Gh(e))lD.call(e,r)&&nc(t,r,e[r]);return t},ne=(t,e,r)=>nc(t,typeof e!="symbol"?e+"":e,r);class uD extends DS{constructor(e){var r;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",j$),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 i=>{var n,s;this.logger.debug("Publishing Request Payload");const o=i.id||Rr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(n=i.params)==null?void 0:n.topic},"relayer.request - publishing...");const a=`${o}:${((s=i.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);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 i,n,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(n=(i=this.provider)==null?void 0:i.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",i=>{this.onProviderPayload(i),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",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(me.error,i),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=Zc({logger:(r=e.logger)!=null?r:k$,name:this.name}),this.messages=new HO(this.logger,e.core),this.subscriber=new oD(this,this.logger),this.publisher=new JO(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Kg,x3()?this.packageName=Du():_3()&&(this.bundleId=Du()),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,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:he.relay},ys.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,n,s;this.isInitialized(),(!(r!=null&&r.transportType)||(r==null?void 0:r.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(n=r==null?void 0:r.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,Yh({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Vt(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(r,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await vh())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 r=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=we(L.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,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 r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(gt.disconnect,s),await Vt(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,i()})}catch(i){await this.subscriber.stop();const n=i;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: ${r}`);break}await new Promise(i=>setTimeout(i,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(As())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.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 Qc(new O$(D3({sdkVersion:Xa,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,r){const{topic:i,message:n}=e;await this.messages.set(i,n,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Xc(e)){if(!e.method.endsWith(L$))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Yh({type:"event",event:r.id},a)),this.events.emit(r.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 r=$n(e.id,!0);await this.provider.connection.send(r)}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 vh();S8(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(fi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&D8())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r==null?void 0:r.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(M$)))))}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 hD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Zh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const fD="[object RegExp]",dD="[object String]",pD="[object Number]",gD="[object Boolean]",Xh="[object Arguments]",yD="[object Symbol]",wD="[object Date]",mD="[object Map]",bD="[object Set]",vD="[object Array]",ED="[object Function]",xD="[object ArrayBuffer]",na="[object Object]",_D="[object Error]",ID="[object DataView]",SD="[object Uint8Array]",$D="[object Uint8ClampedArray]",OD="[object Uint16Array]",DD="[object Uint32Array]",AD="[object BigUint64Array]",PD="[object Int8Array]",CD="[object Int16Array]",BD="[object Int32Array]",TD="[object BigInt64Array]",RD="[object Float32Array]",FD="[object Float64Array]";function ND(){}function Qh(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 UD(t,e,r){return un(t,e,void 0,void 0,void 0,void 0,r)}function un(t,e,r,i,n,s,o){const a=o(t,e,r,i,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,r,i){if(Object.is(t,e))return!0;let n=Jh(t),s=Jh(e);if(n===Xh&&(n=na),s===Xh&&(s=na),n!==s)return!1;switch(n){case dD:return t.toString()===e.toString();case pD:{const c=t.valueOf(),l=e.valueOf();return hD(c,l)}case gD:case wD:case yD:return Object.is(t.valueOf(),e.valueOf());case fD:return t.source===e.source&&t.flags===e.flags;case ED:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(n){case mD:{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,r,i))return!1;return!0}case bD:{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,r,i));if(f===-1)return!1;l.splice(f,1)}return!0}case vD:case SD:case $D:case OD:case DD:case AD:case PD:case CD:case BD:case TD:case RD:case FD:{if(typeof re<"u"&&re.isBuffer(t)!==re.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,r,i))return!1;return!0}case xD:return t.byteLength!==e.byteLength?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case ID:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case _D:return t.name===e.name&&t.message===e.message;case na:{if(!(yn(t.constructor,e.constructor,r,i)||Qh(t)&&Qh(e)))return!1;const c=[...Object.keys(t),...Zh(t)],l=[...Object.keys(e),...Zh(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,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function kD(t,e){return UD(t,e,ND)}var jD=Object.defineProperty,ef=Object.getOwnPropertySymbols,LD=Object.prototype.hasOwnProperty,MD=Object.prototype.propertyIsEnumerable,sc=(t,e,r)=>e in t?jD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,tf=(t,e)=>{for(var r in e||(e={}))LD.call(e,r)&&sc(t,r,e[r]);if(ef)for(var r of ef(e))MD.call(e,r)&&sc(t,r,e[r]);return t},Ze=(t,e,r)=>sc(t,typeof e!="symbol"?e+"":e,r);class pi extends AS{constructor(e,r,i,n=Wt,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,Ze(this,"map",new Map),Ze(this,"version",q$),Ze(this,"cached",[]),Ze(this,"initialized",!1),Ze(this,"getKey"),Ze(this,"storagePrefix",Wt),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&&!_e(o)?this.map.set(this.getKey(o),o):r8(o)?this.map.set(o.id,o):i8(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=>kD(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=tf(tf({},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(r,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 r=this.map.get(e);if(!r){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:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}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:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 qD=Object.defineProperty,zD=(t,e,r)=>e in t?qD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>zD(t,typeof e!="symbol"?e+"":e,r);class VD{constructor(e,r){this.core=e,this.logger=r,ee(this,"name",K$),ee(this,"version",W$),ee(this,"events",new dc),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",Wt),ee(this,"ignoredPayloadTypes",[hr]),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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),ee(this,"create",async i=>{this.isInitialized();const n=Ka(),s=await this.core.crypto.setSymKey(n),o=we(L.FIVE_MINUTES),a={protocol:Hg},c={topic:s,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=hh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Yr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:i==null?void 0:i.transportType,internal:i==null?void 0:i.internal}),{topic:s,uri:l}}),ee(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[jt.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=uh(i.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(ir.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),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Yr.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(ir.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw n.setError(ir.subscribe_pairing_topic_failure),d}return n.addTrace(jt.subscribe_pairing_topic_success),f}),ee(this,"activate",async({topic:i})=>{this.isInitialized();const n=we(L.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),ee(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Kr();this.events.once(ae("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),ee(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),ee(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(n))}),ee(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return hh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(i,n,s)=>{const o=Ct(n,s),a=await this.core.crypto.encode(i,o),c=en[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),ee(this,"sendResult",async(i,n,s)=>{const o=$n(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,l=en[c].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),ee(this,"sendError",async(i,n,s)=>{const o=oo(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).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(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),ee(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>qt(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),ee(this,"onRelayEventRequest",async i=>{const{topic:n,payload:s}=i;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 i=>{const{topic:n,payload:s}=i,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(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Yr.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(i,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(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Yr.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(i,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,i,a),this.logger.error(a)}catch(a){await this.sendError(s,i,a),this.logger.error(a)}}),ee(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",i))}),ee(this,"isValidPair",(i,n)=>{var s;if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(ir.malformed_pairing_uri),new Error(a)}if(!t8(i.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(ir.malformed_pairing_uri),new Error(a)}const o=uh(i==null?void 0:i.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(ir.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(ir.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){n.setError(ir.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 i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidDisconnect",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidPairingTopic",async i=>{if(!be(i,!1)){const{message:n}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(qt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=M("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=dt(r,this.name),this.pairings=new pi(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:r,message:i,transportType:n}=e;if(this.pairings.keys.includes(r)&&n!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const s=await this.core.crypto.decode(r,i);Xc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ao(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,i)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(wt.expired,async e=>{const{topic:r}=Bp(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Yr.expire,{topic:r}))})}}var HD=Object.defineProperty,KD=(t,e,r)=>e in t?HD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>KD(t,typeof e!="symbol"?e+"":e,r);class WD extends SS{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new St.EventEmitter),Be(this,"name",G$),Be(this,"version",Y$),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Wt),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Be(this,"set",(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:i,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(Ot.created,o)}),Be(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=vt(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Ot.updated,n))}),Be(this,"get",async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n))),Be(this,"delete",(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Ot.deleted,s)}}),this.persist()}),Be(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),Be(this,"on",(i,n)=>{this.events.on(i,n)}),Be(this,"once",(i,n)=>{this.events.once(i,n)}),Be(this,"off",(i,n)=>{this.events.off(i,n)}),Be(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,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(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Ct(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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(Ot.created,e=>{const r=Ot.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.updated,e=>{const r=Ot.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.deleted,e=>{const r=Ot.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(fi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Ot.deleted,r,!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 GD=Object.defineProperty,YD=(t,e,r)=>e in t?GD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ze=(t,e,r)=>YD(t,typeof e!="symbol"?e+"":e,r);class ZD extends CS{constructor(e,r){super(e,r),this.core=e,this.logger=r,ze(this,"expirations",new Map),ze(this,"events",new St.EventEmitter),ze(this,"name",Z$),ze(this,"version",J$),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Wt),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),ze(this,"set",(i,n)=>{this.isInitialized();const s=this.formatTarget(i),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",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),ze(this,"del",i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(wt.deleted,{target:n,expiration:s})}}),ze(this,"on",(i,n)=>{this.events.on(i,n)}),ze(this,"once",(i,n)=>{this.events.once(i,n)}),ze(this,"off",(i,n)=>{this.events.off(i,n)}),ze(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,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 A3(e);if(typeof e=="number")return P3(e);const{message:r}=M("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}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:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 r=this.expirations.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;L.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(wt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(fi.pulse,()=>this.checkExpirations()),this.events.on(wt.created,e=>{const r=wt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.expired,e=>{const r=wt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.deleted,e=>{const r=wt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var JD=Object.defineProperty,XD=(t,e,r)=>e in t?JD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ye=(t,e,r)=>XD(t,typeof e!="symbol"?e+"":e,r);class QD extends BS{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,ye(this,"name",X$),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",e6),ye(this,"storagePrefix",Wt),ye(this,"version",Vg),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(!Mi()||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=ii(),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=I=>{if(I.data&&typeof I.data=="string")try{const C=JSON.parse(I.data);if(C.type==="verify_attestation"){if(Pa(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(Pa(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 t6.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=OI(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(r,this.name),this.abortController=new AbortController,this.isDevEnv=jc(),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 e4=Object.defineProperty,t4=(t,e,r)=>e in t?e4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rf=(t,e,r)=>t4(t,typeof e!="symbol"?e+"":e,r);class r4 extends TS{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,rf(this,"context",r6),rf(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${i6}/${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(r,this.context)}}var i4=Object.defineProperty,nf=Object.getOwnPropertySymbols,n4=Object.prototype.hasOwnProperty,s4=Object.prototype.propertyIsEnumerable,oc=(t,e,r)=>e in t?i4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nn=(t,e)=>{for(var r in e||(e={}))n4.call(e,r)&&oc(t,r,e[r]);if(nf)for(var r of nf(e))s4.call(e,r)&&oc(t,r,e[r]);return t},$e=(t,e,r)=>oc(t,typeof e!="symbol"?e+"":e,r);class o4 extends RS{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,$e(this,"context",s6),$e(this,"storagePrefix",Wt),$e(this,"storageVersion",n6),$e(this,"events",new Map),$e(this,"shouldPersist",!1),$e(this,"init",async()=>{if(!jc())try{const n={eventId:Pu(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Pp(this.core.relayer.protocol,this.core.relayer.version,Xa)}}};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=Pu(),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(fi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(n.timestamp)>o6&&(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(`${a6}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Xa}${s}`,{method:"POST",body:JSON.stringify(n)})}),$e(this,"getAppDomain",()=>Ap().url),this.logger=dt(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var a4=Object.defineProperty,sf=Object.getOwnPropertySymbols,c4=Object.prototype.hasOwnProperty,l4=Object.prototype.propertyIsEnumerable,ac=(t,e,r)=>e in t?a4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,of=(t,e)=>{for(var r in e||(e={}))c4.call(e,r)&&ac(t,r,e[r]);if(sf)for(var r of sf(e))l4.call(e,r)&&ac(t,r,e[r]);return t},le=(t,e,r)=>ac(t,typeof e!="symbol"?e+"":e,r);let u4=class s0 extends ES{constructor(e){var r;super(e),le(this,"protocol",zg),le(this,"version",Vg),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 i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}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)||Kg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=c3({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:D$.logger,name:Us}),{logger:s,chunkLoggerController:o}=Op({opts:n,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.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 k8,this.crypto=new UO(this,this.logger,e==null?void 0:e.keychain),this.history=new WD(this,this.logger),this.expirer=new ZD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new mS(of(of({},A$),e==null?void 0:e.storageOptions)),this.relayer=new uD({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new VD(this,this.logger),this.verify=new QD(this,this.logger,this.storage),this.echoClient=new r4(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new o4(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new s0(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(z$,i),r}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(Uh,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(Uh)||[],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 r=`_walletConnectCore_${e}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof xt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const h4=u4,o0="wc",a0=2,c0="client",el=`${o0}@${a0}:${c0}:`,sa={name:c0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},af="WALLETCONNECT_DEEPLINK_CHOICE",f4="proposal",cf="Proposal expired",d4="session",_i=L.SEVEN_DAYS,p4="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}}},oa={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},g4={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:""}},y4="request",w4=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],m4="wc",b4="auth",v4="authKeys",E4="pairingTopics",x4="requests",lo=`${m4}@${1.5}:${b4}:`,ws=`${lo}:PUB_KEY`;var _4=Object.defineProperty,I4=Object.defineProperties,S4=Object.getOwnPropertyDescriptors,lf=Object.getOwnPropertySymbols,$4=Object.prototype.hasOwnProperty,O4=Object.prototype.propertyIsEnumerable,cc=(t,e,r)=>e in t?_4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oe=(t,e)=>{for(var r in e||(e={}))$4.call(e,r)&&cc(t,r,e[r]);if(lf)for(var r of lf(e))O4.call(e,r)&&cc(t,r,e[r]);return t},Re=(t,e)=>I4(t,S4(e)),k=(t,e,r)=>cc(t,typeof e!="symbol"?e+"":e,r);class D4 extends kS{constructor(e){super(e),k(this,"name",p4),k(this,"events",new dc),k(this,"initialized",!1),k(this,"requestQueue",{state:kt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),k(this,"emittedSessionRequests",new j3({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 r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Re(oe({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=ZI(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=((i=h==null?void 0:h[0])==null?void 0:i.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 I=await this.client.core.crypto.generateKeyPair(),C=we(d),b=oe(Re(oe(oe({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:Hg}],proposer:{publicKey:I,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:_,exp:O,nbf:m,type:y,statement:x,requestId:$,resources:E,signatureTypes:S}=A;return{domain:U,chains:j,nonce:B,type:y??"caip122",aud:_,version:"1",iat:new Date().toISOString(),exp:O,nbf:m,statement:x,requestId:$,resources:E,signatureTypes:S}}),walletPay:f}}),v=ae("session_connect",b.id),{reject:D,resolve:P,done:T}=Kr(d,cf),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:cf,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?D(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 r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),k(this,"approve",async r=>{var i,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[Dt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw o.setError(zr.no_internet_connection),U}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(zr.proposal_not_found),U}try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(zr.session_approve_namespace_validation_failure),U}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:I,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:Dt.session_approve_started,properties:{topic:g,trace:[Dt.session_approve_started,Dt.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),D=w.publicKey,P=await this.client.core.crypto.generateSharedKey(v,D),T=Re(oe(oe(oe({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:we(_i)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=he.relay;b.addTrace(Dt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:R,internal:{skipSubscribe:!0}})}catch(U){throw b.setError(zr.subscribe_session_topic_failure),U}b.addTrace(Dt.subscribe_session_topic_success);const A=Re(oe({},T),{topic:P,requiredNamespaces:I,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(Dt.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(Dt.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(_i)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),k(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}s&&await this.sendError({id:i,topic:s,error:n,rpcOpts:Te.wc_sessionPropose.reject}),await this.deleteProposal(i)}),k(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=Kr(L.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Lt(),l=Rr().toString(),u=this.client.session.get(i).namespaces;return this.events.once(ae("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:u}),a(h)}),{acknowledged:s}}),k(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,n=Lt(),{done:s,resolve:o,reject:a}=Kr(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(i,we(_i)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:n,topic:s,expiry:o=Te.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);(a==null?void 0:a.transportType)===he.relay&&await this.confirmOnlineStateOrThrow();const c=Lt(),l=Rr().toString(),{done:u,resolve:h,reject:f}=Kr(o,"Request expired. Please try again.");this.events.once(ae("session_request",c),({error:w,result:I})=>{w?f(w):h(I)});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:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await u();const g={request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:i};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(I=>f(I)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),w()}),new Promise(async w=>{var I;if(!((I=a.sessionConfig)!=null&&I.disableDeepLink)){const C=await R3(this.client.core.storage,af);await C3({id:c,topic:s,wcDeepLink:C})}w()}),u()]).then(w=>w[2])}),k(this,"respond",async r=>{var i,n;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:(r==null?void 0:r.topic)||((n=(i=r==null?void 0:r.response)==null?void 0:i.id)==null?void 0:n.toString()),trace:[Dt.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_validation_failure),h}s.addTrace(Dt.session_request_response_validation_success);const{topic:o,response:a}=r,{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(Dt.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(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_publish_failure),h}}),k(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=Lt(),s=Rr().toString(),{done:o,resolve:a,reject:c}=Kr(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:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),k(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Rr().toString(),a=Lt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),k(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>QI(i,r)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((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}=r,I=[...r.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(),D=ds(v);if(await Promise.all([this.client.auth.authKeys.set(ws,{responseTopic:D,publicKey:v}),this.client.auth.pairingTopics.set(D,{topic:D,pairingTopic:C})]),await this.client.core.relayer.subscribe(D,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),g.length>0){const{namespace:E}=ur(a[0]);let S=Xx(E,"request",g);fs(I)&&(S=e_(S,I.pop())),I.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:I},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}=Kr(P,"Request expired"),_=Lt(),O=ae("session_connect",A.id),m=ae("session_request",_),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(_,{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(O,y),B(E.error.message))}await this.deleteProposal(A.id),this.events.off(O,y);const{cacaos:H,responder:z}=E.result,q=[],K=[];for(const W of H){await Mu({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=[Na(Q.iss)],Ie=Cs(Q.iss);if(pe){const He=qu(pe),Gt=zu(pe);q.push(...He),ve.push(...Gt)}for(const He of ve)K.push(`${He}:${Ie}`)}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(_i),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:gh([...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&&i&&(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(O,y),this.events.once(m,x);let $;try{if(s){const E=Ct("wc_sessionAuthenticate",T,_);this.client.core.history.set(C,E);const S=await this.client.core.crypto.encode("",E,{type:Nn,encoding:Br});$=rs(i,C,S)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:_}),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(O,y),this.events.off(m,x),E}return await this.setProposal(A.id,A),await this.setAuthRequest(_,{request:Re(oe({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:$??b,response:U}}),k(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Vr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(tn.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);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:hr,receiverPublicKey:c,senderPublicKey:l},f=[],d=[];for(const w of n){if(!await Mu({cacao:w,projectId:this.client.core.projectId})){s.setError(tn.invalid_cacao);const D=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:D,encodeOpts:h}),new Error(D.message)}s.addTrace(Vr.cacaos_verified);const{p:I}=w,C=fs(I.resources),b=[Na(I.iss)],v=Cs(I.iss);if(C){const D=qu(C),P=zu(C);f.push(...D),b.push(...P)}for(const D of b)d.push(`${D}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Vr.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(_i),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:gh([...new Set(f)],[...new Set(d)]),transportType:a},s.addTrace(Vr.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(Vr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Vr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Vr.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,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(i,{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 r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ds(o),l={type:hr,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,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(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),k(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return Yp(i,n)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),k(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.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)===r.peer.metadata.url&&s.topic&&s.topic!==i.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(i){this.client.logger.error(i)}}),k(this,"deleteSession",async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{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(af).catch(l=>this.client.logger.warn(l)),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.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(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s==null||s.setError(zr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,fe("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),k(this,"deletePendingSessionRequest",async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:r}))}),k(this,"deletePendingAuthRequest",async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])}),k(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),k(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,we(Te.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),k(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=he.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||we(Te.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:o})}),k(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=r,d=Ct(n,s,c);let p;const g=!!u;try{const C=g?Br:tt;p=await this.client.core.crypto.encode(i,d,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),C}let w;if(w4.includes(n)){const C=bt(JSON.stringify(d)),b=bt(p);w=await this.client.core.verify.register({id:b,decryptedId:C})}const I=oe(oe({},Te[n].req),f);if(I.attestation=w,o&&(I.ttl=o),a&&(I.id=a),this.client.core.history.set(i,d),g){const C=rs(u,i,p);await Y.Linking.openURL(C,this.client.name)}else I.tvf=Re(oe({},h),{correlationId:d.id}),l?(I.internal=Re(oe({},I.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,I)):this.client.core.relayer.publish(i,p,I).catch(C=>this.client.logger.error(C));return d.id}),k(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:n}=r,s=Ct("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,s);const o=await this.client.core.crypto.encode(i.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:i.pairingTopic,sessionProposal:o},opts:Re(oe({},n),{publishMethod:"wc_proposeSession",attestation:l})})}),k(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:n,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=$n(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(i,u,{encoding:tt});this.client.core.history.set(i,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:Re(oe({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=$n(i,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const p=h?Br: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,i);const p=f.request;try{d=this.getTVFParams(i,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}, ${i}) failed`),p}if(h){const p=rs(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:i}),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 r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=oo(i,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const d=h?Br: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,i)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),d}if(h){const d=rs(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 r=[],i=[];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&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{qt(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),k(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),k(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),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 r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=kt.idle}),k(this,"processRequest",async r=>{const{topic:i,payload:n,attestation:s,transportType:o,encryptedId:a}=r,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n,transportType:s}=r,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=M("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),k(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:n,attestation:s,encryptedId:o}=r,{params:a,id:c}=n;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(ir.proposal_listener_not_found)),this.isValidConnect(oe({},n.params));const u=a.expiryTimestamp||we(Te.wc_sessionPropose.req.ttl),h=oe({id:c,pairingTopic:i,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:i,error:l,rpcOpts:Te.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),k(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(Mt(i)){const{result:o}=i;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:r,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:r})}else if(vt(i)){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:i.error})}}),k(this,"onSessionSettleRequest",async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i.params,p=[...this.pendingSessions.values()].find(I=>I.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const g=this.client.proposal.get(p.proposalId),w=Re(oe(oe(oe({topic:r,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:i.id,topic:r,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:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;Mt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ae("session_approve",n),{})):vt(i)&&(await this.client.session.delete(r,fe("USER_DISCONNECTED")),this.events.emit(ae("session_approve",n),{error:i.error}))}),k(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:r},n));try{Qi.set(o,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Qi.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=ae("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_update",n),{}):vt(i)&&this.events.emit(ae("session_update",n),{error:i.error})}),k(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,we(_i)),await this.sendResult({id:n,topic:r,result:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=ae("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_extend",n),{}):vt(i)&&this.events.emit(ae("session_extend",n),{error:i.error})}),k(this,"onSessionPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=ae("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Mt(i)?this.events.emit(ae("session_ping",n),{}):vt(i)&&this.events.emit(ae("session_ping",n),{error:i.error})},500)}),k(this,"onSessionDeleteRequest",async(r,i)=>{const{id:n}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:fe("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:n})}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{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&&(i=d.peer.metadata.redirect)!=null&&i.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",(r,i)=>{const{id:n}=i,s=ae("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(oe({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Qi.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=r;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&&(i=l.metadata.redirect)!=null&&i.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:hr,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",r=>{this.sessionRequestQueue.queue.push(r)}),k(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ae("session_request",s.request.id),{error:i})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),k(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=kt.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),k(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Ct("wc_sessionPropose",Re(oe({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id),attestation:i.attestation,encryptedId:i.encryptedId})}),k(this,"isValidConnect",async r=>{if(!Xe(r)){const{message:l}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(_e(i)||await this.isValidPairingTopic(i),!h8(c,!0)){const{message:l}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(n&&!_e(n)&&Kt(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&&!_e(s)&&Kt(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(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",(r,i)=>{const n=u8(r,"connect()",i);if(n)throw new Error(n.message)}),k(this,"isValidApprove",async r=>{if(!Xe(r))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),l=Jo(n,"approve()");if(l)throw new Error(l.message);const u=mh(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&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(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 r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!d8(n)){const{message:s}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",r=>{if(!Xe(r)){const{message:l}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Tg(i)){const{message:l}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=n8(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 r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),o=Jo(n,"update()");if(o)throw new Error(o.message);const a=mh(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),k(this,"isValidRequest",async r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:n,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!wh(a,s)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!p8(n)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!w8(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 r=>{var i;if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!g8(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 r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidEmit",async r=>{if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!wh(o,s)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!y8(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!m8(o,s,n.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidAuthenticate",r=>{const{chains:i,uri:n,domain:s,nonce:o}=r;if(!Array.isArray(i)||i.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(i.map(c=>ur(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ur(i[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 r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,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:i,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",(r,i)=>{Object.values(r).forEach((n,s)=>{if(n==null){const{message:o}=M("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${n} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),k(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),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",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),k(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,l,u,h,f;return!r||i!==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=r==null?void 0:r.redirect)==null?void 0:u.universal)!==void 0&&((h=r==null?void 0:r.redirect)==null?void 0:h.universal)!==""&&((f=r==null?void 0:r.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(Y==null?void 0:Y.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r==null?void 0:r.redirect)==null?void 0:n.universal:void 0}),k(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Au(r,"topic")||"",n=decodeURIComponent(Au(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var r;if(jc()||kr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=Y==null?void 0:Y.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),k(this,"getTVFApproveParams",r=>{try{const i=Cg(r.namespaces),n=HI(r.namespaces),s=KI(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:n,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),k(this,"getTVFParams",(r,i,n)=>{var s,o,a;if(!((s=i.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const l=this.extractTxHashesFromResult(i.request,n);c.txHashes=l,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.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",r=>{var i;if(!r)return!1;try{const n=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.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",(r,i)=>{var n;try{if(!i)return[];const s=r.method,o=g4[s];if(s==="sui_signTransaction")return[Tx(i.transactionBytes)];if(s==="near_signTransaction")return[Uu(i)];if(s==="near_signTransactions")return i.map(c=>Uu(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(n=i.tx_json)==null?void 0:n.hash];if(s==="polkadot_signTransaction")return[N8({transaction:r.params.transactionPayload,signature:i.signature})];if(s==="algo_signTxn")return _t(i)?i.map(c=>ku(c)):[ku(i)];if(s==="cosmos_signDirect")return[Fx(i)];if(s==="wallet_sendCalls")return Nx(i);if(typeof i=="string")return[i];const a=i[o.key];if(_t(a))return s==="solana_signAllTransactions"?a.map(c=>Bx(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,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,n]of Object.entries(r))for(const s of n)try{await this.onProviderMessageEvent({topic:i,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, 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:r,message:i,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(r,i,{receiverPublicKey:o,encoding:s===he.link_mode?Br:tt});Xc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:bt(i)})):ao(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(wt.expired,async e=>{const{topic:r,id:i}=Bp(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,M("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,M("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Yr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Yr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!be(e,!1)){const{message:r}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!be(e,!1)){const{message:r}=M("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=M("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=M("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}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:r}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!f8(e)){const{message:r}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=M("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!E8(e,oa)){const{message:r}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${oa.min} and ${oa.max}`);throw new Error(r)}}}class A4 extends pi{constructor(e,r){super(e,r,f4,el),this.core=e,this.logger=r}}let P4=class extends pi{constructor(e,r){super(e,r,d4,el),this.core=e,this.logger=r}};class C4 extends pi{constructor(e,r){super(e,r,y4,el,i=>i.id),this.core=e,this.logger=r}}class B4 extends pi{constructor(e,r){super(e,r,v4,lo,()=>ws),this.core=e,this.logger=r}}class T4 extends pi{constructor(e,r){super(e,r,E4,lo),this.core=e,this.logger=r}}class R4 extends pi{constructor(e,r){super(e,r,x4,lo,i=>i.id),this.core=e,this.logger=r}}var F4=Object.defineProperty,N4=(t,e,r)=>e in t?F4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,aa=(t,e,r)=>N4(t,typeof e!="symbol"?e+"":e,r);class U4{constructor(e,r){this.core=e,this.logger=r,aa(this,"authKeys"),aa(this,"pairingTopics"),aa(this,"requests"),this.authKeys=new B4(this.core,this.logger),this.pairingTopics=new T4(this.core,this.logger),this.requests=new R4(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var k4=Object.defineProperty,j4=(t,e,r)=>e in t?k4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>j4(t,typeof e!="symbol"?e+"":e,r);class tl extends US{constructor(e){super(e),te(this,"protocol",o0),te(this,"version",a0),te(this,"name",sa.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",(i,n)=>this.events.on(i,n)),te(this,"once",(i,n)=>this.events.once(i,n)),te(this,"off",(i,n)=>this.events.off(i,n)),te(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),te(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),te(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),te(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=(e==null?void 0:e.name)||sa.name,this.metadata=S3(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=Zc({logger:(e==null?void 0:e.logger)||sa.logger,name:this.name});this.logger=r,this.core=(e==null?void 0:e.core)||new h4(e),this.session=new P4(this.core,this.logger),this.proposal=new A4(this.core,this.logger),this.pendingRequest=new C4(this.core,this.logger),this.engine=new D4(this),this.auth=new U4(this.core,this.logger)}static async init(e){const r=new tl(e);return await r.initialize(),r}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 L4=tl;var M4=Object.defineProperty,q4=Object.defineProperties,z4=Object.getOwnPropertyDescriptors,uf=Object.getOwnPropertySymbols,V4=Object.prototype.hasOwnProperty,H4=Object.prototype.propertyIsEnumerable,hf=(t,e,r)=>e in t?M4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ff=(t,e)=>{for(var r in e||(e={}))V4.call(e,r)&&hf(t,r,e[r]);if(uf)for(var r of uf(e))H4.call(e,r)&&hf(t,r,e[r]);return t},df=(t,e)=>q4(t,z4(e));const K4={Accept:"application/json","Content-Type":"application/json"},W4="POST",pf={headers:K4,method:W4},gf=10;let l0=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new St.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}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 r=oi(e),i=await(await dl(this.url,df(ff({},pf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,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"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=oi({id:1,jsonrpc:"2.0",method:"test",params:[]});await dl(e,df(ff({},pf),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}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 r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return kg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>gf&&this.events.setMaxListeners(gf)}};function rl(t){return t==null||typeof t!="object"&&typeof t!="function"}function u0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function h0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const G4="[object RegExp]",f0="[object String]",d0="[object Number]",p0="[object Boolean]",g0="[object Arguments]",Y4="[object Symbol]",Z4="[object Date]",J4="[object Map]",X4="[object Set]",Q4="[object Array]",eA="[object ArrayBuffer]",tA="[object Object]",rA="[object DataView]",iA="[object Uint8Array]",nA="[object Uint8ClampedArray]",sA="[object Uint16Array]",oA="[object Uint32Array]",aA="[object Int8Array]",cA="[object Int16Array]",lA="[object Int32Array]",uA="[object Float32Array]",hA="[object Float64Array]";function il(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function fA(t,e){return Di(t,void 0,t,new Map,e)}function Di(t,e,r,i=new Map,n=void 0){const s=n==null?void 0:n(t,e,r,i);if(s!=null)return s;if(rl(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,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;i.set(t,o);for(const[a,c]of t)o.set(a,Di(c,a,r,i,n));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Di(a,void 0,r,i,n));return o}if(typeof re<"u"&&re.isBuffer(t))return t.subarray();if(il(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,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 i.set(t,o),Zr(o,t,r,i,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Zr(o,t,r,i,n),o}if(typeof t=="object"&&dA(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Zr(o,t,r,i,n),o}return t}function Zr(t,e,r=t,i,n){const s=[...Object.keys(e),...u0(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Di(e[a],a,r,i,n))}}function dA(t){switch(h0(t)){case g0:case Q4:case eA:case rA:case p0:case Z4:case uA:case hA:case aA:case cA:case lA:case J4:case d0:case tA:case G4:case X4:case f0:case Y4:case iA:case nA:case sA:case oA:return!0;default:return!1}}function pA(t,e){return fA(t,(r,i,n,s)=>{const o=e==null?void 0:e(r,i,n,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case d0:case f0:case p0:{const a=new t.constructor(t==null?void 0:t.valueOf());return Zr(a,t),a}case g0:{const a={};return Zr(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function yf(t){return pA(t)}function wf(t){return t!==null&&typeof t=="object"&&h0(t)==="[object Arguments]"}function mf(t){return typeof t=="object"&&t!==null}function gA(){}function yA(t){return il(t)}function wA(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function mA(t){if(rl(t))return t;if(Array.isArray(t)||il(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function bA(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let n=t;for(let s=0;s<r.length;s++){const o=r[s];n=lc(n,o,i,new Map)}return n}function lc(t,e,r,i){if(rl(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return mA(i.get(e));if(i.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),...u0(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(wf(a)&&(a={...a}),wf(c)&&(c={...c}),typeof re<"u"&&re.isBuffer(a)&&(a=yf(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=r(c,a,o,t,e,i);l!=null?t[o]=l:Array.isArray(a)||mf(c)&&mf(a)?t[o]=lc(c,a,r,i):c==null&&wA(a)?t[o]=lc({},a,r,i):c==null&&yA(a)?t[o]=yf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function vA(t,...e){return bA(t,...e,gA)}const bf="error",EA="wss://relay.walletconnect.org",xA="wc",y0="universal_provider",ss=`${xA}@2:${y0}:`,w0="https://rpc.walletconnect.org/v1/",m0="generic",_A=`${w0}bundler`,Ti="call_status",IA=86400,nl={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var SA=Object.defineProperty,$A=Object.defineProperties,OA=Object.getOwnPropertyDescriptors,vf=Object.getOwnPropertySymbols,DA=Object.prototype.hasOwnProperty,AA=Object.prototype.propertyIsEnumerable,Ef=(t,e,r)=>e in t?SA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,os=(t,e)=>{for(var r in e||(e={}))DA.call(e,r)&&Ef(t,r,e[r]);if(vf)for(var r of vf(e))AA.call(e,r)&&Ef(t,r,e[r]);return t},PA=(t,e)=>$A(t,OA(e));function b0(t,e,r){var i;const n=ur(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${w0}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function CA(t){return t.includes(":")?t.split(":")[1]:t}function v0(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function BA(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function xf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,n;return((i=r==null?void 0:r.chains)==null?void 0:i.length)&&((n=r==null?void 0:r.chains)==null?void 0:n.length)>0}))}function as(t={},e={}){const r=xf(_f(t)),i=xf(_f(e));return vA(r,i)}function _f(t){var e,r,i,n,s;const o={};if(!Kt(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=Oi(a);o[d]=PA(os(os({},o[d]),c),{chains:Ht(l,(e=o[d])==null?void 0:e.chains),methods:Ht(u,(r=o[d])==null?void 0:r.methods),events:Ht(h,(i=o[d])==null?void 0:i.events)}),(Kt(f)||Kt(((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 If(t){return t.includes(":")?t.split(":")[2]:t}function Sf(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=so(r)?[r]:i.chains?i.chains:v0(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function ca(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 TA(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const E0={},Ri=t=>E0[t],la=(t,e)=>{E0[t]=e};var RA=Object.defineProperty,$f=Object.getOwnPropertySymbols,FA=Object.prototype.hasOwnProperty,NA=Object.prototype.propertyIsEnumerable,Of=(t,e,r)=>e in t?RA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Df=(t,e)=>{for(var r in e||(e={}))FA.call(e,r)&&Of(t,r,e[r]);if($f)for(var r of $f(e))NA.call(e,r)&&Of(t,r,e[r]);return t};const Af="eip155",UA=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],kA=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,ua=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Pf=t=>Object.keys(t).filter(e=>UA.includes(e)).reduce((e,r)=>(e[r]=jA(t[r]),e),{}),jA=t=>typeof t=="string"&&TA(t)?JSON.parse(t):t,LA=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:n={}}=t,s={};if(!Kt(n)&&!Kt(i))return;const o=Pf(i);for(const a of r){const c=kA(a);if(!c)continue;s[ua(c)]=o;const l=n==null?void 0:n[`${Af}:${c}`];if(l){const u=l==null?void 0:l[`${Af}:${c}:${e}`];s[ua(c)]=Df(Df({},s[ua(c)]),Pf(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 MA=Object.defineProperty,qA=(t,e,r)=>e in t?MA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zA=(t,e,r)=>qA(t,typeof e!="symbol"?e+"":e,r);let ha,VA=class x0{constructor(e){zA(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,r){return await this.storage.setItem(e,r)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return ha||(ha=new x0(e)),ha}};var HA=Object.defineProperty,KA=Object.defineProperties,WA=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,GA=Object.prototype.hasOwnProperty,YA=Object.prototype.propertyIsEnumerable,Bf=(t,e,r)=>e in t?HA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ZA=(t,e)=>{for(var r in e||(e={}))GA.call(e,r)&&Bf(t,r,e[r]);if(Cf)for(var r of Cf(e))YA.call(e,r)&&Bf(t,r,e[r]);return t},JA=(t,e)=>KA(t,WA(e));async function XA(t,e){const r=ur(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(i.map(h=>QA(r.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 QA(t,e,r){return await r(parseInt(t)).request(Ct("eth_getTransactionReceipt",[e]))}async function eP({sendCalls:t,storage:e}){const r=await e.getItem(Ti);await e.setItem(Ti,JA(ZA({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:we(IA)}}))}async function tP({resultId:t,storage:e}){const r=await e.getItem(Ti);if(r){delete r[t],await e.setItem(Ti,r);for(const i in r)qt(r[i].expiry)&&delete r[i];await e.setItem(Ti,r)}}async function rP({resultId:t,storage:e}){const r=await e.getItem(Ti),i=r==null?void 0:r[t];if(i&&!qt(i.expiry))return i;await tP({resultId:t,storage:e})}var iP=Object.defineProperty,nP=Object.defineProperties,sP=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,oP=Object.prototype.hasOwnProperty,aP=Object.prototype.propertyIsEnumerable,uc=(t,e,r)=>e in t?iP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fa=(t,e)=>{for(var r in e||(e={}))oP.call(e,r)&&uc(t,r,e[r]);if(Tf)for(var r of Tf(e))aP.call(e,r)&&uc(t,r,e[r]);return t},da=(t,e)=>nP(t,sP(e)),Hr=(t,e,r)=>uc(t,typeof e!="symbol"?e+"":e,r);class cP{constructor(e){Hr(this,"name","eip155"),Hr(this,"client"),Hr(this,"chainId"),Hr(this,"namespace"),Hr(this,"httpProviders"),Hr(this,"events"),Hr(this,"storage"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=VA.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,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(nl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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,r){const i=r||b0(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Qc(new l0(i,Ri("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(CA(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=da(fa({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.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:(i=this.namespace.chains)==null?void 0:i[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 r,i,n,s,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[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=LA(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:da(fa({},l.sessionProperties||{}),{capabilities:da(fa({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var r,i,n;const s=this.client.session.get(e.topic),o=(r=s.sessionProperties)==null?void 0:r.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=(i=s.sessionProperties)==null?void 0:i.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 rP({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(c)try{return await XA(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,r){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${_A}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,n;const s=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=s==null?void 0:s.id,c=(s==null?void 0:s.capabilities)||{},l=(i=c==null?void 0:c.caip345)==null?void 0:i.caip2,u=(n=c==null?void 0:c.caip345)==null?void 0:n.transactionHashes;return!a||!l||!(u!=null&&u.length)||await eP({sendCalls:{request:o,result:s},storage:this.storage}),s}}var lP=Object.defineProperty,uP=(t,e,r)=>e in t?lP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ii=(t,e,r)=>uP(t,typeof e!="symbol"?e+"":e,r);class hP{constructor(e){Ii(this,"name",m0),Ii(this,"client"),Ii(this,"httpProviders"),Ii(this,"events"),Ii(this,"namespace"),Ii(this,"chainId"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("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,r){this.httpProviders[e]||this.setHttpProvider(e,r);const i=this.chainId;this.chainId=e,this.events.emit(nl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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 ur(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(n=>{var s,o;const a=ur(n),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(n,c)}),i}getHttpProvider(e){const r=ur(e).reference,i=this.httpProviders[r];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||b0(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Qc(new l0(i,Ri("disableProviderPing")))}}var fP=Object.defineProperty,dP=Object.defineProperties,pP=Object.getOwnPropertyDescriptors,Rf=Object.getOwnPropertySymbols,gP=Object.prototype.hasOwnProperty,yP=Object.prototype.propertyIsEnumerable,hc=(t,e,r)=>e in t?fP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sn=(t,e)=>{for(var r in e||(e={}))gP.call(e,r)&&hc(t,r,e[r]);if(Rf)for(var r of Rf(e))yP.call(e,r)&&hc(t,r,e[r]);return t},cs=(t,e)=>dP(t,pP(e)),at=(t,e,r)=>hc(t,typeof e!="symbol"?e+"":e,r);class sl{constructor(e){at(this,"client"),at(this,"namespaces"),at(this,"optionalNamespaces"),at(this,"sessionProperties"),at(this,"scopedProperties"),at(this,"events",new dc),at(this,"rpcProviders",{}),at(this,"session"),at(this,"providerOpts"),at(this,"logger"),at(this,"uri"),at(this,"disableProviderPing",!1),at(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Zc({logger:(r=e.logger)!=null?r:bf,name:(i=this.providerOpts.name)!=null?i:y0}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new sl(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);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:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(o=>r(null,$n(s,o))).catch(o=>r(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,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const o=Sf(this.session.namespaces);this.namespaces=as(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){var r,i;const{uri:n,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(i=this.connectParams)==null?void 0:i.walletPay});n&&(this.uri=n,this.events.emit("display_uri",n));const o=await s();this.session=o;const a=Sf(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,r){try{if(!this.session)return;const[i,n]=this.validateChain(e);this.getProvider(i).setDefaultChain(n,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!_t(r))return;for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"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,r;if(this.client=this.providerOpts.client||await L4.init({core:this.providerOpts.core,logger:this.providerOpts.logger||bf,relayUrl:this.providerOpts.relayUrl||EA,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(i){throw this.logger.error(i,"Failed to get session"),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[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(r=>Oi(r)))];la("client",this.client),la("events",this.events),la("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=BA(r,this.session);if((i==null?void 0:i.length)===0)return;const n=v0(i),s=as(this.namespaces,this.optionalNamespaces),o=cs(sn({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new cP({namespace:o});break;default:this.rpcProviders[r]=new hP({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:n}=e;if(n!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=i;if(s.name==="accountsChanged"){const o=s.data;o&&_t(o)&&this.events.emit("accountsChanged",o.map(If))}else if(s.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Oi(o),l=ca(o)!==ca(a)?`${c}:${ca(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:r})=>{var i,n;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:s}=r,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:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",cs(sn({},fe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(nl.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(cs(sn({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[m0]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=as(r,i),this.sessionProperties=n,this.scopedProperties=s}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>Oi(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=Oi(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:r,internal:i=!1}){if(!this.namespaces)return;const[n,s]=this.validateChain(e);s&&(this.updateNamespaceChain(n,s),i?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(n).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var n,s;try{if(i===r)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(`${r}:`)).map(If);if(!_t(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,n={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=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,r){var i;const n=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${ss}/${e}${n}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${ss}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${ss}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const i of r)i.startsWith(ss)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const wP=sl,mP="wc",bP="ethereum_provider",vP=`${mP}@2:${bP}:`,EP="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],_0=["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"],I0=["chainChanged","accountsChanged","message","disconnect","connect"],xP=async()=>{const{createAppKit:t}=await T0(()=>import("./core-0c13d1dd.js").then(e=>e.$),["assets/core-0c13d1dd.js","assets/index-726bc846.js","assets/index-a5cbd387.css","assets/index-c2e969f4.js"]);return t};var _P=Object.defineProperty,IP=Object.defineProperties,SP=Object.getOwnPropertyDescriptors,Ff=Object.getOwnPropertySymbols,$P=Object.prototype.hasOwnProperty,OP=Object.prototype.propertyIsEnumerable,fc=(t,e,r)=>e in t?_P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e)=>{for(var r in e||(e={}))$P.call(e,r)&&fc(t,r,e[r]);if(Ff)for(var r of Ff(e))OP.call(e,r)&&fc(t,r,e[r]);return t},on=(t,e)=>IP(t,SP(e)),ct=(t,e,r)=>fc(t,typeof e!="symbol"?e+"":e,r);function Ls(t){return Number(t[0].split(":")[1])}function ls(t){return`0x${t.toString(16)}`}function DP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!_t(e))throw new Error("Invalid chains");const c={chains:e,methods:i||ks,events:s||js,rpcMap:Wr({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},l=s==null?void 0:s.filter(d=>!js.includes(d)),u=i==null?void 0:i.filter(d=>!ks.includes(d));if(!r&&!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)||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:_0))],events:[...new Set(c.events.concat(o!=null&&o.length?o:I0))],rpcMap:a};return{required:e.length?c:void 0,optional:r.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",vP),ct(this,"on",(e,r)=>(this.events.on(e,r),this)),ct(this,"once",(e,r)=>(this.events.once(e,r),this)),ct(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ct(this,"off",(e,r)=>(this.events.off(e,r),this)),ct(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new uo;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}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 r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:n}=DP(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(Wr({namespaces:Wr({},i&&{[this.namespace]:i})},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=Iu(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{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;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(Wr({},e),{chains:this.rpc.chains}),r).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=Iu(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{(i=this.modal)==null||i.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:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.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 r=parseInt(e);this.chainId=r,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(Wr({},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 r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ls(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const n=(r=e==null?void 0:e.chains)!=null?r:[],s=(i=e==null?void 0:e.optionalChains)!=null?i:[],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,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await wP.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 i;try{const n=await xP(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return jP}),o=s(on(Wr({},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");i=n(on(Wr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&_t(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)})),i&&_t(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${EP}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}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(r=>this.parseAccount(r))}}const AP=uo;var PP=Object.defineProperty,CP=Object.defineProperties,BP=Object.getOwnPropertyDescriptors,Nf=Object.getOwnPropertySymbols,TP=Object.prototype.hasOwnProperty,RP=Object.prototype.propertyIsEnumerable,Uf=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,S0=(t,e)=>{for(var r in e||(e={}))TP.call(e,r)&&Uf(t,r,e[r]);if(Nf)for(var r of Nf(e))RP.call(e,r)&&Uf(t,r,e[r]);return t},FP=(t,e)=>CP(t,BP(e));function NP(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 UP=t=>{const[e,r]=t.split(":");return $0({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function kP(t){var e,r,i,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(UP).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:NP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:FP(S0({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.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 $0(t){return S0({formatters:void 0,fees:void 0,serializers:void 0},t)}var jP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:kP,defineChain:$0});const A5=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:AP,OPTIONAL_EVENTS:I0,OPTIONAL_METHODS:_0,REQUIRED_EVENTS:js,REQUIRED_METHODS:ks,default:uo},Symbol.toStringTag,{value:"Module"}));export{O$ as A,Xc as B,hE as C,ao as D,$n as E,fi as F,Ct as G,p2 as H,hi as I,Rr as J,oo as K,Mt as L,vt as M,Lt as N,l0 as O,du as P,sp as Q,A5 as R,iS as a,nS as b,Fg as c,is as d,sS as e,si as f,Ih as g,qf as h,L as i,Et as j,aS as k,ii as l,pc as m,An as n,E1 as o,f1 as p,Fm as q,_E as r,oi as s,nt as t,q0 as u,Mf as v,fn as w,Pa as x,k8 as y,Qc as z};
|
|
39
|
+
***************************************************************************** */var Ya=function(t,e){return Ya=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Ya(t,e)};function KS(t,e){Ya(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Za=function(){return Za=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Za.apply(this,arguments)};function WS(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function GS(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function YS(t,e){return function(r,i){e(r,i,t)}}function ZS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function JS(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):n(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function XS(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=l[0]&2?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,n=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function QS(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function e$(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Ja(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Lg(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function t$(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Lg(arguments[e]));return t}function r$(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function Sn(t){return this instanceof Sn?(this.v=t,this):new Sn(t)}function i$(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(f){i[f]&&(n[f]=function(d){return new Promise(function(p,g){s.push([f,d,p,g])>1||a(f,d)})})}function a(f,d){try{c(i[f](d))}catch(p){h(s[0][3],p)}}function c(f){f.value instanceof Sn?Promise.resolve(f.value.v).then(l,u):h(s[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,d){f(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function n$(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:Sn(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function s$(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Ja=="function"?Ja(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),n(a,c,o.done,o.value)})}}function n(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function o$(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function a$(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function c$(t){return t&&t.__esModule?t:{default:t}}function l$(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function u$(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const h$=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Za},__asyncDelegator:n$,__asyncGenerator:i$,__asyncValues:s$,__await:Sn,__awaiter:JS,__classPrivateFieldGet:l$,__classPrivateFieldSet:u$,__createBinding:QS,__decorate:GS,__exportStar:e$,__extends:KS,__generator:XS,__importDefault:c$,__importStar:a$,__makeTemplateObject:o$,__metadata:ZS,__param:YS,__read:Lg,__rest:WS,__spread:t$,__spreadArrays:r$,__values:Ja},Symbol.toStringTag,{value:"Module"})),f$=kf(h$);var er={},Ah;function d$(){if(Ah)return er;Ah=1,Object.defineProperty(er,"__esModule",{value:!0}),er.isBrowserCryptoAvailable=er.getSubtleCrypto=er.getBrowerCrypto=void 0;function t(){return(gi===null||gi===void 0?void 0:gi.crypto)||(gi===null||gi===void 0?void 0:gi.msCrypto)||{}}er.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}er.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return er.isBrowserCryptoAvailable=r,er}var tr={},Ph;function p$(){if(Ph)return tr;Ph=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.isBrowser=tr.isNode=tr.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}tr.isReactNative=t;function e(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}tr.isNode=e;function r(){return!t()&&!e()}return tr.isBrowser=r,tr}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=f$;e.__exportStar(d$(),t),e.__exportStar(p$(),t)})(jg);function Lt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Rr(t=6){return BigInt(Lt(t))}function Ct(t,e,r){return{id:r||Lt(),jsonrpc:"2.0",method:t,params:e}}function $n(t,e){return{id:t,jsonrpc:"2.0",result:e}}function oo(t,e,r){return{id:t,jsonrpc:"2.0",error:g$(e,r)}}function g$(t,e){return typeof t>"u"?Dh(Ng):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dh(Jc)),{message:t})),typeof e<"u"&&(t.data=e),VS(t.code)&&(t=HS(t.code)),t)}class y${}class w$ extends y${constructor(){super()}}class m$ extends w${constructor(e){super()}}const b$="^https?:",v$="^wss?:";function E$(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Mg(t,e){const r=E$(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ch(t){return Mg(t,b$)}function Bh(t){return Mg(t,v$)}function x$(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function qg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Xc(t){return qg(t)&&"method"in t}function ao(t){return qg(t)&&(Mt(t)||vt(t))}function Mt(t){return"result"in t}function vt(t){return"error"in t}class Qc extends m${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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Ct(e.method,e.params||[],e.id||Rr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{vt(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}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)}}var ta,Th;function _$(){return Th||(Th=1,ta=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),ta}const I$=()=>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:_$(),S$=()=>typeof WebSocket<"u"||typeof Y<"u"&&typeof Y.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Rh=t=>t.split("?")[0],Fh=10,$$=I$();let O$=class{constructor(e){if(this.url=e,this.events=new St.EventEmitter,this.registering=!1,!Bh(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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(oi(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Bh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,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"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=jg.isReactNative()?void 0:{rejectUnauthorized:!x$(e)},s=new $$(e,[],n);S$()?s.onerror=o=>{const a=o;i(this.emitError(a.error))}:s.on("error",o=>{i(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),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 r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return kg(e,Rh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Fh&&this.events.setMaxListeners(Fh)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Rh(this.url)}`));return this.events.emit("register_error",r),r}};const zg="wc",Vg=2,Us="core",Wt=`${zg}@2:${Us}:`,D$={name:Us,logger:"error"},A$={database:":memory:"},P$="crypto",Nh="client_ed25519_seed",C$=L.ONE_DAY,B$="keychain",T$="0.3",R$="messages",F$="0.3",N$=L.SIX_HOURS,U$="publisher",Hg="irn",k$="error",Kg="wss://relay.walletconnect.org",j$="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"},L$="_subscription",gt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},M$=.1,Xa="2.23.1",he={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},q$="0.3",z$="WALLETCONNECT_CLIENT_ID",Uh="WALLETCONNECT_LINK_MODE_APPS",lt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},V$="subscription",H$="0.3",K$="pairing",W$="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}}},Yr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},G$="history",Y$="0.3",Z$="expirer",wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},J$="0.3",X$="verify-api",Q$="https://verify.walletconnect.com",Wg="https://verify.walletconnect.org",gn=Wg,e6=`${gn}/v3`,t6=[Q$,Wg],r6="echo",i6="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"},ir={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"},Dt={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"},zr={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"},Vr={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"},n6=.1,s6="event-client",o6=86400,a6="https://pulse.walletconnect.org/batch";function c6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[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,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*u+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}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,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;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 l6=c6,u6=l6;const Gg=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")},h6=t=>new TextEncoder().encode(t),f6=t=>new TextDecoder().decode(t);class d6{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class p6{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yg(this,e)}}class g6{constructor(e){this.decoders=e}or(e){return Yg(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yg=(t,e)=>new g6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class y6{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new d6(e,r,i),this.decoder=new p6(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const co=({name:t,prefix:e,encode:r,decode:i})=>new y6(t,e,r,i),kn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=u6(r,e);return co({prefix:t,name:e,encode:i,decode:s=>Gg(n(s))})},w6=(t,e,r,i)=>{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*r/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-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},m6=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Ue=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>co({prefix:e,name:t,encode(n){return m6(n,i,r)},decode(n){return w6(n,i,r,t)}}),b6=co({prefix:"\0",name:"identity",encode:t=>f6(t),decode:t=>h6(t)});var v6=Object.freeze({__proto__:null,identity:b6});const E6=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var x6=Object.freeze({__proto__:null,base2:E6});const _6=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var I6=Object.freeze({__proto__:null,base8:_6});const S6=kn({prefix:"9",name:"base10",alphabet:"0123456789"});var $6=Object.freeze({__proto__:null,base10:S6});const O6=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),D6=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var A6=Object.freeze({__proto__:null,base16:O6,base16upper:D6});const P6=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),C6=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),B6=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),T6=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),R6=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),F6=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),N6=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),U6=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),k6=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var j6=Object.freeze({__proto__:null,base32:P6,base32upper:C6,base32pad:B6,base32padupper:T6,base32hex:R6,base32hexupper:F6,base32hexpad:N6,base32hexpadupper:U6,base32z:k6});const L6=kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),M6=kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var q6=Object.freeze({__proto__:null,base36:L6,base36upper:M6});const z6=kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),V6=kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var H6=Object.freeze({__proto__:null,base58btc:z6,base58flickr:V6});const K6=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),W6=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),G6=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Y6=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Z6=Object.freeze({__proto__:null,base64:K6,base64pad:W6,base64url:G6,base64urlpad:Y6});const Zg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),J6=Zg.reduce((t,e,r)=>(t[r]=e,t),[]),X6=Zg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Q6(t){return t.reduce((e,r)=>(e+=J6[r],e),"")}function eO(t){const e=[];for(const r of t){const i=X6[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const tO=co({prefix:"🚀",name:"base256emoji",encode:Q6,decode:eO});var rO=Object.freeze({__proto__:null,base256emoji:tO}),iO=Jg,kh=128,nO=127,sO=~nO,oO=Math.pow(2,31);function Jg(t,e,r){e=e||[],r=r||0;for(var i=r;t>=oO;)e[r++]=t&255|kh,t/=128;for(;t&sO;)e[r++]=t&255|kh,t>>>=7;return e[r]=t|0,Jg.bytes=r-i+1,e}var aO=Qa,cO=128,jh=127;function Qa(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw Qa.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&jh)<<n:(o&jh)*Math.pow(2,n),n+=7}while(o>=cO);return Qa.bytes=s-i,r}var lO=Math.pow(2,7),uO=Math.pow(2,14),hO=Math.pow(2,21),fO=Math.pow(2,28),dO=Math.pow(2,35),pO=Math.pow(2,42),gO=Math.pow(2,49),yO=Math.pow(2,56),wO=Math.pow(2,63),mO=function(t){return t<lO?1:t<uO?2:t<hO?3:t<fO?4:t<dO?5:t<pO?6:t<gO?7:t<yO?8:t<wO?9:10},bO={encode:iO,decode:aO,encodingLength:mO},Xg=bO;const Lh=(t,e,r=0)=>(Xg.encode(t,e,r),e),Mh=t=>Xg.encodingLength(t),ec=(t,e)=>{const r=e.byteLength,i=Mh(t),n=i+Mh(r),s=new Uint8Array(n+r);return Lh(t,s,0),Lh(r,s,i),s.set(e,n),new vO(t,r,e,s)};class vO{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const Qg=({name:t,code:e,encode:r})=>new EO(t,e,r);class EO{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?ec(this.code,r):r.then(i=>ec(this.code,i))}else throw Error("Unknown type, must be binary type")}}const e0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),xO=Qg({name:"sha2-256",code:18,encode:e0("SHA-256")}),_O=Qg({name:"sha2-512",code:19,encode:e0("SHA-512")});var IO=Object.freeze({__proto__:null,sha256:xO,sha512:_O});const t0=0,SO="identity",r0=Gg,$O=t=>ec(t0,r0(t)),OO={code:t0,name:SO,encode:r0,digest:$O};var DO=Object.freeze({__proto__:null,identity:OO});new TextEncoder,new TextDecoder;const qh={...v6,...x6,...I6,...$6,...A6,...j6,...q6,...H6,...Z6,...rO};({...IO,...DO});function i0(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function AO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?i0(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function n0(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const zh=n0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ra=n0("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=AO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),PO={utf8:zh,"utf-8":zh,hex:qh.base16,latin1:ra,ascii:ra,binary:ra,...qh};function CO(t,e="utf8"){const r=PO[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?i0(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var BO=Object.defineProperty,TO=(t,e,r)=>e in t?BO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ut=(t,e,r)=>TO(t,typeof e!="symbol"?e+"":e,r);class RO{constructor(e,r){this.core=e,this.logger=r,Ut(this,"keychain",new Map),Ut(this,"name",B$),Ut(this,"version",T$),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Wt),Ut(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Ut(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Ut(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),Ut(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=M("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),Ut(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=dt(r,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,Ra(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fa(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 FO=Object.defineProperty,NO=(t,e,r)=>e in t?FO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Se=(t,e,r)=>NO(t,typeof e!="symbol"?e+"":e,r);class UO{constructor(e,r,i){this.core=e,this.logger=r,Se(this,"name",P$),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Ka()),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=du(n),o=sp(s.publicKey);return this.clientId=o,o}),Se(this,"generateKeyPair",()=>{this.isInitialized();const n=bI();return this.setPrivateKey(n.publicKey,n.privateKey)}),Se(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=du(s),a=this.randomSessionIdentifier;return await p2(a,n,C$,o)}),Se(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=vI(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=Pg(o),c=oi(s);if(ah(a))return _I(c,o==null?void 0:o.encoding);if(oh(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 EI({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=SI(s,o);if(ah(a)){const c=II(s,o==null?void 0:o.encoding);return si(c)}if(oh(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=xI({symKey:c,encoded:s,encoding:o==null?void 0:o.encoding});return si(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=In({encoded:n,encoding:s});return ci(o.type)}),Se(this,"getPayloadSenderPublicKey",(n,s=tt)=>{const o=In({encoded:n,encoding:s});return o.senderPublicKey?nt(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=dt(r,this.name),this.keychain=i||new RO(this.core,this.logger)}get context(){return st(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Nh)}catch{e=Ka(),await this.keychain.set(Nh,e)}return CO(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 kO=Object.defineProperty,jO=Object.defineProperties,LO=Object.getOwnPropertyDescriptors,Vh=Object.getOwnPropertySymbols,MO=Object.prototype.hasOwnProperty,qO=Object.prototype.propertyIsEnumerable,tc=(t,e,r)=>e in t?kO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zO=(t,e)=>{for(var r in e||(e={}))MO.call(e,r)&&tc(t,r,e[r]);if(Vh)for(var r of Vh(e))qO.call(e,r)&&tc(t,r,e[r]);return t},VO=(t,e)=>jO(t,LO(e)),ot=(t,e,r)=>tc(t,typeof e!="symbol"?e+"":e,r);class HO extends $S{constructor(e,r){super(e,r),this.logger=e,this.core=r,ot(this,"messages",new Map),ot(this,"messagesWithoutClientAck",new Map),ot(this,"name",R$),ot(this,"version",F$),ot(this,"initialized",!1),ot(this,"storagePrefix",Wt),ot(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);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(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ot(this,"set",async(i,n,s)=>{this.isInitialized();const o=bt(n);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(i,a),s===ys.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,VO(zO({},c),{[o]:n}))}return await this.persist(),o}),ot(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),ot(this,"getWithoutAck",i=>{this.isInitialized();const n={};for(const s of i){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),ot(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=bt(n);return typeof s[o]<"u"}),ot(this,"ack",async(i,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(i);if(typeof s>"u")return;const o=bt(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,s),await this.persist()}),ot(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=dt(e,this.name),this.core=r}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,Ra(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ra(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fa(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Fa(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 KO=Object.defineProperty,WO=Object.defineProperties,GO=Object.getOwnPropertyDescriptors,Hh=Object.getOwnPropertySymbols,YO=Object.prototype.hasOwnProperty,ZO=Object.prototype.propertyIsEnumerable,rc=(t,e,r)=>e in t?KO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e)=>{for(var r in e||(e={}))YO.call(e,r)&&rc(t,r,e[r]);if(Hh)for(var r of Hh(e))ZO.call(e,r)&&rc(t,r,e[r]);return t},Kh=(t,e)=>WO(t,GO(e)),yt=(t,e,r)=>rc(t,typeof e!="symbol"?e+"":e,r);class JO extends OS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,yt(this,"events",new St.EventEmitter),yt(this,"name",U$),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(i,n,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const h=(s==null?void 0:s.ttl)||N$,f=(s==null?void 0:s.prompt)||!1,d=(s==null?void 0:s.tag)||0,p=(s==null?void 0:s.id)||Rr().toString(),g=$i(Fs().protocol),w={id:p,method:(s==null?void 0:s.publishMethod)||g.publish,params:Ei({topic:i,message:n,ttl:h,prompt:f,tag:d,attestation:s==null?void 0:s.attestation},s==null?void 0:s.tvf)},I=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{_e((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),_e((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 D=Vt(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 D,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:i,message:n,opts:s}}),await Vt(C,this.publishTimeout,I)}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 i=>{var n,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:l,opts:u={}}=i,{attestation:h,tvf:f,publishMethod:d,prompt:p,tag:g,ttl:w=L.FIVE_MINUTES}=u,I=u.id||Rr().toString(),C=$i(Fs().protocol),b=d||C.publish,v={id:I,method:b,params:Ei(Kh(Ei({},l),{ttl:w,prompt:p,tag:g,attestation:h}),f)},D=`Failed to publish custom payload, please try again. id:${I} tag:${g}`;try{_e((n=v.params)==null?void 0:n.prompt)&&((s=v.params)==null||delete s.prompt),_e((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=Vt(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:${I} tag:${g}`);try{await A,this.events.removeListener(me.publish,R)}catch(U){this.queue.set(I,{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:I,payload:l,opts:u}}),await Vt(P,this.publishTimeout,D)}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(I)}}),yt(this,"on",(i,n)=>{this.events.on(i,n)}),yt(this,"once",(i,n)=>{this.events.once(i,n)}),yt(this,"off",(i,n)=>{this.events.off(i,n)}),yt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=dt(r,this.name),this.registerEventListeners()}get context(){return st(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(me.publish,Ei(Ei({},e),r)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var i;const n=e.attempt+1;this.queue.set(r,Kh(Ei({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.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(fi.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 XO=Object.defineProperty,QO=(t,e,r)=>e in t?XO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xi=(t,e,r)=>QO(t,typeof e!="symbol"?e+"":e,r);class eD{constructor(){xi(this,"map",new Map),xi(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),xi(this,"get",e=>this.map.get(e)||[]),xi(this,"exists",(e,r)=>this.get(e).includes(r)),xi(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),xi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var tD=Object.defineProperty,rD=Object.defineProperties,iD=Object.getOwnPropertyDescriptors,Wh=Object.getOwnPropertySymbols,nD=Object.prototype.hasOwnProperty,sD=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?tD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rn=(t,e)=>{for(var r in e||(e={}))nD.call(e,r)&&ic(t,r,e[r]);if(Wh)for(var r of Wh(e))sD.call(e,r)&&ic(t,r,e[r]);return t},ia=(t,e)=>rD(t,iD(e)),ce=(t,e,r)=>ic(t,typeof e!="symbol"?e+"":e,r);class oD extends PS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ce(this,"subscriptions",new Map),ce(this,"topicMap",new eD),ce(this,"events",new St.EventEmitter),ce(this,"name",V$),ce(this,"version",H$),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Wt),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(i,n)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const o=Fs(n),a={topic:i,relay:o,transportType:n==null?void 0:n.transportType};(s=n==null?void 0:n.internal)!=null&&s.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,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:i,opts:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(i,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),ce(this,"isSubscribed",i=>new Promise(n=>{n(this.topicMap.topics.includes(i))})),ce(this,"isKnownTopic",i=>new Promise(n=>{n(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(s=>s.topic===i))})),ce(this,"on",(i,n)=>{this.events.on(i,n)}),ce(this,"once",(i,n)=>{this.events.once(i,n)}),ce(this,"off",(i,n)=>{this.events.off(i,n)}),ce(this,"removeListener",(i,n)=>{this.events.removeListener(i,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 i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(fi.pulse,async()=>{await this.checkPending()}),this.events.on(lt.created,async i=>{const n=lt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(lt.deleted,async i=>{const n=lt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=dt(r,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,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=Fs(i);await this.restartToComplete({topic:e,id:r,relay:n}),await this.rpcUnsubscribe(e,r,n);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i){var n,s;const o=await this.getSubscriptionId(e);if((n=i==null?void 0:i.internal)!=null&&n.skipSubscribe)return o;(!i||(i==null?void 0:i.transportType)===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:$i(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{if((i==null?void 0:i.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 Vt(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 Vt(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 r=e[0].relay,i={method:$i(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Vt(new Promise(n=>{this.relayer.request(i).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 r=e[0].relay,i={method:$i(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Vt(new Promise((s,o)=>{this.relayer.request(i).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,r,i){const n={method:$i(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,ia(rn({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rn({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rn({},r)),this.topicMap.set(r.topic,e),this.events.emit(lt.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(lt.deleted,ia(rn({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(lt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){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(r=>{var i;return r.topic===((i=this.subscriptions.get(r.id))==null?void 0:i.topic)})){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}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 r=>ia(rn({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await k3(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.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 aD=Object.defineProperty,Gh=Object.getOwnPropertySymbols,cD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,nc=(t,e,r)=>e in t?aD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yh=(t,e)=>{for(var r in e||(e={}))cD.call(e,r)&&nc(t,r,e[r]);if(Gh)for(var r of Gh(e))lD.call(e,r)&&nc(t,r,e[r]);return t},ne=(t,e,r)=>nc(t,typeof e!="symbol"?e+"":e,r);class uD extends DS{constructor(e){var r;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",j$),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 i=>{var n,s;this.logger.debug("Publishing Request Payload");const o=i.id||Rr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(n=i.params)==null?void 0:n.topic},"relayer.request - publishing...");const a=`${o}:${((s=i.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);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 i,n,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(n=(i=this.provider)==null?void 0:i.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",i=>{this.onProviderPayload(i),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",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(me.error,i),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=Zc({logger:(r=e.logger)!=null?r:k$,name:this.name}),this.messages=new HO(this.logger,e.core),this.subscriber=new oD(this,this.logger),this.publisher=new JO(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Kg,x3()?this.packageName=Du():_3()&&(this.bundleId=Du()),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,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:he.relay},ys.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,n,s;this.isInitialized(),(!(r!=null&&r.transportType)||(r==null?void 0:r.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(n=r==null?void 0:r.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,Yh({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Vt(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(r,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await vh())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 r=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=we(L.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,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 r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(gt.disconnect,s),await Vt(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,i()})}catch(i){await this.subscriber.stop();const n=i;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: ${r}`);break}await new Promise(i=>setTimeout(i,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(As())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.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 Qc(new O$(D3({sdkVersion:Xa,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,r){const{topic:i,message:n}=e;await this.messages.set(i,n,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Xc(e)){if(!e.method.endsWith(L$))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Yh({type:"event",event:r.id},a)),this.events.emit(r.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 r=$n(e.id,!0);await this.provider.connection.send(r)}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 vh();S8(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(fi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&D8())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r==null?void 0:r.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(M$)))))}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 hD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Zh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const fD="[object RegExp]",dD="[object String]",pD="[object Number]",gD="[object Boolean]",Xh="[object Arguments]",yD="[object Symbol]",wD="[object Date]",mD="[object Map]",bD="[object Set]",vD="[object Array]",ED="[object Function]",xD="[object ArrayBuffer]",na="[object Object]",_D="[object Error]",ID="[object DataView]",SD="[object Uint8Array]",$D="[object Uint8ClampedArray]",OD="[object Uint16Array]",DD="[object Uint32Array]",AD="[object BigUint64Array]",PD="[object Int8Array]",CD="[object Int16Array]",BD="[object Int32Array]",TD="[object BigInt64Array]",RD="[object Float32Array]",FD="[object Float64Array]";function ND(){}function Qh(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 UD(t,e,r){return un(t,e,void 0,void 0,void 0,void 0,r)}function un(t,e,r,i,n,s,o){const a=o(t,e,r,i,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,r,i){if(Object.is(t,e))return!0;let n=Jh(t),s=Jh(e);if(n===Xh&&(n=na),s===Xh&&(s=na),n!==s)return!1;switch(n){case dD:return t.toString()===e.toString();case pD:{const c=t.valueOf(),l=e.valueOf();return hD(c,l)}case gD:case wD:case yD:return Object.is(t.valueOf(),e.valueOf());case fD:return t.source===e.source&&t.flags===e.flags;case ED:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(n){case mD:{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,r,i))return!1;return!0}case bD:{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,r,i));if(f===-1)return!1;l.splice(f,1)}return!0}case vD:case SD:case $D:case OD:case DD:case AD:case PD:case CD:case BD:case TD:case RD:case FD:{if(typeof re<"u"&&re.isBuffer(t)!==re.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,r,i))return!1;return!0}case xD:return t.byteLength!==e.byteLength?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case ID:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case _D:return t.name===e.name&&t.message===e.message;case na:{if(!(yn(t.constructor,e.constructor,r,i)||Qh(t)&&Qh(e)))return!1;const c=[...Object.keys(t),...Zh(t)],l=[...Object.keys(e),...Zh(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,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function kD(t,e){return UD(t,e,ND)}var jD=Object.defineProperty,ef=Object.getOwnPropertySymbols,LD=Object.prototype.hasOwnProperty,MD=Object.prototype.propertyIsEnumerable,sc=(t,e,r)=>e in t?jD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,tf=(t,e)=>{for(var r in e||(e={}))LD.call(e,r)&&sc(t,r,e[r]);if(ef)for(var r of ef(e))MD.call(e,r)&&sc(t,r,e[r]);return t},Ze=(t,e,r)=>sc(t,typeof e!="symbol"?e+"":e,r);class pi extends AS{constructor(e,r,i,n=Wt,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,Ze(this,"map",new Map),Ze(this,"version",q$),Ze(this,"cached",[]),Ze(this,"initialized",!1),Ze(this,"getKey"),Ze(this,"storagePrefix",Wt),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&&!_e(o)?this.map.set(this.getKey(o),o):r8(o)?this.map.set(o.id,o):i8(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=>kD(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=tf(tf({},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(r,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 r=this.map.get(e);if(!r){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:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}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:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 qD=Object.defineProperty,zD=(t,e,r)=>e in t?qD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>zD(t,typeof e!="symbol"?e+"":e,r);class VD{constructor(e,r){this.core=e,this.logger=r,ee(this,"name",K$),ee(this,"version",W$),ee(this,"events",new dc),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",Wt),ee(this,"ignoredPayloadTypes",[hr]),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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),ee(this,"create",async i=>{this.isInitialized();const n=Ka(),s=await this.core.crypto.setSymKey(n),o=we(L.FIVE_MINUTES),a={protocol:Hg},c={topic:s,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=hh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Yr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:i==null?void 0:i.transportType,internal:i==null?void 0:i.internal}),{topic:s,uri:l}}),ee(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[jt.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=uh(i.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(ir.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),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Yr.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(ir.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw n.setError(ir.subscribe_pairing_topic_failure),d}return n.addTrace(jt.subscribe_pairing_topic_success),f}),ee(this,"activate",async({topic:i})=>{this.isInitialized();const n=we(L.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),ee(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Kr();this.events.once(ae("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),ee(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),ee(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(n))}),ee(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return hh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(i,n,s)=>{const o=Ct(n,s),a=await this.core.crypto.encode(i,o),c=en[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),ee(this,"sendResult",async(i,n,s)=>{const o=$n(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,l=en[c].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),ee(this,"sendError",async(i,n,s)=>{const o=oo(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).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(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),ee(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>qt(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),ee(this,"onRelayEventRequest",async i=>{const{topic:n,payload:s}=i;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 i=>{const{topic:n,payload:s}=i,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(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Yr.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(i,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(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Yr.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(i,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,i,a),this.logger.error(a)}catch(a){await this.sendError(s,i,a),this.logger.error(a)}}),ee(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",i))}),ee(this,"isValidPair",(i,n)=>{var s;if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(ir.malformed_pairing_uri),new Error(a)}if(!t8(i.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(ir.malformed_pairing_uri),new Error(a)}const o=uh(i==null?void 0:i.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(ir.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(ir.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){n.setError(ir.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 i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidDisconnect",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidPairingTopic",async i=>{if(!be(i,!1)){const{message:n}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(qt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=M("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=dt(r,this.name),this.pairings=new pi(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:r,message:i,transportType:n}=e;if(this.pairings.keys.includes(r)&&n!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const s=await this.core.crypto.decode(r,i);Xc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ao(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,i)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(wt.expired,async e=>{const{topic:r}=Bp(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Yr.expire,{topic:r}))})}}var HD=Object.defineProperty,KD=(t,e,r)=>e in t?HD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>KD(t,typeof e!="symbol"?e+"":e,r);class WD extends SS{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new St.EventEmitter),Be(this,"name",G$),Be(this,"version",Y$),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Wt),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Be(this,"set",(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:i,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(Ot.created,o)}),Be(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=vt(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Ot.updated,n))}),Be(this,"get",async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n))),Be(this,"delete",(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Ot.deleted,s)}}),this.persist()}),Be(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),Be(this,"on",(i,n)=>{this.events.on(i,n)}),Be(this,"once",(i,n)=>{this.events.once(i,n)}),Be(this,"off",(i,n)=>{this.events.off(i,n)}),Be(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,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(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Ct(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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(Ot.created,e=>{const r=Ot.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.updated,e=>{const r=Ot.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.deleted,e=>{const r=Ot.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(fi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Ot.deleted,r,!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 GD=Object.defineProperty,YD=(t,e,r)=>e in t?GD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ze=(t,e,r)=>YD(t,typeof e!="symbol"?e+"":e,r);class ZD extends CS{constructor(e,r){super(e,r),this.core=e,this.logger=r,ze(this,"expirations",new Map),ze(this,"events",new St.EventEmitter),ze(this,"name",Z$),ze(this,"version",J$),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Wt),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),ze(this,"set",(i,n)=>{this.isInitialized();const s=this.formatTarget(i),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",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),ze(this,"del",i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(wt.deleted,{target:n,expiration:s})}}),ze(this,"on",(i,n)=>{this.events.on(i,n)}),ze(this,"once",(i,n)=>{this.events.once(i,n)}),ze(this,"off",(i,n)=>{this.events.off(i,n)}),ze(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,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 A3(e);if(typeof e=="number")return P3(e);const{message:r}=M("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}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:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 r=this.expirations.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;L.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(wt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(fi.pulse,()=>this.checkExpirations()),this.events.on(wt.created,e=>{const r=wt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.expired,e=>{const r=wt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.deleted,e=>{const r=wt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var JD=Object.defineProperty,XD=(t,e,r)=>e in t?JD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ye=(t,e,r)=>XD(t,typeof e!="symbol"?e+"":e,r);class QD extends BS{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,ye(this,"name",X$),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",e6),ye(this,"storagePrefix",Wt),ye(this,"version",Vg),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(!Mi()||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=ii(),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=I=>{if(I.data&&typeof I.data=="string")try{const C=JSON.parse(I.data);if(C.type==="verify_attestation"){if(Pa(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(Pa(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 t6.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=OI(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(r,this.name),this.abortController=new AbortController,this.isDevEnv=jc(),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 e4=Object.defineProperty,t4=(t,e,r)=>e in t?e4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rf=(t,e,r)=>t4(t,typeof e!="symbol"?e+"":e,r);class r4 extends TS{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,rf(this,"context",r6),rf(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${i6}/${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(r,this.context)}}var i4=Object.defineProperty,nf=Object.getOwnPropertySymbols,n4=Object.prototype.hasOwnProperty,s4=Object.prototype.propertyIsEnumerable,oc=(t,e,r)=>e in t?i4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nn=(t,e)=>{for(var r in e||(e={}))n4.call(e,r)&&oc(t,r,e[r]);if(nf)for(var r of nf(e))s4.call(e,r)&&oc(t,r,e[r]);return t},$e=(t,e,r)=>oc(t,typeof e!="symbol"?e+"":e,r);class o4 extends RS{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,$e(this,"context",s6),$e(this,"storagePrefix",Wt),$e(this,"storageVersion",n6),$e(this,"events",new Map),$e(this,"shouldPersist",!1),$e(this,"init",async()=>{if(!jc())try{const n={eventId:Pu(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Pp(this.core.relayer.protocol,this.core.relayer.version,Xa)}}};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=Pu(),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(fi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(n.timestamp)>o6&&(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(`${a6}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Xa}${s}`,{method:"POST",body:JSON.stringify(n)})}),$e(this,"getAppDomain",()=>Ap().url),this.logger=dt(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var a4=Object.defineProperty,sf=Object.getOwnPropertySymbols,c4=Object.prototype.hasOwnProperty,l4=Object.prototype.propertyIsEnumerable,ac=(t,e,r)=>e in t?a4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,of=(t,e)=>{for(var r in e||(e={}))c4.call(e,r)&&ac(t,r,e[r]);if(sf)for(var r of sf(e))l4.call(e,r)&&ac(t,r,e[r]);return t},le=(t,e,r)=>ac(t,typeof e!="symbol"?e+"":e,r);let u4=class s0 extends ES{constructor(e){var r;super(e),le(this,"protocol",zg),le(this,"version",Vg),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 i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}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)||Kg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=c3({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:D$.logger,name:Us}),{logger:s,chunkLoggerController:o}=Op({opts:n,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.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 k8,this.crypto=new UO(this,this.logger,e==null?void 0:e.keychain),this.history=new WD(this,this.logger),this.expirer=new ZD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new mS(of(of({},A$),e==null?void 0:e.storageOptions)),this.relayer=new uD({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new VD(this,this.logger),this.verify=new QD(this,this.logger,this.storage),this.echoClient=new r4(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new o4(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new s0(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(z$,i),r}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(Uh,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(Uh)||[],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 r=`_walletConnectCore_${e}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof xt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const h4=u4,o0="wc",a0=2,c0="client",el=`${o0}@${a0}:${c0}:`,sa={name:c0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},af="WALLETCONNECT_DEEPLINK_CHOICE",f4="proposal",cf="Proposal expired",d4="session",_i=L.SEVEN_DAYS,p4="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}}},oa={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},g4={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:""}},y4="request",w4=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],m4="wc",b4="auth",v4="authKeys",E4="pairingTopics",x4="requests",lo=`${m4}@${1.5}:${b4}:`,ws=`${lo}:PUB_KEY`;var _4=Object.defineProperty,I4=Object.defineProperties,S4=Object.getOwnPropertyDescriptors,lf=Object.getOwnPropertySymbols,$4=Object.prototype.hasOwnProperty,O4=Object.prototype.propertyIsEnumerable,cc=(t,e,r)=>e in t?_4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oe=(t,e)=>{for(var r in e||(e={}))$4.call(e,r)&&cc(t,r,e[r]);if(lf)for(var r of lf(e))O4.call(e,r)&&cc(t,r,e[r]);return t},Re=(t,e)=>I4(t,S4(e)),k=(t,e,r)=>cc(t,typeof e!="symbol"?e+"":e,r);class D4 extends kS{constructor(e){super(e),k(this,"name",p4),k(this,"events",new dc),k(this,"initialized",!1),k(this,"requestQueue",{state:kt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),k(this,"emittedSessionRequests",new j3({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 r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Re(oe({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=ZI(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=((i=h==null?void 0:h[0])==null?void 0:i.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 I=await this.client.core.crypto.generateKeyPair(),C=we(d),b=oe(Re(oe(oe({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:Hg}],proposer:{publicKey:I,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:_,exp:O,nbf:m,type:y,statement:x,requestId:$,resources:E,signatureTypes:S}=A;return{domain:U,chains:j,nonce:B,type:y??"caip122",aud:_,version:"1",iat:new Date().toISOString(),exp:O,nbf:m,statement:x,requestId:$,resources:E,signatureTypes:S}}),walletPay:f}}),v=ae("session_connect",b.id),{reject:D,resolve:P,done:T}=Kr(d,cf),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:cf,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?D(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 r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),k(this,"approve",async r=>{var i,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[Dt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw o.setError(zr.no_internet_connection),U}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(zr.proposal_not_found),U}try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(zr.session_approve_namespace_validation_failure),U}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:I,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:Dt.session_approve_started,properties:{topic:g,trace:[Dt.session_approve_started,Dt.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),D=w.publicKey,P=await this.client.core.crypto.generateSharedKey(v,D),T=Re(oe(oe(oe({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:we(_i)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=he.relay;b.addTrace(Dt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:R,internal:{skipSubscribe:!0}})}catch(U){throw b.setError(zr.subscribe_session_topic_failure),U}b.addTrace(Dt.subscribe_session_topic_success);const A=Re(oe({},T),{topic:P,requiredNamespaces:I,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(Dt.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(Dt.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(_i)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),k(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}s&&await this.sendError({id:i,topic:s,error:n,rpcOpts:Te.wc_sessionPropose.reject}),await this.deleteProposal(i)}),k(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=Kr(L.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Lt(),l=Rr().toString(),u=this.client.session.get(i).namespaces;return this.events.once(ae("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:u}),a(h)}),{acknowledged:s}}),k(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,n=Lt(),{done:s,resolve:o,reject:a}=Kr(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(i,we(_i)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:n,topic:s,expiry:o=Te.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);(a==null?void 0:a.transportType)===he.relay&&await this.confirmOnlineStateOrThrow();const c=Lt(),l=Rr().toString(),{done:u,resolve:h,reject:f}=Kr(o,"Request expired. Please try again.");this.events.once(ae("session_request",c),({error:w,result:I})=>{w?f(w):h(I)});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:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await u();const g={request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:i};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(I=>f(I)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),w()}),new Promise(async w=>{var I;if(!((I=a.sessionConfig)!=null&&I.disableDeepLink)){const C=await R3(this.client.core.storage,af);await C3({id:c,topic:s,wcDeepLink:C})}w()}),u()]).then(w=>w[2])}),k(this,"respond",async r=>{var i,n;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:(r==null?void 0:r.topic)||((n=(i=r==null?void 0:r.response)==null?void 0:i.id)==null?void 0:n.toString()),trace:[Dt.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_validation_failure),h}s.addTrace(Dt.session_request_response_validation_success);const{topic:o,response:a}=r,{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(Dt.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(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_publish_failure),h}}),k(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=Lt(),s=Rr().toString(),{done:o,resolve:a,reject:c}=Kr(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:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),k(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Rr().toString(),a=Lt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),k(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>QI(i,r)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((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}=r,I=[...r.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(),D=ds(v);if(await Promise.all([this.client.auth.authKeys.set(ws,{responseTopic:D,publicKey:v}),this.client.auth.pairingTopics.set(D,{topic:D,pairingTopic:C})]),await this.client.core.relayer.subscribe(D,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),g.length>0){const{namespace:E}=ur(a[0]);let S=Xx(E,"request",g);fs(I)&&(S=e_(S,I.pop())),I.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:I},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}=Kr(P,"Request expired"),_=Lt(),O=ae("session_connect",A.id),m=ae("session_request",_),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(_,{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(O,y),B(E.error.message))}await this.deleteProposal(A.id),this.events.off(O,y);const{cacaos:H,responder:z}=E.result,q=[],K=[];for(const W of H){await Mu({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=[Na(Q.iss)],Ie=Cs(Q.iss);if(pe){const He=qu(pe),Gt=zu(pe);q.push(...He),ve.push(...Gt)}for(const He of ve)K.push(`${He}:${Ie}`)}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(_i),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:gh([...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&&i&&(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(O,y),this.events.once(m,x);let $;try{if(s){const E=Ct("wc_sessionAuthenticate",T,_);this.client.core.history.set(C,E);const S=await this.client.core.crypto.encode("",E,{type:Nn,encoding:Br});$=rs(i,C,S)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:_}),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(O,y),this.events.off(m,x),E}return await this.setProposal(A.id,A),await this.setAuthRequest(_,{request:Re(oe({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:$??b,response:U}}),k(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Vr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(tn.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);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:hr,receiverPublicKey:c,senderPublicKey:l},f=[],d=[];for(const w of n){if(!await Mu({cacao:w,projectId:this.client.core.projectId})){s.setError(tn.invalid_cacao);const D=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:D,encodeOpts:h}),new Error(D.message)}s.addTrace(Vr.cacaos_verified);const{p:I}=w,C=fs(I.resources),b=[Na(I.iss)],v=Cs(I.iss);if(C){const D=qu(C),P=zu(C);f.push(...D),b.push(...P)}for(const D of b)d.push(`${D}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Vr.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(_i),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:gh([...new Set(f)],[...new Set(d)]),transportType:a},s.addTrace(Vr.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(Vr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Vr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Vr.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,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(i,{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 r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ds(o),l={type:hr,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,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(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),k(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return Yp(i,n)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),k(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.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)===r.peer.metadata.url&&s.topic&&s.topic!==i.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(i){this.client.logger.error(i)}}),k(this,"deleteSession",async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{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(af).catch(l=>this.client.logger.warn(l)),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.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(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s==null||s.setError(zr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,fe("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),k(this,"deletePendingSessionRequest",async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:r}))}),k(this,"deletePendingAuthRequest",async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])}),k(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),k(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,we(Te.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),k(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=he.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||we(Te.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:o})}),k(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=r,d=Ct(n,s,c);let p;const g=!!u;try{const C=g?Br:tt;p=await this.client.core.crypto.encode(i,d,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),C}let w;if(w4.includes(n)){const C=bt(JSON.stringify(d)),b=bt(p);w=await this.client.core.verify.register({id:b,decryptedId:C})}const I=oe(oe({},Te[n].req),f);if(I.attestation=w,o&&(I.ttl=o),a&&(I.id=a),this.client.core.history.set(i,d),g){const C=rs(u,i,p);await Y.Linking.openURL(C,this.client.name)}else I.tvf=Re(oe({},h),{correlationId:d.id}),l?(I.internal=Re(oe({},I.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,I)):this.client.core.relayer.publish(i,p,I).catch(C=>this.client.logger.error(C));return d.id}),k(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:n}=r,s=Ct("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,s);const o=await this.client.core.crypto.encode(i.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:i.pairingTopic,sessionProposal:o},opts:Re(oe({},n),{publishMethod:"wc_proposeSession",attestation:l})})}),k(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:n,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=$n(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(i,u,{encoding:tt});this.client.core.history.set(i,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:Re(oe({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=$n(i,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const p=h?Br: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,i);const p=f.request;try{d=this.getTVFParams(i,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}, ${i}) failed`),p}if(h){const p=rs(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:i}),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 r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=oo(i,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const d=h?Br: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,i)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),d}if(h){const d=rs(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 r=[],i=[];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&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{qt(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),k(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),k(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),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 r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=kt.idle}),k(this,"processRequest",async r=>{const{topic:i,payload:n,attestation:s,transportType:o,encryptedId:a}=r,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n,transportType:s}=r,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=M("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),k(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:n,attestation:s,encryptedId:o}=r,{params:a,id:c}=n;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(ir.proposal_listener_not_found)),this.isValidConnect(oe({},n.params));const u=a.expiryTimestamp||we(Te.wc_sessionPropose.req.ttl),h=oe({id:c,pairingTopic:i,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:i,error:l,rpcOpts:Te.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),k(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(Mt(i)){const{result:o}=i;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:r,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:r})}else if(vt(i)){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:i.error})}}),k(this,"onSessionSettleRequest",async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i.params,p=[...this.pendingSessions.values()].find(I=>I.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const g=this.client.proposal.get(p.proposalId),w=Re(oe(oe(oe({topic:r,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:i.id,topic:r,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:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;Mt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ae("session_approve",n),{})):vt(i)&&(await this.client.session.delete(r,fe("USER_DISCONNECTED")),this.events.emit(ae("session_approve",n),{error:i.error}))}),k(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:r},n));try{Qi.set(o,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Qi.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=ae("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_update",n),{}):vt(i)&&this.events.emit(ae("session_update",n),{error:i.error})}),k(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,we(_i)),await this.sendResult({id:n,topic:r,result:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=ae("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_extend",n),{}):vt(i)&&this.events.emit(ae("session_extend",n),{error:i.error})}),k(this,"onSessionPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=ae("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Mt(i)?this.events.emit(ae("session_ping",n),{}):vt(i)&&this.events.emit(ae("session_ping",n),{error:i.error})},500)}),k(this,"onSessionDeleteRequest",async(r,i)=>{const{id:n}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:fe("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:n})}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{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&&(i=d.peer.metadata.redirect)!=null&&i.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",(r,i)=>{const{id:n}=i,s=ae("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(oe({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Qi.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=r;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&&(i=l.metadata.redirect)!=null&&i.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:hr,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",r=>{this.sessionRequestQueue.queue.push(r)}),k(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ae("session_request",s.request.id),{error:i})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),k(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=kt.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),k(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Ct("wc_sessionPropose",Re(oe({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id),attestation:i.attestation,encryptedId:i.encryptedId})}),k(this,"isValidConnect",async r=>{if(!Xe(r)){const{message:l}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(_e(i)||await this.isValidPairingTopic(i),!h8(c,!0)){const{message:l}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(n&&!_e(n)&&Kt(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&&!_e(s)&&Kt(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(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",(r,i)=>{const n=u8(r,"connect()",i);if(n)throw new Error(n.message)}),k(this,"isValidApprove",async r=>{if(!Xe(r))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),l=Jo(n,"approve()");if(l)throw new Error(l.message);const u=mh(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&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(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 r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!d8(n)){const{message:s}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",r=>{if(!Xe(r)){const{message:l}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Tg(i)){const{message:l}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=n8(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 r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),o=Jo(n,"update()");if(o)throw new Error(o.message);const a=mh(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),k(this,"isValidRequest",async r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:n,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!wh(a,s)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!p8(n)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!w8(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 r=>{var i;if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!g8(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 r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidEmit",async r=>{if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!wh(o,s)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!y8(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!m8(o,s,n.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidAuthenticate",r=>{const{chains:i,uri:n,domain:s,nonce:o}=r;if(!Array.isArray(i)||i.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(i.map(c=>ur(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ur(i[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 r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,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:i,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",(r,i)=>{Object.values(r).forEach((n,s)=>{if(n==null){const{message:o}=M("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${n} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),k(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),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",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),k(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,l,u,h,f;return!r||i!==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=r==null?void 0:r.redirect)==null?void 0:u.universal)!==void 0&&((h=r==null?void 0:r.redirect)==null?void 0:h.universal)!==""&&((f=r==null?void 0:r.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(Y==null?void 0:Y.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r==null?void 0:r.redirect)==null?void 0:n.universal:void 0}),k(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Au(r,"topic")||"",n=decodeURIComponent(Au(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var r;if(jc()||kr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=Y==null?void 0:Y.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),k(this,"getTVFApproveParams",r=>{try{const i=Cg(r.namespaces),n=HI(r.namespaces),s=KI(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:n,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),k(this,"getTVFParams",(r,i,n)=>{var s,o,a;if(!((s=i.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const l=this.extractTxHashesFromResult(i.request,n);c.txHashes=l,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.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",r=>{var i;if(!r)return!1;try{const n=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.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",(r,i)=>{var n;try{if(!i)return[];const s=r.method,o=g4[s];if(s==="sui_signTransaction")return[Tx(i.transactionBytes)];if(s==="near_signTransaction")return[Uu(i)];if(s==="near_signTransactions")return i.map(c=>Uu(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(n=i.tx_json)==null?void 0:n.hash];if(s==="polkadot_signTransaction")return[N8({transaction:r.params.transactionPayload,signature:i.signature})];if(s==="algo_signTxn")return _t(i)?i.map(c=>ku(c)):[ku(i)];if(s==="cosmos_signDirect")return[Fx(i)];if(s==="wallet_sendCalls")return Nx(i);if(typeof i=="string")return[i];const a=i[o.key];if(_t(a))return s==="solana_signAllTransactions"?a.map(c=>Bx(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,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,n]of Object.entries(r))for(const s of n)try{await this.onProviderMessageEvent({topic:i,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, 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:r,message:i,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(r,i,{receiverPublicKey:o,encoding:s===he.link_mode?Br:tt});Xc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:bt(i)})):ao(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(wt.expired,async e=>{const{topic:r,id:i}=Bp(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,M("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,M("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Yr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Yr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!be(e,!1)){const{message:r}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!be(e,!1)){const{message:r}=M("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=M("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=M("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}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:r}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!f8(e)){const{message:r}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=M("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!E8(e,oa)){const{message:r}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${oa.min} and ${oa.max}`);throw new Error(r)}}}class A4 extends pi{constructor(e,r){super(e,r,f4,el),this.core=e,this.logger=r}}let P4=class extends pi{constructor(e,r){super(e,r,d4,el),this.core=e,this.logger=r}};class C4 extends pi{constructor(e,r){super(e,r,y4,el,i=>i.id),this.core=e,this.logger=r}}class B4 extends pi{constructor(e,r){super(e,r,v4,lo,()=>ws),this.core=e,this.logger=r}}class T4 extends pi{constructor(e,r){super(e,r,E4,lo),this.core=e,this.logger=r}}class R4 extends pi{constructor(e,r){super(e,r,x4,lo,i=>i.id),this.core=e,this.logger=r}}var F4=Object.defineProperty,N4=(t,e,r)=>e in t?F4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,aa=(t,e,r)=>N4(t,typeof e!="symbol"?e+"":e,r);class U4{constructor(e,r){this.core=e,this.logger=r,aa(this,"authKeys"),aa(this,"pairingTopics"),aa(this,"requests"),this.authKeys=new B4(this.core,this.logger),this.pairingTopics=new T4(this.core,this.logger),this.requests=new R4(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var k4=Object.defineProperty,j4=(t,e,r)=>e in t?k4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>j4(t,typeof e!="symbol"?e+"":e,r);class tl extends US{constructor(e){super(e),te(this,"protocol",o0),te(this,"version",a0),te(this,"name",sa.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",(i,n)=>this.events.on(i,n)),te(this,"once",(i,n)=>this.events.once(i,n)),te(this,"off",(i,n)=>this.events.off(i,n)),te(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),te(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),te(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),te(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=(e==null?void 0:e.name)||sa.name,this.metadata=S3(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=Zc({logger:(e==null?void 0:e.logger)||sa.logger,name:this.name});this.logger=r,this.core=(e==null?void 0:e.core)||new h4(e),this.session=new P4(this.core,this.logger),this.proposal=new A4(this.core,this.logger),this.pendingRequest=new C4(this.core,this.logger),this.engine=new D4(this),this.auth=new U4(this.core,this.logger)}static async init(e){const r=new tl(e);return await r.initialize(),r}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 L4=tl;var M4=Object.defineProperty,q4=Object.defineProperties,z4=Object.getOwnPropertyDescriptors,uf=Object.getOwnPropertySymbols,V4=Object.prototype.hasOwnProperty,H4=Object.prototype.propertyIsEnumerable,hf=(t,e,r)=>e in t?M4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ff=(t,e)=>{for(var r in e||(e={}))V4.call(e,r)&&hf(t,r,e[r]);if(uf)for(var r of uf(e))H4.call(e,r)&&hf(t,r,e[r]);return t},df=(t,e)=>q4(t,z4(e));const K4={Accept:"application/json","Content-Type":"application/json"},W4="POST",pf={headers:K4,method:W4},gf=10;let l0=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new St.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}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 r=oi(e),i=await(await dl(this.url,df(ff({},pf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,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"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=oi({id:1,jsonrpc:"2.0",method:"test",params:[]});await dl(e,df(ff({},pf),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}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 r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return kg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>gf&&this.events.setMaxListeners(gf)}};function rl(t){return t==null||typeof t!="object"&&typeof t!="function"}function u0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function h0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const G4="[object RegExp]",f0="[object String]",d0="[object Number]",p0="[object Boolean]",g0="[object Arguments]",Y4="[object Symbol]",Z4="[object Date]",J4="[object Map]",X4="[object Set]",Q4="[object Array]",eA="[object ArrayBuffer]",tA="[object Object]",rA="[object DataView]",iA="[object Uint8Array]",nA="[object Uint8ClampedArray]",sA="[object Uint16Array]",oA="[object Uint32Array]",aA="[object Int8Array]",cA="[object Int16Array]",lA="[object Int32Array]",uA="[object Float32Array]",hA="[object Float64Array]";function il(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function fA(t,e){return Di(t,void 0,t,new Map,e)}function Di(t,e,r,i=new Map,n=void 0){const s=n==null?void 0:n(t,e,r,i);if(s!=null)return s;if(rl(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,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;i.set(t,o);for(const[a,c]of t)o.set(a,Di(c,a,r,i,n));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Di(a,void 0,r,i,n));return o}if(typeof re<"u"&&re.isBuffer(t))return t.subarray();if(il(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,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 i.set(t,o),Zr(o,t,r,i,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Zr(o,t,r,i,n),o}if(typeof t=="object"&&dA(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Zr(o,t,r,i,n),o}return t}function Zr(t,e,r=t,i,n){const s=[...Object.keys(e),...u0(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Di(e[a],a,r,i,n))}}function dA(t){switch(h0(t)){case g0:case Q4:case eA:case rA:case p0:case Z4:case uA:case hA:case aA:case cA:case lA:case J4:case d0:case tA:case G4:case X4:case f0:case Y4:case iA:case nA:case sA:case oA:return!0;default:return!1}}function pA(t,e){return fA(t,(r,i,n,s)=>{const o=e==null?void 0:e(r,i,n,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case d0:case f0:case p0:{const a=new t.constructor(t==null?void 0:t.valueOf());return Zr(a,t),a}case g0:{const a={};return Zr(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function yf(t){return pA(t)}function wf(t){return t!==null&&typeof t=="object"&&h0(t)==="[object Arguments]"}function mf(t){return typeof t=="object"&&t!==null}function gA(){}function yA(t){return il(t)}function wA(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function mA(t){if(rl(t))return t;if(Array.isArray(t)||il(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function bA(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let n=t;for(let s=0;s<r.length;s++){const o=r[s];n=lc(n,o,i,new Map)}return n}function lc(t,e,r,i){if(rl(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return mA(i.get(e));if(i.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),...u0(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(wf(a)&&(a={...a}),wf(c)&&(c={...c}),typeof re<"u"&&re.isBuffer(a)&&(a=yf(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=r(c,a,o,t,e,i);l!=null?t[o]=l:Array.isArray(a)||mf(c)&&mf(a)?t[o]=lc(c,a,r,i):c==null&&wA(a)?t[o]=lc({},a,r,i):c==null&&yA(a)?t[o]=yf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function vA(t,...e){return bA(t,...e,gA)}const bf="error",EA="wss://relay.walletconnect.org",xA="wc",y0="universal_provider",ss=`${xA}@2:${y0}:`,w0="https://rpc.walletconnect.org/v1/",m0="generic",_A=`${w0}bundler`,Ti="call_status",IA=86400,nl={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var SA=Object.defineProperty,$A=Object.defineProperties,OA=Object.getOwnPropertyDescriptors,vf=Object.getOwnPropertySymbols,DA=Object.prototype.hasOwnProperty,AA=Object.prototype.propertyIsEnumerable,Ef=(t,e,r)=>e in t?SA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,os=(t,e)=>{for(var r in e||(e={}))DA.call(e,r)&&Ef(t,r,e[r]);if(vf)for(var r of vf(e))AA.call(e,r)&&Ef(t,r,e[r]);return t},PA=(t,e)=>$A(t,OA(e));function b0(t,e,r){var i;const n=ur(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${w0}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function CA(t){return t.includes(":")?t.split(":")[1]:t}function v0(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function BA(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function xf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,n;return((i=r==null?void 0:r.chains)==null?void 0:i.length)&&((n=r==null?void 0:r.chains)==null?void 0:n.length)>0}))}function as(t={},e={}){const r=xf(_f(t)),i=xf(_f(e));return vA(r,i)}function _f(t){var e,r,i,n,s;const o={};if(!Kt(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=Oi(a);o[d]=PA(os(os({},o[d]),c),{chains:Ht(l,(e=o[d])==null?void 0:e.chains),methods:Ht(u,(r=o[d])==null?void 0:r.methods),events:Ht(h,(i=o[d])==null?void 0:i.events)}),(Kt(f)||Kt(((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 If(t){return t.includes(":")?t.split(":")[2]:t}function Sf(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=so(r)?[r]:i.chains?i.chains:v0(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function ca(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 TA(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const E0={},Ri=t=>E0[t],la=(t,e)=>{E0[t]=e};var RA=Object.defineProperty,$f=Object.getOwnPropertySymbols,FA=Object.prototype.hasOwnProperty,NA=Object.prototype.propertyIsEnumerable,Of=(t,e,r)=>e in t?RA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Df=(t,e)=>{for(var r in e||(e={}))FA.call(e,r)&&Of(t,r,e[r]);if($f)for(var r of $f(e))NA.call(e,r)&&Of(t,r,e[r]);return t};const Af="eip155",UA=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],kA=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,ua=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Pf=t=>Object.keys(t).filter(e=>UA.includes(e)).reduce((e,r)=>(e[r]=jA(t[r]),e),{}),jA=t=>typeof t=="string"&&TA(t)?JSON.parse(t):t,LA=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:n={}}=t,s={};if(!Kt(n)&&!Kt(i))return;const o=Pf(i);for(const a of r){const c=kA(a);if(!c)continue;s[ua(c)]=o;const l=n==null?void 0:n[`${Af}:${c}`];if(l){const u=l==null?void 0:l[`${Af}:${c}:${e}`];s[ua(c)]=Df(Df({},s[ua(c)]),Pf(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 MA=Object.defineProperty,qA=(t,e,r)=>e in t?MA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zA=(t,e,r)=>qA(t,typeof e!="symbol"?e+"":e,r);let ha,VA=class x0{constructor(e){zA(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,r){return await this.storage.setItem(e,r)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return ha||(ha=new x0(e)),ha}};var HA=Object.defineProperty,KA=Object.defineProperties,WA=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,GA=Object.prototype.hasOwnProperty,YA=Object.prototype.propertyIsEnumerable,Bf=(t,e,r)=>e in t?HA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ZA=(t,e)=>{for(var r in e||(e={}))GA.call(e,r)&&Bf(t,r,e[r]);if(Cf)for(var r of Cf(e))YA.call(e,r)&&Bf(t,r,e[r]);return t},JA=(t,e)=>KA(t,WA(e));async function XA(t,e){const r=ur(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(i.map(h=>QA(r.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 QA(t,e,r){return await r(parseInt(t)).request(Ct("eth_getTransactionReceipt",[e]))}async function eP({sendCalls:t,storage:e}){const r=await e.getItem(Ti);await e.setItem(Ti,JA(ZA({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:we(IA)}}))}async function tP({resultId:t,storage:e}){const r=await e.getItem(Ti);if(r){delete r[t],await e.setItem(Ti,r);for(const i in r)qt(r[i].expiry)&&delete r[i];await e.setItem(Ti,r)}}async function rP({resultId:t,storage:e}){const r=await e.getItem(Ti),i=r==null?void 0:r[t];if(i&&!qt(i.expiry))return i;await tP({resultId:t,storage:e})}var iP=Object.defineProperty,nP=Object.defineProperties,sP=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,oP=Object.prototype.hasOwnProperty,aP=Object.prototype.propertyIsEnumerable,uc=(t,e,r)=>e in t?iP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fa=(t,e)=>{for(var r in e||(e={}))oP.call(e,r)&&uc(t,r,e[r]);if(Tf)for(var r of Tf(e))aP.call(e,r)&&uc(t,r,e[r]);return t},da=(t,e)=>nP(t,sP(e)),Hr=(t,e,r)=>uc(t,typeof e!="symbol"?e+"":e,r);class cP{constructor(e){Hr(this,"name","eip155"),Hr(this,"client"),Hr(this,"chainId"),Hr(this,"namespace"),Hr(this,"httpProviders"),Hr(this,"events"),Hr(this,"storage"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=VA.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,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(nl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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,r){const i=r||b0(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Qc(new l0(i,Ri("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(CA(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=da(fa({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.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:(i=this.namespace.chains)==null?void 0:i[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 r,i,n,s,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[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=LA(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:da(fa({},l.sessionProperties||{}),{capabilities:da(fa({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var r,i,n;const s=this.client.session.get(e.topic),o=(r=s.sessionProperties)==null?void 0:r.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=(i=s.sessionProperties)==null?void 0:i.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 rP({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(c)try{return await XA(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,r){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${_A}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,n;const s=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=s==null?void 0:s.id,c=(s==null?void 0:s.capabilities)||{},l=(i=c==null?void 0:c.caip345)==null?void 0:i.caip2,u=(n=c==null?void 0:c.caip345)==null?void 0:n.transactionHashes;return!a||!l||!(u!=null&&u.length)||await eP({sendCalls:{request:o,result:s},storage:this.storage}),s}}var lP=Object.defineProperty,uP=(t,e,r)=>e in t?lP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ii=(t,e,r)=>uP(t,typeof e!="symbol"?e+"":e,r);class hP{constructor(e){Ii(this,"name",m0),Ii(this,"client"),Ii(this,"httpProviders"),Ii(this,"events"),Ii(this,"namespace"),Ii(this,"chainId"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("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,r){this.httpProviders[e]||this.setHttpProvider(e,r);const i=this.chainId;this.chainId=e,this.events.emit(nl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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 ur(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(n=>{var s,o;const a=ur(n),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(n,c)}),i}getHttpProvider(e){const r=ur(e).reference,i=this.httpProviders[r];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||b0(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Qc(new l0(i,Ri("disableProviderPing")))}}var fP=Object.defineProperty,dP=Object.defineProperties,pP=Object.getOwnPropertyDescriptors,Rf=Object.getOwnPropertySymbols,gP=Object.prototype.hasOwnProperty,yP=Object.prototype.propertyIsEnumerable,hc=(t,e,r)=>e in t?fP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sn=(t,e)=>{for(var r in e||(e={}))gP.call(e,r)&&hc(t,r,e[r]);if(Rf)for(var r of Rf(e))yP.call(e,r)&&hc(t,r,e[r]);return t},cs=(t,e)=>dP(t,pP(e)),at=(t,e,r)=>hc(t,typeof e!="symbol"?e+"":e,r);class sl{constructor(e){at(this,"client"),at(this,"namespaces"),at(this,"optionalNamespaces"),at(this,"sessionProperties"),at(this,"scopedProperties"),at(this,"events",new dc),at(this,"rpcProviders",{}),at(this,"session"),at(this,"providerOpts"),at(this,"logger"),at(this,"uri"),at(this,"disableProviderPing",!1),at(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Zc({logger:(r=e.logger)!=null?r:bf,name:(i=this.providerOpts.name)!=null?i:y0}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new sl(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);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:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(o=>r(null,$n(s,o))).catch(o=>r(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,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const o=Sf(this.session.namespaces);this.namespaces=as(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){var r,i;const{uri:n,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(i=this.connectParams)==null?void 0:i.walletPay});n&&(this.uri=n,this.events.emit("display_uri",n));const o=await s();this.session=o;const a=Sf(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,r){try{if(!this.session)return;const[i,n]=this.validateChain(e);this.getProvider(i).setDefaultChain(n,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!_t(r))return;for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"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,r;if(this.client=this.providerOpts.client||await L4.init({core:this.providerOpts.core,logger:this.providerOpts.logger||bf,relayUrl:this.providerOpts.relayUrl||EA,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(i){throw this.logger.error(i,"Failed to get session"),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[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(r=>Oi(r)))];la("client",this.client),la("events",this.events),la("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=BA(r,this.session);if((i==null?void 0:i.length)===0)return;const n=v0(i),s=as(this.namespaces,this.optionalNamespaces),o=cs(sn({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new cP({namespace:o});break;default:this.rpcProviders[r]=new hP({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:n}=e;if(n!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=i;if(s.name==="accountsChanged"){const o=s.data;o&&_t(o)&&this.events.emit("accountsChanged",o.map(If))}else if(s.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Oi(o),l=ca(o)!==ca(a)?`${c}:${ca(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:r})=>{var i,n;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:s}=r,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:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",cs(sn({},fe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(nl.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(cs(sn({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[m0]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=as(r,i),this.sessionProperties=n,this.scopedProperties=s}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>Oi(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=Oi(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:r,internal:i=!1}){if(!this.namespaces)return;const[n,s]=this.validateChain(e);s&&(this.updateNamespaceChain(n,s),i?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(n).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var n,s;try{if(i===r)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(`${r}:`)).map(If);if(!_t(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,n={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=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,r){var i;const n=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${ss}/${e}${n}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${ss}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${ss}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const i of r)i.startsWith(ss)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const wP=sl,mP="wc",bP="ethereum_provider",vP=`${mP}@2:${bP}:`,EP="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],_0=["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"],I0=["chainChanged","accountsChanged","message","disconnect","connect"],xP=async()=>{const{createAppKit:t}=await T0(()=>import("./core-806d78ea.js").then(e=>e.$),["assets/core-806d78ea.js","assets/index-2ef9f1d1.js","assets/index-a8255d1c.css","assets/index-c1c8440f.js"]);return t};var _P=Object.defineProperty,IP=Object.defineProperties,SP=Object.getOwnPropertyDescriptors,Ff=Object.getOwnPropertySymbols,$P=Object.prototype.hasOwnProperty,OP=Object.prototype.propertyIsEnumerable,fc=(t,e,r)=>e in t?_P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e)=>{for(var r in e||(e={}))$P.call(e,r)&&fc(t,r,e[r]);if(Ff)for(var r of Ff(e))OP.call(e,r)&&fc(t,r,e[r]);return t},on=(t,e)=>IP(t,SP(e)),ct=(t,e,r)=>fc(t,typeof e!="symbol"?e+"":e,r);function Ls(t){return Number(t[0].split(":")[1])}function ls(t){return`0x${t.toString(16)}`}function DP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!_t(e))throw new Error("Invalid chains");const c={chains:e,methods:i||ks,events:s||js,rpcMap:Wr({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},l=s==null?void 0:s.filter(d=>!js.includes(d)),u=i==null?void 0:i.filter(d=>!ks.includes(d));if(!r&&!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)||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:_0))],events:[...new Set(c.events.concat(o!=null&&o.length?o:I0))],rpcMap:a};return{required:e.length?c:void 0,optional:r.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",vP),ct(this,"on",(e,r)=>(this.events.on(e,r),this)),ct(this,"once",(e,r)=>(this.events.once(e,r),this)),ct(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ct(this,"off",(e,r)=>(this.events.off(e,r),this)),ct(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new uo;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}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 r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:n}=DP(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(Wr({namespaces:Wr({},i&&{[this.namespace]:i})},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=Iu(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{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;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(Wr({},e),{chains:this.rpc.chains}),r).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=Iu(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{(i=this.modal)==null||i.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:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.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 r=parseInt(e);this.chainId=r,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(Wr({},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 r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ls(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const n=(r=e==null?void 0:e.chains)!=null?r:[],s=(i=e==null?void 0:e.optionalChains)!=null?i:[],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,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await wP.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 i;try{const n=await xP(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return jP}),o=s(on(Wr({},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");i=n(on(Wr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&_t(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)})),i&&_t(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${EP}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}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(r=>this.parseAccount(r))}}const AP=uo;var PP=Object.defineProperty,CP=Object.defineProperties,BP=Object.getOwnPropertyDescriptors,Nf=Object.getOwnPropertySymbols,TP=Object.prototype.hasOwnProperty,RP=Object.prototype.propertyIsEnumerable,Uf=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,S0=(t,e)=>{for(var r in e||(e={}))TP.call(e,r)&&Uf(t,r,e[r]);if(Nf)for(var r of Nf(e))RP.call(e,r)&&Uf(t,r,e[r]);return t},FP=(t,e)=>CP(t,BP(e));function NP(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 UP=t=>{const[e,r]=t.split(":");return $0({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function kP(t){var e,r,i,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(UP).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:NP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:FP(S0({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.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 $0(t){return S0({formatters:void 0,fees:void 0,serializers:void 0},t)}var jP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:kP,defineChain:$0});const A5=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:AP,OPTIONAL_EVENTS:I0,OPTIONAL_METHODS:_0,REQUIRED_EVENTS:js,REQUIRED_METHODS:ks,default:uo},Symbol.toStringTag,{value:"Module"}));export{O$ as A,Xc as B,hE as C,ao as D,$n as E,fi as F,Ct as G,p2 as H,hi as I,Rr as J,oo as K,Mt as L,vt as M,Lt as N,l0 as O,du as P,sp as Q,A5 as R,iS as a,nS as b,Fg as c,is as d,sS as e,si as f,Ih as g,qf as h,L as i,Et as j,aS as k,ii as l,pc as m,An as n,E1 as o,f1 as p,Fm as q,_E as r,oi as s,nt as t,q0 as u,Mf as v,fn as w,Pa as x,k8 as y,Qc as z};
|